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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! PipelineBuilder - Flexible pipeline construction with explicit configuration
//!
//! The PipelineBuilder provides a fluent API for constructing Vulkan pipelines
//! with zero defaults but full configuration control. All state is explicit.

use crate::core::{Device, Pipeline, PipelineLayout};
use crate::ex::errors::PipelineError;
use ash::vk;
use std::ffi::CString;

/// PipelineBuilder - Flexible pipeline construction with explicit configuration
///
/// No defaults - all configuration is explicit. This ensures you understand
/// exactly what state your pipeline uses.
///
/// # Example
///
/// ```rust,no_run
/// use shdrlib::ex::*;
/// use ash::vk;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let runtime = RuntimeManager::new(RuntimeConfig::default())?;
/// # let device = runtime.device();
/// # let vert_module = vk::ShaderModule::null();
/// # let frag_module = vk::ShaderModule::null();
/// let pipeline = PipelineBuilder::new()
///     .vertex_shader(vert_module, "main")
///     .fragment_shader(frag_module, "main")
///     .color_attachment_formats(vec![vk::Format::R8G8B8A8_UNORM])
///     .build_graphics(&device)?;
/// # Ok(())
/// # }
/// ```
pub struct PipelineBuilder {
    // Shader stages
    vertex_shader: Option<(vk::ShaderModule, CString)>,
    fragment_shader: Option<(vk::ShaderModule, CString)>,
    geometry_shader: Option<(vk::ShaderModule, CString)>,
    /// Reserved for future tessellation control shader support.
    /// See CHANGELOG v0.1.3 for planned tessellation implementation.
    #[allow(dead_code)]
    tess_control_shader: Option<(vk::ShaderModule, CString)>,
    /// Reserved for future tessellation evaluation shader support.
    /// See CHANGELOG v0.1.3 for planned tessellation implementation.
    #[allow(dead_code)]
    tess_eval_shader: Option<(vk::ShaderModule, CString)>,
    compute_shader: Option<(vk::ShaderModule, CString)>,

    // Vertex input
    vertex_bindings: Vec<vk::VertexInputBindingDescription>,
    vertex_attributes: Vec<vk::VertexInputAttributeDescription>,

    // Input assembly
    topology: vk::PrimitiveTopology,
    primitive_restart: bool,

    // Viewport/scissor
    viewports: Vec<vk::Viewport>,
    scissors: Vec<vk::Rect2D>,
    dynamic_viewport: bool,
    dynamic_scissor: bool,

    // Rasterization
    depth_clamp: bool,
    rasterizer_discard: bool,
    polygon_mode: vk::PolygonMode,
    cull_mode: vk::CullModeFlags,
    front_face: vk::FrontFace,
    depth_bias_enable: bool,

    // Multisample
    sample_count: vk::SampleCountFlags,

    // Depth/stencil
    depth_test: bool,
    depth_write: bool,
    depth_compare: vk::CompareOp,

    // Color blending
    color_formats: Vec<vk::Format>,
    blend_attachments: Vec<vk::PipelineColorBlendAttachmentState>,

    // Depth format
    depth_format: Option<vk::Format>,

    // Descriptors
    descriptor_layouts: Vec<vk::DescriptorSetLayout>,
    push_constant_ranges: Vec<vk::PushConstantRange>,

    // Dynamic state
    dynamic_states: Vec<vk::DynamicState>,
}

impl Default for PipelineBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl PipelineBuilder {
    /// Create a new pipeline builder with sensible starting values
    ///
    /// Note: These are NOT complete defaults - you still need to provide shaders
    /// and render target formats.
    pub fn new() -> Self {
        Self {
            vertex_shader: None,
            fragment_shader: None,
            geometry_shader: None,
            tess_control_shader: None,
            tess_eval_shader: None,
            compute_shader: None,
            vertex_bindings: Vec::new(),
            vertex_attributes: Vec::new(),
            topology: vk::PrimitiveTopology::TRIANGLE_LIST,
            primitive_restart: false,
            viewports: Vec::new(),
            scissors: Vec::new(),
            dynamic_viewport: false,
            dynamic_scissor: false,
            depth_clamp: false,
            rasterizer_discard: false,
            polygon_mode: vk::PolygonMode::FILL,
            cull_mode: vk::CullModeFlags::BACK,
            front_face: vk::FrontFace::COUNTER_CLOCKWISE,
            depth_bias_enable: false,
            sample_count: vk::SampleCountFlags::TYPE_1,
            depth_test: false,
            depth_write: false,
            depth_compare: vk::CompareOp::LESS_OR_EQUAL,
            color_formats: Vec::new(),
            blend_attachments: Vec::new(),
            depth_format: None,
            descriptor_layouts: Vec::new(),
            push_constant_ranges: Vec::new(),
            dynamic_states: Vec::new(),
        }
    }

