shdrlib 0.1.2

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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! Command module - CommandPool and CommandBuffer wrappers
//!
//! **WARNING**: CORE objects do NOT enforce lifetime dependencies.
//! Command buffers must not outlive their pool, and the pool must not outlive the device.

use crate::core::Device;
use ash::vk;
use thiserror::Error;

/// Command pool operation error
#[derive(Debug, Error)]
pub enum CommandPoolError {
    #[error("Command pool creation failed: {0}")]
    CreationFailed(vk::Result),

    #[error("Command buffer allocation failed: {0}")]
    AllocationFailed(vk::Result),

    #[error("Command pool reset failed: {0}")]
    ResetFailed(vk::Result),
}

/// Command buffer operation error
#[derive(Debug, Error)]
pub enum CommandBufferError {
    #[error("Begin recording failed: {0}")]
    BeginFailed(vk::Result),

    #[error("End recording failed: {0}")]
    EndFailed(vk::Result),

    #[error("Invalid command buffer state")]
    InvalidState,
}

/// Command pool wrapper
///
/// Allocates and manages command buffers.
///
/// # Safety
///
/// This object does NOT enforce that the device outlives it.
/// Using the pool after dropping the device causes undefined behavior.
pub struct CommandPool {
    pool: vk::CommandPool,
    family_index: u32,
}

impl CommandPool {
    /// Create a new command pool
    ///
    /// # Arguments
    ///
    /// * `device` - The device to create the pool on
    /// * `queue_family_index` - The queue family this pool will allocate for
    /// * `flags` - Pool creation flags
    ///
    /// # Errors
    ///
    /// Returns `CommandPoolError::CreationFailed` if creation fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use shdrlib::core::{CommandPool, Device};
    /// use ash::vk;
    ///
    /// # fn example(device: &Device, queue_family: u32) -> Result<(), shdrlib::core::CommandPoolError> {
    /// let pool = CommandPool::new(
    ///     device,
    ///     queue_family,
    ///     vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER,
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(
        device: &Device,
        queue_family_index: u32,
        flags: vk::CommandPoolCreateFlags,
    ) -> Result<Self, CommandPoolError> {
        let create_info = vk::CommandPoolCreateInfo {
            queue_family_index,
            flags,
            ..Default::default()
        };

        // SAFETY: device is valid, create_info is properly initialized
        let pool = unsafe {
            device
                .handle()
                .create_command_pool(&create_info, None)
                .map_err(CommandPoolError::CreationFailed)?
        };

        Ok(Self {
            pool,
            family_index: queue_family_index,
        })
    }

    /// Get the raw Vulkan command pool handle
    #[inline]
    pub fn handle(&self) -> vk::CommandPool {
        self.pool
    }

    /// Get the queue family index this pool allocates for
    #[inline]
    pub fn family_index(&self) -> u32 {
        self.family_index
    }

    /// Allocate command buffers from the pool
    ///
    /// # Arguments
    ///
    /// * `device` - The device handle
    /// * `level` - Primary or secondary command buffer level
    /// * `count` - Number of command buffers to allocate
    ///
    /// # Errors
    ///
    /// Returns `CommandPoolError::AllocationFailed` if allocation fails.
    pub fn allocate(
        &self,
        device: &Device,
        level: vk::CommandBufferLevel,
        count: u32,
    ) -> Result<Vec<CommandBuffer>, CommandPoolError> {
        let alloc_info = vk::CommandBufferAllocateInfo {
            command_pool: self.pool,
            level,
            command_buffer_count: count,
            ..Default::default()
        };

        // SAFETY: device and pool are valid, alloc_info is properly initialized
        let buffers = unsafe {
            device
                .handle()
                .allocate_command_buffers(&alloc_info)
                .map_err(CommandPoolError::AllocationFailed)?
        };

        Ok(buffers
            .into_iter()
            .map(|buffer| CommandBuffer { buffer, level })
            .collect())
    }

    /// Allocate a single primary command buffer
    pub fn allocate_primary(&self, device: &Device) -> Result<CommandBuffer, CommandPoolError> {
        let mut buffers = self.allocate(device, vk::CommandBufferLevel::PRIMARY, 1)?;
        Ok(buffers.remove(0))
    }

    /// Allocate a single secondary command buffer
    pub fn allocate_secondary(&self, device: &Device) -> Result<CommandBuffer, CommandPoolError> {
        let mut buffers = self.allocate(device, vk::CommandBufferLevel::SECONDARY, 1)?;
        Ok(buffers.remove(0))
    }

