### Setup Bind Group with WGSL Bindings Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md This example demonstrates creating a wgpu bind group using generated types for type-safe uniform buffers, textures, and samplers. It utilizes generated structs and methods for creating and populating the bind group. ```rust use shader_bindings::my_shader; fn setup_bind_group(device: &wgpu::Device, texture_view: &wgpu::TextureView, sampler: &wgpu::Sampler) -> my_shader::WgpuBindGroup0 { // Create uniform buffer with generated struct let uniforms = my_shader::Uniforms::new( glam::Mat4::IDENTITY, // transform 0.0, // time ); let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { contents: bytemuck::cast_slice(&[uniforms]), usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, }); // Create bind group using generated types - fully type-safe! my_shader::WgpuBindGroup0::from_bindings( device, my_shader::WgpuBindGroup0Entries::new(my_shader::WgpuBindGroup0EntriesParams { uniforms: wgpu::BufferBinding { buffer: &uniform_buffer, offset: 0, size: None, }, my_texture: texture_view, my_sampler: sampler, }) ) } ``` -------------------------------- ### Setup Render Pipeline with WGSL Bindings Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md This snippet shows how to create a wgpu render pipeline using generated bindings from WGSL shaders. It includes using the generated shader module, pipeline layout, and vertex entry points, ensuring type safety and proper buffer layouts. ```rust mod shader_bindings; use shader_bindings::my_shader; fn setup_render_pipeline(device: &wgpu::Device, surface_format: wgpu::TextureFormat) -> wgpu::RenderPipeline { // Create shader module from generated code let shader = my_shader::create_shader_module_embed_source(device); // Use generated pipeline layout let pipeline_layout = my_shader::create_pipeline_layout(device); // Use generated vertex entry with proper buffer layout let vertex_entry = my_shader::vs_main_entry(wgpu::VertexStepMode::Vertex); device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { layout: Some(&pipeline_layout), vertex: my_shader::vertex_state(&shader, &vertex_entry), fragment: Some(my_shader::fragment_state(&shader, &my_shader::fs_main_entry([ Some(wgpu::ColorTargetState { format: surface_format, blend: Some(wgpu::BlendState::REPLACE), write_mask: wgpu::ColorWrites::ALL, }) ]))), // ... other pipeline state }) } ``` -------------------------------- ### File Visitor Pattern for Shader Processing Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md Provides an example of using the `visit_shader_files` function from wgsl-bindgen to process shader files. This pattern is useful for advanced use cases like hot reloading, caching, debugging, and custom asset systems. ```Rust use shader_bindings::visit_shader_files; visit_shader_files( "shaders", ShaderEntry::MyShader, |path| std::fs::read_to_string(path), |file_path, file_content| { println!("Processing shader: {}", file_path); // Add to file watcher, cache, etc. } )?; ``` -------------------------------- ### Generate WGSL Bindings with wgsl-bindgen Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md This Rust code snippet demonstrates how to use the wgsl-bindgen library to generate bindings from WGSL shader files. It configures options such as the workspace root, entry points, serialization strategy (Bytemuck), type mapping (GlamWgslTypeMap), and the output file path. The example assumes the use of the 'miette' crate for error handling. ```rust use miette::{IntoDiagnostic, Result}; use wgsl_bindgen::{WgslTypeSerializeStrategy, WgslBindgenOptionBuilder, GlamWgslTypeMap}; // src/build.rs fn main() -> Result<()> { WgslBindgenOptionBuilder::default() .workspace_root("src/shader") .add_entry_point("src/shader/testbed.wgsl") .add_entry_point("src/shader/triangle.wgsl") .serialization_strategy(WgslTypeSerializeStrategy::Bytemuck) .type_map(GlamWgslTypeMap) .derive_serde(false) .output("src/shader.rs") .build()? .generate() .into_diagnostic() } ``` -------------------------------- ### Load Naga Module with Custom File Loader Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md This Rust code illustrates how to load a Naga module from a specified path using a custom file loading function. It shows two examples: one using standard file system reading and another using a custom asset manager. ```rust // In your application code let module = main::load_naga_module_from_path( "assets/shaders", // Base directory ShaderEntry::Main, // Entry point enum variant &mut composer, shader_defs, |path| std::fs::read_to_string(path), // Your custom file loader )?; // Or use your own asset system let module = main::load_naga_module_from_path( "shaders", ShaderEntry::Main, &mut composer, shader_defs, |path| asset_manager.load_text_file(path), // Custom asset manager )?; ``` -------------------------------- ### Configure wgsl-bindgen Build Script Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md Sets up the build script to generate Rust bindings from WGSL shaders. It configures the workspace root, entry points, serialization strategy, type mapping (using glam), and output file. ```rust use wgsl_bindgen::{WgslBindgenOptionBuilder, WgslTypeSerializeStrategy, GlamWgslTypeMap}; fn main() -> Result<(), Box> { WgslBindgenOptionBuilder::default() .workspace_root("shaders") .add_entry_point("shaders/my_shader.wgsl") .serialization_strategy(WgslTypeSerializeStrategy::Bytemuck) .type_map(GlamWgslTypeMap) // Use glam for math types .output("src/shader_bindings.rs") .build()? .generate()?; Ok(()) } ``` -------------------------------- ### Manual WGSL Bindings (Before) Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md Demonstrates the manual and error-prone process of creating WGSL bind groups in Rust before using wgsl-bindgen. This highlights the potential for mistakes in binding indices and resource types. ```Rust let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { entries: &[ wgpu::BindGroupEntry { binding: 0, // Is this the right binding index? resource: texture_view.as_binding(), // Is this the right type? }, wgpu::BindGroupEntry { binding: 1, // What if you change the shader? resource: sampler.as_binding(), }, ], // ... more boilerplate }); ``` -------------------------------- ### Configure Serialization Strategy Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md Demonstrates how to configure the serialization strategy for WGSL types to Rust, choosing between compile-time verified layouts with `Bytemuck` or runtime padding/alignment handling with `Encase`. ```rust // For zero-copy, compile-time verified layouts (recommended) .serialization_strategy(WgslTypeSerializeStrategy::Bytemuck) // For runtime padding/alignment handling .serialization_strategy(WgslTypeSerializeStrategy::Encase) ``` -------------------------------- ### Add wgsl-bindgen to Cargo.toml Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md Specifies the build and regular dependencies required for using wgsl-bindgen, including the crate itself, wgpu, and bytemuck. ```toml [build-dependencies] wgsl_bindgen = "0.19" [dependencies] wgpu = "25" bytemuck = { version = "1.0", features = ["derive"] } # Optional: for additional features # encase = "0.8" # serde = { version = "1.0", features = ["derive"] } # Note: When using ComposerWithRelativePath, enable naga-ir feature for optimal performance: # wgpu = { version = "25", features = ["naga-ir"] } ``` -------------------------------- ### Seamless Struct Integration with wgpu (Rust) Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md Shows how generated structs from wgsl_bindgen integrate seamlessly with wgpu, allowing for type-safe creation of vertex data. ```rust // Generated structs work seamlessly with wgpu let vertices = vec![ my_shader::VertexInput::new(glam::Vec3::ZERO, glam::Vec2::ZERO), my_shader::VertexInput::new(glam::Vec3::X, glam::Vec2::X), my_shader::VertexInput::new(glam::Vec3::Y, glam::Vec2::Y), ]; ``` -------------------------------- ### WGSL Shader Definition Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md Defines WGSL structs for uniforms and vertex inputs/outputs, along with shader entry points for vertex and fragment stages, demonstrating texture sampling and uniform data usage. ```wgsl struct Uniforms { transform: mat4x4, time: f32, } struct VertexInput { @location(0) position: vec3, @location(1) uv: vec2, } struct VertexOutput { @builtin(position) clip_position: vec4, @location(0) uv: vec2, } @group(0) @binding(0) var uniforms: Uniforms; @group(0) @binding(1) var my_texture: texture_2d; @group(0) @binding(2) var my_sampler: sampler; @vertex fn vs_main(input: VertexInput) -> VertexOutput { var output: VertexOutput; output.clip_position = uniforms.transform * vec4(input.position, 1.0); output.uv = input.uv; return output; } @fragment fn fs_main(input: VertexOutput) -> @location(0) vec4 { return textureSample(my_texture, my_sampler, input.uv); } ``` -------------------------------- ### Configure Type Mapping for Math Libraries Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md Shows how to configure type mapping to use different math libraries like `glam` (recommended for games), `nalgebra` (recommended for scientific computing), or built-in Rust arrays. ```rust // glam (recommended for games) .type_map(GlamWgslTypeMap) // nalgebra (recommended for scientific computing) .type_map(NalgebraWgslTypeMap) // Use built-in Rust arrays (no external dependencies) .type_map(RustWgslTypeMap) ``` -------------------------------- ### Use RenderBundles for Static Geometry (Rust) Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md Demonstrates using RenderBundles to efficiently handle static geometry in wgpu. A RenderBundleEncoder is created, bind groups are set, and draw calls are recorded before finishing the bundle. ```rust let render_bundle = device.create_render_bundle_encoder(&descriptor); bind_group.set(&mut render_bundle); render_bundle.draw(0..vertex_count, 0..1); let bundle = render_bundle.finish(&descriptor); ``` -------------------------------- ### Prefer bytemuck for Zero-Copy Performance (Rust) Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md Configures wgsl_bindgen to use bytemuck for serialization, enabling zero-copy performance for shader data. ```rust .serialization_strategy(WgslTypeSerializeStrategy::Bytemuck) ``` -------------------------------- ### Configure Shader Source Embedding Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md Explains different strategies for embedding WGSL shader source code, including direct embedding, using file paths for hot-reloading, employing Naga-oil composer, or using relative paths with custom file loading. ```rust // Embed shader source directly (recommended for most cases) .shader_source_type(WgslShaderSourceType::EmbedSource) // Use file paths for hot-reloading during development .shader_source_type(WgslShaderSourceType::HardCodedFilePath) // Use naga-oil composer for advanced import features .shader_source_type(WgslShaderSourceType::EmbedWithNagaOilComposer) // Use relative paths with custom file loading (no nightly Rust required) // Requires wgpu "naga-ir" feature for optimal performance .shader_source_type(WgslShaderSourceType::ComposerWithRelativePath) ``` -------------------------------- ### Typesafe WGSL Bindings (After) Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md Illustrates the typesafe and auto-generated approach to WGSL bind groups using wgsl-bindgen. This shows how generated code ensures compile-time safety and exact matching with WGSL shader definitions. ```Rust let bind_group = my_shader::WgpuBindGroup0::from_bindings( device, my_shader::WgpuBindGroup0Entries::new(my_shader::WgpuBindGroup0EntriesParams { my_texture: &texture_view, // Type-checked parameter names my_sampler: &sampler, // Matches your WGSL exactly }) ); bind_group.set(&mut render_pass); // Simple, safe usage ``` -------------------------------- ### Enable wgpu naga-ir Feature Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md This TOML snippet shows how to enable the 'naga-ir' feature for the wgpu dependency in your Cargo.toml file. This feature is used by wgsl-bindgen for performance optimizations by passing Naga IR modules directly to the GPU. ```toml [dependencies] wgpu = { version = "25", features = ["naga-ir"] } ``` -------------------------------- ### Update Uniforms Safely with Type Checking (Rust) Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md Illustrates updating uniform buffers safely using generated types from wgsl_bindgen, ensuring type correctness during the process. ```rust // Update uniforms safely with type checking let uniforms = my_shader::Uniforms::new( camera.view_projection_matrix(), time.elapsed_secs(), ); queue.write_buffer(&uniform_buffer, 0, bytemuck::cast_slice(&[uniforms])); ``` -------------------------------- ### Include Generated Bindings in Rust Project Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md This Rust code snippet shows how to include the generated shader bindings into a project's main source file. It uses a module declaration to bring the generated code into scope. ```rust // src/lib.rs mod shader; ``` -------------------------------- ### Organize Bind Groups by Update Frequency (Rust) Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md Organizes bind groups based on their update frequency to optimize rendering. Bind group 0 is for per-frame data, bind group 1 for per-material, and bind group 2 for per-object data. ```rust // Bind group 0: Per-frame data (transforms, time) // Bind group 1: Per-material data (textures, material properties) // Bind group 2: Per-object data (model matrices, instance data) ``` -------------------------------- ### Configure Shader Source Type in build.rs Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md This Rust code snippet demonstrates how to set the shader source type to WgslShaderSourceType::ComposerWithRelativePath in your build.rs file. This configuration enables custom file loading logic for shaders. ```rust // In your build.rs .shader_source_type(WgslShaderSourceType::ComposerWithRelativePath) ``` -------------------------------- ### Rust PaddedField Struct for WGSL Alignment Source: https://github.com/swoorup/wgsl-bindgen/blob/main/TODO.md Defines a generic `PaddedField` struct in Rust to manage field alignment and padding, potentially for use with WGSL. This structure helps in creating memory layouts that are compatible with shader requirements. ```Rust #[repr(C)] struct PaddedField { field: T, padding: [u8; N], } impl PaddedField { pub fn new(value: T) -> Self { Self { field: value, padding: [0; N], } } } ``` -------------------------------- ### Configure Custom Type Overrides Source: https://github.com/swoorup/wgsl-bindgen/blob/main/README.md Illustrates how to override specific WGSL struct field types or map WGSL structs to custom Rust structs for greater flexibility in type handling. ```rust .override_struct_field_type([ ("MyStruct", "my_field", quote!(MyCustomType)) ]) .add_override_struct_mapping(("MyWgslStruct", quote!(my_crate::MyRustStruct))) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.