    // ========== Shader Stages ==========

    /// Set vertex shader
    pub fn vertex_shader(mut self, module: vk::ShaderModule, entry: &str) -> Self {
        self.vertex_shader = Some((module, CString::new(entry).unwrap()));
        self
    }

    /// Set fragment shader
    pub fn fragment_shader(mut self, module: vk::ShaderModule, entry: &str) -> Self {
        self.fragment_shader = Some((module, CString::new(entry).unwrap()));
        self
    }

    /// Set geometry shader
    pub fn geometry_shader(mut self, module: vk::ShaderModule, entry: &str) -> Self {
        self.geometry_shader = Some((module, CString::new(entry).unwrap()));
        self
    }

    /// Set compute shader (for compute pipelines)
    pub fn compute_shader(mut self, module: vk::ShaderModule, entry: &str) -> Self {
        self.compute_shader = Some((module, CString::new(entry).unwrap()));
        self
    }

    // ========== Vertex Input ==========

    /// Set vertex input bindings
    pub fn vertex_bindings(mut self, bindings: Vec<vk::VertexInputBindingDescription>) -> Self {
        self.vertex_bindings = bindings;
        self
    }

    /// Set vertex input attributes
    pub fn vertex_attributes(
        mut self,
        attributes: Vec<vk::VertexInputAttributeDescription>,
    ) -> Self {
        self.vertex_attributes = attributes;
        self
    }

    // ========== Input Assembly ==========

    /// Set primitive topology
    pub fn topology(mut self, topology: vk::PrimitiveTopology) -> Self {
        self.topology = topology;
        self
    }

    /// Enable primitive restart
    pub fn primitive_restart(mut self, enable: bool) -> Self {
        self.primitive_restart = enable;
        self
    }

    // ========== Viewport/Scissor ==========

    /// Set viewport
    pub fn viewport(mut self, viewport: vk::Viewport) -> Self {
        self.viewports = vec![viewport];
        self.dynamic_viewport = false;
        self
    }

    /// Set scissor
    pub fn scissor(mut self, scissor: vk::Rect2D) -> Self {
        self.scissors = vec![scissor];
        self.dynamic_scissor = false;
        self
    }

    /// Use dynamic viewport state
    pub fn dynamic_viewport(mut self) -> Self {
        self.dynamic_viewport = true;
        if !self.dynamic_states.contains(&vk::DynamicState::VIEWPORT) {
            self.dynamic_states.push(vk::DynamicState::VIEWPORT);
        }
        self
    }

    /// Use dynamic scissor state
    pub fn dynamic_scissor(mut self) -> Self {
        self.dynamic_scissor = true;
        if !self.dynamic_states.contains(&vk::DynamicState::SCISSOR) {
            self.dynamic_states.push(vk::DynamicState::SCISSOR);
        }
        self
    }

    // ========== Rasterization ==========

    /// Set polygon mode
    pub fn polygon_mode(mut self, mode: vk::PolygonMode) -> Self {
        self.polygon_mode = mode;
        self
    }

    /// Set cull mode
    pub fn cull_mode(mut self, mode: vk::CullModeFlags) -> Self {
        self.cull_mode = mode;
        self
    }

    /// Set front face orientation
    pub fn front_face(mut self, front_face: vk::FrontFace) -> Self {
        self.front_face = front_face;
        self
    }

    // ========== Depth/Stencil ==========

    /// Enable depth testing
    pub fn depth_test(mut self, enable: bool, write: bool, compare: vk::CompareOp) -> Self {
        self.depth_test = enable;
        self.depth_write = write;
        self.depth_compare = compare;
        self
    }