    /// Reset the command pool
    ///
    /// This resets all command buffers allocated from the pool.
    ///
    /// # Errors
    ///
    /// Returns `CommandPoolError::ResetFailed` if reset fails.
    pub fn reset(
        &self,
        device: &Device,
        flags: vk::CommandPoolResetFlags,
    ) -> Result<(), CommandPoolError> {
        // SAFETY: device and pool are valid
        unsafe {
            device
                .handle()
                .reset_command_pool(self.pool, flags)
                .map_err(CommandPoolError::ResetFailed)
        }
    }

    /// Destroy the command pool manually
    ///
    /// # Safety
    ///
    /// The device must be the same device used to create this pool.
    /// After calling destroy(), the pool handle is invalidated.
    /// All command buffers allocated from this pool are automatically freed.
    pub fn destroy(&self, device: &Device) {
        // SAFETY: device and pool are valid
        unsafe {
            device.handle().destroy_command_pool(self.pool, None);
        }
    }
}

impl Drop for CommandPool {
    fn drop(&mut self) {
        if self.pool != vk::CommandPool::null() {
            eprintln!(
                "WARNING: CommandPool dropped without calling .destroy() - potential memory leak"
            );
        }
    }
}

/// Command buffer wrapper
///
/// Records GPU commands for execution.
///
/// # Lifecycle
///
/// **IMPORTANT**: CommandBuffer objects do NOT have a `.destroy()` method.
/// Command buffers are automatically freed when their parent CommandPool is destroyed.
/// This is standard Vulkan behavior - command buffers are pool resources.
///
/// # Safety
///
/// This object does NOT enforce that the pool outlives it.
/// Using the buffer after dropping the pool causes undefined behavior.
///
/// **IMPORTANT**: Command recording methods accept raw `vk::*` handles,
/// not CORE wrappers, to avoid borrow checker issues.
pub struct CommandBuffer {
    buffer: vk::CommandBuffer,
    level: vk::CommandBufferLevel,
}

impl CommandBuffer {
    /// Create CommandBuffer from raw handle (for EX tier usage)
    ///
    /// # Safety
    ///
    /// The handle must be valid and the level must match the actual command buffer.
    pub(crate) fn from_handle(buffer: vk::CommandBuffer, level: vk::CommandBufferLevel) -> Self {
        Self { buffer, level }
    }

    /// Get the raw Vulkan command buffer handle
    #[inline]
    pub fn handle(&self) -> vk::CommandBuffer {
        self.buffer
    }

    /// Get the command buffer level
    #[inline]
    pub fn level(&self) -> vk::CommandBufferLevel {
        self.level
    }

    /// Begin recording commands
    ///
    /// # Errors
    ///
    /// Returns `CommandBufferError::BeginFailed` if begin fails.
    pub fn begin(
        &self,
        device: &Device,
        flags: vk::CommandBufferUsageFlags,
    ) -> Result<(), CommandBufferError> {
        let begin_info = vk::CommandBufferBeginInfo {
            flags,
            ..Default::default()
        };

        // SAFETY: device and buffer are valid, begin_info is properly initialized
        unsafe {
            device
                .handle()
                .begin_command_buffer(self.buffer, &begin_info)
                .map_err(CommandBufferError::BeginFailed)
        }
    }

    /// End recording commands
    ///
    /// # Errors
    ///
    /// Returns `CommandBufferError::EndFailed` if end fails.
    pub fn end(&self, device: &Device) -> Result<(), CommandBufferError> {
        // SAFETY: device and buffer are valid
        unsafe {
            device
                .handle()
                .end_command_buffer(self.buffer)
                .map_err(CommandBufferError::EndFailed)
        }
    }

    /// Reset the command buffer
    ///
    /// # Errors
    ///
    /// Returns `CommandBufferError` if reset fails.
    pub fn reset(
        &self,
        device: &Device,
        flags: vk::CommandBufferResetFlags,
    ) -> Result<(), CommandBufferError> {
        // SAFETY: device and buffer are valid
        unsafe {
            device
                .handle()
                .reset_command_buffer(self.buffer, flags)
                .map_err(CommandBufferError::BeginFailed)
        }
    }

    // ============================================================================
    // Command Recording Methods
    // NOTE: These accept raw vk::* handles to avoid borrow checker hell
    // ============================================================================

