shdrlib 0.2.0

High-level shader compilation and rendering library built on wgpu and naga
Documentation
# shdrlib


A high-level shader compilation and rendering library for Rust, built on top of `wgpu` and `naga`. shdrlib abstracts away the complexity of GPU programming, allowing developers to focus on shader logic rather than boilerplate setup.

## Overview


shdrlib provides a streamlined API for shader compilation, pipeline management, and GPU-accelerated rendering. The library handles device initialization, shader validation, pipeline configuration, and render execution with minimal user intervention.

**Key Features:**
- Multi-language shader support (WGSL, GLSL, SPIR-V)
- Automatic GPU device and queue management
- Pipeline builder pattern for render configuration
- Asset management system for shaders and pipelines
- Offscreen and window-based rendering support

## Architecture


The library is organized into three primary modules:

### Frontend (`front/`)

Handles shader parsing and compilation to Naga IR:
- `compiler.rs`: Parses WGSL, GLSL, and SPIR-V into Naga's intermediate representation
- `storage.rs`: Provides `ShaderObject` wrapper for compiled shader data

### Backend (`back/`)

Manages wgpu integration:
- `device.rs`: GPU device, queue, and adapter initialization
- `shader.rs`: Conversion from Naga IR to wgpu shader modules
- `pipeline.rs`: Builder pattern for render pipeline configuration

### Managers (`managers/`)

High-level API for asset and runtime management:
- `asset_manager.rs`: Stores and manages shaders and pipelines by name
- `runtime_manager.rs`: Executes render passes and manages surface rendering

## Installation


Add shdrlib to your `Cargo.toml`:

```toml
[dependencies]
shdrlib = "0.2.0"
```

## Usage


### Basic Example


```rust
use shdrlib::{AssetManager, RuntimeManager, Language};

fn main() {
    // Define your shader
    let shader_source = r#"
        @vertex
        fn vs_main(@builtin(vertex_index) idx: u32) -> @builtin(position) vec4<f32> {
            var positions = array<vec2<f32>, 3>(
                vec2(0.0, 0.5), vec2(-0.5, -0.5), vec2(0.5, -0.5)
            );
            return vec4<f32>(positions[idx], 0.0, 1.0);
        }

        @fragment
        fn fs_main() -> @location(0) vec4<f32> {
            return vec4<f32>(1.0, 0.0, 0.5, 1.0);
        }
    "#;

    // Initialize asset manager (handles GPU setup automatically)
    let mut assets = AssetManager::new();

    // vertex example 
    assets.add_shader(
        "vertex",
        shader_source,
        naga::ShaderStage::Vertex,
        Language::WGSL,
    ).unwrap();
    // fragment example 
    assets.add_shader(
        "fragment",
        shader_source,
        naga::ShaderStage::Fragment,
        Language::WGSL,
    ).unwrap();

    // Create render pipeline
    assets.create_pipeline(
        "main_pipeline",
        "vertex",
        Some("fragment"),
        vec![],
        wgpu::TextureFormat::Rgba8UnormSrgb,
    ).unwrap();

    // Render to texture
    let runtime = RuntimeManager::new(&assets);
    let texture = runtime.render_to_texture(
        "main_pipeline",
        800,
        600,
        wgpu::TextureFormat::Rgba8UnormSrgb,
        wgpu::Color::BLACK,
        3,
    ).unwrap();

    println!("Rendered texture: {}x{}", texture.width(), texture.height());
}
```

### Window Rendering


For window-based rendering with `winit`, see `examples/window_demo.rs`.

### Supported Shader Languages


- **WGSL**: WebGPU Shading Language (recommended)
- **GLSL**: OpenGL Shading Language
- **SPIR-V**: Binary intermediate representation

## Examples


The repository includes several examples demonstrating different use cases:

- `minimal_usage.rs`: Minimal offscreen rendering example
- `triangle_demo.rs`: Complete offscreen render with pixel readback
- `window_demo.rs`: Real-time window rendering with `winit`

Run an example:
```bash
cargo run --example minimal_usage
```

## Design Goals


shdrlib aims to reduce the verbosity of GPU programming without sacrificing control. The library handles initialization and resource management while exposing key configuration options for pipeline customization.

**Comparison to raw wgpu:**
- Raw wgpu setup: ~150-200 lines for basic rendering
- shdrlib setup: ~10 lines of actual configuration code

The library is suitable for:
- Rapid prototyping of shader effects
- Educational purposes and shader experimentation
- Applications requiring simplified GPU access
- Research projects involving shader compilation pipelines

## Dependencies


- `wgpu` (v22): Cross-platform GPU API
- `naga` (v22): Shader translation and validation
- `pollster` (v0.3): Blocking executor for async operations
- `winit` (v0.30): Window creation (optional, for examples)

## Testing


Run the test suite:
```bash
cargo test
```

Tests verify shader compilation, GPU device initialization, and pipeline creation.

## License

This project is licensed under the MIT License. It’s provided as-is

## Contributing


Contributions are welcome. Please ensure code follows existing patterns and includes appropriate tests.

## Acknowledgments


Built on the wgpu and naga projects, which provide the underlying GPU abstraction and shader infrastructure.