├── .gitignore ├── src ├── imp.rs ├── std430.rs ├── std140.rs ├── bool.rs ├── imp │ ├── imp_glam.rs │ ├── imp_mint.rs │ ├── imp_cgmath.rs │ └── imp_nalgebra.rs ├── internal.rs ├── std140 │ ├── dynamic_uniform.rs │ ├── sizer.rs │ ├── writer.rs │ ├── primitives.rs │ └── traits.rs ├── std430 │ ├── sizer.rs │ ├── writer.rs │ ├── primitives.rs │ └── traits.rs ├── glsl.rs ├── util.rs └── lib.rs ├── tests ├── snapshots │ └── test__generate_struct_glsl.snap └── test.rs ├── crevice-tests ├── Cargo.toml └── src │ ├── util.rs │ ├── lib.rs │ └── gpu.rs ├── crevice-derive ├── Cargo.toml └── src │ ├── lib.rs │ ├── glsl.rs │ └── layout.rs ├── LICENSE-MIT ├── README.tpl ├── Cargo.toml ├── .github └── workflows │ └── ci.yml ├── README.md ├── CHANGELOG.md └── LICENSE-APACHE /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | 4 | # Uncommitted snapshot files generated by Insta 5 | **/*.snap.new -------------------------------------------------------------------------------- /src/imp.rs: -------------------------------------------------------------------------------- 1 | mod imp_mint; 2 | 3 | #[cfg(feature = "cgmath")] 4 | mod imp_cgmath; 5 | 6 | #[cfg(feature = "glam")] 7 | mod imp_glam; 8 | 9 | #[cfg(feature = "nalgebra")] 10 | mod imp_nalgebra; 11 | -------------------------------------------------------------------------------- /tests/snapshots/test__generate_struct_glsl.snap: -------------------------------------------------------------------------------- 1 | --- 2 | source: tests/test.rs 3 | expression: "TestGlsl::glsl_definition()" 4 | 5 | --- 6 | struct TestGlsl { 7 | vec3 foo; 8 | mat2 bar; 9 | }; 10 | -------------------------------------------------------------------------------- /src/std430.rs: -------------------------------------------------------------------------------- 1 | //! Defines traits and types for working with data adhering to GLSL's `std430` 2 | //! layout specification. 3 | 4 | mod primitives; 5 | mod sizer; 6 | mod traits; 7 | #[cfg(feature = "std")] 8 | mod writer; 9 | 10 | pub use crate::bool::Bool; 11 | 12 | pub use self::primitives::*; 13 | pub use self::sizer::*; 14 | pub use self::traits::*; 15 | #[cfg(feature = "std")] 16 | pub use self::writer::*; 17 | 18 | pub use crevice_derive::AsStd430; 19 | -------------------------------------------------------------------------------- /src/std140.rs: -------------------------------------------------------------------------------- 1 | //! Defines traits and types for working with data adhering to GLSL's `std140` 2 | //! layout specification. 3 | 4 | mod dynamic_uniform; 5 | mod primitives; 6 | mod sizer; 7 | mod traits; 8 | #[cfg(feature = "std")] 9 | mod writer; 10 | 11 | pub use crate::bool::Bool; 12 | 13 | pub use self::dynamic_uniform::*; 14 | pub use self::primitives::*; 15 | pub use self::sizer::*; 16 | pub use self::traits::*; 17 | #[cfg(feature = "std")] 18 | pub use self::writer::*; 19 | 20 | pub use crevice_derive::AsStd140; 21 | -------------------------------------------------------------------------------- /crevice-tests/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "crevice-tests" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | [features] 7 | default = ["std"] 8 | std = ["crevice/std"] 9 | wgpu-validation = ["std", "wgpu", "naga", "futures"] 10 | 11 | [dependencies] 12 | crevice = { path = "..", default-features = false } 13 | crevice-derive = { path = "../crevice-derive", features = ["debug-methods"] } 14 | 15 | anyhow = "1.0.44" 16 | bytemuck = "1.7.2" 17 | memoffset = "0.9" 18 | mint = "0.5.5" 19 | 20 | futures = { version = "0.3.17", features = ["executor"], optional = true } 21 | naga = { version = "22", features = ["glsl-in", "wgsl-out"], optional = true } 22 | wgpu = { version = "22", optional = true } 23 | -------------------------------------------------------------------------------- /src/bool.rs: -------------------------------------------------------------------------------- 1 | use core::fmt::{Debug, Formatter}; 2 | 3 | use bytemuck::{Pod, Zeroable}; 4 | 5 | /// GLSL's `bool` type. 6 | /// 7 | /// Boolean values in GLSL are 32 bits, in contrast with Rust's 8 bit bools. 8 | #[derive(Clone, Copy, Eq, PartialEq)] 9 | #[repr(transparent)] 10 | pub struct Bool(u32); 11 | 12 | unsafe impl Zeroable for Bool {} 13 | unsafe impl Pod for Bool {} 14 | 15 | impl From for Bool { 16 | fn from(v: bool) -> Self { 17 | Self(v as u32) 18 | } 19 | } 20 | 21 | impl From for bool { 22 | fn from(v: Bool) -> Self { 23 | v.0 != 0 24 | } 25 | } 26 | 27 | impl Debug for Bool { 28 | fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { 29 | write!(f, "Bool({:?})", bool::from(*self)) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /crevice-derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "crevice-derive" 3 | description = "Derive crate for the 'crevice' crate" 4 | version = "0.18.0" 5 | edition = "2018" 6 | authors = ["Lucien Greathouse "] 7 | documentation = "https://docs.rs/crevice-derive" 8 | homepage = "https://github.com/LPGhatguy/crevice" 9 | repository = "https://github.com/LPGhatguy/crevice" 10 | license = "MIT OR Apache-2.0" 11 | 12 | [features] 13 | default = [] 14 | 15 | # Enable methods that let you introspect into the generated structs. 16 | debug-methods = [] 17 | 18 | [lib] 19 | proc-macro = true 20 | 21 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 22 | 23 | [dependencies] 24 | syn = "2" 25 | quote = "1.0.7" 26 | proc-macro2 = "1.0.21" 27 | -------------------------------------------------------------------------------- /src/imp/imp_glam.rs: -------------------------------------------------------------------------------- 1 | minty_impl! { 2 | mint::Vector2 => glam::Vec2, 3 | mint::Vector3 => glam::Vec3, 4 | mint::Vector4 => glam::Vec4, 5 | 6 | mint::Vector2 => glam::IVec2, 7 | mint::Vector3 => glam::IVec3, 8 | mint::Vector4 => glam::IVec4, 9 | 10 | mint::Vector2 => glam::UVec2, 11 | mint::Vector3 => glam::UVec3, 12 | mint::Vector4 => glam::UVec4, 13 | 14 | // mint::Vector2 => glam::BVec2, 15 | // mint::Vector3 => glam::BVec3, 16 | // mint::Vector4 => glam::BVec4, 17 | 18 | mint::Vector2 => glam::DVec2, 19 | mint::Vector3 => glam::DVec3, 20 | mint::Vector4 => glam::DVec4, 21 | 22 | mint::ColumnMatrix2 => glam::Mat2, 23 | mint::ColumnMatrix3 => glam::Mat3, 24 | mint::ColumnMatrix4 => glam::Mat4, 25 | 26 | mint::ColumnMatrix2 => glam::DMat2, 27 | mint::ColumnMatrix3 => glam::DMat3, 28 | mint::ColumnMatrix4 => glam::DMat4, 29 | } 30 | -------------------------------------------------------------------------------- /crevice-derive/src/lib.rs: -------------------------------------------------------------------------------- 1 | mod glsl; 2 | mod layout; 3 | 4 | use proc_macro::TokenStream as CompilerTokenStream; 5 | 6 | use syn::{parse_macro_input, DeriveInput}; 7 | 8 | #[proc_macro_derive(AsStd140)] 9 | pub fn derive_as_std140(input: CompilerTokenStream) -> CompilerTokenStream { 10 | let input = parse_macro_input!(input as DeriveInput); 11 | let expanded = layout::emit(input, "Std140", "std140", 16); 12 | 13 | CompilerTokenStream::from(expanded) 14 | } 15 | 16 | #[proc_macro_derive(AsStd430)] 17 | pub fn derive_as_std430(input: CompilerTokenStream) -> CompilerTokenStream { 18 | let input = parse_macro_input!(input as DeriveInput); 19 | let expanded = layout::emit(input, "Std430", "std430", 0); 20 | 21 | CompilerTokenStream::from(expanded) 22 | } 23 | 24 | #[proc_macro_derive(GlslStruct)] 25 | pub fn derive_glsl_struct(input: CompilerTokenStream) -> CompilerTokenStream { 26 | let input = parse_macro_input!(input as DeriveInput); 27 | let expanded = glsl::emit(input); 28 | 29 | CompilerTokenStream::from(expanded) 30 | } 31 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2020 Lucien Greathouse 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. -------------------------------------------------------------------------------- /src/internal.rs: -------------------------------------------------------------------------------- 1 | //! This module is internal to crevice but used by its derive macro. No 2 | //! guarantees are made about its contents. 3 | 4 | pub use bytemuck; 5 | 6 | /// Gives the number of bytes needed to make `offset` be aligned to `alignment`. 7 | pub const fn align_offset(offset: usize, alignment: usize) -> usize { 8 | if alignment == 0 || offset % alignment == 0 { 9 | 0 10 | } else { 11 | alignment - offset % alignment 12 | } 13 | } 14 | 15 | /// Max of two `usize`. Implemented because the `max` method from `Ord` cannot 16 | /// be used in const fns. 17 | pub const fn max(a: usize, b: usize) -> usize { 18 | if a > b { 19 | a 20 | } else { 21 | b 22 | } 23 | } 24 | 25 | /// Max of an array of `usize`. This function's implementation is funky because 26 | /// we have no for loops! 27 | pub const fn max_arr(input: [usize; N]) -> usize { 28 | let mut max = 0; 29 | let mut i = 0; 30 | 31 | while i < N { 32 | if input[i] > max { 33 | max = input[i]; 34 | } 35 | 36 | i += 1; 37 | } 38 | 39 | max 40 | } 41 | -------------------------------------------------------------------------------- /README.tpl: -------------------------------------------------------------------------------- 1 | # Crevice 2 | 3 | {{readme}} 4 | 5 | [std140::AsStd140]: https://docs.rs/crevice/latest/crevice/std140/trait.AsStd140.html 6 | [std140::AsStd140::as_std140]: https://docs.rs/crevice/latest/crevice/std140/trait.AsStd140.html#method.as_std140 7 | [std140::Std140::as_bytes]: https://docs.rs/crevice/latest/crevice/std140/trait.Std140.html#method.as_bytes 8 | [std140::Writer]: https://docs.rs/crevice/latest/crevice/std140/struct.Writer.html 9 | 10 | [`std::io::Write`]: https://doc.rust-lang.org/stable/std/io/trait.Write.html 11 | 12 | [`bytemuck::Pod`]: https://docs.rs/bytemuck/latest/bytemuck/trait.Pod.html 13 | [`bytemuck::Zeroable`]: https://docs.rs/bytemuck/latest/bytemuck/trait.Zeroable.html 14 | 15 | [glsl-layout]: https://docs.rs/glsl-layout/latest/glsl_layout/ 16 | 17 | ## License 18 | 19 | Licensed under either of 20 | 21 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 22 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 23 | 24 | at your option. 25 | 26 | ### Contribution 27 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. -------------------------------------------------------------------------------- /tests/test.rs: -------------------------------------------------------------------------------- 1 | use crevice::std140::AsStd140; 2 | 3 | #[test] 4 | fn there_and_back_again() { 5 | #[derive(AsStd140, Debug, PartialEq)] 6 | struct ThereAndBackAgain { 7 | view: mint::ColumnMatrix3, 8 | origin: mint::Vector3, 9 | } 10 | 11 | let x = ThereAndBackAgain { 12 | view: mint::ColumnMatrix3 { 13 | x: mint::Vector3 { 14 | x: 1.0, 15 | y: 0.0, 16 | z: 0.0, 17 | }, 18 | y: mint::Vector3 { 19 | x: 0.0, 20 | y: 1.0, 21 | z: 0.0, 22 | }, 23 | z: mint::Vector3 { 24 | x: 0.0, 25 | y: 0.0, 26 | z: 1.0, 27 | }, 28 | }, 29 | origin: mint::Vector3 { 30 | x: 0.0, 31 | y: 1.0, 32 | z: 2.0, 33 | }, 34 | }; 35 | let x_as = x.as_std140(); 36 | assert_eq!(::from_std140(x_as), x); 37 | } 38 | 39 | #[test] 40 | #[cfg(feature = "std")] 41 | fn generate_struct_glsl() { 42 | use crevice::glsl::GlslStruct; 43 | 44 | #[allow(dead_code)] 45 | #[derive(GlslStruct)] 46 | struct TestGlsl { 47 | foo: mint::Vector3, 48 | bar: mint::ColumnMatrix2, 49 | } 50 | 51 | insta::assert_display_snapshot!(TestGlsl::glsl_definition()); 52 | } 53 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "crevice" 3 | description = "Create GLSL-compatible versions of structs with explicitly-initialized padding" 4 | version = "0.18.0" 5 | rust-version = "1.74.0" 6 | edition = "2021" 7 | authors = ["Lucien Greathouse "] 8 | documentation = "https://docs.rs/crevice" 9 | homepage = "https://github.com/LPGhatguy/crevice" 10 | repository = "https://github.com/LPGhatguy/crevice" 11 | readme = "README.md" 12 | keywords = ["glsl", "std140", "std430"] 13 | license = "MIT OR Apache-2.0" 14 | resolver = "2" 15 | 16 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 17 | 18 | [features] 19 | default = ["std"] 20 | std = [] 21 | test-all-math-libraries = ["cgmath", "glam", "glam/std", "nalgebra"] 22 | 23 | [workspace] 24 | members = [".", "crevice-derive", "crevice-tests"] 25 | default-members = [".", "crevice-derive", "crevice-tests"] 26 | 27 | [dependencies] 28 | crevice-derive = { version = "0.18.0", path = "crevice-derive" } 29 | 30 | bytemuck = "1.12.3" 31 | mint = "0.5.9" 32 | 33 | cgmath = { version = "0.18.0", default-features = false, optional = true } 34 | glam = { version = "0.30", default-features = false, features = ["mint"], optional = true } 35 | nalgebra = { version = "0.33", default-features = false, features = ["mint"], optional = true } 36 | 37 | [dev-dependencies] 38 | insta = "1.21.0" 39 | 40 | [package.metadata."docs.rs"] 41 | all-features = true 42 | -------------------------------------------------------------------------------- /src/imp/imp_mint.rs: -------------------------------------------------------------------------------- 1 | easy_impl! { 2 | Vec2 mint::Vector2 { x, y }, 3 | Vec3 mint::Vector3 { x, y, z }, 4 | Vec4 mint::Vector4 { x, y, z, w }, 5 | 6 | Vec2 mint::Point2 { x, y }, 7 | Vec3 mint::Point3 { x, y, z }, 8 | 9 | IVec2 mint::Vector2 { x, y }, 10 | IVec3 mint::Vector3 { x, y, z }, 11 | IVec4 mint::Vector4 { x, y, z, w }, 12 | 13 | IVec2 mint::Point2 { x, y }, 14 | IVec3 mint::Point3 { x, y, z }, 15 | 16 | UVec2 mint::Vector2 { x, y }, 17 | UVec3 mint::Vector3 { x, y, z }, 18 | UVec4 mint::Vector4 { x, y, z, w }, 19 | 20 | UVec2 mint::Point2 { x, y }, 21 | UVec3 mint::Point3 { x, y, z }, 22 | 23 | BVec2 mint::Vector2 { x, y }, 24 | BVec3 mint::Vector3 { x, y, z }, 25 | BVec4 mint::Vector4 { x, y, z, w }, 26 | 27 | BVec2 mint::Point2 { x, y }, 28 | BVec3 mint::Point3 { x, y, z }, 29 | 30 | DVec2 mint::Vector2 { x, y }, 31 | DVec3 mint::Vector3 { x, y, z }, 32 | DVec4 mint::Vector4 { x, y, z, w }, 33 | 34 | DVec2 mint::Point2 { x, y }, 35 | DVec3 mint::Point3 { x, y, z }, 36 | 37 | Mat2 mint::ColumnMatrix2 { x, y }, 38 | Mat3 mint::ColumnMatrix3 { x, y, z }, 39 | Mat4 mint::ColumnMatrix4 { x, y, z, w }, 40 | 41 | DMat2 mint::ColumnMatrix2 { x, y }, 42 | DMat3 mint::ColumnMatrix3 { x, y, z }, 43 | DMat4 mint::ColumnMatrix4 { x, y, z, w }, 44 | } 45 | -------------------------------------------------------------------------------- /src/imp/imp_cgmath.rs: -------------------------------------------------------------------------------- 1 | easy_impl! { 2 | Vec2 cgmath::Vector2 { x, y }, 3 | Vec3 cgmath::Vector3 { x, y, z }, 4 | Vec4 cgmath::Vector4 { x, y, z, w }, 5 | 6 | Vec2 cgmath::Point2 { x, y }, 7 | Vec3 cgmath::Point3 { x, y, z }, 8 | 9 | IVec2 cgmath::Vector2 { x, y }, 10 | IVec3 cgmath::Vector3 { x, y, z }, 11 | IVec4 cgmath::Vector4 { x, y, z, w }, 12 | 13 | IVec2 cgmath::Point2 { x, y }, 14 | IVec3 cgmath::Point3 { x, y, z }, 15 | 16 | UVec2 cgmath::Vector2 { x, y }, 17 | UVec3 cgmath::Vector3 { x, y, z }, 18 | UVec4 cgmath::Vector4 { x, y, z, w }, 19 | 20 | UVec2 cgmath::Point2 { x, y }, 21 | UVec3 cgmath::Point3 { x, y, z }, 22 | 23 | BVec2 cgmath::Vector2 { x, y }, 24 | BVec3 cgmath::Vector3 { x, y, z }, 25 | BVec4 cgmath::Vector4 { x, y, z, w }, 26 | 27 | BVec2 cgmath::Point2 { x, y }, 28 | BVec3 cgmath::Point3 { x, y, z }, 29 | 30 | DVec2 cgmath::Vector2 { x, y }, 31 | DVec3 cgmath::Vector3 { x, y, z }, 32 | DVec4 cgmath::Vector4 { x, y, z, w }, 33 | 34 | DVec2 cgmath::Point2 { x, y }, 35 | DVec3 cgmath::Point3 { x, y, z }, 36 | 37 | Mat2 cgmath::Matrix2 { x, y }, 38 | Mat3 cgmath::Matrix3 { x, y, z }, 39 | Mat4 cgmath::Matrix4 { x, y, z, w }, 40 | 41 | DMat2 cgmath::Matrix2 { x, y }, 42 | DMat3 cgmath::Matrix3 { x, y, z }, 43 | DMat4 cgmath::Matrix4 { x, y, z, w }, 44 | } 45 | -------------------------------------------------------------------------------- /src/imp/imp_nalgebra.rs: -------------------------------------------------------------------------------- 1 | minty_impl! { 2 | mint::Vector2 => nalgebra::Vector2, 3 | mint::Vector3 => nalgebra::Vector3, 4 | mint::Vector4 => nalgebra::Vector4, 5 | 6 | mint::Point2 => nalgebra::Point2, 7 | mint::Point3 => nalgebra::Point3, 8 | 9 | mint::Vector2 => nalgebra::Vector2, 10 | mint::Vector3 => nalgebra::Vector3, 11 | mint::Vector4 => nalgebra::Vector4, 12 | 13 | mint::Point2 => nalgebra::Point2, 14 | mint::Point3 => nalgebra::Point3, 15 | 16 | mint::Vector2 => nalgebra::Vector2, 17 | mint::Vector3 => nalgebra::Vector3, 18 | mint::Vector4 => nalgebra::Vector4, 19 | 20 | mint::Point2 => nalgebra::Point2, 21 | mint::Point3 => nalgebra::Point3, 22 | 23 | mint::Vector2 => nalgebra::Vector2, 24 | mint::Vector3 => nalgebra::Vector3, 25 | mint::Vector4 => nalgebra::Vector4, 26 | 27 | mint::Point2 => nalgebra::Point2, 28 | mint::Point3 => nalgebra::Point3, 29 | 30 | mint::Vector2 => nalgebra::Vector2, 31 | mint::Vector3 => nalgebra::Vector3, 32 | mint::Vector4 => nalgebra::Vector4, 33 | 34 | mint::Point2 => nalgebra::Point2, 35 | mint::Point3 => nalgebra::Point3, 36 | 37 | mint::ColumnMatrix2 => nalgebra::Matrix2, 38 | mint::ColumnMatrix3 => nalgebra::Matrix3, 39 | mint::ColumnMatrix4 => nalgebra::Matrix4, 40 | 41 | mint::ColumnMatrix2 => nalgebra::Matrix2, 42 | mint::ColumnMatrix3 => nalgebra::Matrix3, 43 | mint::ColumnMatrix4 => nalgebra::Matrix4, 44 | } 45 | -------------------------------------------------------------------------------- /crevice-derive/src/glsl.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::{Literal, TokenStream}; 2 | use quote::quote; 3 | use syn::{parse_quote, Data, DeriveInput, Fields, Path}; 4 | 5 | pub fn emit(input: DeriveInput) -> TokenStream { 6 | let fields = match &input.data { 7 | Data::Struct(data) => match &data.fields { 8 | Fields::Named(fields) => fields, 9 | Fields::Unnamed(_) => panic!("Tuple structs are not supported"), 10 | Fields::Unit => panic!("Unit structs are not supported"), 11 | }, 12 | Data::Enum(_) | Data::Union(_) => panic!("Only structs are supported"), 13 | }; 14 | 15 | let base_trait_path: Path = parse_quote!(::crevice::glsl::Glsl); 16 | let struct_trait_path: Path = parse_quote!(::crevice::glsl::GlslStruct); 17 | 18 | let name = input.ident; 19 | let name_str = Literal::string(&name.to_string()); 20 | 21 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 22 | 23 | let glsl_fields = fields.named.iter().map(|field| { 24 | let field_ty = &field.ty; 25 | let field_name_str = Literal::string(&field.ident.as_ref().unwrap().to_string()); 26 | 27 | quote! { 28 | ::crevice::glsl::GlslField { 29 | ty: <#field_ty as ::crevice::glsl::Glsl>::NAME, 30 | name: #field_name_str, 31 | } 32 | } 33 | }); 34 | 35 | quote! { 36 | unsafe impl #impl_generics #base_trait_path for #name #ty_generics #where_clause { 37 | const NAME: &'static str = #name_str; 38 | } 39 | 40 | unsafe impl #impl_generics #struct_trait_path for #name #ty_generics #where_clause { 41 | const FIELDS: &'static [::crevice::glsl::GlslField] = &[ 42 | #( #glsl_fields, )* 43 | ]; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/std140/dynamic_uniform.rs: -------------------------------------------------------------------------------- 1 | use bytemuck::{Pod, Zeroable}; 2 | 3 | use crate::internal::max; 4 | use crate::std140::{AsStd140, Std140}; 5 | 6 | /// Wrapper type that aligns the inner type to at least 256 bytes. 7 | /// 8 | /// This type is useful for ensuring correct alignment when creating dynamic 9 | /// uniform buffers in APIs like WebGPU. 10 | pub struct DynamicUniform(pub T); 11 | 12 | impl AsStd140 for DynamicUniform { 13 | type Output = DynamicUniformStd140<::Output>; 14 | 15 | fn as_std140(&self) -> Self::Output { 16 | DynamicUniformStd140(self.0.as_std140()) 17 | } 18 | 19 | fn from_std140(value: Self::Output) -> Self { 20 | DynamicUniform(::from_std140(value.0)) 21 | } 22 | } 23 | 24 | /// std140 variant of [`DynamicUniform`]. 25 | #[derive(Clone, Copy)] 26 | #[repr(transparent)] 27 | pub struct DynamicUniformStd140(T); 28 | 29 | unsafe impl Std140 for DynamicUniformStd140 { 30 | const ALIGNMENT: usize = max(256, T::ALIGNMENT); 31 | } 32 | 33 | unsafe impl Zeroable for DynamicUniformStd140 {} 34 | unsafe impl Pod for DynamicUniformStd140 {} 35 | 36 | #[cfg(test)] 37 | mod test { 38 | use super::*; 39 | 40 | use crate::std140::AsStd140; 41 | 42 | #[test] 43 | fn size_is_unchanged() { 44 | assert_eq!( 45 | DynamicUniform::::std140_size_static(), 46 | f32::std140_size_static() 47 | ); 48 | } 49 | 50 | #[test] 51 | #[cfg(feature = "std")] 52 | fn alignment_applies() { 53 | use crate::std140; 54 | 55 | let mut output = Vec::new(); 56 | let mut writer = std140::Writer::new(&mut output); 57 | 58 | writer.write(&DynamicUniform(0.0f32)).unwrap(); 59 | assert_eq!(writer.len(), 4); 60 | 61 | writer.write(&DynamicUniform(1.0f32)).unwrap(); 62 | assert_eq!(writer.len(), 260); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | pull_request: 9 | branches: 10 | - main 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | strategy: 16 | fail-fast: false 17 | matrix: 18 | include: 19 | - label: Stable 20 | rust_version: stable 21 | - label: MSRV 22 | rust_version: 1.74 23 | - label: Stable (All Features) 24 | rust_version: stable 25 | flags: --features test-all-math-libraries 26 | - label: Stable (no_std) 27 | rust_version: stable 28 | flags: --no-default-features 29 | 30 | name: ${{ matrix.label }} 31 | 32 | steps: 33 | - uses: actions/checkout@v3 34 | 35 | - name: Install Rust 36 | uses: actions-rs/toolchain@v1 37 | with: 38 | toolchain: ${{ matrix.rust_version }} 39 | override: true 40 | profile: minimal 41 | 42 | - name: Build 43 | run: cargo build --verbose ${{ matrix.flags }} 44 | 45 | - name: Run tests 46 | run: cargo test --verbose ${{ matrix.flags }} 47 | 48 | lint: 49 | name: Rustfmt and Clippy 50 | runs-on: ubuntu-latest 51 | 52 | steps: 53 | - uses: actions/checkout@v3 54 | 55 | - name: Install Rust 56 | uses: actions-rs/toolchain@v1 57 | with: 58 | toolchain: stable 59 | override: true 60 | components: rustfmt, clippy 61 | 62 | - name: Rustfmt 63 | run: cargo fmt -- --check 64 | 65 | - name: Clippy 66 | run: cargo clippy --all-features 67 | 68 | wgpu-validation: 69 | runs-on: windows-latest 70 | 71 | steps: 72 | - uses: actions/checkout@v3 73 | 74 | - name: Install Rust 75 | uses: actions-rs/toolchain@v1 76 | with: 77 | toolchain: stable 78 | override: true 79 | profile: minimal 80 | 81 | - name: Run Validation Tests 82 | run: cargo test --package crevice-tests --features wgpu-validation --no-fail-fast --verbose 83 | -------------------------------------------------------------------------------- /src/std140/sizer.rs: -------------------------------------------------------------------------------- 1 | use core::mem::size_of; 2 | 3 | use crate::internal::align_offset; 4 | use crate::std140::{AsStd140, Std140}; 5 | 6 | /** 7 | Type that computes the buffer size needed by a series of `std140` types laid 8 | out. 9 | 10 | This type works well well when paired with `Writer`, precomputing a buffer's 11 | size to alleviate the need to dynamically re-allocate buffers. 12 | 13 | ## Example 14 | 15 | ```glsl 16 | struct Frob { 17 | vec3 size; 18 | float frobiness; 19 | } 20 | 21 | buffer FROBS { 22 | uint len; 23 | Frob[] frobs; 24 | } frobs; 25 | ``` 26 | 27 | ``` 28 | use crevice::std140::{self, AsStd140}; 29 | 30 | #[derive(AsStd140)] 31 | struct Frob { 32 | size: mint::Vector3, 33 | frobiness: f32, 34 | } 35 | 36 | // Many APIs require that buffers contain at least enough space for all 37 | // fixed-size bindiongs to a buffer as well as one element of any arrays, if 38 | // there are any. 39 | let mut sizer = std140::Sizer::new(); 40 | sizer.add::(); 41 | sizer.add::(); 42 | 43 | # fn create_buffer_with_size(size: usize) {} 44 | let buffer = create_buffer_with_size(sizer.len()); 45 | # assert_eq!(sizer.len(), 32); 46 | ``` 47 | */ 48 | pub struct Sizer { 49 | offset: usize, 50 | } 51 | 52 | impl Sizer { 53 | /// Create a new `Sizer`. 54 | pub fn new() -> Self { 55 | Self { offset: 0 } 56 | } 57 | 58 | /// Add a type's necessary padding and size to the `Sizer`. Returns the 59 | /// offset into the buffer where that type would be written. 60 | pub fn add(&mut self) -> usize 61 | where 62 | T: AsStd140, 63 | { 64 | let size = size_of::<::Output>(); 65 | let alignment = ::Output::ALIGNMENT; 66 | let padding = align_offset(self.offset, alignment); 67 | 68 | self.offset += padding; 69 | let write_here = self.offset; 70 | 71 | self.offset += size; 72 | 73 | write_here 74 | } 75 | 76 | /// Returns the number of bytes required to contain all the types added to 77 | /// the `Sizer`. 78 | pub fn len(&self) -> usize { 79 | self.offset 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/std430/sizer.rs: -------------------------------------------------------------------------------- 1 | use core::mem::size_of; 2 | 3 | use crate::internal::align_offset; 4 | use crate::std430::{AsStd430, Std430}; 5 | 6 | /** 7 | Type that computes the buffer size needed by a series of `std430` types laid 8 | out. 9 | 10 | This type works well well when paired with `Writer`, precomputing a buffer's 11 | size to alleviate the need to dynamically re-allocate buffers. 12 | 13 | ## Example 14 | 15 | ```glsl 16 | struct Frob { 17 | vec3 size; 18 | float frobiness; 19 | } 20 | 21 | buffer FROBS { 22 | uint len; 23 | Frob[] frobs; 24 | } frobs; 25 | ``` 26 | 27 | ``` 28 | use crevice::std430::{self, AsStd430}; 29 | 30 | #[derive(AsStd430)] 31 | struct Frob { 32 | size: mint::Vector3, 33 | frobiness: f32, 34 | } 35 | 36 | // Many APIs require that buffers contain at least enough space for all 37 | // fixed-size bindiongs to a buffer as well as one element of any arrays, if 38 | // there are any. 39 | let mut sizer = std430::Sizer::new(); 40 | sizer.add::(); 41 | sizer.add::(); 42 | 43 | # fn create_buffer_with_size(size: usize) {} 44 | let buffer = create_buffer_with_size(sizer.len()); 45 | # assert_eq!(sizer.len(), 32); 46 | ``` 47 | */ 48 | pub struct Sizer { 49 | offset: usize, 50 | } 51 | 52 | impl Sizer { 53 | /// Create a new `Sizer`. 54 | pub fn new() -> Self { 55 | Self { offset: 0 } 56 | } 57 | 58 | /// Add a type's necessary padding and size to the `Sizer`. Returns the 59 | /// offset into the buffer where that type would be written. 60 | pub fn add(&mut self) -> usize 61 | where 62 | T: AsStd430, 63 | { 64 | let size = size_of::<::Output>(); 65 | let alignment = ::Output::ALIGNMENT; 66 | let padding = align_offset(self.offset, alignment); 67 | 68 | self.offset += padding; 69 | let write_here = self.offset; 70 | 71 | self.offset += size; 72 | 73 | write_here 74 | } 75 | 76 | /// Returns the number of bytes required to contain all the types added to 77 | /// the `Sizer`. 78 | pub fn len(&self) -> usize { 79 | self.offset 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/glsl.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | Defines traits and types for generating GLSL code from Rust definitions. 3 | 4 | All GLSL primitives, like `int` or `vec3`, implement the [`Glsl`] trait. Structs 5 | should implement [`GlslStruct`], which can be derived. 6 | 7 | ## Examples 8 | Given this struct: 9 | */ 10 | #![cfg_attr( 11 | feature = "std", 12 | doc = r##" 13 | ```rust 14 | use mint::{ColumnMatrix4, Vector3}; 15 | use crevice::glsl::GlslStruct; 16 | 17 | #[derive(GlslStruct)] 18 | struct SpotLight { 19 | transform: ColumnMatrix4, 20 | color: Vector3, 21 | intensity: f32, 22 | } 23 | 24 | println!("{}", SpotLight::glsl_definition()); 25 | ``` 26 | "## 27 | )] 28 | /*! 29 | The output will be: 30 | ```glsl 31 | struct SpotLight { 32 | mat4 transform; 33 | vec3 color; 34 | float intensity; 35 | }; 36 | ``` 37 | */ 38 | 39 | pub use crevice_derive::GlslStruct; 40 | 41 | /// Trait for types that have a GLSL equivalent. Useful for generating GLSL code 42 | /// from Rust structs. 43 | pub unsafe trait Glsl { 44 | /// The name of this type in GLSL, like `vec2` or `mat4`. 45 | const NAME: &'static str; 46 | } 47 | 48 | /// A field contained within a GLSL struct definition. 49 | pub struct GlslField { 50 | /// The type of the field, like `vec2` or `mat3`. 51 | pub ty: &'static str, 52 | 53 | /// The field's name. This must be a valid GLSL identifier. 54 | pub name: &'static str, 55 | } 56 | 57 | /// Trait for types that can be represented as a struct in GLSL. 58 | /// 59 | /// This trait should not generally be implemented by hand, but can be derived. 60 | #[cfg(feature = "std")] 61 | pub unsafe trait GlslStruct: Glsl { 62 | /// The fields contained in this struct. 63 | const FIELDS: &'static [GlslField]; 64 | 65 | /// Generates GLSL code that represents this struct and its fields. 66 | fn glsl_definition() -> String { 67 | let mut output = String::new(); 68 | output.push_str("struct "); 69 | output.push_str(Self::NAME); 70 | output.push_str(" {\n"); 71 | 72 | for field in Self::FIELDS { 73 | output.push('\t'); 74 | output.push_str(field.ty); 75 | output.push(' '); 76 | output.push_str(field.name); 77 | output.push_str(";\n"); 78 | } 79 | 80 | output.push_str("};"); 81 | output 82 | } 83 | } 84 | 85 | unsafe impl Glsl for f32 { 86 | const NAME: &'static str = "float"; 87 | } 88 | 89 | unsafe impl Glsl for f64 { 90 | const NAME: &'static str = "double"; 91 | } 92 | 93 | unsafe impl Glsl for i32 { 94 | const NAME: &'static str = "int"; 95 | } 96 | 97 | unsafe impl Glsl for u32 { 98 | const NAME: &'static str = "uint"; 99 | } 100 | -------------------------------------------------------------------------------- /src/util.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused_macros)] 2 | 3 | macro_rules! easy_impl { 4 | ( $( $std_name:ident $imp_ty:ty { $($field:ident),* }, )* ) => { 5 | $( 6 | #[allow(clippy::needless_update)] 7 | impl crate::std140::AsStd140 for $imp_ty { 8 | type Output = crate::std140::$std_name; 9 | 10 | #[inline] 11 | fn as_std140(&self) -> Self::Output { 12 | crate::std140::$std_name { 13 | $( 14 | $field: self.$field.as_std140(), 15 | )* 16 | ..bytemuck::Zeroable::zeroed() 17 | } 18 | } 19 | 20 | #[inline] 21 | fn from_std140(value: Self::Output) -> Self { 22 | Self { 23 | $( 24 | $field: <_ as crate::std140::AsStd140>::from_std140(value.$field), 25 | )* 26 | } 27 | } 28 | } 29 | 30 | #[allow(clippy::needless_update)] 31 | impl crate::std430::AsStd430 for $imp_ty { 32 | type Output = crate::std430::$std_name; 33 | 34 | #[inline] 35 | fn as_std430(&self) -> Self::Output { 36 | crate::std430::$std_name { 37 | $( 38 | $field: self.$field.as_std430(), 39 | )* 40 | ..bytemuck::Zeroable::zeroed() 41 | } 42 | } 43 | 44 | #[inline] 45 | fn from_std430(value: Self::Output) -> Self { 46 | Self { 47 | $( 48 | $field: <_ as crate::std430::AsStd430>::from_std430(value.$field), 49 | )* 50 | } 51 | } 52 | } 53 | 54 | unsafe impl crate::glsl::Glsl for $imp_ty { 55 | const NAME: &'static str = crate::std140::$std_name::NAME; 56 | } 57 | )* 58 | }; 59 | } 60 | 61 | macro_rules! minty_impl { 62 | ( $( $mint_ty:ty => $imp_ty:ty, )* ) => { 63 | $( 64 | impl crate::std140::AsStd140 for $imp_ty { 65 | type Output = <$mint_ty as crate::std140::AsStd140>::Output; 66 | 67 | #[inline] 68 | fn as_std140(&self) -> Self::Output { 69 | let mint: $mint_ty = (*self).into(); 70 | mint.as_std140() 71 | } 72 | 73 | #[inline] 74 | fn from_std140(value: Self::Output) -> Self { 75 | <$mint_ty>::from_std140(value).into() 76 | } 77 | } 78 | 79 | impl crate::std430::AsStd430 for $imp_ty { 80 | type Output = <$mint_ty as crate::std430::AsStd430>::Output; 81 | 82 | #[inline] 83 | fn as_std430(&self) -> Self::Output { 84 | let mint: $mint_ty = (*self).into(); 85 | mint.as_std430() 86 | } 87 | 88 | #[inline] 89 | fn from_std430(value: Self::Output) -> Self { 90 | <$mint_ty>::from_std430(value).into() 91 | } 92 | } 93 | 94 | unsafe impl crate::glsl::Glsl for $imp_ty { 95 | const NAME: &'static str = <$mint_ty>::NAME; 96 | } 97 | )* 98 | }; 99 | } 100 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Crevice 2 | 3 | [![GitHub CI Status](https://github.com/LPGhatguy/crevice/workflows/CI/badge.svg)](https://github.com/LPGhatguy/crevice/actions) 4 | [![crevice on crates.io](https://img.shields.io/crates/v/crevice.svg)](https://crates.io/crates/crevice) 5 | [![crevice docs](https://img.shields.io/badge/docs-docs.rs-orange.svg)](https://docs.rs/crevice) 6 | 7 | Crevice creates GLSL-compatible versions of types through the power of derive 8 | macros. Generated structures provide an [`as_bytes`][std140::Std140::as_bytes] 9 | method to allow safely packing data into buffers for uploading. 10 | 11 | Generated structs also implement [`bytemuck::Zeroable`] and 12 | [`bytemuck::Pod`] for use with other libraries. 13 | 14 | Crevice is similar to [`glsl-layout`][glsl-layout], but supports types from many 15 | math crates, can generate GLSL source from structs, and explicitly initializes 16 | padding to remove one source of undefined behavior. 17 | 18 | Crevice has support for many Rust math libraries via feature flags, and most 19 | other math libraries by use of the mint crate. Crevice currently supports: 20 | 21 | * mint 0.5, enabled by default 22 | * cgmath 0.18, using the `cgmath` feature 23 | * nalgebra 0.33, using the `nalgebra` feature 24 | * glam 0.29, using the `glam` feature 25 | 26 | PRs are welcome to add or update math libraries to Crevice. 27 | 28 | If your math library is not supported, it's possible to define structs using the 29 | types from mint and convert your math library's types into mint types. This is 30 | supported by most Rust math libraries. 31 | 32 | Your math library may require you to turn on a feature flag to get mint support. 33 | For example, cgmath requires the "mint" feature to be enabled to allow 34 | conversions to and from mint types. 35 | 36 | ### Examples 37 | 38 | #### Single Value 39 | 40 | Uploading many types can be done by deriving [`AsStd140`][std140::AsStd140] and 41 | using [`as_std140`][std140::AsStd140::as_std140] and 42 | [`as_bytes`][std140::Std140::as_bytes] to turn the result into bytes. 43 | 44 | ```glsl 45 | uniform MAIN { 46 | mat3 orientation; 47 | vec3 position; 48 | float scale; 49 | } main; 50 | ``` 51 | 52 | ```rust 53 | use crevice::std140::AsStd140; 54 | 55 | #[derive(AsStd140)] 56 | struct MainUniform { 57 | orientation: mint::ColumnMatrix3, 58 | position: mint::Point3, 59 | scale: f32, 60 | } 61 | 62 | let value = MainUniform { 63 | orientation: [ 64 | [1.0, 0.0, 0.0], 65 | [0.0, 1.0, 0.0], 66 | [0.0, 0.0, 1.0], 67 | ].into(), 68 | position: [1.0, 2.0, 3.0].into(), 69 | scale: 4.0, 70 | }; 71 | 72 | let value_std140 = value.as_std140(); 73 | 74 | upload_data_to_gpu(value_std140.as_bytes()); 75 | ``` 76 | 77 | #### Sequential Types 78 | 79 | More complicated data can be uploaded using the std140 80 | [`Writer`][std140::Writer] type. 81 | 82 | ```glsl 83 | struct PointLight { 84 | vec3 position; 85 | vec3 color; 86 | float brightness; 87 | }; 88 | 89 | buffer POINT_LIGHTS { 90 | uint len; 91 | PointLight[] lights; 92 | } point_lights; 93 | ``` 94 | 95 | 96 | [std140::AsStd140]: https://docs.rs/crevice/latest/crevice/std140/trait.AsStd140.html 97 | [std140::AsStd140::as_std140]: https://docs.rs/crevice/latest/crevice/std140/trait.AsStd140.html#method.as_std140 98 | [std140::Std140::as_bytes]: https://docs.rs/crevice/latest/crevice/std140/trait.Std140.html#method.as_bytes 99 | [std140::Writer]: https://docs.rs/crevice/latest/crevice/std140/struct.Writer.html 100 | 101 | [`std::io::Write`]: https://doc.rust-lang.org/stable/std/io/trait.Write.html 102 | 103 | [`bytemuck::Pod`]: https://docs.rs/bytemuck/latest/bytemuck/trait.Pod.html 104 | [`bytemuck::Zeroable`]: https://docs.rs/bytemuck/latest/bytemuck/trait.Zeroable.html 105 | 106 | [glsl-layout]: https://docs.rs/glsl-layout/latest/glsl_layout/ 107 | 108 | ## License 109 | 110 | Licensed under either of 111 | 112 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 113 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 114 | 115 | at your option. 116 | 117 | ### Contribution 118 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 119 | -------------------------------------------------------------------------------- /src/std430/writer.rs: -------------------------------------------------------------------------------- 1 | use std::io::{self, Write}; 2 | use std::mem::size_of; 3 | 4 | use bytemuck::bytes_of; 5 | 6 | use crate::internal::align_offset; 7 | use crate::std430::{AsStd430, Std430, WriteStd430}; 8 | 9 | /** 10 | Type that enables writing correctly aligned `std430` values to a buffer. 11 | 12 | `Writer` is useful when many values need to be laid out in a row that cannot be 13 | represented by a struct alone, like dynamically sized arrays or dynamically 14 | laid-out values. 15 | 16 | ## Example 17 | In this example, we'll write a length-prefixed list of lights to a buffer. 18 | `std430::Writer` helps align correctly, even across multiple structs, which can 19 | be tricky and error-prone otherwise. 20 | 21 | ```glsl 22 | struct PointLight { 23 | vec3 position; 24 | vec3 color; 25 | float brightness; 26 | }; 27 | 28 | buffer POINT_LIGHTS { 29 | uint len; 30 | PointLight[] lights; 31 | } point_lights; 32 | ``` 33 | 34 | ``` 35 | use crevice::std430::{self, AsStd430}; 36 | 37 | #[derive(AsStd430)] 38 | struct PointLight { 39 | position: mint::Point3, 40 | color: mint::Vector3, 41 | brightness: f32, 42 | } 43 | 44 | let lights = vec![ 45 | PointLight { 46 | position: [0.0, 1.0, 0.0].into(), 47 | color: [1.0, 0.0, 0.0].into(), 48 | brightness: 0.6, 49 | }, 50 | PointLight { 51 | position: [0.0, 4.0, 3.0].into(), 52 | color: [1.0, 1.0, 1.0].into(), 53 | brightness: 1.0, 54 | }, 55 | ]; 56 | 57 | # fn map_gpu_buffer_for_write() -> &'static mut [u8] { 58 | # Box::leak(vec![0; 1024].into_boxed_slice()) 59 | # } 60 | let target_buffer = map_gpu_buffer_for_write(); 61 | let mut writer = std430::Writer::new(target_buffer); 62 | 63 | let light_count = lights.len() as u32; 64 | writer.write(&light_count)?; 65 | 66 | // Crevice will automatically insert the required padding to align the 67 | // PointLight structure correctly. In this case, there will be 12 bytes of 68 | // padding between the length field and the light list. 69 | 70 | writer.write(lights.as_slice())?; 71 | 72 | # fn unmap_gpu_buffer() {} 73 | unmap_gpu_buffer(); 74 | 75 | # Ok::<(), std::io::Error>(()) 76 | ``` 77 | */ 78 | pub struct Writer { 79 | writer: W, 80 | offset: usize, 81 | } 82 | 83 | impl Writer { 84 | /// Create a new `Writer`, wrapping a buffer, file, or other type that 85 | /// implements [`std::io::Write`]. 86 | pub fn new(writer: W) -> Self { 87 | Self { writer, offset: 0 } 88 | } 89 | 90 | /// Write a new value to the underlying buffer, writing zeroed padding where 91 | /// necessary. 92 | /// 93 | /// Returns the offset into the buffer that the value was written to. 94 | pub fn write(&mut self, value: &T) -> io::Result 95 | where 96 | T: WriteStd430 + ?Sized, 97 | { 98 | value.write_std430(self) 99 | } 100 | 101 | /// Write an iterator of values to the underlying buffer. 102 | /// 103 | /// Returns the offset into the buffer that the first value was written to. 104 | /// If no values were written, returns the `len()`. 105 | pub fn write_iter(&mut self, iter: I) -> io::Result 106 | where 107 | I: IntoIterator, 108 | T: WriteStd430, 109 | { 110 | let mut offset = self.offset; 111 | 112 | let mut iter = iter.into_iter(); 113 | 114 | if let Some(item) = iter.next() { 115 | offset = item.write_std430(self)?; 116 | } 117 | 118 | for item in iter { 119 | item.write_std430(self)?; 120 | } 121 | 122 | Ok(offset) 123 | } 124 | 125 | /// Write an `Std430` type to the underlying buffer. 126 | pub fn write_std430(&mut self, value: &T) -> io::Result 127 | where 128 | T: Std430, 129 | { 130 | let padding = align_offset(self.offset, T::ALIGNMENT); 131 | 132 | for _ in 0..padding { 133 | self.writer.write_all(&[0])?; 134 | } 135 | self.offset += padding; 136 | 137 | let value = value.as_std430(); 138 | self.writer.write_all(bytes_of(&value))?; 139 | 140 | let write_here = self.offset; 141 | self.offset += size_of::(); 142 | 143 | Ok(write_here) 144 | } 145 | 146 | /// Returns the amount of data written by this `Writer`. 147 | pub fn len(&self) -> usize { 148 | self.offset 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /crevice-tests/src/util.rs: -------------------------------------------------------------------------------- 1 | #[macro_export] 2 | macro_rules! print_std140 { 3 | ($type:ty) => { 4 | println!( 5 | "{}", 6 | <$type as crevice::std140::AsStd140>::Output::debug_metrics() 7 | ); 8 | println!(); 9 | println!(); 10 | println!( 11 | "{}", 12 | <$type as crevice::std140::AsStd140>::Output::debug_definitions() 13 | ); 14 | }; 15 | } 16 | 17 | #[macro_export] 18 | macro_rules! print_std430 { 19 | ($type:ty) => { 20 | println!( 21 | "{}", 22 | <$type as crevice::std430::AsStd430>::Output::debug_metrics() 23 | ); 24 | println!(); 25 | println!(); 26 | println!( 27 | "{}", 28 | <$type as crevice::std430::AsStd430>::Output::debug_definitions() 29 | ); 30 | }; 31 | } 32 | 33 | #[macro_export] 34 | macro_rules! assert_std140 { 35 | ((size = $size:literal, align = $align:literal) $struct:ident { 36 | $( $field:ident: $offset:literal, )* 37 | }) => {{ 38 | type Target = <$struct as crevice::std140::AsStd140>::Output; 39 | 40 | let mut fail = false; 41 | 42 | let actual_size = std::mem::size_of::(); 43 | if actual_size != $size { 44 | fail = true; 45 | println!( 46 | "Invalid size for std140 struct {}\n\ 47 | Expected: {}\n\ 48 | Actual: {}\n", 49 | stringify!($struct), 50 | $size, 51 | actual_size, 52 | ); 53 | } 54 | 55 | let actual_alignment = ::ALIGNMENT; 56 | if actual_alignment != $align { 57 | fail = true; 58 | println!( 59 | "Invalid alignment for std140 struct {}\n\ 60 | Expected: {}\n\ 61 | Actual: {}\n", 62 | stringify!($struct), 63 | $align, 64 | actual_alignment, 65 | ); 66 | } 67 | 68 | $({ 69 | let actual_offset = memoffset::offset_of!(Target, $field); 70 | if actual_offset != $offset { 71 | fail = true; 72 | println!( 73 | "Invalid offset for field {}\n\ 74 | Expected: {}\n\ 75 | Actual: {}\n", 76 | stringify!($field), 77 | $offset, 78 | actual_offset, 79 | ); 80 | } 81 | })* 82 | 83 | if fail { 84 | panic!("Invalid std140 result for {}", stringify!($struct)); 85 | } 86 | }}; 87 | } 88 | 89 | #[macro_export] 90 | macro_rules! assert_std430 { 91 | ((size = $size:literal, align = $align:literal) $struct:ident { 92 | $( $field:ident: $offset:literal, )* 93 | }) => {{ 94 | type Target = <$struct as crevice::std430::AsStd430>::Output; 95 | 96 | let mut fail = false; 97 | 98 | let actual_size = std::mem::size_of::(); 99 | if actual_size != $size { 100 | fail = true; 101 | println!( 102 | "Invalid size for std430 struct {}\n\ 103 | Expected: {}\n\ 104 | Actual: {}\n", 105 | stringify!($struct), 106 | $size, 107 | actual_size, 108 | ); 109 | } 110 | 111 | let actual_alignment = ::ALIGNMENT; 112 | if actual_alignment != $align { 113 | fail = true; 114 | println!( 115 | "Invalid alignment for std430 struct {}\n\ 116 | Expected: {}\n\ 117 | Actual: {}\n", 118 | stringify!($struct), 119 | $align, 120 | actual_alignment, 121 | ); 122 | } 123 | 124 | $({ 125 | let actual_offset = memoffset::offset_of!(Target, $field); 126 | if actual_offset != $offset { 127 | fail = true; 128 | println!( 129 | "Invalid offset for std430 field {}\n\ 130 | Expected: {}\n\ 131 | Actual: {}\n", 132 | stringify!($field), 133 | $offset, 134 | actual_offset, 135 | ); 136 | } 137 | })* 138 | 139 | if fail { 140 | panic!("Invalid std430 result for {}", stringify!($struct)); 141 | } 142 | }}; 143 | } 144 | -------------------------------------------------------------------------------- /src/std140/writer.rs: -------------------------------------------------------------------------------- 1 | use std::io::{self, Write}; 2 | use std::mem::size_of; 3 | 4 | use bytemuck::bytes_of; 5 | 6 | use crate::internal::align_offset; 7 | use crate::std140::{AsStd140, Std140, WriteStd140}; 8 | 9 | /** 10 | Type that enables writing correctly aligned `std140` values to a buffer. 11 | 12 | `Writer` is useful when many values need to be laid out in a row that cannot be 13 | represented by a struct alone, like dynamically sized arrays or dynamically 14 | laid-out values. 15 | 16 | ## Example 17 | In this example, we'll write a length-prefixed list of lights to a buffer. 18 | `std140::Writer` helps align correctly, even across multiple structs, which can 19 | be tricky and error-prone otherwise. 20 | 21 | ```glsl 22 | struct PointLight { 23 | vec3 position; 24 | vec3 color; 25 | float brightness; 26 | }; 27 | 28 | buffer POINT_LIGHTS { 29 | uint len; 30 | PointLight[] lights; 31 | } point_lights; 32 | ``` 33 | 34 | ``` 35 | use crevice::std140::{self, AsStd140}; 36 | 37 | #[derive(AsStd140)] 38 | struct PointLight { 39 | position: mint::Point3, 40 | color: mint::Vector3, 41 | brightness: f32, 42 | } 43 | 44 | let lights = vec![ 45 | PointLight { 46 | position: [0.0, 1.0, 0.0].into(), 47 | color: [1.0, 0.0, 0.0].into(), 48 | brightness: 0.6, 49 | }, 50 | PointLight { 51 | position: [0.0, 4.0, 3.0].into(), 52 | color: [1.0, 1.0, 1.0].into(), 53 | brightness: 1.0, 54 | }, 55 | ]; 56 | 57 | # fn map_gpu_buffer_for_write() -> &'static mut [u8] { 58 | # Box::leak(vec![0; 1024].into_boxed_slice()) 59 | # } 60 | let target_buffer = map_gpu_buffer_for_write(); 61 | let mut writer = std140::Writer::new(target_buffer); 62 | 63 | let light_count = lights.len() as u32; 64 | writer.write(&light_count)?; 65 | 66 | // Crevice will automatically insert the required padding to align the 67 | // PointLight structure correctly. In this case, there will be 12 bytes of 68 | // padding between the length field and the light list. 69 | 70 | writer.write(lights.as_slice())?; 71 | 72 | # fn unmap_gpu_buffer() {} 73 | unmap_gpu_buffer(); 74 | 75 | # Ok::<(), std::io::Error>(()) 76 | ``` 77 | */ 78 | pub struct Writer { 79 | writer: W, 80 | offset: usize, 81 | } 82 | 83 | impl Writer { 84 | /// Create a new `Writer`, wrapping a buffer, file, or other type that 85 | /// implements [`std::io::Write`]. 86 | pub fn new(writer: W) -> Self { 87 | Self { writer, offset: 0 } 88 | } 89 | 90 | /// Write a new value to the underlying buffer, writing zeroed padding where 91 | /// necessary. 92 | /// 93 | /// Returns the offset into the buffer that the value was written to. 94 | pub fn write(&mut self, value: &T) -> io::Result 95 | where 96 | T: WriteStd140 + ?Sized, 97 | { 98 | value.write_std140(self) 99 | } 100 | 101 | /// Write an iterator of values to the underlying buffer. 102 | /// 103 | /// Returns the offset into the buffer that the first value was written to. 104 | /// If no values were written, returns the `len()`. 105 | pub fn write_iter(&mut self, iter: I) -> io::Result 106 | where 107 | I: IntoIterator, 108 | T: WriteStd140, 109 | { 110 | let mut offset = self.offset; 111 | 112 | let mut iter = iter.into_iter(); 113 | 114 | if let Some(item) = iter.next() { 115 | offset = item.write_std140(self)?; 116 | } 117 | 118 | for item in iter { 119 | item.write_std140(self)?; 120 | } 121 | 122 | Ok(offset) 123 | } 124 | 125 | /// Write an `Std140` type to the underlying buffer. 126 | pub fn write_std140(&mut self, value: &T) -> io::Result 127 | where 128 | T: Std140, 129 | { 130 | let padding = align_offset(self.offset, T::ALIGNMENT); 131 | 132 | for _ in 0..padding { 133 | self.writer.write_all(&[0])?; 134 | } 135 | self.offset += padding; 136 | 137 | let value = value.as_std140(); 138 | self.writer.write_all(bytes_of(&value))?; 139 | 140 | let write_here = self.offset; 141 | self.offset += size_of::(); 142 | 143 | Ok(write_here) 144 | } 145 | 146 | /// Write a slice of values to the underlying buffer. 147 | #[deprecated( 148 | since = "0.6.0", 149 | note = "Use `write` instead -- it now works on slices." 150 | )] 151 | pub fn write_slice(&mut self, slice: &[T]) -> io::Result 152 | where 153 | T: AsStd140, 154 | { 155 | self.write(slice) 156 | } 157 | 158 | /// Returns the amount of data written by this `Writer`. 159 | pub fn len(&self) -> usize { 160 | self.offset 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | [![GitHub CI Status](https://github.com/LPGhatguy/crevice/workflows/CI/badge.svg)](https://github.com/LPGhatguy/crevice/actions) 3 | [![crevice on crates.io](https://img.shields.io/crates/v/crevice.svg)](https://crates.io/crates/crevice) 4 | [![crevice docs](https://img.shields.io/badge/docs-docs.rs-orange.svg)](https://docs.rs/crevice) 5 | 6 | Crevice creates GLSL-compatible versions of types through the power of derive 7 | macros. Generated structures provide an [`as_bytes`][std140::Std140::as_bytes] 8 | method to allow safely packing data into buffers for uploading. 9 | 10 | Generated structs also implement [`bytemuck::Zeroable`] and 11 | [`bytemuck::Pod`] for use with other libraries. 12 | 13 | Crevice is similar to [`glsl-layout`][glsl-layout], but supports types from many 14 | math crates, can generate GLSL source from structs, and explicitly initializes 15 | padding to remove one source of undefined behavior. 16 | 17 | Crevice has support for many Rust math libraries via feature flags, and most 18 | other math libraries by use of the mint crate. Crevice currently supports: 19 | 20 | * mint 0.5, enabled by default 21 | * cgmath 0.18, using the `cgmath` feature 22 | * nalgebra 0.33, using the `nalgebra` feature 23 | * glam 0.29, using the `glam` feature 24 | 25 | PRs are welcome to add or update math libraries to Crevice. 26 | 27 | If your math library is not supported, it's possible to define structs using the 28 | types from mint and convert your math library's types into mint types. This is 29 | supported by most Rust math libraries. 30 | 31 | Your math library may require you to turn on a feature flag to get mint support. 32 | For example, cgmath requires the "mint" feature to be enabled to allow 33 | conversions to and from mint types. 34 | 35 | ## Examples 36 | 37 | ### Single Value 38 | 39 | Uploading many types can be done by deriving [`AsStd140`][std140::AsStd140] and 40 | using [`as_std140`][std140::AsStd140::as_std140] and 41 | [`as_bytes`][std140::Std140::as_bytes] to turn the result into bytes. 42 | 43 | ```glsl 44 | uniform MAIN { 45 | mat3 orientation; 46 | vec3 position; 47 | float scale; 48 | } main; 49 | ``` 50 | 51 | ```rust 52 | use crevice::std140::AsStd140; 53 | 54 | #[derive(AsStd140)] 55 | struct MainUniform { 56 | orientation: mint::ColumnMatrix3, 57 | position: mint::Point3, 58 | scale: f32, 59 | } 60 | 61 | let value = MainUniform { 62 | orientation: [ 63 | [1.0, 0.0, 0.0], 64 | [0.0, 1.0, 0.0], 65 | [0.0, 0.0, 1.0], 66 | ].into(), 67 | position: [1.0, 2.0, 3.0].into(), 68 | scale: 4.0, 69 | }; 70 | 71 | let value_std140 = value.as_std140(); 72 | 73 | # fn upload_data_to_gpu(_value: &[u8]) {} 74 | upload_data_to_gpu(value_std140.as_bytes()); 75 | ``` 76 | 77 | ### Sequential Types 78 | 79 | More complicated data can be uploaded using the std140 80 | [`Writer`][std140::Writer] type. 81 | 82 | ```glsl 83 | struct PointLight { 84 | vec3 position; 85 | vec3 color; 86 | float brightness; 87 | }; 88 | 89 | buffer POINT_LIGHTS { 90 | uint len; 91 | PointLight[] lights; 92 | } point_lights; 93 | ``` 94 | 95 | */ 96 | #![cfg_attr( 97 | feature = "std", 98 | doc = r##" 99 | ```rust 100 | use crevice::std140::{self, AsStd140}; 101 | 102 | #[derive(AsStd140)] 103 | struct PointLight { 104 | position: mint::Point3, 105 | color: mint::Vector3, 106 | brightness: f32, 107 | } 108 | 109 | let lights = vec![ 110 | PointLight { 111 | position: [0.0, 1.0, 0.0].into(), 112 | color: [1.0, 0.0, 0.0].into(), 113 | brightness: 0.6, 114 | }, 115 | PointLight { 116 | position: [0.0, 4.0, 3.0].into(), 117 | color: [1.0, 1.0, 1.0].into(), 118 | brightness: 1.0, 119 | }, 120 | ]; 121 | 122 | # fn map_gpu_buffer_for_write() -> &'static mut [u8] { 123 | # Box::leak(vec![0; 1024].into_boxed_slice()) 124 | # } 125 | let target_buffer = map_gpu_buffer_for_write(); 126 | let mut writer = std140::Writer::new(target_buffer); 127 | 128 | let light_count = lights.len() as u32; 129 | writer.write(&light_count)?; 130 | 131 | // Crevice will automatically insert the required padding to align the 132 | // PointLight structure correctly. In this case, there will be 12 bytes of 133 | // padding between the length field and the light list. 134 | 135 | writer.write(lights.as_slice())?; 136 | 137 | # fn unmap_gpu_buffer() {} 138 | unmap_gpu_buffer(); 139 | 140 | # Ok::<(), std::io::Error>(()) 141 | ``` 142 | "## 143 | )] 144 | /*! 145 | 146 | ## Features 147 | 148 | * `std` (default): Enables [`std::io::Write`]-based structs. 149 | * `cgmath`: Enables support for types from cgmath. 150 | * `nalgebra`: Enables support for types from nalgebra. 151 | * `glam`: Enables support for types from glam. 152 | 153 | ## Minimum Supported Rust Version (MSRV) 154 | 155 | Crevice supports Rust 1.74. 156 | 157 | [glsl-layout]: https://github.com/rustgd/glsl-layout 158 | */ 159 | 160 | #![deny(missing_docs)] 161 | #![cfg_attr(not(feature = "std"), no_std)] 162 | 163 | #[macro_use] 164 | mod util; 165 | 166 | pub mod glsl; 167 | pub mod std140; 168 | pub mod std430; 169 | 170 | #[doc(hidden)] 171 | pub mod internal; 172 | 173 | mod bool; 174 | mod imp; 175 | -------------------------------------------------------------------------------- /src/std430/primitives.rs: -------------------------------------------------------------------------------- 1 | use bytemuck::{Pod, Zeroable}; 2 | 3 | use crate::bool::Bool; 4 | use crate::glsl::Glsl; 5 | use crate::std430::{AsStd430, Std430}; 6 | 7 | unsafe impl Std430 for f32 { 8 | const ALIGNMENT: usize = 4; 9 | } 10 | 11 | unsafe impl Std430 for f64 { 12 | const ALIGNMENT: usize = 8; 13 | } 14 | 15 | unsafe impl Std430 for i32 { 16 | const ALIGNMENT: usize = 4; 17 | } 18 | 19 | unsafe impl Std430 for u32 { 20 | const ALIGNMENT: usize = 4; 21 | } 22 | 23 | unsafe impl Std430 for Bool { 24 | const ALIGNMENT: usize = 4; 25 | } 26 | 27 | impl AsStd430 for bool { 28 | type Output = Bool; 29 | 30 | fn as_std430(&self) -> Self::Output { 31 | (*self).into() 32 | } 33 | 34 | fn from_std430(val: Self::Output) -> Self { 35 | val.into() 36 | } 37 | } 38 | 39 | macro_rules! vectors { 40 | ( 41 | $( 42 | #[$doc:meta] align($align:literal) $glsl_name:ident $name:ident <$prim:ident> ($($field:ident),+) 43 | )+ 44 | ) => { 45 | $( 46 | #[$doc] 47 | #[allow(missing_docs)] 48 | #[derive(Debug, Clone, Copy)] 49 | #[repr(C)] 50 | pub struct $name { 51 | $(pub $field: $prim,)+ 52 | } 53 | 54 | unsafe impl Zeroable for $name {} 55 | unsafe impl Pod for $name {} 56 | 57 | unsafe impl Std430 for $name { 58 | const ALIGNMENT: usize = $align; 59 | } 60 | 61 | unsafe impl Glsl for $name { 62 | const NAME: &'static str = stringify!($glsl_name); 63 | } 64 | )+ 65 | }; 66 | } 67 | 68 | vectors! { 69 | #[doc = "Corresponds to a GLSL `vec2` in std430 layout."] align(8) vec2 Vec2(x, y) 70 | #[doc = "Corresponds to a GLSL `vec3` in std430 layout."] align(16) vec3 Vec3(x, y, z) 71 | #[doc = "Corresponds to a GLSL `vec4` in std430 layout."] align(16) vec4 Vec4(x, y, z, w) 72 | 73 | #[doc = "Corresponds to a GLSL `ivec2` in std430 layout."] align(8) ivec2 IVec2(x, y) 74 | #[doc = "Corresponds to a GLSL `ivec3` in std430 layout."] align(16) ivec3 IVec3(x, y, z) 75 | #[doc = "Corresponds to a GLSL `ivec4` in std430 layout."] align(16) ivec4 IVec4(x, y, z, w) 76 | 77 | #[doc = "Corresponds to a GLSL `uvec2` in std430 layout."] align(8) uvec2 UVec2(x, y) 78 | #[doc = "Corresponds to a GLSL `uvec3` in std430 layout."] align(16) uvec3 UVec3(x, y, z) 79 | #[doc = "Corresponds to a GLSL `uvec4` in std430 layout."] align(16) uvec4 UVec4(x, y, z, w) 80 | 81 | #[doc = "Corresponds to a GLSL `bvec2` in std430 layout."] align(8) bvec2 BVec2(x, y) 82 | #[doc = "Corresponds to a GLSL `bvec3` in std430 layout."] align(16) bvec3 BVec3(x, y, z) 83 | #[doc = "Corresponds to a GLSL `bvec4` in std430 layout."] align(16) bvec4 BVec4(x, y, z, w) 84 | 85 | #[doc = "Corresponds to a GLSL `dvec2` in std430 layout."] align(16) dvec2 DVec2(x, y) 86 | #[doc = "Corresponds to a GLSL `dvec3` in std430 layout."] align(32) dvec3 DVec3(x, y, z) 87 | #[doc = "Corresponds to a GLSL `dvec4` in std430 layout."] align(32) dvec4 DVec4(x, y, z, w) 88 | } 89 | 90 | macro_rules! matrices { 91 | ( 92 | $( 93 | #[$doc:meta] 94 | align($align:literal) 95 | $glsl_name:ident $name:ident { 96 | $($field:ident: $field_ty:ty,)+ 97 | } 98 | )+ 99 | ) => { 100 | $( 101 | #[$doc] 102 | #[allow(missing_docs)] 103 | #[derive(Debug, Clone, Copy)] 104 | #[repr(C)] 105 | pub struct $name { 106 | $(pub $field: $field_ty,)+ 107 | } 108 | 109 | unsafe impl Zeroable for $name {} 110 | unsafe impl Pod for $name {} 111 | 112 | unsafe impl Std430 for $name { 113 | const ALIGNMENT: usize = $align; 114 | } 115 | 116 | unsafe impl Glsl for $name { 117 | const NAME: &'static str = stringify!($glsl_name); 118 | } 119 | )+ 120 | }; 121 | } 122 | 123 | matrices! { 124 | #[doc = "Corresponds to a GLSL `mat2` in std430 layout."] 125 | align(8) 126 | mat2 Mat2 { 127 | x: Vec2, 128 | y: Vec2, 129 | } 130 | 131 | #[doc = "Corresponds to a GLSL `mat3` in std430 layout."] 132 | align(16) 133 | mat3 Mat3 { 134 | x: Vec3, 135 | _pad_x: f32, 136 | y: Vec3, 137 | _pad_y: f32, 138 | z: Vec3, 139 | _pad_z: f32, 140 | } 141 | 142 | #[doc = "Corresponds to a GLSL `mat4` in std430 layout."] 143 | align(16) 144 | mat4 Mat4 { 145 | x: Vec4, 146 | y: Vec4, 147 | z: Vec4, 148 | w: Vec4, 149 | } 150 | 151 | #[doc = "Corresponds to a GLSL `dmat2` in std430 layout."] 152 | align(16) 153 | dmat2 DMat2 { 154 | x: DVec2, 155 | y: DVec2, 156 | } 157 | 158 | #[doc = "Corresponds to a GLSL `dmat3` in std430 layout."] 159 | align(32) 160 | dmat3 DMat3 { 161 | x: DVec3, 162 | _pad_x: f64, 163 | y: DVec3, 164 | _pad_y: f64, 165 | z: DVec3, 166 | _pad_z: f64, 167 | } 168 | 169 | #[doc = "Corresponds to a GLSL `dmat3` in std430 layout."] 170 | align(32) 171 | dmat4 DMat4 { 172 | x: DVec4, 173 | y: DVec4, 174 | z: DVec4, 175 | w: DVec4, 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /src/std140/primitives.rs: -------------------------------------------------------------------------------- 1 | use bytemuck::{Pod, Zeroable}; 2 | 3 | use crate::bool::Bool; 4 | use crate::glsl::Glsl; 5 | use crate::std140::{AsStd140, Std140}; 6 | 7 | unsafe impl Std140 for f32 { 8 | const ALIGNMENT: usize = 4; 9 | } 10 | 11 | unsafe impl Std140 for f64 { 12 | const ALIGNMENT: usize = 8; 13 | } 14 | 15 | unsafe impl Std140 for i32 { 16 | const ALIGNMENT: usize = 4; 17 | } 18 | 19 | unsafe impl Std140 for u32 { 20 | const ALIGNMENT: usize = 4; 21 | } 22 | 23 | unsafe impl Std140 for Bool { 24 | const ALIGNMENT: usize = 4; 25 | } 26 | 27 | impl AsStd140 for bool { 28 | type Output = Bool; 29 | 30 | fn as_std140(&self) -> Self::Output { 31 | (*self).into() 32 | } 33 | 34 | fn from_std140(val: Self::Output) -> Self { 35 | val.into() 36 | } 37 | } 38 | 39 | macro_rules! vectors { 40 | ( 41 | $( 42 | #[$doc:meta] align($align:literal) $glsl_name:ident $name:ident <$prim:ident> ($($field:ident),+) 43 | )+ 44 | ) => { 45 | $( 46 | #[$doc] 47 | #[allow(missing_docs)] 48 | #[derive(Debug, Clone, Copy, PartialEq)] 49 | #[repr(C)] 50 | pub struct $name { 51 | $(pub $field: $prim,)+ 52 | } 53 | 54 | unsafe impl Zeroable for $name {} 55 | unsafe impl Pod for $name {} 56 | 57 | unsafe impl Std140 for $name { 58 | const ALIGNMENT: usize = $align; 59 | } 60 | 61 | unsafe impl Glsl for $name { 62 | const NAME: &'static str = stringify!($glsl_name); 63 | } 64 | )+ 65 | }; 66 | } 67 | 68 | vectors! { 69 | #[doc = "Corresponds to a GLSL `vec2` in std140 layout."] align(8) vec2 Vec2(x, y) 70 | #[doc = "Corresponds to a GLSL `vec3` in std140 layout."] align(16) vec3 Vec3(x, y, z) 71 | #[doc = "Corresponds to a GLSL `vec4` in std140 layout."] align(16) vec4 Vec4(x, y, z, w) 72 | 73 | #[doc = "Corresponds to a GLSL `ivec2` in std140 layout."] align(8) ivec2 IVec2(x, y) 74 | #[doc = "Corresponds to a GLSL `ivec3` in std140 layout."] align(16) ivec3 IVec3(x, y, z) 75 | #[doc = "Corresponds to a GLSL `ivec4` in std140 layout."] align(16) ivec4 IVec4(x, y, z, w) 76 | 77 | #[doc = "Corresponds to a GLSL `uvec2` in std140 layout."] align(8) uvec2 UVec2(x, y) 78 | #[doc = "Corresponds to a GLSL `uvec3` in std140 layout."] align(16) uvec3 UVec3(x, y, z) 79 | #[doc = "Corresponds to a GLSL `uvec4` in std140 layout."] align(16) uvec4 UVec4(x, y, z, w) 80 | 81 | #[doc = "Corresponds to a GLSL `bvec2` in std140 layout."] align(8) bvec2 BVec2(x, y) 82 | #[doc = "Corresponds to a GLSL `bvec3` in std140 layout."] align(16) bvec3 BVec3(x, y, z) 83 | #[doc = "Corresponds to a GLSL `bvec4` in std140 layout."] align(16) bvec4 BVec4(x, y, z, w) 84 | 85 | #[doc = "Corresponds to a GLSL `dvec2` in std140 layout."] align(16) dvec2 DVec2(x, y) 86 | #[doc = "Corresponds to a GLSL `dvec3` in std140 layout."] align(32) dvec3 DVec3(x, y, z) 87 | #[doc = "Corresponds to a GLSL `dvec4` in std140 layout."] align(32) dvec4 DVec4(x, y, z, w) 88 | } 89 | 90 | macro_rules! matrices { 91 | ( 92 | $( 93 | #[$doc:meta] 94 | align($align:literal) 95 | $glsl_name:ident $name:ident { 96 | $($field:ident: $field_ty:ty,)+ 97 | } 98 | )+ 99 | ) => { 100 | $( 101 | #[$doc] 102 | #[allow(missing_docs)] 103 | #[derive(Debug, Clone, Copy)] 104 | #[repr(C)] 105 | pub struct $name { 106 | $(pub $field: $field_ty,)+ 107 | } 108 | 109 | unsafe impl Zeroable for $name {} 110 | unsafe impl Pod for $name {} 111 | 112 | unsafe impl Std140 for $name { 113 | const ALIGNMENT: usize = $align; 114 | } 115 | 116 | unsafe impl Glsl for $name { 117 | const NAME: &'static str = stringify!($glsl_name); 118 | } 119 | )+ 120 | }; 121 | } 122 | 123 | matrices! { 124 | #[doc = "Corresponds to a GLSL `mat2` in std140 layout."] 125 | align(16) 126 | mat2 Mat2 { 127 | x: Vec2, 128 | _pad_x: [f32; 2], 129 | y: Vec2, 130 | _pad_y: [f32; 2], 131 | } 132 | 133 | #[doc = "Corresponds to a GLSL `mat3` in std140 layout."] 134 | align(16) 135 | mat3 Mat3 { 136 | x: Vec3, 137 | _pad_x: f32, 138 | y: Vec3, 139 | _pad_y: f32, 140 | z: Vec3, 141 | _pad_z: f32, 142 | } 143 | 144 | #[doc = "Corresponds to a GLSL `mat4` in std140 layout."] 145 | align(16) 146 | mat4 Mat4 { 147 | x: Vec4, 148 | y: Vec4, 149 | z: Vec4, 150 | w: Vec4, 151 | } 152 | 153 | #[doc = "Corresponds to a GLSL `dmat2` in std140 layout."] 154 | align(16) 155 | dmat2 DMat2 { 156 | x: DVec2, 157 | y: DVec2, 158 | } 159 | 160 | #[doc = "Corresponds to a GLSL `dmat3` in std140 layout."] 161 | align(32) 162 | dmat3 DMat3 { 163 | x: DVec3, 164 | _pad_x: f64, 165 | y: DVec3, 166 | _pad_y: f64, 167 | z: DVec3, 168 | _pad_z: f64, 169 | } 170 | 171 | #[doc = "Corresponds to a GLSL `dmat3` in std140 layout."] 172 | align(32) 173 | dmat4 DMat4 { 174 | x: DVec4, 175 | y: DVec4, 176 | z: DVec4, 177 | w: DVec4, 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /src/std430/traits.rs: -------------------------------------------------------------------------------- 1 | use core::mem::size_of; 2 | #[cfg(feature = "std")] 3 | use std::io::{self, Write}; 4 | 5 | use bytemuck::{bytes_of, Pod, Zeroable}; 6 | 7 | #[cfg(feature = "std")] 8 | use crate::std430::Writer; 9 | 10 | /// Trait implemented for all `std430` primitives. Generally should not be 11 | /// implemented outside this crate. 12 | pub unsafe trait Std430: Copy + Zeroable + Pod { 13 | /// The required alignment of the type. Must be a power of two. 14 | /// 15 | /// This is distinct from the value returned by `std::mem::align_of` because 16 | /// `AsStd430` structs do not use Rust's alignment. This enables them to 17 | /// control and zero their padding bytes, making converting them to and from 18 | /// slices safe. 19 | const ALIGNMENT: usize; 20 | 21 | /// Casts the type to a byte array. Implementors should not override this 22 | /// method. 23 | /// 24 | /// # Safety 25 | /// This is always safe due to the requirements of [`bytemuck::Pod`] being a 26 | /// prerequisite for this trait. 27 | fn as_bytes(&self) -> &[u8] { 28 | bytes_of(self) 29 | } 30 | } 31 | 32 | /** 33 | Trait implemented for all types that can be turned into `std430` values. 34 | 35 | This trait can often be `#[derive]`'d instead of manually implementing it. Any 36 | struct which contains only fields that also implement `AsStd430` can derive 37 | `AsStd430`. 38 | 39 | Types from the mint crate implement `AsStd430`, making them convenient for use 40 | in uniform types. Most Rust geometry crates, like cgmath, nalgebra, and 41 | ultraviolet support mint. 42 | 43 | ## Example 44 | 45 | ```glsl 46 | uniform CAMERA { 47 | mat4 view; 48 | mat4 projection; 49 | } camera; 50 | ``` 51 | 52 | ```no_run 53 | use crevice::std430::AsStd430; 54 | 55 | #[derive(AsStd430)] 56 | struct CameraUniform { 57 | view: mint::ColumnMatrix4, 58 | projection: mint::ColumnMatrix4, 59 | } 60 | 61 | let view: mint::ColumnMatrix4 = todo!("your math code here"); 62 | let projection: mint::ColumnMatrix4 = todo!("your math code here"); 63 | 64 | let camera = CameraUniform { 65 | view, 66 | projection, 67 | }; 68 | 69 | # fn write_to_gpu_buffer(bytes: &[u8]) {} 70 | let camera_std430 = camera.as_std430(); 71 | write_to_gpu_buffer(camera_std430.as_bytes()); 72 | ``` 73 | */ 74 | pub trait AsStd430 { 75 | /// The `std430` version of this value. 76 | type Output: Std430; 77 | 78 | /// Convert this value into the `std430` version of itself. 79 | fn as_std430(&self) -> Self::Output; 80 | 81 | /// Returns the size of the `std430` version of this type. Useful for 82 | /// pre-sizing buffers. 83 | fn std430_size_static() -> usize { 84 | size_of::() 85 | } 86 | 87 | /// Converts from `std430` version of self to self. 88 | fn from_std430(value: Self::Output) -> Self; 89 | } 90 | 91 | impl AsStd430 for T 92 | where 93 | T: Std430, 94 | { 95 | type Output = Self; 96 | 97 | fn as_std430(&self) -> Self { 98 | *self 99 | } 100 | 101 | fn from_std430(value: Self) -> Self { 102 | value 103 | } 104 | } 105 | 106 | /// Trait implemented for all types that can be written into a buffer as 107 | /// `std430` bytes. This type is more general than [`AsStd430`]: all `AsStd430` 108 | /// types implement `WriteStd430`, but not the other way around. 109 | /// 110 | /// While `AsStd430` requires implementers to return a type that implements the 111 | /// `Std430` trait, `WriteStd430` directly writes bytes using a [`Writer`]. This 112 | /// makes `WriteStd430` usable for writing slices or other DSTs that could not 113 | /// implement `AsStd430` without allocating new memory on the heap. 114 | #[cfg(feature = "std")] 115 | pub trait WriteStd430 { 116 | /// Writes this value into the given [`Writer`] using `std430` layout rules. 117 | /// 118 | /// Should return the offset of the first byte of this type, as returned by 119 | /// the first call to [`Writer::write`]. 120 | fn write_std430(&self, writer: &mut Writer) -> io::Result; 121 | 122 | /// The space required to write this value using `std430` layout rules. This 123 | /// does not include alignment padding that may be needed before or after 124 | /// this type when written as part of a larger buffer. 125 | fn std430_size(&self) -> usize { 126 | let mut writer = Writer::new(io::sink()); 127 | self.write_std430(&mut writer).unwrap(); 128 | writer.len() 129 | } 130 | } 131 | 132 | #[cfg(feature = "std")] 133 | impl WriteStd430 for T 134 | where 135 | T: AsStd430, 136 | { 137 | fn write_std430(&self, writer: &mut Writer) -> io::Result { 138 | writer.write_std430(&self.as_std430()) 139 | } 140 | 141 | fn std430_size(&self) -> usize { 142 | size_of::<::Output>() 143 | } 144 | } 145 | 146 | #[cfg(feature = "std")] 147 | impl WriteStd430 for [T] 148 | where 149 | T: WriteStd430, 150 | { 151 | fn write_std430(&self, writer: &mut Writer) -> io::Result { 152 | let mut offset = writer.len(); 153 | 154 | let mut iter = self.iter(); 155 | 156 | if let Some(item) = iter.next() { 157 | offset = item.write_std430(writer)?; 158 | } 159 | 160 | for item in iter { 161 | item.write_std430(writer)?; 162 | } 163 | 164 | Ok(offset) 165 | } 166 | 167 | fn std430_size(&self) -> usize { 168 | let mut writer = Writer::new(io::sink()); 169 | self.write_std430(&mut writer).unwrap(); 170 | writer.len() 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /src/std140/traits.rs: -------------------------------------------------------------------------------- 1 | use core::mem::size_of; 2 | #[cfg(feature = "std")] 3 | use std::io::{self, Write}; 4 | 5 | use bytemuck::{bytes_of, Pod, Zeroable}; 6 | 7 | #[cfg(feature = "std")] 8 | use crate::std140::Writer; 9 | 10 | /// Trait implemented for all `std140` primitives. Generally should not be 11 | /// implemented outside this crate. 12 | pub unsafe trait Std140: Copy + Zeroable + Pod { 13 | /// The required alignment of the type. Must be a power of two. 14 | /// 15 | /// This is distinct from the value returned by `std::mem::align_of` because 16 | /// `AsStd140` structs do not use Rust's alignment. This enables them to 17 | /// control and zero their padding bytes, making converting them to and from 18 | /// slices safe. 19 | const ALIGNMENT: usize; 20 | 21 | /// Casts the type to a byte array. Implementors should not override this 22 | /// method. 23 | /// 24 | /// # Safety 25 | /// This is always safe due to the requirements of [`bytemuck::Pod`] being a 26 | /// prerequisite for this trait. 27 | fn as_bytes(&self) -> &[u8] { 28 | bytes_of(self) 29 | } 30 | } 31 | 32 | /** 33 | Trait implemented for all types that can be turned into `std140` values. 34 | 35 | This trait can often be `#[derive]`'d instead of manually implementing it. Any 36 | struct which contains only fields that also implement `AsStd140` can derive 37 | `AsStd140`. 38 | 39 | Types from the mint crate implement `AsStd140`, making them convenient for use 40 | in uniform types. Most Rust math crates, like cgmath, nalgebra, and 41 | ultraviolet support mint. 42 | 43 | ## Example 44 | 45 | ```glsl 46 | uniform CAMERA { 47 | mat4 view; 48 | mat4 projection; 49 | } camera; 50 | ``` 51 | 52 | ```no_run 53 | use crevice::std140::AsStd140; 54 | 55 | #[derive(AsStd140)] 56 | struct CameraUniform { 57 | view: mint::ColumnMatrix4, 58 | projection: mint::ColumnMatrix4, 59 | } 60 | 61 | let view: mint::ColumnMatrix4 = todo!("your math code here"); 62 | let projection: mint::ColumnMatrix4 = todo!("your math code here"); 63 | 64 | let camera = CameraUniform { 65 | view, 66 | projection, 67 | }; 68 | 69 | # fn write_to_gpu_buffer(bytes: &[u8]) {} 70 | let camera_std140 = camera.as_std140(); 71 | write_to_gpu_buffer(camera_std140.as_bytes()); 72 | ``` 73 | */ 74 | pub trait AsStd140 { 75 | /// The `std140` version of this value. 76 | type Output: Std140; 77 | 78 | /// Convert this value into the `std140` version of itself. 79 | fn as_std140(&self) -> Self::Output; 80 | 81 | /// Returns the size of the `std140` version of this type. Useful for 82 | /// pre-sizing buffers. 83 | fn std140_size_static() -> usize { 84 | size_of::() 85 | } 86 | 87 | /// Converts from `std140` version of self to self. 88 | fn from_std140(val: Self::Output) -> Self; 89 | } 90 | 91 | impl AsStd140 for T 92 | where 93 | T: Std140, 94 | { 95 | type Output = Self; 96 | 97 | fn as_std140(&self) -> Self { 98 | *self 99 | } 100 | 101 | fn from_std140(x: Self) -> Self { 102 | x 103 | } 104 | } 105 | 106 | /// Trait implemented for all types that can be written into a buffer as 107 | /// `std140` bytes. This type is more general than [`AsStd140`]: all `AsStd140` 108 | /// types implement `WriteStd140`, but not the other way around. 109 | /// 110 | /// While `AsStd140` requires implementers to return a type that implements the 111 | /// `Std140` trait, `WriteStd140` directly writes bytes using a [`Writer`]. This 112 | /// makes `WriteStd140` usable for writing slices or other DSTs that could not 113 | /// implement `AsStd140` without allocating new memory on the heap. 114 | #[cfg(feature = "std")] 115 | pub trait WriteStd140 { 116 | /// Writes this value into the given [`Writer`] using `std140` layout rules. 117 | /// 118 | /// Should return the offset of the first byte of this type, as returned by 119 | /// the first call to [`Writer::write`]. 120 | fn write_std140(&self, writer: &mut Writer) -> io::Result; 121 | 122 | /// The space required to write this value using `std140` layout rules. This 123 | /// does not include alignment padding that may be needed before or after 124 | /// this type when written as part of a larger buffer. 125 | fn std140_size(&self) -> usize { 126 | let mut writer = Writer::new(io::sink()); 127 | self.write_std140(&mut writer).unwrap(); 128 | writer.len() 129 | } 130 | } 131 | 132 | #[cfg(feature = "std")] 133 | impl WriteStd140 for T 134 | where 135 | T: AsStd140, 136 | { 137 | fn write_std140(&self, writer: &mut Writer) -> io::Result { 138 | writer.write_std140(&self.as_std140()) 139 | } 140 | 141 | fn std140_size(&self) -> usize { 142 | size_of::<::Output>() 143 | } 144 | } 145 | 146 | #[cfg(feature = "std")] 147 | impl WriteStd140 for [T] 148 | where 149 | T: WriteStd140, 150 | { 151 | fn write_std140(&self, writer: &mut Writer) -> io::Result { 152 | // if no items are written, offset is current position of the writer 153 | let mut offset = writer.len(); 154 | 155 | let mut iter = self.iter(); 156 | 157 | if let Some(item) = iter.next() { 158 | offset = item.write_std140(writer)?; 159 | } 160 | 161 | for item in iter { 162 | item.write_std140(writer)?; 163 | } 164 | 165 | Ok(offset) 166 | } 167 | 168 | fn std140_size(&self) -> usize { 169 | let mut writer = Writer::new(io::sink()); 170 | self.write_std140(&mut writer).unwrap(); 171 | writer.len() 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Crevice Changelog 2 | 3 | ## Unreleased Changes 4 | 5 | ## [0.18.0] - 2024-05-06 6 | * Upgraded to glam 0.30. 7 | * Upgraded to syn 2.0. 8 | * No longer generates warnings or rustdoc entries for generated structs. 9 | 10 | [0.18.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.18.0 11 | 12 | ## [0.17.0] - 2024-05-06 13 | * Upgraded to glam 0.29. 14 | 15 | [0.17.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.17.0 16 | 17 | ## [0.16.0] - 2024-05-06 18 | * Upgraded to glam 0.27. 19 | 20 | [0.16.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.16.0 21 | 22 | ## 0.15.0 - 2024-03-16 23 | * Fixed usage in no-std environments when using math library features ([#61]) 24 | * Upgraded to glam 0.25. 25 | 26 | [#61]: https://github.com/LPGhatguy/crevice/pull/61 27 | 28 | ## [0.14.0] - 2023-09-08 29 | * Upgraded to glam 0.24. 30 | * Upgraded to nalgebra 0.32. 31 | 32 | [0.14.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.14.0 33 | 34 | ## [0.13.0] - 2023-03-20 35 | * Upgraded to glam 0.23. 36 | 37 | [0.13.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.13.0 38 | 39 | ## [0.12.0] - 2022-11-09 40 | * Upgraded to glam 0.22. 41 | 42 | [0.12.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.12.0 43 | 44 | ## [0.11.0] - 2022-07-01 45 | * Upgraded to glam 0.21. 46 | 47 | [0.11.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.11.0 48 | 49 | ## [0.10.0] - 2022-05-26 50 | * Removed the now-obsolete `PAD_AT_END` associated value. ([#43]) 51 | * Added support for `Point` types from mint and all supported math libraries. ([#47]) 52 | * Added `as_bytes` to generated types, reducing the need to import traits. ([#48]) 53 | * Fixed `WriteStd430` on arrays writing the first element twice. ([#46]) 54 | * Fixed no_std build and drastically improved Crevice's CI pipeline. ([#54]) 55 | 56 | [#43]: https://github.com/LPGhatguy/crevice/pull/43 57 | [#46]: https://github.com/LPGhatguy/crevice/pull/46 58 | [#47]: https://github.com/LPGhatguy/crevice/pull/47 59 | [#48]: https://github.com/LPGhatguy/crevice/pull/48 60 | [#54]: https://github.com/LPGhatguy/crevice/pull/54 61 | [0.10.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.10.0 62 | 63 | ## [0.9.0] - 2022-05-26 64 | * Added correct support for bool-based types. ([#39]) 65 | * Updated to glam 0.20 and nalgebra 0.31. 66 | 67 | [#39]: https://github.com/LPGhatguy/crevice/pull/39 68 | [0.9.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.9.0 69 | 70 | ## [0.8.0] - 2021-10-26 71 | * Added support for many math libraries directly: ([#37]) 72 | * cgmath 0.18, behind the `cgmath` feature 73 | * nalgebra 0.29, behind the `nalgebra` feature 74 | * glam 0.19, behind the `glam` feature 75 | * Added support for generating GLSL source from structs. ([#33]) 76 | * Fixed many, many subtle alignment bugs. ([#28], [#35]) 77 | * Disabled bool-based types temporarily ([#36]) 78 | * Renamed `AsStdN::StdNType` to `Output`. 79 | * Increased MSRV to 1.52.1. 80 | 81 | [#28]: https://github.com/LPGhatguy/crevice/issues/28 82 | [#33]: https://github.com/LPGhatguy/crevice/pull/33 83 | [#35]: https://github.com/LPGhatguy/crevice/pull/35 84 | [#36]: https://github.com/LPGhatguy/crevice/issues/36 85 | [#37]: https://github.com/LPGhatguy/crevice/pull/37 86 | [0.8.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.8.0 87 | 88 | ## [0.7.1] - 2021-07-24 89 | * Fixed broken crates.io release by publishing crevice-derive too. 90 | 91 | [0.7.1]: https://github.com/LPGhatguy/crevice/releases/tag/v0.7.1 92 | 93 | ## [0.7.0] - 2021-07-20 (Yanked) 94 | **This release was yanked due to an issue reported in [#32].** 95 | 96 | * Added `ivec`, `uvec`, and `bvec` structs ([#18]) 97 | * Improved padding behavior for structs and matrices ([#20]) 98 | * Implemented Crevice traits for more types ([#23]) 99 | * Added conversions from Std* types to AsStd* types ([#24]) 100 | * Added no_std support ([#25]) 101 | 102 | [#18]: https://github.com/LPGhatguy/crevice/pull/18 103 | [#20]: https://github.com/LPGhatguy/crevice/pull/20 104 | [#23]: https://github.com/LPGhatguy/crevice/pull/23 105 | [#24]: https://github.com/LPGhatguy/crevice/pull/24 106 | [#25]: https://github.com/LPGhatguy/crevice/pull/25 107 | [#32]: https://github.com/LPGhatguy/crevice/issues/32 108 | [0.7.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.7.0 109 | 110 | ## [0.6.0] - 2021-02-24 111 | * Added `std430` support. Most APIs between `std140` and `std430` are the same! 112 | * Added the `WriteStd140` trait. This trait is more general than `AsStd140` and is automatically implemented for all existing `AsStd140` implementers. 113 | * Added `Writer::write_std140` to write a type that implements `Std140`. 114 | * Added `AsStd140::std140_size_static`. This is similar to the old size method, `std140_size`, but no longer requires a value to be passed. For size measurements that depend on a value, use `WriteStd140::std140_size` instead. 115 | * Deprecated `Writer::write_slice`, as `Writer::write` now accepts slices. 116 | * Changed bounds of some functions, like `Writer::write` to use `WriteStd140` instead of `AsStd140`. This should affect no existing consumers. 117 | * Moved `std140_size` from `AsStd140` to `WriteStd140`. Some existing consumers may need to import the other trait to access this m ethod. 118 | 119 | [0.6.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.6.0 120 | 121 | ## [0.5.0] - 2020-10-18 122 | * Added f64-based std140 types: `DVec2`, `DVec3`, `DVec4`, `DMat2`, `DMat3`, and `DMat4`. 123 | * Added support for std140 structs with alignment greater than 16. 124 | * Fixed padding for std140 matrices; they were previously missing trailing padding. 125 | 126 | [0.5.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.5.0 127 | 128 | ## [0.4.0] - 2020-10-01 129 | * Added `AsStd140::std140_size` for easily pre-sizing buffers. 130 | * `Writer::write` and `Sizer::add` now return the offset the value is or would be written to. 131 | * Added `std140::DynamicUniform` for aligning dynamic uniform members. 132 | * Added `Writer::write_slice` for writing multiple values in a row. 133 | 134 | [0.4.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.4.0 135 | 136 | ## [0.3.0] - 2020-09-22 137 | * Added `Std140::as_bytes`, reducing the need to work with bytemuck directly. 138 | * Removed public re-export of bytemuck. 139 | 140 | [0.3.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.3.0 141 | 142 | ## [0.2.0] - 2020-09-22 143 | * Added documentation for everything in the crate. 144 | * Removed `type_layout` being exposed except for internal tests. 145 | * Fixed alignment offset not taking into account previously added alignment. 146 | * Added `std140::Writer`, for writing dynamically laid out types to buffers. 147 | * Added `std140::Sizer`, for pre-calculating buffer sizes. 148 | 149 | [0.2.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.2.0 150 | 151 | ## [0.1.0] - 2020-09-18 152 | * Initial MVP release 153 | 154 | [0.1.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.1.0 155 | -------------------------------------------------------------------------------- /crevice-tests/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg(test)] 2 | 3 | #[cfg(feature = "wgpu-validation")] 4 | mod gpu; 5 | 6 | #[cfg(feature = "wgpu-validation")] 7 | use gpu::{test_round_trip_primitive, test_round_trip_struct}; 8 | 9 | #[cfg(not(feature = "wgpu-validation"))] 10 | fn test_round_trip_struct(_value: T) {} 11 | 12 | #[cfg(not(feature = "wgpu-validation"))] 13 | fn test_round_trip_primitive(_value: T) {} 14 | 15 | #[macro_use] 16 | mod util; 17 | 18 | use crevice::std140::AsStd140; 19 | use crevice::std430::AsStd430; 20 | use mint::{ColumnMatrix2, ColumnMatrix3, ColumnMatrix4, Vector2, Vector3, Vector4}; 21 | 22 | #[cfg(feature = "wgpu-validation")] 23 | use crevice::glsl::GlslStruct; 24 | 25 | #[test] 26 | fn two_f32() { 27 | #[derive(Debug, PartialEq, AsStd140, AsStd430)] 28 | #[cfg_attr(feature = "wgpu-validation", derive(GlslStruct))] 29 | struct TwoF32 { 30 | x: f32, 31 | y: f32, 32 | } 33 | 34 | assert_std140!((size = 16, align = 16) TwoF32 { 35 | x: 0, 36 | y: 4, 37 | }); 38 | 39 | assert_std430!((size = 8, align = 4) TwoF32 { 40 | x: 0, 41 | y: 4, 42 | }); 43 | 44 | test_round_trip_struct(TwoF32 { x: 5.0, y: 7.0 }); 45 | } 46 | 47 | #[test] 48 | fn vec2() { 49 | #[derive(Debug, PartialEq, AsStd140, AsStd430)] 50 | #[cfg_attr(feature = "wgpu-validation", derive(GlslStruct))] 51 | struct UseVec2 { 52 | one: Vector2, 53 | } 54 | 55 | assert_std140!((size = 16, align = 16) UseVec2 { 56 | one: 0, 57 | }); 58 | 59 | test_round_trip_struct(UseVec2 { 60 | one: [1.0, 2.0].into(), 61 | }); 62 | } 63 | 64 | #[test] 65 | fn mat2_bare() { 66 | type Mat2 = ColumnMatrix2; 67 | 68 | assert_std140!((size = 32, align = 16) Mat2 { 69 | x: 0, 70 | y: 16, 71 | }); 72 | 73 | assert_std430!((size = 16, align = 8) Mat2 { 74 | x: 0, 75 | y: 8, 76 | }); 77 | 78 | // Naga doesn't work with std140 mat2 values. 79 | // https://github.com/gfx-rs/naga/issues/1400 80 | 81 | // test_round_trip_primitive(Mat2 { 82 | // x: [1.0, 2.0].into(), 83 | // y: [3.0, 4.0].into(), 84 | // }); 85 | } 86 | 87 | #[test] 88 | fn mat3_bare() { 89 | type Mat3 = ColumnMatrix3; 90 | 91 | assert_std140!((size = 48, align = 16) Mat3 { 92 | x: 0, 93 | y: 16, 94 | z: 32, 95 | }); 96 | 97 | // Naga produces invalid HLSL for mat3 value. 98 | // https://github.com/gfx-rs/naga/issues/1466 99 | 100 | // test_round_trip_primitive(Mat3 { 101 | // x: [1.0, 2.0, 3.0].into(), 102 | // y: [4.0, 5.0, 6.0].into(), 103 | // z: [7.0, 8.0, 9.0].into(), 104 | // }); 105 | } 106 | 107 | #[test] 108 | fn mat4_bare() { 109 | type Mat4 = ColumnMatrix4; 110 | 111 | assert_std140!((size = 64, align = 16) Mat4 { 112 | x: 0, 113 | y: 16, 114 | z: 32, 115 | w: 48, 116 | }); 117 | 118 | test_round_trip_primitive(Mat4 { 119 | x: [1.0, 2.0, 3.0, 4.0].into(), 120 | y: [5.0, 6.0, 7.0, 8.0].into(), 121 | z: [9.0, 10.0, 11.0, 12.0].into(), 122 | w: [13.0, 14.0, 15.0, 16.0].into(), 123 | }); 124 | } 125 | 126 | #[test] 127 | fn mat3() { 128 | #[derive(Debug, PartialEq, AsStd140, AsStd430)] 129 | #[cfg_attr(feature = "wgpu-validation", derive(GlslStruct))] 130 | struct TestData { 131 | one: ColumnMatrix3, 132 | } 133 | 134 | // Naga produces invalid HLSL for mat3 value. 135 | // https://github.com/gfx-rs/naga/issues/1466 136 | 137 | // test_round_trip_struct(TestData { 138 | // one: [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]].into(), 139 | // }); 140 | } 141 | 142 | #[test] 143 | fn dvec4() { 144 | #[derive(Debug, PartialEq, AsStd140, AsStd430)] 145 | #[cfg_attr(feature = "wgpu-validation", derive(GlslStruct))] 146 | struct UsingDVec4 { 147 | doubles: Vector4, 148 | } 149 | 150 | assert_std140!((size = 32, align = 32) UsingDVec4 { 151 | doubles: 0, 152 | }); 153 | 154 | // Naga does not appear to support doubles. 155 | // https://github.com/gfx-rs/naga/issues/1272 156 | 157 | // test_round_trip_struct(UsingDVec4 { 158 | // doubles: [1.0, 2.0, 3.0, 4.0].into(), 159 | // }); 160 | } 161 | 162 | #[test] 163 | fn four_f64() { 164 | #[derive(Debug, PartialEq, AsStd140, AsStd430)] 165 | #[cfg_attr(feature = "wgpu-validation", derive(GlslStruct))] 166 | struct FourF64 { 167 | x: f64, 168 | y: f64, 169 | z: f64, 170 | w: f64, 171 | } 172 | 173 | assert_std140!((size = 32, align = 16) FourF64 { 174 | x: 0, 175 | y: 8, 176 | z: 16, 177 | w: 24, 178 | }); 179 | 180 | // Naga does not appear to support doubles. 181 | // https://github.com/gfx-rs/naga/issues/1272 182 | 183 | // test_round_trip_struct(FourF64 { 184 | // x: 5.0, 185 | // y: 7.0, 186 | // z: 9.0, 187 | // w: 11.0, 188 | // }); 189 | } 190 | 191 | #[test] 192 | fn two_vec3() { 193 | #[derive(Debug, PartialEq, AsStd140, AsStd430)] 194 | #[cfg_attr(feature = "wgpu-validation", derive(GlslStruct))] 195 | struct TwoVec3 { 196 | one: Vector3, 197 | two: Vector3, 198 | } 199 | 200 | print_std140!(TwoVec3); 201 | print_std430!(TwoVec3); 202 | 203 | assert_std140!((size = 32, align = 16) TwoVec3 { 204 | one: 0, 205 | two: 16, 206 | }); 207 | 208 | assert_std430!((size = 32, align = 16) TwoVec3 { 209 | one: 0, 210 | two: 16, 211 | }); 212 | 213 | test_round_trip_struct(TwoVec3 { 214 | one: [1.0, 2.0, 3.0].into(), 215 | two: [4.0, 5.0, 6.0].into(), 216 | }); 217 | } 218 | 219 | #[test] 220 | fn two_vec4() { 221 | #[derive(Debug, PartialEq, AsStd140, AsStd430)] 222 | #[cfg_attr(feature = "wgpu-validation", derive(GlslStruct))] 223 | struct TwoVec4 { 224 | one: Vector4, 225 | two: Vector4, 226 | } 227 | 228 | assert_std140!((size = 32, align = 16) TwoVec4 { 229 | one: 0, 230 | two: 16, 231 | }); 232 | 233 | test_round_trip_struct(TwoVec4 { 234 | one: [1.0, 2.0, 3.0, 4.0].into(), 235 | two: [5.0, 6.0, 7.0, 8.0].into(), 236 | }); 237 | } 238 | 239 | #[test] 240 | fn vec3_then_f32() { 241 | #[derive(Debug, PartialEq, AsStd140, AsStd430)] 242 | #[cfg_attr(feature = "wgpu-validation", derive(GlslStruct))] 243 | struct Vec3ThenF32 { 244 | one: Vector3, 245 | two: f32, 246 | } 247 | 248 | assert_std140!((size = 16, align = 16) Vec3ThenF32 { 249 | one: 0, 250 | two: 12, 251 | }); 252 | 253 | test_round_trip_struct(Vec3ThenF32 { 254 | one: [1.0, 2.0, 3.0].into(), 255 | two: 4.0, 256 | }); 257 | } 258 | 259 | #[test] 260 | fn mat3_padding() { 261 | #[derive(Debug, PartialEq, AsStd140, AsStd430)] 262 | #[cfg_attr(feature = "wgpu-validation", derive(GlslStruct))] 263 | struct Mat3Padding { 264 | // Three rows of 16 bytes (3x f32 + 4 bytes padding) 265 | one: mint::ColumnMatrix3, 266 | two: f32, 267 | } 268 | 269 | assert_std140!((size = 64, align = 16) Mat3Padding { 270 | one: 0, 271 | two: 48, 272 | }); 273 | 274 | // Naga produces invalid HLSL for mat3 value. 275 | // https://github.com/gfx-rs/naga/issues/1466 276 | 277 | // test_round_trip_struct(Mat3Padding { 278 | // one: [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]].into(), 279 | // two: 10.0, 280 | // }); 281 | } 282 | 283 | #[test] 284 | fn padding_after_struct() { 285 | #[derive(AsStd140)] 286 | struct TwoF32 { 287 | x: f32, 288 | } 289 | 290 | #[derive(AsStd140)] 291 | struct PaddingAfterStruct { 292 | base_value: TwoF32, 293 | // There should be 8 bytes of padding inserted here. 294 | small_field: f32, 295 | } 296 | 297 | assert_std140!((size = 32, align = 16) PaddingAfterStruct { 298 | base_value: 0, 299 | small_field: 16, 300 | }); 301 | } 302 | 303 | #[test] 304 | fn proper_offset_calculations_for_differing_member_sizes() { 305 | #[derive(AsStd140)] 306 | struct Foo { 307 | x: f32, 308 | } 309 | 310 | #[derive(AsStd140)] 311 | struct Bar { 312 | first: Foo, 313 | second: Foo, 314 | } 315 | 316 | #[derive(AsStd140)] 317 | struct Outer { 318 | leading: Bar, 319 | trailing: Foo, 320 | } 321 | 322 | // Offset Size Contents 323 | // 0 4 Bar.leading.first.x 324 | // 4 12 [padding] 325 | // 16 4 Bar.leading.second.x 326 | // 20 12 [padding] 327 | // 32 4 Bar.trailing.x 328 | // 36 12 [padding] 329 | // 330 | // Total size is 48. 331 | 332 | assert_std140!((size = 48, align = 16) Outer { 333 | leading: 0, 334 | trailing: 32, 335 | }); 336 | } 337 | 338 | #[test] 339 | fn bools_and_bool_vectors() { 340 | #[derive(AsStd140, AsStd430)] 341 | struct ContainsBools { 342 | x: bool, 343 | y: Vector2, 344 | } 345 | 346 | assert_std140!((size = 16, align = 16) ContainsBools { 347 | x: 0, 348 | y: 8, 349 | }); 350 | 351 | assert_std430!((size = 16, align = 8) ContainsBools { 352 | x: 0, 353 | y: 8, 354 | }); 355 | } 356 | -------------------------------------------------------------------------------- /crevice-tests/src/gpu.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Cow; 2 | use std::fmt::{Debug, Write}; 3 | use std::marker::PhantomData; 4 | 5 | use crevice::glsl::{Glsl, GlslStruct}; 6 | use crevice::std140::{AsStd140, Std140}; 7 | use crevice::std430::{AsStd430, Std430}; 8 | use futures::executor::block_on; 9 | use wgpu::util::DeviceExt; 10 | 11 | const BASE_SHADER: &str = "#version 450 12 | 13 | {struct_definition} 14 | 15 | layout({layout}, set = 0, binding = 0) readonly buffer INPUT { 16 | {struct_name} in_data; 17 | }; 18 | 19 | layout({layout}, set = 0, binding = 1) buffer OUTPUT { 20 | {struct_name} out_data; 21 | }; 22 | 23 | void main() { 24 | {struct_copy} 25 | }"; 26 | 27 | pub fn test_round_trip_struct(value: T) { 28 | let shader_std140 = glsl_shader_for_struct::("std140"); 29 | let shader_std430 = glsl_shader_for_struct::("std430"); 30 | 31 | let context = Context::new(); 32 | context.test_round_trip_std140(&shader_std140, &value); 33 | context.test_round_trip_std430(&shader_std430, &value); 34 | } 35 | 36 | pub fn test_round_trip_primitive(value: T) { 37 | let shader_std140 = glsl_shader_for_primitive::("std140"); 38 | let shader_std430 = glsl_shader_for_primitive::("std430"); 39 | 40 | let context = Context::new(); 41 | context.test_round_trip_std140(&shader_std140, &value); 42 | context.test_round_trip_std430(&shader_std430, &value); 43 | } 44 | 45 | fn glsl_shader_for_struct(layout: &str) -> String { 46 | BASE_SHADER 47 | .replace("{struct_name}", T::NAME) 48 | .replace("{struct_definition}", &T::glsl_definition()) 49 | .replace("{struct_copy}", &struct_copy::()) 50 | .replace("{layout}", layout) 51 | } 52 | 53 | fn struct_copy() -> String { 54 | let mut output = String::new(); 55 | 56 | for field in T::FIELDS { 57 | writeln!( 58 | output, 59 | "out_data.{name} = in_data.{name};", 60 | name = field.name 61 | ) 62 | .unwrap(); 63 | } 64 | 65 | output 66 | } 67 | 68 | fn glsl_shader_for_primitive(layout: &str) -> String { 69 | BASE_SHADER 70 | .replace("{struct_name}", T::NAME) 71 | .replace("{struct_definition}", "") 72 | .replace("{struct_copy}", "out_data = in_data;\n") 73 | .replace("{layout}", layout) 74 | } 75 | 76 | fn compile_glsl(glsl: &str) -> String { 77 | match compile(glsl) { 78 | Ok(shader) => shader, 79 | Err(err) => { 80 | eprintln!("Bad shader: {}", glsl); 81 | panic!("{}", err); 82 | } 83 | } 84 | } 85 | 86 | struct Context { 87 | device: wgpu::Device, 88 | queue: wgpu::Queue, 89 | _phantom: PhantomData<*const T>, 90 | } 91 | 92 | impl Context 93 | where 94 | T: Debug + PartialEq + AsStd140 + AsStd430 + Glsl, 95 | { 96 | fn new() -> Self { 97 | let (device, queue) = setup(); 98 | Self { 99 | device, 100 | queue, 101 | _phantom: PhantomData, 102 | } 103 | } 104 | 105 | fn test_round_trip_std140(&self, glsl_shader: &str, value: &T) { 106 | let mut data = Vec::new(); 107 | data.extend_from_slice(value.as_std140().as_bytes()); 108 | 109 | let wgsl_shader = compile_glsl(glsl_shader); 110 | let bytes = self.round_trip(&wgsl_shader, &data); 111 | 112 | let std140 = bytemuck::from_bytes::<::Output>(&bytes); 113 | let output = T::from_std140(*std140); 114 | 115 | if value != &output { 116 | println!( 117 | "std140 value did not round-trip through wgpu successfully.\n\ 118 | Input: {:?}\n\ 119 | Output: {:?}\n\n\ 120 | GLSL shader:\n{}\n\n\ 121 | WGSL shader:\n{}", 122 | value, output, glsl_shader, wgsl_shader, 123 | ); 124 | 125 | panic!("wgpu round-trip failure for {}", T::NAME); 126 | } 127 | } 128 | 129 | fn test_round_trip_std430(&self, glsl_shader: &str, value: &T) { 130 | let mut data = Vec::new(); 131 | data.extend_from_slice(value.as_std430().as_bytes()); 132 | 133 | let wgsl_shader = compile_glsl(glsl_shader); 134 | let bytes = self.round_trip(&wgsl_shader, &data); 135 | 136 | let std430 = bytemuck::from_bytes::<::Output>(&bytes); 137 | let output = T::from_std430(*std430); 138 | 139 | if value != &output { 140 | println!( 141 | "std430 value did not round-trip through wgpu successfully.\n\ 142 | Input: {:?}\n\ 143 | Output: {:?}\n\n\ 144 | GLSL shader:\n{}\n\n\ 145 | WGSL shader:\n{}", 146 | value, output, glsl_shader, wgsl_shader, 147 | ); 148 | 149 | panic!("wgpu round-trip failure for {}", T::NAME); 150 | } 151 | } 152 | 153 | fn round_trip(&self, shader: &str, data: &[u8]) -> Vec { 154 | let input_buffer = self 155 | .device 156 | .create_buffer_init(&wgpu::util::BufferInitDescriptor { 157 | label: Some("Input Buffer"), 158 | contents: &data, 159 | usage: wgpu::BufferUsages::STORAGE 160 | | wgpu::BufferUsages::COPY_DST 161 | | wgpu::BufferUsages::COPY_SRC, 162 | }); 163 | 164 | let output_gpu_buffer = self.device.create_buffer(&wgpu::BufferDescriptor { 165 | label: Some("Output Buffer"), 166 | size: data.len() as wgpu::BufferAddress, 167 | usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, 168 | mapped_at_creation: false, 169 | }); 170 | 171 | let output_cpu_buffer = self.device.create_buffer(&wgpu::BufferDescriptor { 172 | label: Some("Output Buffer"), 173 | size: data.len() as wgpu::BufferAddress, 174 | usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, 175 | mapped_at_creation: false, 176 | }); 177 | 178 | let cs_module = self 179 | .device 180 | .create_shader_module(wgpu::ShaderModuleDescriptor { 181 | label: None, 182 | source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(shader)), 183 | }); 184 | 185 | let compute_pipeline = 186 | self.device 187 | .create_compute_pipeline(&wgpu::ComputePipelineDescriptor { 188 | label: None, 189 | layout: None, 190 | module: &cs_module, 191 | entry_point: "main", 192 | cache: None, 193 | compilation_options: Default::default(), 194 | }); 195 | 196 | let bind_group_layout = compute_pipeline.get_bind_group_layout(0); 197 | let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor { 198 | label: None, 199 | layout: &bind_group_layout, 200 | entries: &[ 201 | wgpu::BindGroupEntry { 202 | binding: 0, 203 | resource: input_buffer.as_entire_binding(), 204 | }, 205 | wgpu::BindGroupEntry { 206 | binding: 1, 207 | resource: output_gpu_buffer.as_entire_binding(), 208 | }, 209 | ], 210 | }); 211 | 212 | let mut encoder = self 213 | .device 214 | .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); 215 | 216 | { 217 | let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor::default()); 218 | cpass.set_pipeline(&compute_pipeline); 219 | cpass.set_bind_group(0, &bind_group, &[]); 220 | cpass.dispatch_workgroups(1, 1, 1); 221 | } 222 | 223 | encoder.copy_buffer_to_buffer( 224 | &output_gpu_buffer, 225 | 0, 226 | &output_cpu_buffer, 227 | 0, 228 | data.len() as wgpu::BufferAddress, 229 | ); 230 | 231 | self.queue.submit(std::iter::once(encoder.finish())); 232 | 233 | let output_slice = output_cpu_buffer.slice(..); 234 | output_slice.map_async(wgpu::MapMode::Read, |res| { 235 | res.unwrap(); 236 | }); 237 | 238 | self.device.poll(wgpu::Maintain::Wait); 239 | let output = output_slice.get_mapped_range().to_vec(); 240 | output_cpu_buffer.unmap(); 241 | 242 | output 243 | } 244 | } 245 | 246 | fn setup() -> (wgpu::Device, wgpu::Queue) { 247 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default()); 248 | let adapter = 249 | block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).unwrap(); 250 | 251 | println!("Adapter info: {:#?}", adapter.get_info()); 252 | 253 | block_on(adapter.request_device( 254 | &wgpu::DeviceDescriptor { 255 | label: None, 256 | required_features: wgpu::Features::empty(), 257 | required_limits: wgpu::Limits::downlevel_defaults(), 258 | memory_hints: wgpu::MemoryHints::Performance, 259 | }, 260 | None, 261 | )) 262 | .unwrap() 263 | } 264 | 265 | fn compile(glsl_source: &str) -> anyhow::Result { 266 | let mut parser = naga::front::glsl::Frontend::default(); 267 | 268 | let module = parser 269 | .parse( 270 | &naga::front::glsl::Options { 271 | stage: naga::ShaderStage::Compute, 272 | defines: Default::default(), 273 | }, 274 | glsl_source, 275 | ) 276 | .map_err(|err| anyhow::format_err!("{:?}", err))?; 277 | 278 | let info = naga::valid::Validator::new( 279 | naga::valid::ValidationFlags::default(), 280 | naga::valid::Capabilities::all(), 281 | ) 282 | .validate(&module)?; 283 | 284 | let wgsl = naga::back::wgsl::write_string( 285 | &module, 286 | &info, 287 | naga::back::wgsl::WriterFlags::EXPLICIT_TYPES, 288 | )?; 289 | 290 | Ok(wgsl) 291 | } 292 | -------------------------------------------------------------------------------- /crevice-derive/src/layout.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::{Span, TokenStream}; 2 | use quote::{format_ident, quote}; 3 | use syn::{parse_quote, Data, DeriveInput, Fields, Ident, Path, Type}; 4 | 5 | pub fn emit( 6 | input: DeriveInput, 7 | trait_name: &'static str, 8 | mod_name: &'static str, 9 | min_struct_alignment: usize, 10 | ) -> TokenStream { 11 | let mod_name = Ident::new(mod_name, Span::call_site()); 12 | let trait_name = Ident::new(trait_name, Span::call_site()); 13 | 14 | let mod_path: Path = parse_quote!(::crevice::#mod_name); 15 | let trait_path: Path = parse_quote!(#mod_path::#trait_name); 16 | 17 | let as_trait_name = format_ident!("As{}", trait_name); 18 | let as_trait_path: Path = parse_quote!(#mod_path::#as_trait_name); 19 | let as_trait_method = format_ident!("as_{}", mod_name); 20 | let from_trait_method = format_ident!("from_{}", mod_name); 21 | 22 | let visibility = input.vis; 23 | let input_name = input.ident; 24 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 25 | 26 | let generated_name = format_ident!("{}{}", trait_name, input_name); 27 | 28 | // Crevice's derive only works on regular structs. We could potentially 29 | // support transparent tuple structs in the future. 30 | let fields: Vec<_> = match &input.data { 31 | Data::Struct(data) => match &data.fields { 32 | Fields::Named(fields) => fields.named.iter().collect(), 33 | Fields::Unnamed(_) => panic!("Tuple structs are not supported"), 34 | Fields::Unit => panic!("Unit structs are not supported"), 35 | }, 36 | Data::Enum(_) | Data::Union(_) => panic!("Only structs are supported"), 37 | }; 38 | 39 | // Gives the layout-specific version of the given type. 40 | let layout_version_of_ty = |ty: &Type| { 41 | quote! { 42 | <#ty as #as_trait_path>::Output 43 | } 44 | }; 45 | 46 | // Gives an expression returning the layout-specific alignment for the type. 47 | let layout_alignment_of_ty = |ty: &Type| { 48 | quote! { 49 | <<#ty as #as_trait_path>::Output as #trait_path>::ALIGNMENT 50 | } 51 | }; 52 | 53 | let field_alignments = fields.iter().map(|field| layout_alignment_of_ty(&field.ty)); 54 | let struct_alignment = quote! { 55 | ::crevice::internal::max_arr([ 56 | #min_struct_alignment, 57 | #(#field_alignments,)* 58 | ]) 59 | }; 60 | 61 | // Generate names for each padding calculation function. 62 | let pad_fns: Vec<_> = (0..fields.len()) 63 | .map(|index| format_ident!("_{}__{}Pad{}", input_name, trait_name, index)) 64 | .collect(); 65 | 66 | // Computes the offset immediately AFTER the field with the given index. 67 | // 68 | // This function depends on the generated padding calculation functions to 69 | // do correct alignment. Be careful not to cause recursion! 70 | let offset_after_field = |target: usize| { 71 | let mut output = vec![quote!(0usize)]; 72 | 73 | for index in 0..=target { 74 | let field_ty = &fields[index].ty; 75 | let layout_ty = layout_version_of_ty(field_ty); 76 | 77 | output.push(quote! { 78 | + ::core::mem::size_of::<#layout_ty>() 79 | }); 80 | 81 | // For every field except our target field, also add the generated 82 | // padding. Padding occurs after each field, so it isn't included in 83 | // this value. 84 | if index < target { 85 | let pad_fn = &pad_fns[index]; 86 | output.push(quote! { 87 | + #pad_fn() 88 | }); 89 | } 90 | } 91 | 92 | output.into_iter().collect::() 93 | }; 94 | 95 | let pad_fn_impls: TokenStream = pad_fns 96 | .iter() 97 | .enumerate() 98 | .map(|(index, pad_fn)| { 99 | let starting_offset = offset_after_field(index); 100 | 101 | let next_field_or_self_alignment = fields 102 | .get(index + 1) 103 | .map(|next_field| layout_alignment_of_ty(&next_field.ty)) 104 | .unwrap_or(quote!(#struct_alignment)); 105 | 106 | quote! { 107 | /// Tells how many bytes of padding have to be inserted after 108 | /// the field with index #index. 109 | #[allow(non_snake_case)] 110 | const fn #pad_fn() -> usize { 111 | // First up, calculate our offset into the struct so far. 112 | // We'll use this value to figure out how far out of 113 | // alignment we are. 114 | let starting_offset = #starting_offset; 115 | 116 | // We set our target alignment to the larger of the 117 | // alignment due to the previous field and the alignment 118 | // requirement of the next field. 119 | let alignment = #next_field_or_self_alignment; 120 | 121 | // Using everything we've got, compute our padding amount. 122 | ::crevice::internal::align_offset(starting_offset, alignment) 123 | } 124 | } 125 | }) 126 | .collect(); 127 | 128 | let generated_struct_fields: TokenStream = fields 129 | .iter() 130 | .enumerate() 131 | .map(|(index, field)| { 132 | let field_name = field.ident.as_ref().unwrap(); 133 | let field_ty = layout_version_of_ty(&field.ty); 134 | let pad_field_name = format_ident!("_pad{}", index); 135 | let pad_fn = &pad_fns[index]; 136 | 137 | quote! { 138 | #field_name: #field_ty, 139 | #pad_field_name: [u8; #pad_fn()], 140 | } 141 | }) 142 | .collect(); 143 | 144 | let generated_struct_field_init: TokenStream = fields 145 | .iter() 146 | .map(|field| { 147 | let field_name = field.ident.as_ref().unwrap(); 148 | 149 | quote! { 150 | #field_name: self.#field_name.#as_trait_method(), 151 | } 152 | }) 153 | .collect(); 154 | 155 | let input_struct_field_init: TokenStream = fields 156 | .iter() 157 | .map(|field| { 158 | let field_name = field.ident.as_ref().unwrap(); 159 | 160 | quote! { 161 | #field_name: #as_trait_path::#from_trait_method(input.#field_name), 162 | } 163 | }) 164 | .collect(); 165 | 166 | let struct_definition = quote! { 167 | #[derive(Debug, Clone, Copy)] 168 | #[repr(C)] 169 | #[doc(hidden)] 170 | #[allow(warnings)] 171 | #visibility struct #generated_name #ty_generics #where_clause { 172 | #generated_struct_fields 173 | } 174 | }; 175 | 176 | let debug_methods = if cfg!(feature = "debug-methods") { 177 | let debug_fields: TokenStream = fields 178 | .iter() 179 | .map(|field| { 180 | let field_name = field.ident.as_ref().unwrap(); 181 | let field_ty = &field.ty; 182 | 183 | quote! { 184 | fields.push(Field { 185 | name: stringify!(#field_name), 186 | size: ::core::mem::size_of::<#field_ty>(), 187 | offset: (&zeroed.#field_name as *const _ as usize) 188 | - (&zeroed as *const _ as usize), 189 | }); 190 | } 191 | }) 192 | .collect(); 193 | 194 | quote! { 195 | impl #impl_generics #generated_name #ty_generics #where_clause { 196 | fn debug_metrics() -> String { 197 | let size = ::core::mem::size_of::(); 198 | let align = ::ALIGNMENT; 199 | 200 | let zeroed: Self = ::crevice::internal::bytemuck::Zeroable::zeroed(); 201 | 202 | #[derive(Debug)] 203 | struct Field { 204 | name: &'static str, 205 | offset: usize, 206 | size: usize, 207 | } 208 | let mut fields = Vec::new(); 209 | 210 | #debug_fields 211 | 212 | format!("Size {}, Align {}, fields: {:#?}", size, align, fields) 213 | } 214 | 215 | fn debug_definitions() -> &'static str { 216 | stringify!( 217 | #struct_definition 218 | #pad_fn_impls 219 | ) 220 | } 221 | } 222 | } 223 | } else { 224 | quote!() 225 | }; 226 | 227 | quote! { 228 | #pad_fn_impls 229 | #struct_definition 230 | 231 | impl #impl_generics #generated_name #ty_generics #where_clause { 232 | #[allow(warnings)] 233 | pub fn as_bytes(&self) -> &[u8] { 234 | <#generated_name #ty_generics as #trait_path>::as_bytes(self) 235 | } 236 | } 237 | 238 | unsafe impl #impl_generics ::crevice::internal::bytemuck::Zeroable for #generated_name #ty_generics #where_clause {} 239 | unsafe impl #impl_generics ::crevice::internal::bytemuck::Pod for #generated_name #ty_generics #where_clause {} 240 | 241 | unsafe impl #impl_generics #trait_path for #generated_name #ty_generics #where_clause { 242 | const ALIGNMENT: usize = #struct_alignment; 243 | } 244 | 245 | impl #impl_generics #as_trait_path for #input_name #ty_generics #where_clause { 246 | type Output = #generated_name; 247 | 248 | fn #as_trait_method(&self) -> Self::Output { 249 | Self::Output { 250 | #generated_struct_field_init 251 | 252 | ..::crevice::internal::bytemuck::Zeroable::zeroed() 253 | } 254 | } 255 | 256 | fn #from_trait_method(input: Self::Output) -> Self { 257 | Self { 258 | #input_struct_field_init 259 | } 260 | } 261 | } 262 | 263 | #debug_methods 264 | } 265 | } 266 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | i Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------