Expand description
ยงwgsl_bindgen
๐ Generate typesafe Rust bindings from WGSL shaders for wgpu
wgsl_bindgen transforms your WGSL shader development workflow by automatically generating Rust types, constants, and boilerplate code that perfectly match your shaders. Powered by naga-oil, it integrates seamlessly into your build process to catch shader-related errors at compile time rather than runtime.
ยง๐ฏ Key Benefits
- ๐ก๏ธ Type Safety: Catch shader binding mismatches at compile time
- ๐ Automatic Sync: Changes to WGSL automatically update Rust bindings
- ๐ Reduced Boilerplate: Generate tedious wgpu setup code automatically
- ๐ฎ Shader-First Workflow: Design in WGSL, get Rust bindings for free
- ๐ง Flexible: Works with bytemuck, encase, serde, and custom types
- โก Fast: Build-time generation with intelligent caching
ยง๐ Quick Example
WGSL Shader (shaders/my_shader.wgsl
):
struct Uniforms {
transform: mat4x4<f32>,
time: f32,
}
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var my_texture: texture_2d<f32>;
@group(0) @binding(2) var my_sampler: sampler;
Build Script (build.rs
):
use wgsl_bindgen::{WgslBindgenOptionBuilder, WgslTypeSerializeStrategy, GlamWgslTypeMap};
fn main() -> Result<(), Box<dyn std::error::Error>> {
WgslBindgenOptionBuilder::default()
.workspace_root("shaders")
.add_entry_point("shaders/my_shader.wgsl")
.serialization_strategy(WgslTypeSerializeStrategy::Bytemuck)
.type_map(GlamWgslTypeMap)
.output("src/shader_bindings.rs")
.build()?
.generate()?;
Ok(())
}
Generated Rust Usage:
โ
// Fully type-safe bindings generated from your WGSL!
let bind_group = my_shader::WgpuBindGroup0::from_bindings(
device,
my_shader::WgpuBindGroup0Entries::new(my_shader::WgpuBindGroup0EntriesParams {
uniforms: uniform_buffer.as_entire_binding(),
my_texture: &texture_view, // Type-checked parameter names
my_sampler: &sampler, // Matches your WGSL exactly
})
);
bind_group.set(&mut render_pass); // Simple, safe usage
ยง๐ฆ Generated Code Features
The code generated by wgsl_bindgen provides:
ยงType Safety & Validation
- โ Compile-time struct layout validation when using bytemuck
- โ Type-safe bind group creation with named parameters
- โ Automatic vertex attribute setup with correct offsets and formats
- โ Pipeline layout generation matching your shaderโs resource bindings
ยงConvenience & Ergonomics
- ๐ง Shader module creation with embedded or file-based sources
- ๐ง Entry point helpers for vertex/fragment/compute stages
- ๐ง Constructor functions for structs with proper padding
- ๐ง Bind group helpers for setting individual or multiple groups
ยงFlexibility & Customization
- ๐๏ธ Multiple serialization strategies (bytemuck, encase)
- ๐๏ธ Custom type mapping (glam, nalgebra, custom types)
- ๐๏ธ Struct field overrides for specific use cases
- ๐๏ธ Import system support via naga-oil composer
ยง๐ ๏ธ Configuration Options
ยงBasic Configuration
WgslBindgenOptionBuilder::default()
.workspace_root("shaders") // Shader directory
.add_entry_point("shader.wgsl") // Add shader files
.output("src/bindings.rs") // Output file
.build()?
.generate()?;
ยงAdvanced Configuration
WgslBindgenOptionBuilder::default()
.workspace_root("shaders")
.add_entry_point("pbr.wgsl")
.add_entry_point("postfx.wgsl")
// Serialization strategy
.serialization_strategy(WgslTypeSerializeStrategy::Bytemuck)
// Math library integration
.type_map(GlamWgslTypeMap)
// Custom type overrides
.override_struct_field_type(vec![
("MyStruct", "my_field", quote!(MyCustomType)).into()
])
// Shader embedding options
.shader_source_type(WgslShaderSourceType::EmbedSource)
// Optional features
.derive_serde(true)
.short_constructor(2)
.skip_hash_check(false)
.output("src/shaders.rs")
.build()?
.generate()?;
ยง๐ Error Handling
wgsl_bindgen provides detailed error reporting for common issues:
- Shader compilation errors with source location information
- Bind group validation (consecutive indices, no duplicates)
- Type mapping failures with suggestions for fixes
- Import resolution errors with detailed path resolution info
ยง๐ See Also
- Repository - Source code and issues
- Example Project - Complete working demo
- WGSL Specification - WebGPU Shading Language reference
- wgpu Documentation - WebGPU implementation for Rust
Modulesยง
Macrosยง
Structsยง
- Additional
Scan Directory - A struct representing a directory to scan for additional source files.
- Bind
Group Layout Generator - Represents a generator for creating WGSL bind group layout structures.
- Binding
Generator - Glam
Wgsl Type Map glam
types likeglam::Vec4
orglam::Mat4
. Types not representable byglam
likemat2x3<f32>
will use the output from RustWgslTypeMap.- Import
Path Part - Import part path used in the import statement
- Nalgebra
Wgsl Type Map nalgebra
types likenalgebra::SVector<f64, 4>
ornalgebra::SMatrix<f32, 2, 3>
.- Override
Bind Group Entry Module Path - Struct for overriding binding module path of bindgroup entry
- Override
Sampler Type - Struct for overriding sampler types for specific bindings
- Override
Struct - This struct is used to create a custom mapping from the wgsl side to rust side, skipping generation of the struct and using the custom one instead. This also means skipping checks for alignment and size when using bytemuck for the struct. This is useful for core primitive types you would want to model in Rust side
- Override
Struct Alignment - Struct for overriding alignment of specific structs.
- Override
Struct Field Type - Struct for overriding the field type of specific structs.
- Override
Texture Filterability - Struct for overriding texture filterability for specific bindings
- Pipeline
Layout Generator - Regex
- A compiled regular expression for searching Unicode haystacks.
- Rust
Wgsl Type Map - Rust types like
[f32; 4]
or[[f32; 4]; 4]
. - Source
File Dir - Source
File Path - Source
Location - Source
Module Name - WGSL
Bindgen - Wgpu
GetBindings Generator Config - Wgsl
Bindgen Option - Wgsl
Bindgen Option Builder - Builder for
WgslBindgenOption
. - Wgsl
MatType Iter - An iterator over the variants of WgslMatType
- Wgsl
Shader IrCapabilities - Allowed IR capabilities.
- Wgsl
Type Info - Information about a WGSL type including its Rust representation, size, and alignment
- Wgsl
VecType Iter - An iterator over the variants of WgslVecType
Enumsยง
- Bind
Resource Type - Create
Module Error - Errors while generating Rust source for a WGSl shader module.
- Sampler
Type - Enum for sampler binding types
- Shader
DefValue - Wgsl
Bindgen Error - Enum representing the possible errors that can occur in the
wgsl_bindgen
process. - Wgsl
Bindgen Option Builder Error - Error type for WgslBindgenOptionBuilder
- Wgsl
MatType - The
WgslType
enum represents various Wgsl matrices. See spec - Wgsl
Shader Source Type - An enum representing the source type that will be generated for the output.
- Wgsl
Type - The
WgslType
enum represents various WGSL types, such as vectors and matrices. See spec - Wgsl
Type Serialize Strategy - Enum representing the possible serialization strategies for WGSL types.
- Wgsl
Type Visibility - An enum representing the visibility of the type generated in the output
- Wgsl
VecType - The
WgslType
enum represents various WGSL vectors. See spec
Traitsยง
- GetBindings
Generator Config - Wgsl
Type MapBuild - A trait for building
WgslType
toTokenStream
map.
Functionsยง
Type Aliasesยง
- Fast
Index Map - Insertion-order-preserving hash map (
IndexMap<K, V>
), but with the same hasher asFastHashMap<K, V>
(faster but not resilient to DoS attacks). - FxIndex
Map - FxIndex
Set - Wgsl
Type Map