    /// Bind a graphics or compute pipeline
    #[inline]
    pub fn bind_pipeline(
        &self,
        device: &Device,
        bind_point: vk::PipelineBindPoint,
        pipeline: vk::Pipeline,
    ) {
        // SAFETY: device, buffer, and pipeline are valid
        unsafe {
            device
                .handle()
                .cmd_bind_pipeline(self.buffer, bind_point, pipeline);
        }
    }

    /// Bind descriptor sets
    #[inline]
    pub fn bind_descriptor_sets(
        &self,
        device: &Device,
        bind_point: vk::PipelineBindPoint,
        layout: vk::PipelineLayout,
        first_set: u32,
        descriptor_sets: &[vk::DescriptorSet],
        dynamic_offsets: &[u32],
    ) {
        // SAFETY: device, buffer, layout, and sets are valid
        unsafe {
            device.handle().cmd_bind_descriptor_sets(
                self.buffer,
                bind_point,
                layout,
                first_set,
                descriptor_sets,
                dynamic_offsets,
            );
        }
    }

    /// Bind vertex buffers
    #[inline]
    pub fn bind_vertex_buffers(
        &self,
        device: &Device,
        first_binding: u32,
        buffers: &[vk::Buffer],
        offsets: &[vk::DeviceSize],
    ) {
        // SAFETY: device, buffer, and vertex buffers are valid
        unsafe {
            device
                .handle()
                .cmd_bind_vertex_buffers(self.buffer, first_binding, buffers, offsets);
        }
    }

    /// Bind an index buffer
    #[inline]
    pub fn bind_index_buffer(
        &self,
        device: &Device,
        buffer: vk::Buffer,
        offset: vk::DeviceSize,
        index_type: vk::IndexType,
    ) {
        // SAFETY: device, command buffer, and index buffer are valid
        unsafe {
            device
                .handle()
                .cmd_bind_index_buffer(self.buffer, buffer, offset, index_type);
        }
    }

    /// Draw command
    #[inline]
    pub fn draw(
        &self,
        device: &Device,
        vertex_count: u32,
        instance_count: u32,
        first_vertex: u32,
        first_instance: u32,
    ) {
        // SAFETY: device and buffer are valid
        unsafe {
            device.handle().cmd_draw(
                self.buffer,
                vertex_count,
                instance_count,
                first_vertex,
                first_instance,
            );
        }
    }

    /// Draw indexed command
    #[inline]
    pub fn draw_indexed(
        &self,
        device: &Device,
        index_count: u32,
        instance_count: u32,
        first_index: u32,
        vertex_offset: i32,
        first_instance: u32,
    ) {
        // SAFETY: device and buffer are valid
        unsafe {
            device.handle().cmd_draw_indexed(
                self.buffer,
                index_count,
                instance_count,
                first_index,
                vertex_offset,
                first_instance,
            );
        }
    }

    /// Dispatch compute work
    #[inline]
    pub fn dispatch(
        &self,
        device: &Device,
        group_count_x: u32,
        group_count_y: u32,
        group_count_z: u32,
    ) {
        // SAFETY: device and buffer are valid
        unsafe {
            device
                .handle()
                .cmd_dispatch(self.buffer, group_count_x, group_count_y, group_count_z);
        }
    }

    /// Begin dynamic rendering (Vulkan 1.3+)
    #[inline]
    pub fn begin_rendering(&self, device: &Device, rendering_info: &vk::RenderingInfo) {
        // SAFETY: device, buffer, and rendering_info are valid
        unsafe {
            device
                .handle()
                .cmd_begin_rendering(self.buffer, rendering_info);
        }
    }

    /// End dynamic rendering
    #[inline]
    pub fn end_rendering(&self, device: &Device) {
        // SAFETY: device and buffer are valid
        unsafe {
            device.handle().cmd_end_rendering(self.buffer);
        }
    }