    /// Set depth format
    pub fn depth_format(mut self, format: vk::Format) -> Self {
        self.depth_format = Some(format);
        self
    }

    // ========== Color Blending ==========

    /// Set color attachment formats (required for graphics pipelines)
    pub fn color_attachment_formats(mut self, formats: Vec<vk::Format>) -> Self {
        // Create default blend attachments (no blending)
        self.blend_attachments = formats
            .iter()
            .map(|_| vk::PipelineColorBlendAttachmentState {
                blend_enable: vk::FALSE,
                src_color_blend_factor: vk::BlendFactor::ONE,
                dst_color_blend_factor: vk::BlendFactor::ZERO,
                color_blend_op: vk::BlendOp::ADD,
                src_alpha_blend_factor: vk::BlendFactor::ONE,
                dst_alpha_blend_factor: vk::BlendFactor::ZERO,
                alpha_blend_op: vk::BlendOp::ADD,
                color_write_mask: vk::ColorComponentFlags::RGBA,
            })
            .collect();
        self.color_formats = formats;
        self
    }

    /// Set custom blend attachments
    pub fn blend_attachments(
        mut self,
        attachments: Vec<vk::PipelineColorBlendAttachmentState>,
    ) -> Self {
        self.blend_attachments = attachments;
        self
    }

    // ========== Descriptors ==========

    /// Set descriptor set layouts
    pub fn descriptor_layouts(mut self, layouts: Vec<vk::DescriptorSetLayout>) -> Self {
        self.descriptor_layouts = layouts;
        self
    }

    /// Set push constant ranges
    pub fn push_constants(mut self, ranges: Vec<vk::PushConstantRange>) -> Self {
        self.push_constant_ranges = ranges;
        self
    }

    // ========== Build ==========

