shdrlib 0.1.5

A three-tiered Vulkan shader compilation and rendering framework built in pure Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# Error Handling in shdrlib


shdrlib provides **rich, user-friendly error messages** across all three tiers. This guide explains how to handle errors effectively.

## Overview


Each tier has progressively more helpful error messages:
- **CORE**: Wraps raw Vulkan error codes
- **EX**: Adds context and suggestions 
- **EZ**: Provides beginner-friendly explanations with step-by-step recovery

## Error Types by Tier


### EZ Tier Errors


EZ errors are designed for maximum friendliness:

```rust
use shdrlib::ez::*;

fn main() -> Result<(), EzError> {
    // EZ errors include:
    // - Clear explanation of what went wrong
    // - Common causes
    // - Step-by-step solutions
    // - Links to documentation
    
    let mut renderer = EzRenderer::new(EzConfig::default())?;
    
    // If initialization fails, you'll see:
    // ❌ Failed to initialize Vulkan renderer
    //
    // What happened:
    // Instance creation failed: ...
    //
    // Common causes:
    // • Vulkan runtime not installed
    // • Outdated GPU drivers
    // • GPU doesn't support Vulkan 1.3
    //
    // Try these fixes:
    // 1. Update your GPU drivers
    // 2. Download and install Vulkan SDK
    // ...
    
    Ok(())
}
```

### EX Tier Errors


EX errors provide context without being overwhelming:

```rust
use shdrlib::ex::*;

fn main() -> Result<(), RuntimeError> {
    let runtime = RuntimeManager::new(RuntimeConfig::default())?;
    
    // EX errors include:
    // - What operation failed
    // - Underlying cause
    // - Actionable suggestions
    // - Technical context
    
    Ok(())
}
```

### CORE Tier Errors


CORE errors are thin wrappers around Vulkan errors:

```rust
use shdrlib::core::*;

// CORE errors expose raw Vulkan result codes
// but still provide context about the operation
```

## Error Handling Patterns


### Basic Error Propagation


The simplest approach - just propagate errors:

```rust
use shdrlib::ez::*;

fn render_frame(renderer: &mut EzRenderer) -> Result<(), EzError> {
    renderer.render_frame(|frame| {
        // Your rendering code
        Ok(())
    })?; // Propagate any errors
    
    Ok(())
}
```

### Custom Error Handling


Handle specific errors differently:

```rust
use shdrlib::ez::*;

fn main() {
    let mut renderer = match EzRenderer::new(EzConfig::default()) {
        Ok(r) => r,
        Err(EzError::InitializationFailed { details }) => {
            eprintln!("Failed to initialize: {}", details);
            eprintln!("Make sure Vulkan is installed!");
            return;
        }
        Err(e) => {
            eprintln!("Unexpected error: {}", e);
            return;
        }
    };
    
    // ... use renderer
}
```

### Shader Compilation Errors


Shader errors show exactly what's wrong:

```rust
use shdrlib::ez::*;

fn compile_shaders(renderer: &mut EzRenderer) -> Result<(), EzError> {
    let vert = r#"
        #version 450
        layout(location = 0) in vec3 position;
        
        void main() {
            gl_Position = vec4(position, 1.0);
        }
    "#;
    
    match renderer.add_shader(vert, ShaderStage::Vertex) {
        Ok(shader) => Ok(()),
        Err(EzError::ShaderCompilationFailed { details }) => {
            // You'll see:
            // ❌ Shader compilation failed
            //
            // Details:
            // Line 4: undeclared identifier 'position'
            //
            // Debugging tips:
            // • Check variable declarations
            // • Verify shader version is #version 450
            // ...
            
            eprintln!("Shader error: {}", details);
            Err(EzError::ShaderCompilationFailed { details })
        }
        Err(e) => Err(e),
    }
}
```

### Validation Errors


Enable validation layers for detailed diagnostics:

```rust
use shdrlib::ez::*;

fn main() -> Result<(), EzError> {
    let config = EzConfig {
        enable_validation: true, // Enable validation layers
        ..Default::default()
    };
    
    let renderer = EzRenderer::new(config)?;
    
    // Now you'll get validation errors if you misuse the API:
    // ❌ Vulkan Validation Error
    //
    // Message ID: VUID-vkBeginCommandBuffer-commandBuffer-00049
    // Severity: ERROR
    //
    // Command buffer is already in recording state
    //
    // What are validation errors?
    // Validation layers catch API misuse before it crashes.
    // These errors are CRITICAL and must be fixed!
    
    Ok(())
}
```

## EX Tier: Advanced Error Context


The EX tier includes helper utilities for building error traces:

```rust
use shdrlib::ex::*;
use shdrlib::ex::helpers::*;

fn create_buffer_with_context() -> Result<(), RuntimeError> {
    // Use with_context! macro for automatic file/line tracking
    let buffer = create_buffer()
        .with_context!("creating vertex buffer")?;
    
    // If this fails, you'll see:
    // ╔════════════════════════════════════════════════════════════╗
    // ║ ERROR TRACEBACK                                            ║
    // ╠════════════════════════════════════════════════════════════╣
    //
    // ❯ creating vertex buffer
    //   at src/main.rs:42:9
    //
    // ❯ allocating device memory
    //   at src/memory.rs:156:13
    //
    // ╠════════════════════════════════════════════════════════════╣
    // ║ ROOT CAUSE                                                 ║
    // ╠════════════════════════════════════════════════════════════╣
    //
    // ERROR_OUT_OF_DEVICE_MEMORY
    // The GPU has run out of video memory (VRAM)
    // ...
    
    Ok(())
}
```

## Vulkan Error Code Reference


The library includes friendly explanations for all Vulkan error codes:

```rust
use shdrlib::ex::helpers::vk_result::VkErrorInfo;
use ash::vk;

// Get detailed info about any Vulkan error
let info = VkErrorInfo::from_result(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY);

println!("{}", info);
// Vulkan Error: ERROR_OUT_OF_DEVICE_MEMORY (ERROR_OUT_OF_DEVICE_MEMORY)
// The GPU has run out of video memory (VRAM)
//
// Possible causes:
//   • Allocating too many buffers or textures
//   • Creating large render targets
//   • Not freeing resources
//   • GPU has limited VRAM
//
// Suggested solutions:
//   → Reduce texture sizes or use compression
//   → Free unused buffers and images
//   → Use memory budget queries to track usage
//   → Consider streaming assets instead of loading all at once
```

## Best Practices


### 1. Always Handle Errors


Don't ignore errors - they provide critical information:

```rust
// ❌ BAD - silently ignores errors
let _ = renderer.render_frame(|frame| Ok(()));

// ✅ GOOD - handles or propagates
renderer.render_frame(|frame| Ok(()))?;
```

### 2. Enable Validation in Development


Always use validation layers during development:

```rust
let config = EzConfig {
    enable_validation: cfg!(debug_assertions), // Auto-enable in debug builds
    ..Default::default()
};
```

### 3. Provide Context


When building libraries on top of shdrlib, add your own context:

```rust
fn load_model(path: &str) -> Result<Model, MyError> {
    let buffer = create_buffer()
        .map_err(|e| MyError::BufferCreation {
            path: path.to_string(),
            source: e,
        })?;
    
    // ...
}
```

### 4. Display Errors Nicely


For end-user applications, format errors nicely:

```rust
use shdrlib::ez::*;

fn main() {
    if let Err(e) = run() {
        // EZ errors already have nice formatting
        eprintln!("{}", e);
        std::process::exit(1);
    }
}

fn run() -> Result<(), EzError> {
    // Your application code
    Ok(())
}
```

### 5. Log Validation Messages


Set up validation message callbacks for detailed diagnostics:

```rust
// The library automatically prints validation messages to stderr
// when validation layers are enabled.
//
// You can also set up custom callbacks at the CORE tier
// for logging to a file or custom logger.
```

## Common Error Scenarios


### Out of Memory


```
ERROR_OUT_OF_DEVICE_MEMORY

Possible causes:
• Too many textures loaded
• Buffers not being freed
• Resource leak

Solutions:
→ Free unused resources with .destroy()
→ Use smaller textures
→ Track memory usage
```

### Device Lost


```
ERROR_DEVICE_LOST

Possible causes:
• GPU driver crash (TDR timeout)
• Infinite loop in shader
• Invalid command buffer

Solutions:
→ Check for shader infinite loops
→ Enable validation layers
→ Update GPU drivers
→ Reinitialize after device loss
```

### Shader Compilation Failed


```
Shader compilation failed: Line 12: undeclared identifier

Debugging tips:
• Check line 12 in your shader
• Verify all variables are declared
• Make sure shader version is correct
```

### Window Resize


```
ERROR_OUT_OF_DATE_KHR

This is normal! Recreate your swapchain when the window resizes.
```

## Error Handling Checklist


- [ ] Enable validation layers in debug builds
- [ ] Propagate errors with `?` operator
- [ ] Handle initialization errors gracefully
- [ ] Log errors for debugging
- [ ] Provide user-friendly error messages
- [ ] Clean up resources properly
- [ ] Test error paths
- [ ] Document error conditions in your API

## Further Reading


- [Vulkan Error Database]https://vulkan.lunarg.com/doc/view/latest/windows/validation_error_database.html
- [Validation Layers Guide]https://vulkan-tutorial.com/Drawing_a_triangle/Setup/Validation_layers
- [EX Tier Guide]ex-tier-guide.md
- [EZ Tier Guide]ez-tier-guide.md
- [Troubleshooting]../getting-started/troubleshooting.md