feat: Starting a proper attribtues description for voxel attributes
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "vxls-attributes-derive"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
proc-macro2.workspace = true
|
||||
quote.workspace = true
|
||||
syn.workspace = true
|
||||
@@ -0,0 +1,313 @@
|
||||
//! Derive macro for the `vxls_production::Attributes` trait.
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! ```ignore
|
||||
//! use bytemuck::{Pod, Zeroable};
|
||||
//! use vxls_production::Attributes;
|
||||
//!
|
||||
//! #[derive(Clone, Copy, PartialEq, Default, Pod, Zeroable, Attributes)]
|
||||
//! #[repr(C)]
|
||||
//! pub struct VoxelAttributes
|
||||
//! {
|
||||
//! #[attribute(label = "color", semantic = "color")]
|
||||
//! pub color: u32,
|
||||
//!
|
||||
//! #[attribute(label = "normal", semantic = "normal")]
|
||||
//! pub normal: [f32; 3],
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! Each non-skipped field becomes one cache attribute, in declaration order.
|
||||
//! The derive also implements `vxls_production::Attribute` for the struct by
|
||||
//! averaging every field independently.
|
||||
//!
|
||||
//! Field options:
|
||||
//!
|
||||
//! - `#[attribute(label = "...")]`: name of the attribute. Defaults to the
|
||||
//! field name.
|
||||
//! - `#[attribute(semantic = "...")]`: optional shader-facing role of the
|
||||
//! attribute, stored in the layout for diagnostics.
|
||||
//! - `#[attribute(skip)]`: the field stays part of the struct but is not an
|
||||
//! attribute. It is reset to its default when averaging.
|
||||
//!
|
||||
//! The derive requires the struct to be `#[repr(C)]` or `#[repr(transparent)]`
|
||||
//! and to not be generic. It emits compile-time checks that every attribute
|
||||
//! field is a whole number of `u32` words and that the struct has no padding.
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::quote;
|
||||
use syn::parse_macro_input;
|
||||
use syn::Data;
|
||||
use syn::DeriveInput;
|
||||
use syn::Error;
|
||||
use syn::Fields;
|
||||
use syn::LitStr;
|
||||
use syn::Result;
|
||||
|
||||
#[proc_macro_derive(Attributes, attributes(attribute))]
|
||||
pub fn derive_attributes(input: TokenStream) -> TokenStream
|
||||
{
|
||||
let input = parse_macro_input!(input as DeriveInput);
|
||||
|
||||
expand(input)
|
||||
.unwrap_or_else(|error| error.to_compile_error())
|
||||
.into()
|
||||
}
|
||||
|
||||
fn expand(input: DeriveInput) -> Result<TokenStream2>
|
||||
{
|
||||
let ident = &input.ident;
|
||||
|
||||
if !input.generics.params.is_empty()
|
||||
{
|
||||
return Err(Error::new_spanned(
|
||||
&input.generics,
|
||||
"`Attributes` cannot be derived for generic structs",
|
||||
));
|
||||
}
|
||||
|
||||
check_repr(&input)?;
|
||||
|
||||
let data = match &input.data
|
||||
{
|
||||
Data::Struct(data) => data,
|
||||
Data::Enum(_) => {
|
||||
return Err(Error::new_spanned(
|
||||
&input.ident,
|
||||
"`Attributes` can only be derived for structs",
|
||||
));
|
||||
}
|
||||
Data::Union(_) => {
|
||||
return Err(Error::new_spanned(
|
||||
&input.ident,
|
||||
"`Attributes` can only be derived for structs",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let fields = match &data.fields
|
||||
{
|
||||
Fields::Named(fields) => &fields.named,
|
||||
_ => {
|
||||
return Err(Error::new_spanned(
|
||||
&data.fields,
|
||||
"`Attributes` requires named fields",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let mut descriptors = Vec::new();
|
||||
let mut getters = Vec::new();
|
||||
let mut getters_mut = Vec::new();
|
||||
let mut averages = Vec::new();
|
||||
let mut skipped = Vec::new();
|
||||
let mut field_types = Vec::new();
|
||||
let mut index = 0usize;
|
||||
|
||||
for field in fields
|
||||
{
|
||||
let name = field
|
||||
.ident
|
||||
.as_ref()
|
||||
.expect("named fields always have an identifier");
|
||||
let ty = &field.ty;
|
||||
|
||||
field_types.push(quote! { #ty });
|
||||
|
||||
let mut options = FieldOptions::default();
|
||||
for attribute in &field.attrs
|
||||
{
|
||||
if !attribute.path().is_ident("attribute")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
attribute.parse_nested_meta(|meta| {
|
||||
if meta.path.is_ident("skip")
|
||||
{
|
||||
options.skip = true;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if meta.path.is_ident("label")
|
||||
{
|
||||
options.label = Some(meta.value()?.parse::<LitStr>()?);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if meta.path.is_ident("semantic")
|
||||
{
|
||||
options.semantic = Some(meta.value()?.parse::<LitStr>()?);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Err(meta.error(
|
||||
"unknown attribute option, expected `skip`, `label = \"...\"` or `semantic = \"...\"`",
|
||||
))
|
||||
})?;
|
||||
}
|
||||
|
||||
if options.skip
|
||||
{
|
||||
skipped.push(quote! {
|
||||
#name: ::core::default::Default::default()
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
let label = options
|
||||
.label
|
||||
.unwrap_or_else(|| LitStr::new(&name.to_string(), name.span()));
|
||||
|
||||
let semantic = match options.semantic
|
||||
{
|
||||
Some(semantic) => quote! { ::core::option::Option::Some(#semantic) },
|
||||
None => quote! { ::core::option::Option::None },
|
||||
};
|
||||
|
||||
descriptors.push(quote! {
|
||||
::vxls_production::AttributeDescriptor {
|
||||
label: #label,
|
||||
word_count: (::core::mem::size_of::<#ty>() / 4) as u32,
|
||||
semantic: #semantic,
|
||||
}
|
||||
});
|
||||
|
||||
getters.push(quote! {
|
||||
#index => ::vxls_production::bytemuck::bytes_of(&self.#name),
|
||||
});
|
||||
|
||||
getters_mut.push(quote! {
|
||||
#index => ::vxls_production::bytemuck::bytes_of_mut(&mut self.#name),
|
||||
});
|
||||
|
||||
averages.push(quote! {
|
||||
#name: <#ty as ::vxls_production::Attribute>::average(
|
||||
&items
|
||||
.iter()
|
||||
.map(|item| item.#name)
|
||||
.collect::<::std::vec::Vec<_>>()
|
||||
),
|
||||
});
|
||||
|
||||
index += 1;
|
||||
}
|
||||
|
||||
let field_size_sum = quote! {
|
||||
0usize #( + ::core::mem::size_of::<#field_types>() )*
|
||||
};
|
||||
|
||||
Ok(quote! {
|
||||
#[automatically_derived]
|
||||
impl ::vxls_production::Attributes for #ident
|
||||
{
|
||||
const LAYOUT: ::vxls_production::AttributesLayout =
|
||||
::vxls_production::AttributesLayout {
|
||||
attributes: &[ #(#descriptors),* ],
|
||||
};
|
||||
|
||||
#[inline]
|
||||
fn get_attr(&self, index: usize) -> &[u8]
|
||||
{
|
||||
match index
|
||||
{
|
||||
#(#getters)*
|
||||
_ => ::core::panic!(
|
||||
"attribute index out of bounds for `{}` ({} attributes)",
|
||||
::core::stringify!(#ident),
|
||||
#index,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn get_attr_mut(&mut self, index: usize) -> &mut [u8]
|
||||
{
|
||||
match index
|
||||
{
|
||||
#(#getters_mut)*
|
||||
_ => ::core::panic!(
|
||||
"attribute index out of bounds for `{}` ({} attributes)",
|
||||
::core::stringify!(#ident),
|
||||
#index,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[automatically_derived]
|
||||
impl ::vxls_production::Attribute for #ident
|
||||
{
|
||||
fn average(items: &[Self]) -> Self
|
||||
{
|
||||
if items.is_empty()
|
||||
{
|
||||
return <Self as ::core::default::Default>::default();
|
||||
}
|
||||
|
||||
Self {
|
||||
#(#averages)*
|
||||
#(#skipped,)*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const _: () = {
|
||||
#(
|
||||
::core::assert!(
|
||||
::core::mem::size_of::<#field_types>() % 4 == 0,
|
||||
"attribute field size must be a multiple of 4 bytes",
|
||||
);
|
||||
)*
|
||||
|
||||
::core::assert!(
|
||||
::core::mem::size_of::<#ident>() == #field_size_sum,
|
||||
"`Attributes` structs must not contain padding",
|
||||
);
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
/// Collects the `#[attribute(...)]` options of a single field.
|
||||
#[derive(Default)]
|
||||
struct FieldOptions
|
||||
{
|
||||
skip: bool,
|
||||
label: Option<LitStr>,
|
||||
semantic: Option<LitStr>,
|
||||
}
|
||||
|
||||
fn check_repr(input: &DeriveInput) -> Result<()>
|
||||
{
|
||||
let mut found = false;
|
||||
|
||||
for attribute in &input.attrs
|
||||
{
|
||||
if !attribute.path().is_ident("repr")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
attribute.parse_nested_meta(|meta| {
|
||||
if meta.path.is_ident("C") || meta.path.is_ident("transparent")
|
||||
{
|
||||
found = true;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
|
||||
if found
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
else
|
||||
{
|
||||
Err(Error::new_spanned(
|
||||
&input.ident,
|
||||
"`Attributes` requires the struct to be `#[repr(C)]` or `#[repr(transparent)]`",
|
||||
))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user