    /// Build a graphics pipeline
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - No vertex shader provided
    /// - No fragment shader provided (unless rasterizer_discard is true)
    /// - No color attachment formats provided
    /// - Pipeline creation fails
    pub fn build_graphics(self, device: &Device) -> Result<Pipeline, PipelineError> {
        // Validate required fields
        let (vert_module, vert_entry) = self.vertex_shader.ok_or(PipelineError::NoVertexShader)?;

        let (frag_module, frag_entry) = if !self.rasterizer_discard {
            self.fragment_shader
                .ok_or(PipelineError::NoFragmentShader)?
        } else {
            // Rasterizer discard - no fragment shader needed
            (vk::ShaderModule::null(), CString::new("main").unwrap())
        };

        if self.color_formats.is_empty() && !self.rasterizer_discard {
            return Err(PipelineError::NoColorAttachmentFormats);
        }

        // Build shader stages
        let mut shader_stages = vec![vk::PipelineShaderStageCreateInfo {
            stage: vk::ShaderStageFlags::VERTEX,
            module: vert_module,
            p_name: vert_entry.as_ptr(),
            ..Default::default()
        }];

        if !self.rasterizer_discard {
            shader_stages.push(vk::PipelineShaderStageCreateInfo {
                stage: vk::ShaderStageFlags::FRAGMENT,
                module: frag_module,
                p_name: frag_entry.as_ptr(),
                ..Default::default()
            });
        }

        // Add optional shader stages
        if let Some((module, entry)) = &self.geometry_shader {
            shader_stages.push(vk::PipelineShaderStageCreateInfo {
                stage: vk::ShaderStageFlags::GEOMETRY,
                module: *module,
                p_name: entry.as_ptr(),
                ..Default::default()
            });
        }

        // Create pipeline layout
        let layout =
            PipelineLayout::new(device, &self.descriptor_layouts, &self.push_constant_ranges)?;

        // Vertex input state
        let vertex_input_state = vk::PipelineVertexInputStateCreateInfo {
            vertex_binding_description_count: self.vertex_bindings.len() as u32,
            p_vertex_binding_descriptions: self.vertex_bindings.as_ptr(),
            vertex_attribute_description_count: self.vertex_attributes.len() as u32,
            p_vertex_attribute_descriptions: self.vertex_attributes.as_ptr(),
            ..Default::default()
        };

        // Input assembly state
        let input_assembly_state = vk::PipelineInputAssemblyStateCreateInfo {
            topology: self.topology,
            primitive_restart_enable: if self.primitive_restart {
                vk::TRUE
            } else {
                vk::FALSE
            },
            ..Default::default()
        };

        // Viewport state
        let viewport_state = vk::PipelineViewportStateCreateInfo {
            viewport_count: if self.dynamic_viewport {
                1
            } else {
                self.viewports.len() as u32
            },
            p_viewports: if self.dynamic_viewport {
                std::ptr::null()
            } else {
                self.viewports.as_ptr()
            },
            scissor_count: if self.dynamic_scissor {
                1
            } else {
                self.scissors.len() as u32
            },
            p_scissors: if self.dynamic_scissor {
                std::ptr::null()
            } else {
                self.scissors.as_ptr()
            },
            ..Default::default()
        };

        // Rasterization state
        let rasterization_state = vk::PipelineRasterizationStateCreateInfo {
            depth_clamp_enable: if self.depth_clamp {
                vk::TRUE
            } else {
                vk::FALSE
            },
            rasterizer_discard_enable: if self.rasterizer_discard {
                vk::TRUE
            } else {
                vk::FALSE
            },
            polygon_mode: self.polygon_mode,
            cull_mode: self.cull_mode,
            front_face: self.front_face,
            depth_bias_enable: if self.depth_bias_enable {
                vk::TRUE
            } else {
                vk::FALSE
            },
            line_width: 1.0,
            ..Default::default()
        };

        // Multisample state
        let multisample_state = vk::PipelineMultisampleStateCreateInfo {
            rasterization_samples: self.sample_count,
            ..Default::default()
        };

        // Depth/stencil state
        let depth_stencil_state = vk::PipelineDepthStencilStateCreateInfo {
            depth_test_enable: if self.depth_test { vk::TRUE } else { vk::FALSE },
            depth_write_enable: if self.depth_write {
                vk::TRUE
            } else {
                vk::FALSE
            },
            depth_compare_op: self.depth_compare,
            ..Default::default()
        };

        // Color blend state
        let color_blend_state = vk::PipelineColorBlendStateCreateInfo {
            attachment_count: self.blend_attachments.len() as u32,
            p_attachments: self.blend_attachments.as_ptr(),
            ..Default::default()
        };

        // Dynamic state
        let dynamic_state = if !self.dynamic_states.is_empty() {
            Some(vk::PipelineDynamicStateCreateInfo {
                dynamic_state_count: self.dynamic_states.len() as u32,
                p_dynamic_states: self.dynamic_states.as_ptr(),
                ..Default::default()
            })
        } else {
            None
        };

        // Dynamic rendering info (Vulkan 1.3+)
        let rendering_info = vk::PipelineRenderingCreateInfo {
            color_attachment_count: self.color_formats.len() as u32,
            p_color_attachment_formats: self.color_formats.as_ptr(),
            depth_attachment_format: self.depth_format.unwrap_or(vk::Format::UNDEFINED),
            ..Default::default()
        };

        // Create graphics pipeline
        let pipeline_info = vk::GraphicsPipelineCreateInfo {
            p_next: &rendering_info as *const _ as *const std::ffi::c_void,
            stage_count: shader_stages.len() as u32,
            p_stages: shader_stages.as_ptr(),
            p_vertex_input_state: &vertex_input_state,
            p_input_assembly_state: &input_assembly_state,
            p_viewport_state: &viewport_state,
            p_rasterization_state: &rasterization_state,
            p_multisample_state: &multisample_state,
            p_depth_stencil_state: &depth_stencil_state,
            p_color_blend_state: &color_blend_state,
            p_dynamic_state: dynamic_state.as_ref().map_or(std::ptr::null(), |s| s),
            layout: layout.handle(),
            ..Default::default()
        };

        // SAFETY: All pointers are valid and pipeline_info is properly initialized
        let pipeline_handle = unsafe {
            device
                .handle()
                .create_graphics_pipelines(vk::PipelineCache::null(), &[pipeline_info], None)
                .map_err(|(_, err)| crate::core::PipelineError::CreationFailed(err))?[0]
        };

        Ok(Pipeline::from_handle(
            pipeline_handle,
            layout,
            vk::PipelineBindPoint::GRAPHICS,
        ))
    }
}