use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt;
use std::hash::Hash;
use std::marker::PhantomData;
use bevy::prelude::{App, Plugin, Resource};
use serde::{Deserialize, Serialize};
#[cfg(feature = "items")]
use crate::items::{DefaultItem, DropTable, DropTableEntry, ItemType};
use crate::voxel::{DefaultVoxel, VoxelType};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ContentId(String);
impl ContentId {
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl From<&str> for ContentId {
fn from(value: &str) -> Self {
Self::new(value)
}
}
impl From<String> for ContentId {
fn from(value: String) -> Self {
Self::new(value)
}
}
impl AsRef<str> for ContentId {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for ContentId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ContentValue {
Bool(bool),
Integer(i64),
Float(f64),
Text(String),
TextList(Vec<String>),
NumberList(Vec<f64>),
Color([f32; 4]),
}
impl ContentValue {
pub fn strings(values: impl IntoIterator<Item = impl Into<String>>) -> Self {
Self::TextList(values.into_iter().map(Into::into).collect())
}
pub fn as_bool(&self) -> Option<bool> {
match self {
Self::Bool(value) => Some(*value),
_ => None,
}
}
pub fn as_i64(&self) -> Option<i64> {
match self {
Self::Integer(value) => Some(*value),
_ => None,
}
}
pub fn as_f64(&self) -> Option<f64> {
match self {
Self::Float(value) => Some(*value),
_ => None,
}
}
pub fn as_number(&self) -> Option<f64> {
match self {
Self::Integer(value) => Some(*value as f64),
Self::Float(value) => Some(*value),
_ => None,
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
Self::Text(value) => Some(value.as_str()),
_ => None,
}
}
pub fn as_text_list(&self) -> Option<&[String]> {
match self {
Self::TextList(value) => Some(value.as_slice()),
_ => None,
}
}
pub fn as_number_list(&self) -> Option<&[f64]> {
match self {
Self::NumberList(value) => Some(value.as_slice()),
_ => None,
}
}
pub fn as_color(&self) -> Option<[f32; 4]> {
match self {
Self::Color(value) => Some(*value),
_ => None,
}
}
}
impl From<bool> for ContentValue {
fn from(value: bool) -> Self {
Self::Bool(value)
}
}
impl From<i64> for ContentValue {
fn from(value: i64) -> Self {
Self::Integer(value)
}
}
impl From<i32> for ContentValue {
fn from(value: i32) -> Self {
Self::Integer(value.into())
}
}
impl From<u32> for ContentValue {
fn from(value: u32) -> Self {
Self::Integer(value.into())
}
}
impl From<f32> for ContentValue {
fn from(value: f32) -> Self {
Self::Float(value.into())
}
}
impl From<f64> for ContentValue {
fn from(value: f64) -> Self {
Self::Float(value)
}
}
impl From<&str> for ContentValue {
fn from(value: &str) -> Self {
Self::Text(value.to_owned())
}
}
impl From<String> for ContentValue {
fn from(value: String) -> Self {
Self::Text(value)
}
}
impl From<[f32; 4]> for ContentValue {
fn from(value: [f32; 4]) -> Self {
Self::Color(value)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct BlockEngineProperties {
pub emits_mesh: bool,
pub collidable: bool,
pub opacity: f32,
pub color: [f32; 4],
pub texture_layers: [u32; 6],
}
impl BlockEngineProperties {
pub fn new(
emits_mesh: bool,
collidable: bool,
opacity: f32,
color: [f32; 4],
texture_layers: [u32; 6],
) -> Self {
Self {
emits_mesh,
collidable,
opacity,
color,
texture_layers,
}
}
pub fn from_voxel<V: VoxelType>(voxel: V) -> Self {
Self {
emits_mesh: voxel.is_solid(),
collidable: voxel.is_solid(),
opacity: voxel.alpha(),
color: voxel.color(),
texture_layers: [
voxel.texture_layer(0),
voxel.texture_layer(1),
voxel.texture_layer(2),
voxel.texture_layer(3),
voxel.texture_layer(4),
voxel.texture_layer(5),
],
}
}
pub fn empty() -> Self {
Self::new(false, false, 0.0, [0.0, 0.0, 0.0, 0.0], [0; 6])
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct BlockDefinition<V: VoxelType> {
id: ContentId,
voxel: V,
display_name: String,
engine: BlockEngineProperties,
attributes: HashMap<String, ContentValue>,
tags: HashSet<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BlockContentSnapshot {
pub id: ContentId,
pub display_name: String,
pub voxel_byte: u8,
pub engine: BlockEngineProperties,
pub attributes: BTreeMap<String, ContentValue>,
pub tags: Vec<String>,
}
impl<V: VoxelType> BlockDefinition<V> {
pub fn new(id: impl Into<ContentId>, voxel: V) -> Self {
Self {
id: id.into(),
voxel,
display_name: voxel.name().to_owned(),
engine: BlockEngineProperties::from_voxel(voxel),
attributes: HashMap::new(),
tags: HashSet::new(),
}
}
pub fn id(&self) -> &ContentId {
&self.id
}
pub fn voxel(&self) -> V {
self.voxel
}
pub fn display_name(&self) -> &str {
&self.display_name
}
pub fn named(mut self, name: impl Into<String>) -> Self {
self.display_name = name.into();
self
}
pub fn engine(&self) -> BlockEngineProperties {
self.engine
}
pub fn engine_properties(mut self, engine: BlockEngineProperties) -> Self {
self.engine = engine;
self
}
pub fn attribute(mut self, key: impl Into<String>, value: impl Into<ContentValue>) -> Self {
self.attributes.insert(key.into(), value.into());
self
}
pub fn tag(mut self, tag: impl Into<String>) -> Self {
self.tags.insert(tag.into());
self
}
pub fn get_attribute(&self, key: &str) -> Option<&ContentValue> {
self.attributes.get(key)
}
pub fn bool_attribute(&self, key: &str) -> Option<bool> {
self.get_attribute(key).and_then(ContentValue::as_bool)
}
pub fn integer_attribute(&self, key: &str) -> Option<i64> {
self.get_attribute(key).and_then(ContentValue::as_i64)
}
pub fn number_attribute(&self, key: &str) -> Option<f64> {
self.get_attribute(key).and_then(ContentValue::as_number)
}
pub fn text_attribute(&self, key: &str) -> Option<&str> {
self.get_attribute(key).and_then(ContentValue::as_str)
}
pub fn text_list_attribute(&self, key: &str) -> Option<&[String]> {
self.get_attribute(key).and_then(ContentValue::as_text_list)
}
pub fn number_list_attribute(&self, key: &str) -> Option<&[f64]> {
self.get_attribute(key)
.and_then(ContentValue::as_number_list)
}
pub fn color_attribute(&self, key: &str) -> Option<[f32; 4]> {
self.get_attribute(key).and_then(ContentValue::as_color)
}
pub fn attributes(&self) -> &HashMap<String, ContentValue> {
&self.attributes
}
pub fn has_tag(&self, tag: &str) -> bool {
self.tags.contains(tag)
}
pub fn tags(&self) -> &HashSet<String> {
&self.tags
}
pub fn snapshot(&self) -> BlockContentSnapshot {
BlockContentSnapshot {
id: self.id.clone(),
display_name: self.display_name.clone(),
voxel_byte: self.voxel.to_byte(),
engine: self.engine,
attributes: ordered_attributes(&self.attributes),
tags: ordered_tags(&self.tags),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ContentRegistryError<V: VoxelType> {
DuplicateId { id: ContentId },
DuplicateVoxel { voxel: V, existing_id: ContentId },
MissingId { id: ContentId },
}
impl<V: VoxelType + fmt::Debug> fmt::Display for ContentRegistryError<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::DuplicateId { id } => {
write!(f, "content id `{id}` is already registered")
}
Self::DuplicateVoxel { voxel, existing_id } => {
write!(
f,
"voxel value `{voxel:?}` is already registered as `{existing_id}`"
)
}
Self::MissingId { id } => {
write!(f, "content id `{id}` is not registered")
}
}
}
}
impl<V: VoxelType + fmt::Debug> std::error::Error for ContentRegistryError<V> {}
#[derive(Debug, Clone, Resource)]
pub struct BlockRegistry<V: VoxelType> {
blocks_by_id: HashMap<ContentId, BlockDefinition<V>>,
ids_by_voxel: HashMap<V, ContentId>,
}
impl<V: VoxelType> Default for BlockRegistry<V> {
fn default() -> Self {
Self {
blocks_by_id: HashMap::new(),
ids_by_voxel: HashMap::new(),
}
}
}
impl<V: VoxelType> BlockRegistry<V> {
pub fn register(
&mut self,
definition: BlockDefinition<V>,
) -> Result<(), ContentRegistryError<V>> {
if self.blocks_by_id.contains_key(definition.id()) {
return Err(ContentRegistryError::DuplicateId {
id: definition.id().clone(),
});
}
if let Some(existing_id) = self.ids_by_voxel.get(&definition.voxel()) {
return Err(ContentRegistryError::DuplicateVoxel {
voxel: definition.voxel(),
existing_id: existing_id.clone(),
});
}
self.ids_by_voxel
.insert(definition.voxel(), definition.id().clone());
self.blocks_by_id
.insert(definition.id().clone(), definition);
Ok(())
}
pub fn insert_or_replace(&mut self, definition: BlockDefinition<V>) {
if let Some(old) = self.blocks_by_id.remove(definition.id()) {
self.ids_by_voxel.remove(&old.voxel());
}
if let Some(old_id) = self.ids_by_voxel.remove(&definition.voxel()) {
self.blocks_by_id.remove(&old_id);
}
self.ids_by_voxel
.insert(definition.voxel(), definition.id().clone());
self.blocks_by_id
.insert(definition.id().clone(), definition);
}
pub fn get(&self, id: impl AsRef<str>) -> Option<&BlockDefinition<V>> {
let id = ContentId::new(id.as_ref());
self.blocks_by_id.get(&id)
}
pub fn require(
&self,
id: impl AsRef<str>,
) -> Result<&BlockDefinition<V>, ContentRegistryError<V>> {
let id = ContentId::new(id.as_ref());
self.blocks_by_id
.get(&id)
.ok_or(ContentRegistryError::MissingId { id })
}
pub fn get_by_voxel(&self, voxel: V) -> Option<&BlockDefinition<V>> {
self.ids_by_voxel
.get(&voxel)
.and_then(|id| self.blocks_by_id.get(id))
}
pub fn contains_id(&self, id: impl AsRef<str>) -> bool {
self.get(id).is_some()
}
pub fn len(&self) -> usize {
self.blocks_by_id.len()
}
pub fn is_empty(&self) -> bool {
self.blocks_by_id.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = &BlockDefinition<V>> {
self.blocks_by_id.values()
}
pub fn snapshot(&self) -> Vec<BlockContentSnapshot> {
let mut blocks: Vec<_> = self.iter().map(BlockDefinition::snapshot).collect();
blocks.sort_by(|left, right| left.id.as_str().cmp(right.id.as_str()));
blocks
}
}
#[cfg(feature = "items")]
#[derive(Debug, Clone, PartialEq)]
pub struct ItemDefinition<I: ItemType> {
id: ContentId,
item: I,
display_name: String,
color: [f32; 4],
attributes: HashMap<String, ContentValue>,
tags: HashSet<String>,
}
#[cfg(feature = "items")]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ItemContentSnapshot {
pub id: ContentId,
pub display_name: String,
pub item_byte: u8,
pub color: [f32; 4],
pub attributes: BTreeMap<String, ContentValue>,
pub tags: Vec<String>,
}
#[cfg(feature = "items")]
impl<I: ItemType> ItemDefinition<I> {
pub fn new(id: impl Into<ContentId>, item: I) -> Self {
Self {
id: id.into(),
item,
display_name: item.name().to_owned(),
color: item.color(),
attributes: HashMap::new(),
tags: HashSet::new(),
}
}
pub fn id(&self) -> &ContentId {
&self.id
}
pub fn item(&self) -> I {
self.item
}
pub fn display_name(&self) -> &str {
&self.display_name
}
pub fn named(mut self, name: impl Into<String>) -> Self {
self.display_name = name.into();
self
}
pub fn color(&self) -> [f32; 4] {
self.color
}
pub fn color_override(mut self, color: [f32; 4]) -> Self {
self.color = color;
self
}
pub fn attribute(mut self, key: impl Into<String>, value: impl Into<ContentValue>) -> Self {
self.attributes.insert(key.into(), value.into());
self
}
pub fn tag(mut self, tag: impl Into<String>) -> Self {
self.tags.insert(tag.into());
self
}
pub fn get_attribute(&self, key: &str) -> Option<&ContentValue> {
self.attributes.get(key)
}
pub fn bool_attribute(&self, key: &str) -> Option<bool> {
self.get_attribute(key).and_then(ContentValue::as_bool)
}
pub fn integer_attribute(&self, key: &str) -> Option<i64> {
self.get_attribute(key).and_then(ContentValue::as_i64)
}
pub fn number_attribute(&self, key: &str) -> Option<f64> {
self.get_attribute(key).and_then(ContentValue::as_number)
}
pub fn text_attribute(&self, key: &str) -> Option<&str> {
self.get_attribute(key).and_then(ContentValue::as_str)
}
pub fn text_list_attribute(&self, key: &str) -> Option<&[String]> {
self.get_attribute(key).and_then(ContentValue::as_text_list)
}
pub fn number_list_attribute(&self, key: &str) -> Option<&[f64]> {
self.get_attribute(key)
.and_then(ContentValue::as_number_list)
}
pub fn color_attribute(&self, key: &str) -> Option<[f32; 4]> {
self.get_attribute(key).and_then(ContentValue::as_color)
}
pub fn attributes(&self) -> &HashMap<String, ContentValue> {
&self.attributes
}
pub fn has_tag(&self, tag: &str) -> bool {
self.tags.contains(tag)
}
pub fn tags(&self) -> &HashSet<String> {
&self.tags
}
pub fn snapshot(&self) -> ItemContentSnapshot {
ItemContentSnapshot {
id: self.id.clone(),
display_name: self.display_name.clone(),
item_byte: self.item.to_byte(),
color: self.color,
attributes: ordered_attributes(&self.attributes),
tags: ordered_tags(&self.tags),
}
}
}
#[cfg(feature = "items")]
#[derive(Debug, Clone, PartialEq)]
pub enum ItemRegistryError<I: ItemType> {
DuplicateId { id: ContentId },
DuplicateItem { item: I, existing_id: ContentId },
MissingId { id: ContentId },
}
#[cfg(feature = "items")]
impl<I: ItemType + fmt::Debug> fmt::Display for ItemRegistryError<I> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::DuplicateId { id } => {
write!(f, "content id `{id}` is already registered")
}
Self::DuplicateItem { item, existing_id } => {
write!(
f,
"item value `{item:?}` is already registered as `{existing_id}`"
)
}
Self::MissingId { id } => {
write!(f, "content id `{id}` is not registered")
}
}
}
}
#[cfg(feature = "items")]
impl<I: ItemType + fmt::Debug> std::error::Error for ItemRegistryError<I> {}
#[cfg(feature = "items")]
#[derive(Debug, Clone, Resource)]
pub struct ItemRegistry<I: ItemType> {
items_by_id: HashMap<ContentId, ItemDefinition<I>>,
ids_by_item: HashMap<I, ContentId>,
}
#[cfg(feature = "items")]
impl<I: ItemType> Default for ItemRegistry<I> {
fn default() -> Self {
Self {
items_by_id: HashMap::new(),
ids_by_item: HashMap::new(),
}
}
}
#[cfg(feature = "items")]
impl<I: ItemType> ItemRegistry<I> {
pub fn register(&mut self, definition: ItemDefinition<I>) -> Result<(), ItemRegistryError<I>> {
if self.items_by_id.contains_key(definition.id()) {
return Err(ItemRegistryError::DuplicateId {
id: definition.id().clone(),
});
}
if let Some(existing_id) = self.ids_by_item.get(&definition.item()) {
return Err(ItemRegistryError::DuplicateItem {
item: definition.item(),
existing_id: existing_id.clone(),
});
}
self.ids_by_item
.insert(definition.item(), definition.id().clone());
self.items_by_id.insert(definition.id().clone(), definition);
Ok(())
}
pub fn insert_or_replace(&mut self, definition: ItemDefinition<I>) {
if let Some(old) = self.items_by_id.remove(definition.id()) {
self.ids_by_item.remove(&old.item());
}
if let Some(old_id) = self.ids_by_item.remove(&definition.item()) {
self.items_by_id.remove(&old_id);
}
self.ids_by_item
.insert(definition.item(), definition.id().clone());
self.items_by_id.insert(definition.id().clone(), definition);
}
pub fn get(&self, id: impl AsRef<str>) -> Option<&ItemDefinition<I>> {
let id = ContentId::new(id.as_ref());
self.items_by_id.get(&id)
}
pub fn require(&self, id: impl AsRef<str>) -> Result<&ItemDefinition<I>, ItemRegistryError<I>> {
let id = ContentId::new(id.as_ref());
self.items_by_id
.get(&id)
.ok_or(ItemRegistryError::MissingId { id })
}
pub fn get_by_item(&self, item: I) -> Option<&ItemDefinition<I>> {
self.ids_by_item
.get(&item)
.and_then(|id| self.items_by_id.get(id))
}
pub fn contains_id(&self, id: impl AsRef<str>) -> bool {
self.get(id).is_some()
}
pub fn len(&self) -> usize {
self.items_by_id.len()
}
pub fn is_empty(&self) -> bool {
self.items_by_id.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = &ItemDefinition<I>> {
self.items_by_id.values()
}
pub fn snapshot(&self) -> Vec<ItemContentSnapshot> {
let mut items: Vec<_> = self.iter().map(ItemDefinition::snapshot).collect();
items.sort_by(|left, right| left.id.as_str().cmp(right.id.as_str()));
items
}
}
#[cfg(feature = "items")]
pub struct ItemContentPlugin<I: ItemType = DefaultItem> {
_marker: PhantomData<I>,
}
#[cfg(feature = "items")]
impl<I: ItemType> ItemContentPlugin<I> {
pub fn new() -> Self {
Self {
_marker: PhantomData,
}
}
}
#[cfg(feature = "items")]
impl<I: ItemType> Default for ItemContentPlugin<I> {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "items")]
impl<I: ItemType> Plugin for ItemContentPlugin<I> {
fn build(&self, app: &mut App) {
app.init_resource::<ItemRegistry<I>>();
}
}
#[cfg(feature = "items")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct DropCount {
pub min: u32,
pub max: u32,
}
#[cfg(feature = "items")]
impl DropCount {
pub fn fixed(count: u32) -> Self {
Self {
min: count,
max: count,
}
}
pub fn range(min: u32, max: u32) -> Self {
Self {
min: min.min(max),
max: min.max(max),
}
}
}
#[cfg(feature = "items")]
#[derive(Debug, Clone, PartialEq)]
pub struct BlockDropDefinition<I: ItemType> {
item: I,
count: DropCount,
chance: f32,
attributes: HashMap<String, ContentValue>,
}
#[cfg(feature = "items")]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BlockDropContentSnapshot {
pub block_id: ContentId,
pub item_byte: u8,
pub min_count: u32,
pub max_count: u32,
pub chance: f32,
pub attributes: BTreeMap<String, ContentValue>,
}
#[cfg(feature = "items")]
impl<I: ItemType> BlockDropDefinition<I> {
pub fn fixed(item: I, count: u32) -> Self {
Self::new(item, DropCount::fixed(count))
}
pub fn new(item: I, count: DropCount) -> Self {
Self {
item,
count,
chance: 1.0,
attributes: HashMap::new(),
}
}
pub fn item(&self) -> I {
self.item
}
pub fn count(&self) -> DropCount {
self.count
}
pub fn chance(&self) -> f32 {
self.chance
}
pub fn with_chance(mut self, chance: f32) -> Self {
self.chance = chance.clamp(0.0, 1.0);
self
}
pub fn attribute(mut self, key: impl Into<String>, value: impl Into<ContentValue>) -> Self {
self.attributes.insert(key.into(), value.into());
self
}
pub fn get_attribute(&self, key: &str) -> Option<&ContentValue> {
self.attributes.get(key)
}
pub fn bool_attribute(&self, key: &str) -> Option<bool> {
self.get_attribute(key).and_then(ContentValue::as_bool)
}
pub fn integer_attribute(&self, key: &str) -> Option<i64> {
self.get_attribute(key).and_then(ContentValue::as_i64)
}
pub fn number_attribute(&self, key: &str) -> Option<f64> {
self.get_attribute(key).and_then(ContentValue::as_number)
}
pub fn text_attribute(&self, key: &str) -> Option<&str> {
self.get_attribute(key).and_then(ContentValue::as_str)
}
pub fn text_list_attribute(&self, key: &str) -> Option<&[String]> {
self.get_attribute(key).and_then(ContentValue::as_text_list)
}
pub fn number_list_attribute(&self, key: &str) -> Option<&[f64]> {
self.get_attribute(key)
.and_then(ContentValue::as_number_list)
}
pub fn color_attribute(&self, key: &str) -> Option<[f32; 4]> {
self.get_attribute(key).and_then(ContentValue::as_color)
}
pub fn attributes(&self) -> &HashMap<String, ContentValue> {
&self.attributes
}
pub fn to_drop_table_entry(&self) -> DropTableEntry<I> {
DropTableEntry::with_chance(self.item, self.count.min, self.count.max, self.chance)
}
fn snapshot(&self, block_id: &ContentId) -> BlockDropContentSnapshot {
BlockDropContentSnapshot {
block_id: block_id.clone(),
item_byte: self.item.to_byte(),
min_count: self.count.min,
max_count: self.count.max,
chance: self.chance,
attributes: ordered_attributes(&self.attributes),
}
}
}
#[cfg(feature = "items")]
#[derive(Debug, Clone, PartialEq)]
pub enum BlockDropRegistryError<I: ItemType> {
UnknownBlockId { id: ContentId },
UnknownItem { block_id: ContentId, item: I },
}
#[cfg(feature = "items")]
impl<I: ItemType + fmt::Debug> fmt::Display for BlockDropRegistryError<I> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnknownBlockId { id } => {
write!(f, "drop table references unknown block id `{id}`")
}
Self::UnknownItem { block_id, item } => {
write!(
f,
"drop table for block `{block_id}` references unknown item `{item:?}`"
)
}
}
}
}
#[cfg(feature = "items")]
impl<I: ItemType + fmt::Debug> std::error::Error for BlockDropRegistryError<I> {}
#[cfg(feature = "items")]
#[derive(Debug, Clone, Resource)]
pub struct BlockDropRegistry<I: ItemType> {
drops_by_block_id: HashMap<ContentId, Vec<BlockDropDefinition<I>>>,
}
#[cfg(feature = "items")]
impl<I: ItemType> Default for BlockDropRegistry<I> {
fn default() -> Self {
Self {
drops_by_block_id: HashMap::new(),
}
}
}
#[cfg(feature = "items")]
impl<I: ItemType> BlockDropRegistry<I> {
pub fn register_drop(&mut self, block_id: impl Into<ContentId>, drop: BlockDropDefinition<I>) {
self.drops_by_block_id
.entry(block_id.into())
.or_default()
.push(drop);
}
pub fn get(&self, block_id: impl AsRef<str>) -> &[BlockDropDefinition<I>] {
let id = ContentId::new(block_id.as_ref());
self.drops_by_block_id
.get(&id)
.map(Vec::as_slice)
.unwrap_or(&[])
}
pub fn contains_block_id(&self, block_id: impl AsRef<str>) -> bool {
let id = ContentId::new(block_id.as_ref());
self.drops_by_block_id.contains_key(&id)
}
pub fn len_for(&self, block_id: impl AsRef<str>) -> usize {
self.get(block_id).len()
}
pub fn iter(&self) -> impl Iterator<Item = (&ContentId, &[BlockDropDefinition<I>])> {
self.drops_by_block_id
.iter()
.map(|(id, drops)| (id, drops.as_slice()))
}
pub fn snapshot(&self) -> Vec<BlockDropContentSnapshot> {
let mut drops: Vec<_> = self
.iter()
.flat_map(|(block_id, drops)| drops.iter().map(|drop| drop.snapshot(block_id)))
.collect();
drops.sort_by(|left, right| {
left.block_id
.as_str()
.cmp(right.block_id.as_str())
.then(left.item_byte.cmp(&right.item_byte))
.then(left.min_count.cmp(&right.min_count))
.then(left.max_count.cmp(&right.max_count))
});
drops
}
pub fn get_for_voxel<V: VoxelType>(
&self,
voxel: V,
blocks: &BlockRegistry<V>,
) -> &[BlockDropDefinition<I>] {
let Some(block) = blocks.get_by_voxel(voxel) else {
return &[];
};
self.get(block.id().as_str())
}
pub fn validate_blocks<V: VoxelType>(
&self,
blocks: &BlockRegistry<V>,
) -> Result<(), BlockDropRegistryError<I>> {
for block_id in self.drops_by_block_id.keys() {
if !blocks.contains_id(block_id.as_str()) {
return Err(BlockDropRegistryError::UnknownBlockId {
id: block_id.clone(),
});
}
}
Ok(())
}
pub fn validate_items(&self, items: &ItemRegistry<I>) -> Result<(), BlockDropRegistryError<I>> {
for (block_id, drops) in &self.drops_by_block_id {
for drop in drops {
if items.get_by_item(drop.item()).is_none() {
return Err(BlockDropRegistryError::UnknownItem {
block_id: block_id.clone(),
item: drop.item(),
});
}
}
}
Ok(())
}
pub fn to_drop_table<V: VoxelType>(
&self,
blocks: &BlockRegistry<V>,
) -> Result<DropTable<I>, BlockDropRegistryError<I>> {
let mut table = DropTable::new();
self.apply_to_drop_table(blocks, &mut table)?;
Ok(table)
}
pub fn apply_to_drop_table<V: VoxelType>(
&self,
blocks: &BlockRegistry<V>,
table: &mut DropTable<I>,
) -> Result<(), BlockDropRegistryError<I>> {
for (block_id, drops) in &self.drops_by_block_id {
let Some(block) = blocks.get(block_id.as_str()) else {
return Err(BlockDropRegistryError::UnknownBlockId {
id: block_id.clone(),
});
};
table.replace_entries(
block.voxel().to_byte(),
drops.iter().map(BlockDropDefinition::to_drop_table_entry),
);
}
Ok(())
}
pub fn len(&self) -> usize {
self.drops_by_block_id.len()
}
pub fn is_empty(&self) -> bool {
self.drops_by_block_id.is_empty()
}
}
#[cfg(feature = "items")]
pub struct BlockDropContentPlugin<I: ItemType = DefaultItem> {
_marker: PhantomData<I>,
}
#[cfg(feature = "items")]
impl<I: ItemType> BlockDropContentPlugin<I> {
pub fn new() -> Self {
Self {
_marker: PhantomData,
}
}
}
#[cfg(feature = "items")]
impl<I: ItemType> Default for BlockDropContentPlugin<I> {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "items")]
impl<I: ItemType> Plugin for BlockDropContentPlugin<I> {
fn build(&self, app: &mut App) {
app.init_resource::<BlockDropRegistry<I>>();
}
}
pub struct VoxelContentPlugin<V: VoxelType = DefaultVoxel> {
_marker: PhantomData<V>,
}
impl<V: VoxelType> VoxelContentPlugin<V> {
pub fn new() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl<V: VoxelType> Default for VoxelContentPlugin<V> {
fn default() -> Self {
Self::new()
}
}
impl<V: VoxelType> Plugin for VoxelContentPlugin<V> {
fn build(&self, app: &mut App) {
app.init_resource::<BlockRegistry<V>>();
}
}
fn ordered_attributes(
attributes: &HashMap<String, ContentValue>,
) -> BTreeMap<String, ContentValue> {
attributes
.iter()
.map(|(key, value)| (key.clone(), value.clone()))
.collect()
}
fn ordered_tags(tags: &HashSet<String>) -> Vec<String> {
let mut tags: Vec<_> = tags.iter().cloned().collect();
tags.sort();
tags
}
#[cfg(test)]
mod tests {
use bevy::prelude::{App, MinimalPlugins};
use super::*;
#[cfg(feature = "items")]
use crate::items::DefaultItem;
use crate::voxel::DefaultTerrainVoxel;
#[test]
fn block_definition_keeps_author_defined_attributes_and_tags() {
let definition = BlockDefinition::new("regolith", DefaultTerrainVoxel::Sand)
.named("Regolith")
.tag("terrain")
.attribute("hardness", 0.8)
.attribute("dusty", true)
.attribute("drops", ContentValue::strings(["regolith"]));
assert_eq!(definition.id().as_str(), "regolith");
assert_eq!(definition.voxel(), DefaultTerrainVoxel::Sand);
assert_eq!(definition.display_name(), "Regolith");
assert!(definition.has_tag("terrain"));
assert_eq!(definition.number_attribute("hardness"), Some(0.8));
assert_eq!(definition.bool_attribute("dusty"), Some(true));
assert_eq!(
definition.text_list_attribute("drops"),
Some(&["regolith".to_owned()][..])
);
}
#[test]
fn content_value_number_accepts_integers_and_floats() {
assert_eq!(ContentValue::from(5).as_number(), Some(5.0));
assert_eq!(ContentValue::from(0.75).as_number(), Some(0.75));
assert_eq!(ContentValue::from("not_a_number").as_number(), None);
}
#[test]
fn registry_rejects_duplicate_ids_and_duplicate_voxels() {
let mut registry = BlockRegistry::<DefaultTerrainVoxel>::default();
registry
.register(BlockDefinition::new("stone", DefaultTerrainVoxel::Stone))
.expect("first block should register");
let duplicate_id =
registry.register(BlockDefinition::new("stone", DefaultTerrainVoxel::Dirt));
assert!(matches!(
duplicate_id,
Err(ContentRegistryError::DuplicateId { .. })
));
let duplicate_voxel = registry.register(BlockDefinition::new(
"another_stone",
DefaultTerrainVoxel::Stone,
));
assert!(matches!(
duplicate_voxel,
Err(ContentRegistryError::DuplicateVoxel { .. })
));
}
#[test]
fn registry_can_lookup_by_id_and_voxel() {
let mut registry = BlockRegistry::<DefaultTerrainVoxel>::default();
registry
.register(BlockDefinition::new("wood", DefaultTerrainVoxel::Wood).tag("organic"))
.expect("block should register");
assert_eq!(registry.len(), 1);
assert!(registry.contains_id("wood"));
assert_eq!(
registry.require("wood").expect("wood should exist").voxel(),
DefaultTerrainVoxel::Wood
);
assert!(matches!(
registry.require("missing"),
Err(ContentRegistryError::MissingId { .. })
));
assert!(
registry
.get_by_voxel(DefaultTerrainVoxel::Wood)
.expect("wood voxel should resolve")
.has_tag("organic")
);
}
#[test]
fn block_registry_snapshot_is_serializable_and_deterministic() {
let mut registry = BlockRegistry::<DefaultTerrainVoxel>::default();
registry
.register(
BlockDefinition::new("wood", DefaultTerrainVoxel::Wood)
.tag("organic")
.tag("solid")
.attribute("hardness", 1.5)
.attribute("flammable", true),
)
.expect("block should register");
let snapshot = registry.snapshot();
assert_eq!(snapshot.len(), 1);
assert_eq!(snapshot[0].id.as_str(), "wood");
assert_eq!(snapshot[0].voxel_byte, DefaultTerrainVoxel::Wood.to_byte());
assert_eq!(
snapshot[0].tags,
vec!["organic".to_owned(), "solid".to_owned()]
);
assert_eq!(
snapshot[0]
.attributes
.get("hardness")
.and_then(ContentValue::as_number),
Some(1.5)
);
let json = serde_json::to_string(&snapshot).expect("snapshot should serialize");
assert!(json.contains("\"id\":\"wood\""));
assert!(json.contains("\"voxel_byte\""));
}
#[test]
fn content_plugin_initializes_empty_registry_without_defaults() {
let mut app = App::new();
app.add_plugins(MinimalPlugins);
app.add_plugins(VoxelContentPlugin::<DefaultTerrainVoxel>::new());
assert!(
app.world()
.resource::<BlockRegistry<DefaultTerrainVoxel>>()
.is_empty(),
"content plugin must not register game-specific default blocks"
);
}
#[cfg(feature = "items")]
#[test]
fn item_definition_keeps_author_defined_attributes_and_tags() {
let definition = ItemDefinition::new("dream_glass_shard", DefaultItem::Crystal)
.named("Dream Glass Shard")
.color_override([0.45, 0.75, 1.0, 1.0])
.tag("ritual_material")
.attribute("mana_conductivity", 12.0);
assert_eq!(definition.id().as_str(), "dream_glass_shard");
assert_eq!(definition.item(), DefaultItem::Crystal);
assert_eq!(definition.display_name(), "Dream Glass Shard");
assert_eq!(definition.color(), [0.45, 0.75, 1.0, 1.0]);
assert!(definition.has_tag("ritual_material"));
assert_eq!(definition.number_attribute("mana_conductivity"), Some(12.0));
}
#[cfg(feature = "items")]
#[test]
fn item_registry_rejects_duplicate_ids_and_duplicate_items() {
let mut registry = ItemRegistry::<DefaultItem>::default();
registry
.register(ItemDefinition::new("sand_item", DefaultItem::Sand))
.expect("first item should register");
let duplicate_id =
registry.register(ItemDefinition::new("sand_item", DefaultItem::Crystal));
assert!(matches!(
duplicate_id,
Err(ItemRegistryError::DuplicateId { .. })
));
let duplicate_item =
registry.register(ItemDefinition::new("another_sand", DefaultItem::Sand));
assert!(matches!(
duplicate_item,
Err(ItemRegistryError::DuplicateItem { .. })
));
assert!(registry.require("sand_item").is_ok());
assert!(matches!(
registry.require("missing"),
Err(ItemRegistryError::MissingId { .. })
));
}
#[cfg(feature = "items")]
#[test]
fn item_registry_snapshot_is_serializable_and_deterministic() {
let mut registry = ItemRegistry::<DefaultItem>::default();
registry
.register(
ItemDefinition::new("dream_glass_shard", DefaultItem::Crystal)
.tag("ritual_material")
.attribute("mana_conductivity", 12.0),
)
.expect("item should register");
let snapshot = registry.snapshot();
assert_eq!(snapshot.len(), 1);
assert_eq!(snapshot[0].id.as_str(), "dream_glass_shard");
assert_eq!(snapshot[0].item_byte, DefaultItem::Crystal.to_byte());
assert_eq!(snapshot[0].tags, vec!["ritual_material".to_owned()]);
let json = serde_json::to_string(&snapshot).expect("snapshot should serialize");
assert!(json.contains("\"item_byte\""));
}
#[cfg(feature = "items")]
#[test]
fn block_drop_registry_resolves_drops_by_block_id_and_voxel() {
let mut blocks = BlockRegistry::<DefaultTerrainVoxel>::default();
blocks
.register(BlockDefinition::new(
"moon_regolith",
DefaultTerrainVoxel::Sand,
))
.expect("block should register");
let mut drops = BlockDropRegistry::<DefaultItem>::default();
drops.register_drop(
"moon_regolith",
BlockDropDefinition::new(DefaultItem::Sand, DropCount::range(3, 1)).with_chance(1.4),
);
let by_id = drops.get("moon_regolith");
assert_eq!(by_id.len(), 1);
assert_eq!(by_id[0].item(), DefaultItem::Sand);
assert_eq!(by_id[0].count(), DropCount { min: 1, max: 3 });
assert_eq!(by_id[0].chance(), 1.0);
assert!(drops.contains_block_id("moon_regolith"));
assert_eq!(drops.len_for("moon_regolith"), 1);
let by_voxel = drops.get_for_voxel(DefaultTerrainVoxel::Sand, &blocks);
assert_eq!(by_voxel.len(), 1);
assert_eq!(by_voxel[0].item(), DefaultItem::Sand);
assert!(
drops
.get_for_voxel(DefaultTerrainVoxel::Stone, &blocks)
.is_empty()
);
}
#[cfg(feature = "items")]
#[test]
fn block_drop_registry_validates_block_and_item_references() {
let mut blocks = BlockRegistry::<DefaultTerrainVoxel>::default();
blocks
.register(BlockDefinition::new(
"moon_regolith",
DefaultTerrainVoxel::Sand,
))
.expect("block should register");
let mut items = ItemRegistry::<DefaultItem>::default();
items
.register(ItemDefinition::new("moon_regolith", DefaultItem::Sand))
.expect("item should register");
let mut drops = BlockDropRegistry::<DefaultItem>::default();
drops.register_drop(
"moon_regolith",
BlockDropDefinition::fixed(DefaultItem::Sand, 1),
);
assert!(drops.validate_blocks(&blocks).is_ok());
assert!(drops.validate_items(&items).is_ok());
drops.register_drop(
"missing_block",
BlockDropDefinition::fixed(DefaultItem::Sand, 1),
);
assert!(matches!(
drops.validate_blocks(&blocks),
Err(BlockDropRegistryError::UnknownBlockId { .. })
));
drops.register_drop(
"moon_regolith",
BlockDropDefinition::fixed(DefaultItem::Crystal, 1),
);
assert!(matches!(
drops.validate_items(&items),
Err(BlockDropRegistryError::UnknownItem { .. })
));
}
#[cfg(feature = "items")]
#[test]
fn block_drop_registry_builds_runtime_drop_table() {
let mut blocks = BlockRegistry::<DefaultTerrainVoxel>::default();
blocks
.register(BlockDefinition::new(
"moon_regolith",
DefaultTerrainVoxel::Sand,
))
.expect("block should register");
let mut drops = BlockDropRegistry::<DefaultItem>::default();
drops.register_drop(
"moon_regolith",
BlockDropDefinition::new(DefaultItem::Sand, DropCount::range(1, 3)),
);
drops.register_drop(
"moon_regolith",
BlockDropDefinition::fixed(DefaultItem::Crystal, 1).with_chance(1.0),
);
let table = drops
.to_drop_table(&blocks)
.expect("content drops should resolve through blocks");
let runtime_drops = table.get_drops(DefaultTerrainVoxel::Sand.to_byte(), 42);
assert_eq!(runtime_drops.len(), 2);
assert_eq!(runtime_drops[0].0, DefaultItem::Sand);
assert!((1..=3).contains(&runtime_drops[0].1));
assert_eq!(runtime_drops[1], (DefaultItem::Crystal, 1));
}
#[cfg(feature = "items")]
#[test]
fn block_drop_registry_applies_to_existing_drop_table_idempotently() {
let mut blocks = BlockRegistry::<DefaultTerrainVoxel>::default();
blocks
.register(BlockDefinition::new(
"moon_regolith",
DefaultTerrainVoxel::Sand,
))
.expect("block should register");
let mut drops = BlockDropRegistry::<DefaultItem>::default();
drops.register_drop(
"moon_regolith",
BlockDropDefinition::fixed(DefaultItem::Sand, 1),
);
let mut table = DropTable::<DefaultItem>::new();
table.register(1, DefaultItem::Dirt, 1, 1);
drops
.apply_to_drop_table(&blocks, &mut table)
.expect("first apply should resolve");
drops
.apply_to_drop_table(&blocks, &mut table)
.expect("second apply should replace rather than duplicate");
let runtime_drops = table.get_drops(DefaultTerrainVoxel::Sand.to_byte(), 0);
assert_eq!(runtime_drops, vec![(DefaultItem::Sand, 1)]);
assert_eq!(
table.get_drops(1, 0),
vec![(DefaultItem::Dirt, 1)],
"unrelated hand-written runtime drops should remain untouched"
);
}
#[cfg(feature = "items")]
#[test]
fn block_drop_registry_to_drop_table_reports_missing_blocks() {
let blocks = BlockRegistry::<DefaultTerrainVoxel>::default();
let mut drops = BlockDropRegistry::<DefaultItem>::default();
drops.register_drop(
"missing_block",
BlockDropDefinition::fixed(DefaultItem::Sand, 1),
);
assert!(matches!(
drops.to_drop_table(&blocks),
Err(BlockDropRegistryError::UnknownBlockId { .. })
));
}
#[cfg(feature = "items")]
#[test]
fn block_drop_registry_snapshot_is_serializable_and_deterministic() {
let mut drops = BlockDropRegistry::<DefaultItem>::default();
drops.register_drop(
"moon_regolith",
BlockDropDefinition::new(DefaultItem::Sand, DropCount::range(3, 1))
.with_chance(0.5)
.attribute("source", "surface_layer"),
);
let snapshot = drops.snapshot();
assert_eq!(snapshot.len(), 1);
assert_eq!(snapshot[0].block_id.as_str(), "moon_regolith");
assert_eq!(snapshot[0].item_byte, DefaultItem::Sand.to_byte());
assert_eq!(snapshot[0].min_count, 1);
assert_eq!(snapshot[0].max_count, 3);
assert_eq!(snapshot[0].chance, 0.5);
let json = serde_json::to_string(&snapshot).expect("snapshot should serialize");
assert!(json.contains("\"block_id\":\"moon_regolith\""));
assert!(json.contains("\"chance\":0.5"));
}
#[cfg(feature = "items")]
#[test]
fn item_and_drop_plugins_initialize_empty_registries_without_defaults() {
let mut app = App::new();
app.add_plugins(MinimalPlugins);
app.add_plugins(ItemContentPlugin::<DefaultItem>::new());
app.add_plugins(BlockDropContentPlugin::<DefaultItem>::new());
assert!(
app.world()
.resource::<ItemRegistry<DefaultItem>>()
.is_empty(),
"item content plugin must not register game-specific default items"
);
assert!(
app.world()
.resource::<BlockDropRegistry<DefaultItem>>()
.is_empty(),
"block-drop content plugin must not register game-specific default drops"
);
}
}