encase/core/
traits.rs

1use std::num::NonZeroU64;
2
3use super::{AlignmentValue, BufferMut, BufferRef, Reader, SizeValue, Writer};
4
5const UNIFORM_MIN_ALIGNMENT: AlignmentValue = AlignmentValue::new(16);
6
7pub struct Metadata<E> {
8    pub alignment: AlignmentValue,
9    pub has_uniform_min_alignment: bool,
10    pub min_size: SizeValue,
11    pub is_pod: bool,
12    pub extra: E,
13}
14
15impl Metadata<()> {
16    pub const fn from_alignment_and_size(alignment: u64, size: u64) -> Self {
17        Self {
18            alignment: AlignmentValue::new(alignment),
19            has_uniform_min_alignment: false,
20            min_size: SizeValue::new(size),
21            is_pod: false,
22            extra: (),
23        }
24    }
25}
26
27// using forget() avoids "destructors cannot be evaluated at compile-time" error
28// track #![feature(const_precise_live_drops)] (https://github.com/rust-lang/rust/issues/73255)
29
30impl<E> Metadata<E> {
31    #[inline]
32    pub const fn alignment(self) -> AlignmentValue {
33        let value = self.alignment;
34        core::mem::forget(self);
35        value
36    }
37
38    #[inline]
39    pub const fn uniform_min_alignment(self) -> Option<AlignmentValue> {
40        let value = self.has_uniform_min_alignment;
41        core::mem::forget(self);
42        match value {
43            true => Some(UNIFORM_MIN_ALIGNMENT),
44            false => None,
45        }
46    }
47
48    #[inline]
49    pub const fn min_size(self) -> SizeValue {
50        let value = self.min_size;
51        core::mem::forget(self);
52        value
53    }
54
55    #[inline]
56    pub const fn is_pod(self) -> bool {
57        let value = self.is_pod;
58        core::mem::forget(self);
59        value
60    }
61
62    #[inline]
63    pub const fn pod(mut self) -> Self {
64        self.is_pod = true;
65        self
66    }
67
68    #[inline]
69    pub const fn no_pod(mut self) -> Self {
70        self.is_pod = false;
71        self
72    }
73}
74
75/// Base trait for all [WGSL host-shareable types](https://gpuweb.github.io/gpuweb/wgsl/#host-shareable-types)
76pub trait ShaderType {
77    #[doc(hidden)]
78    type ExtraMetadata;
79    #[doc(hidden)]
80    const METADATA: Metadata<Self::ExtraMetadata>;
81
82    /// Represents the minimum size of `Self` (equivalent to [GPUBufferBindingLayout.minBindingSize](https://gpuweb.github.io/gpuweb/#dom-gpubufferbindinglayout-minbindingsize))
83    ///
84    /// For [WGSL fixed-footprint types](https://gpuweb.github.io/gpuweb/wgsl/#fixed-footprint-types)
85    /// it represents [WGSL Size](https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size)
86    /// (equivalent to [`ShaderSize::SHADER_SIZE`])
87    ///
88    /// For
89    /// [WGSL runtime-sized arrays](https://gpuweb.github.io/gpuweb/wgsl/#runtime-sized) and
90    /// [WGSL structs containing runtime-sized arrays](https://gpuweb.github.io/gpuweb/wgsl/#struct-types)
91    /// (non fixed-footprint types)
92    /// this will be calculated by assuming the array has one element
93    #[inline]
94    fn min_size() -> NonZeroU64 {
95        Self::METADATA.min_size().0
96    }
97
98    /// Returns the size of `Self` at runtime
99    ///
100    /// For [WGSL fixed-footprint types](https://gpuweb.github.io/gpuweb/wgsl/#fixed-footprint-types)
101    /// it's equivalent to [`Self::min_size`] and [`ShaderSize::SHADER_SIZE`]
102    #[inline]
103    fn size(&self) -> NonZeroU64 {
104        Self::METADATA.min_size().0
105    }
106
107    #[doc(hidden)]
108    const UNIFORM_COMPAT_ASSERT: fn() = || {};
109
110    /// Asserts that `Self` meets the requirements of the
111    /// [uniform address space restrictions on stored values](https://gpuweb.github.io/gpuweb/wgsl/#address-spaces-uniform) and the
112    /// [uniform address space layout constraints](https://gpuweb.github.io/gpuweb/wgsl/#address-space-layout-constraints)
113    ///
114    /// # Examples
115    ///
116    /// ## Array
117    ///
118    /// Will panic since runtime-sized arrays are not compatible with the
119    /// uniform address space restrictions on stored values
120    ///
121    /// ```should_panic
122    /// # use crate::encase::ShaderType;
123    /// <Vec<test_impl::Vec4f>>::assert_uniform_compat();
124    /// ```
125    ///
126    /// Will panic since the stride is 4 bytes
127    ///
128    /// ```should_panic
129    /// # use crate::encase::ShaderType;
130    /// <[f32; 2]>::assert_uniform_compat();
131    /// ```
132    ///
133    /// Will not panic since the stride is 16 bytes
134    ///
135    /// ```
136    /// # use crate::encase::ShaderType;
137    /// <[test_impl::Vec4f; 2]>::assert_uniform_compat();
138    /// ```
139    ///
140    /// ## Struct
141    ///
142    /// Will panic since runtime-sized arrays are not compatible with the
143    /// uniform address space restrictions on stored values
144    ///
145    /// ```should_panic
146    /// # use crate::encase::ShaderType;
147    /// #[derive(ShaderType)]
148    /// struct Invalid {
149    ///     #[shader(size(runtime))]
150    ///     vec: Vec<test_impl::Vec4f>
151    /// }
152    /// Invalid::assert_uniform_compat();
153    /// ```
154    ///
155    /// Will panic since the inner struct's size must be a multiple of 16
156    ///
157    /// ```should_panic
158    /// # use crate::encase::ShaderType;
159    /// #[derive(ShaderType)]
160    /// struct S {
161    ///     x: f32,
162    /// }
163    ///
164    /// #[derive(ShaderType)]
165    /// struct Invalid {
166    ///     a: f32,
167    ///     b: S, // offset between fields 'a' and 'b' must be at least 16 (currently: 4)
168    /// }
169    /// Invalid::assert_uniform_compat();
170    /// ```
171    ///
172    /// Will not panic (fixed via #[shader(align)] attribute)
173    ///
174    /// ```
175    /// # use crate::encase::ShaderType;
176    /// # #[derive(ShaderType)]
177    /// # struct S {
178    /// #     x: f32,
179    /// # }
180    /// #[derive(ShaderType)]
181    /// struct Valid {
182    ///     a: f32,
183    ///     #[shader(align(16))]
184    ///     b: S,
185    /// }
186    /// Valid::assert_uniform_compat();
187    /// ```
188    ///
189    /// Will not panic (fixed via size attribute)
190    ///
191    /// ```
192    /// # use crate::encase::ShaderType;
193    /// # #[derive(ShaderType)]
194    /// # struct S {
195    /// #     x: f32,
196    /// # }
197    /// #[derive(ShaderType)]
198    /// struct Valid {
199    ///     #[shader(size(16))]
200    ///     a: f32,
201    ///     b: S,
202    /// }
203    /// Valid::assert_uniform_compat();
204    /// ```
205    #[inline]
206    fn assert_uniform_compat() {
207        Self::UNIFORM_COMPAT_ASSERT();
208    }
209
210    // fn assert_can_write_into()
211    // where
212    //     Self: WriteInto,
213    // {
214    // }
215
216    // fn assert_can_read_from()
217    // where
218    //     Self: ReadFrom,
219    // {
220    // }
221
222    // fn assert_can_create_from()
223    // where
224    //     Self: CreateFrom,
225    // {
226    // }
227}
228
229/// Trait implemented for all [WGSL fixed-footprint types](https://gpuweb.github.io/gpuweb/wgsl/#fixed-footprint-types)
230pub trait ShaderSize: ShaderType {
231    /// Represents [WGSL Size](https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size) (equivalent to [`ShaderType::min_size`])
232    const SHADER_SIZE: NonZeroU64 = Self::METADATA.min_size().0;
233}
234
235/// Trait implemented for
236/// [WGSL runtime-sized arrays](https://gpuweb.github.io/gpuweb/wgsl/#runtime-sized) and
237/// [WGSL structs containing runtime-sized arrays](https://gpuweb.github.io/gpuweb/wgsl/#struct-types)
238/// (non fixed-footprint types)
239pub trait CalculateSizeFor {
240    /// Returns the size of `Self` assuming the (contained) runtime-sized array has `nr_of_el` elements
241    fn calculate_size_for(nr_of_el: u64) -> NonZeroU64;
242}
243
244#[allow(clippy::len_without_is_empty)]
245pub trait RuntimeSizedArray {
246    fn len(&self) -> usize;
247}
248
249pub trait WriteInto {
250    fn write_into<B>(&self, writer: &mut Writer<B>)
251    where
252        B: BufferMut;
253}
254
255pub trait ReadFrom {
256    fn read_from<B>(&mut self, reader: &mut Reader<B>)
257    where
258        B: BufferRef;
259}
260
261pub trait CreateFrom: Sized {
262    fn create_from<B>(reader: &mut Reader<B>) -> Self
263    where
264        B: BufferRef;
265}