Skip to main content

azalea_block/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod behavior;
4pub mod block_state;
5pub mod fluid_state;
6mod generated;
7mod range;
8
9use core::fmt::Debug;
10use std::{any::Any, collections::HashMap, str::FromStr};
11
12use azalea_registry::builtin::BlockKind;
13pub use behavior::BlockBehavior;
14// re-exported for convenience
15pub use block_state::BlockState;
16pub use generated::{blocks, properties};
17pub use range::BlockStates;
18
19pub trait BlockTrait: Debug + Any {
20    fn behavior(&self) -> BlockBehavior;
21    /// Get the Minecraft string ID for this block.
22    ///
23    /// For example, `stone` or `grass_block`.
24    fn id(&self) -> &'static str;
25    /// Convert the block struct to a [`BlockState`].
26    ///
27    /// This is a lossless conversion, as [`BlockState`] also contains state
28    /// data.
29    fn as_block_state(&self) -> BlockState;
30    /// Convert the block struct to a [`BlockKind`].
31    ///
32    /// This is a lossy conversion, as [`BlockKind`] doesn't contain any state
33    /// data.
34    fn as_block_kind(&self) -> BlockKind;
35    #[deprecated = "renamed to as_block_kind"]
36    #[doc(hidden)]
37    fn as_registry_block(&self) -> BlockKind {
38        self.as_block_kind()
39    }
40
41    /// Returns a map of property names on this block to their values as
42    /// strings.
43    ///
44    /// Consider using [`Self::get_property`] if you only need a single
45    /// property.
46    fn property_map(&self) -> HashMap<&'static str, &'static str>;
47    /// Get a property's value as a string by its name, or `None` if the block
48    /// has no property with that name.
49    ///
50    /// To get all properties, you may use [`Self::property_map`].
51    ///
52    /// To set a property, use [`Self::set_property`].
53    fn get_property(&self, name: &str) -> Option<&'static str>;
54    /// Update a property on this block, with the name and value being strings.
55    ///
56    /// Returns `Ok(())`, if the property name and value are valid, otherwise it
57    /// returns `Err(InvalidPropertyError)`.
58    ///
59    /// To get a property, use [`Self::get_property`].
60    fn set_property(&mut self, name: &str, new_value: &str) -> Result<(), InvalidPropertyError>;
61}
62
63#[derive(Debug)]
64pub struct InvalidPropertyError;
65
66impl dyn BlockTrait {
67    pub fn downcast_ref<T: BlockTrait>(&self) -> Option<&T> {
68        (self as &dyn Any).downcast_ref::<T>()
69    }
70}
71
72pub trait Property: FromStr {
73    type Value;
74
75    fn try_from_block_state(state: BlockState) -> Option<Self::Value>;
76
77    /// Convert the value of the property to a string, like "x" or "true".
78    fn to_static_str(&self) -> &'static str;
79}
80
81#[cfg(test)]
82mod tests {
83    use crate::BlockTrait;
84
85    #[test]
86    pub fn roundtrip_block_state() {
87        let block = crate::blocks::OakTrapdoor {
88            facing: crate::properties::FacingCardinal::East,
89            half: crate::properties::TopBottom::Bottom,
90            open: true,
91            powered: false,
92            waterlogged: false,
93        };
94        let block_state = block.as_block_state();
95        let block_from_state = Box::<dyn BlockTrait>::from(block_state);
96        let block_from_state = *block_from_state
97            .downcast_ref::<crate::blocks::OakTrapdoor>()
98            .unwrap();
99        assert_eq!(block, block_from_state);
100    }
101
102    #[test]
103    pub fn test_property_map() {
104        let block = crate::blocks::OakTrapdoor {
105            facing: crate::properties::FacingCardinal::East,
106            half: crate::properties::TopBottom::Bottom,
107            open: true,
108            powered: false,
109            waterlogged: false,
110        };
111
112        let property_map = block.property_map();
113
114        assert_eq!(property_map.len(), 5);
115        assert_eq!(property_map.get("facing"), Some(&"east"));
116        assert_eq!(property_map.get("half"), Some(&"bottom"));
117        assert_eq!(property_map.get("open"), Some(&"true"));
118        assert_eq!(property_map.get("powered"), Some(&"false"));
119        assert_eq!(property_map.get("waterlogged"), Some(&"false"));
120    }
121
122    #[test]
123    pub fn test_integer_properties() {
124        // Test with oak sapling that has an integer-like stage property
125        let sapling_stage_0 = crate::blocks::OakSapling {
126            stage: crate::properties::Stage::_0,
127        };
128
129        let sapling_stage_1 = crate::blocks::OakSapling {
130            stage: crate::properties::Stage::_1,
131        };
132
133        // Test stage 0
134        let properties_0 = sapling_stage_0.property_map();
135        assert_eq!(properties_0.len(), 1);
136        assert_eq!(properties_0.get("stage"), Some(&"0"));
137        assert_eq!(sapling_stage_0.get_property("stage"), Some("0"));
138
139        // Test stage 1
140        let properties_1 = sapling_stage_1.property_map();
141        assert_eq!(properties_1.len(), 1);
142        assert_eq!(properties_1.get("stage"), Some(&"1"));
143        assert_eq!(sapling_stage_1.get_property("stage"), Some("1"));
144
145        // Test non-existent property
146        assert_eq!(sapling_stage_0.get_property("nonexistent"), None);
147    }
148}