    /// Pipeline barrier for synchronization
    ///
    /// Note: This function has many parameters by design to match Vulkan's API requirements.
    #[allow(clippy::too_many_arguments)]
    #[inline]
    pub fn pipeline_barrier(
        &self,
        device: &Device,
        src_stage_mask: vk::PipelineStageFlags,
        dst_stage_mask: vk::PipelineStageFlags,
        dependency_flags: vk::DependencyFlags,
        memory_barriers: &[vk::MemoryBarrier],
        buffer_barriers: &[vk::BufferMemoryBarrier],
        image_barriers: &[vk::ImageMemoryBarrier],
    ) {
        // SAFETY: device, buffer, and barriers are valid
        unsafe {
            device.handle().cmd_pipeline_barrier(
                self.buffer,
                src_stage_mask,
                dst_stage_mask,
                dependency_flags,
                memory_barriers,
                buffer_barriers,
                image_barriers,
            );
        }
    }

    /// Copy buffer to buffer
    #[inline]
    pub fn copy_buffer(
        &self,
        device: &Device,
        src_buffer: vk::Buffer,
        dst_buffer: vk::Buffer,
        regions: &[vk::BufferCopy],
    ) {
        // SAFETY: device, buffers, and regions are valid
        unsafe {
            device
                .handle()
                .cmd_copy_buffer(self.buffer, src_buffer, dst_buffer, regions);
        }
    }

    /// Copy buffer to image
    #[inline]
    pub fn copy_buffer_to_image(
        &self,
        device: &Device,
        src_buffer: vk::Buffer,
        dst_image: vk::Image,
        dst_image_layout: vk::ImageLayout,
        regions: &[vk::BufferImageCopy],
    ) {
        // SAFETY: device, buffer, image, and regions are valid
        unsafe {
            device.handle().cmd_copy_buffer_to_image(
                self.buffer,
                src_buffer,
                dst_image,
                dst_image_layout,
                regions,
            );
        }
    }
}

// No Drop implementation - command buffers are freed when pool is destroyed

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{Device, DeviceCreateInfo, Instance, InstanceCreateInfo, QueueCreateInfo};

    fn create_test_device() -> (Instance, Device, u32) {
        let instance = Instance::new(InstanceCreateInfo {
            enable_validation: false,
            ..Default::default()
        })
        .unwrap();
        let physical_devices = instance.enumerate_physical_devices().unwrap();
        let physical_device = physical_devices[0];

        let graphics_family = unsafe {
            instance
                .get_physical_device_queue_family_properties(physical_device)
                .iter()
                .enumerate()
                .find(|(_, qf)| qf.queue_flags.contains(vk::QueueFlags::GRAPHICS))
                .map(|(i, _)| i as u32)
                .unwrap()
        };

        let device = Device::new(
            &instance,
            physical_device,
            DeviceCreateInfo {
                queue_create_infos: vec![QueueCreateInfo {
                    queue_family_index: graphics_family,
                    queue_count: 1,
                    queue_priorities: vec![1.0],
                }],
                ..Default::default()
            },
        )
        .unwrap();

        (instance, device, graphics_family)
    }

    #[test]
    fn test_command_pool_creation() {
        let (_instance, device, graphics_family) = create_test_device();
        let pool = CommandPool::new(
            &device,
            graphics_family,
            vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER,
        )
        .unwrap();
        assert_ne!(pool.handle(), vk::CommandPool::null());
        assert_eq!(pool.family_index(), graphics_family);
        pool.destroy(&device);
    }

    #[test]
    fn test_command_buffer_allocation() {
        let (_instance, device, graphics_family) = create_test_device();
        let pool = CommandPool::new(
            &device,
            graphics_family,
            vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER,
        )
        .unwrap();

        let buffer = pool.allocate_primary(&device).unwrap();
        assert_ne!(buffer.handle(), vk::CommandBuffer::null());
        assert_eq!(buffer.level(), vk::CommandBufferLevel::PRIMARY);

        pool.destroy(&device);
    }

    #[test]
    fn test_command_buffer_recording() {
        let (_instance, device, graphics_family) = create_test_device();
        let pool = CommandPool::new(
            &device,
            graphics_family,
            vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER,
        )
        .unwrap();

        let buffer = pool.allocate_primary(&device).unwrap();

        // Begin and end recording
        assert!(buffer
            .begin(&device, vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT)
            .is_ok());
        assert!(buffer.end(&device).is_ok());

        pool.destroy(&device);
    }

    #[test]
    fn test_command_pool_reset() {
        let (_instance, device, graphics_family) = create_test_device();
        let pool = CommandPool::new(
            &device,
            graphics_family,
            vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER,
        )
        .unwrap();

        assert!(pool
            .reset(&device, vk::CommandPoolResetFlags::empty())
            .is_ok());

        pool.destroy(&device);
    }
}