veloren_common/terrain/sprite/
magic.rs1#[macro_export]
2macro_rules! sprites {
3 (
4 $($category_name:ident = $category_disc:literal $(has $($attr:ident),* $(,)?)? {
5 $($sprite_name:ident = $sprite_id:literal),* $(,)?
6 }),* $(,)?
7 ) => {
8 make_case_elim!(
9 category,
10 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Serialize, Deserialize, EnumIter, FromPrimitive)]
11 #[repr(u32)]
12 pub enum Category {
13 $($category_name = $category_disc,)*
14 }
15 );
16
17 impl Category {
18 #[inline] pub const fn all() -> &'static [Self] {
19 &[$(Self::$category_name,)*]
20 }
21
22 #[cfg(test)]
23 #[inline] const fn all_sprites(&self) -> &'static [SpriteKind] {
24 match self {
25 $(Self::$category_name => &[$(SpriteKind::$sprite_name,)*],)*
26 }
27 }
28
29 #[inline] pub const fn sprite_id_mask(&self) -> u32 {
31 match self {
32 $(Self::$category_name => ((0u32 $(| $sprite_id)*) + 1).next_power_of_two() - 1,)*
33 }
34 }
35
36 #[inline] pub const fn sprite_id_size(&self) -> u32 { self.sprite_id_mask().count_ones() }
38
39 #[inline(always)] pub const fn sprite_kind_mask(&self) -> u32 { 0x00FF0000 | self.sprite_id_mask() }
41
42 #[expect(non_upper_case_globals)]
45 #[inline] pub(super) const fn from_block(block: Block) -> Option<Self> {
46 $(const $category_name: u8 = Category::$category_name as u8;)*
47 match block.sprite_category_byte() {
48 $($category_name => Some(Self::$category_name),)*
49 _ => None,
50 }
51 }
52
53 #[inline] pub const fn attr_offsets(&self) -> &[Option<u8>; Attributes::all().len()] {
59 match self {
60 $(Self::$category_name => {
61 #[allow(unused_mut, unused_variables, unused_assignments)]
62 const fn gen_attr_offsets() -> [Option<u8>; Attributes::all().len()] {
63 let mut lut = [None; Attributes::all().len()];
64 let mut offset = Category::$category_name.sprite_id_size();
66 $($({
67 if offset + $attr::BITS as u32 > 16 {
69 panic!("Sprite category has an attribute set that will not fit in the block data");
70 } else if lut[$attr::INDEX].is_some() {
71 panic!("Sprite category cannot have more than one instance of an attribute");
72 } else if offset > (!0u8) as u32 {
73 panic!("Uhhh");
74 }
75 lut[$attr::INDEX] = Some(offset as u8);
76 offset += $attr::BITS as u32;
77 })*)*
78 lut
79 }
80 const ATTR_OFFSETS: [Option<u8>; Attributes::all().len()] = gen_attr_offsets();
81 &ATTR_OFFSETS
82 },)*
83 }
84 }
85
86 #[inline] pub fn has_attr<A: Attribute>(&self) -> bool {
88 self.attr_offsets()[A::INDEX].is_some()
89 }
90
91 #[inline] pub(super) fn read_attr<A: Attribute>(&self, block: Block) -> Result<A, AttributeError<A::Error>> {
96 let offset = match self.attr_offsets()[A::INDEX] {
97 Some(offset) => offset,
98 None => return Err(AttributeError::NotPresent),
99 };
100 let bits = (block.to_be_u32() >> offset as u32) & ((1 << A::BITS as u32) - 1);
101 A::from_bits(bits as u16).map_err(AttributeError::Attribute)
102 }
103
104 #[inline] pub(super) fn write_attr<A: Attribute>(&self, block: &mut Block, attr: A) -> Result<(), AttributeError<core::convert::Infallible>> {
109 let offset = match self.attr_offsets()[A::INDEX] {
110 Some(offset) => offset,
111 None => return Err(AttributeError::NotPresent),
112 };
113 let bits = attr.into_bits() as u32;
114 #[cfg(debug_assertions)]
115 assert!(bits < (1 << A::BITS as u32), "The bit representation of the attribute {} must fit within {} bits, but the representation was {:0b}", core::any::type_name::<A>(), A::BITS, bits);
116 let data = ((block.to_be_u32() & (!(((1 << A::BITS as u32) - 1) << offset as u32))) | (bits << offset as u32)).to_be_bytes();
117 *block = block.with_data([data[1], data[2], data[3]]);
118 Ok(())
119 }
120 }
121
122 #[inline] const fn gen_discriminant(category: Category, id: u16) -> u32 {
123 (category as u32) << 16 | id as u32
124 }
125
126 make_case_elim!(
127 sprite_kind,
128 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Serialize, Deserialize, EnumIter, FromPrimitive)]
129 #[repr(u32)]
130 pub enum SpriteKind {
131 $($($sprite_name = $crate::terrain::sprite::gen_discriminant($crate::terrain::sprite::Category::$category_name, $sprite_id),)*)*
132 }
133 );
134
135 impl SpriteKind {
136 #[inline] pub const fn all() -> &'static [Self] {
137 &[$($(Self::$sprite_name,)*)*]
138 }
139
140 #[inline] pub const fn category(&self) -> Category {
141 match self {
142 $($(Self::$sprite_name => Category::$category_name,)*)*
143 }
144 }
145
146 #[expect(non_upper_case_globals)]
149 #[inline] pub(super) const fn from_block(block: Block) -> Option<Self> {
150 match block.sprite_category() {
151 None => None,
152 $(Some(category @ Category::$category_name) => {
153 $(const $sprite_name: u32 = SpriteKind::$sprite_name as u32;)*
154 match block.to_be_u32() & category.sprite_kind_mask() {
155 $($sprite_name => Some(Self::$sprite_name),)*
156 _ => None,
157 }
158 },)*
159 }
160 }
161
162 #[inline] pub(super) fn to_initial_bytes(self) -> [u8; 3] {
163 let sprite_bytes = (self as u32).to_be_bytes();
164 let block = Block::from_raw(super::BlockKind::Air, [sprite_bytes[1], sprite_bytes[2], sprite_bytes[3]]);
165 match self.category() {
166 $(Category::$category_name => block$($(.with_attr($attr::default()).unwrap())*)?,)*
167 }
168 .data()
169 }
170 }
171 };
172}
173
174#[derive(Debug)]
175pub enum AttributeError<E> {
176 NotPresent,
178 Attribute(E),
180}
181
182pub trait Attribute: Default + Sized {
183 const INDEX: usize;
186 const BITS: u8;
188 type Error: core::fmt::Debug;
190 fn from_bits(bits: u16) -> Result<Self, Self::Error>;
191 fn into_bits(self) -> u16;
192}
193
194#[macro_export]
195macro_rules! attributes {
196 ($(
197 $name:ident { bits: $bits:literal, err: $err:path, from: $from_bits:expr, into: $into_bits:expr $(,)? }
198 ),* $(,)?) => {
199 #[derive(Copy, Clone, Debug)]
200 #[repr(u16)]
201 pub enum Attributes {
202 $($name,)*
203 }
204
205 impl Attributes {
206 #[inline] pub const fn all() -> &'static [Self] {
207 &[$(Self::$name,)*]
208 }
209 }
210
211 $(
212 impl Attribute for $name {
213 const INDEX: usize = Attributes::$name as usize;
214 const BITS: u8 = $bits;
215 type Error = $err;
216 #[inline(always)] fn from_bits(bits: u16) -> Result<Self, Self::Error> { $from_bits(bits) }
217 #[inline(always)] fn into_bits(self) -> u16 { $into_bits(self) }
218 }
219 )*
220 };
221}