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
//! RuntimeManager - Owns fundamental Vulkan resources
//!
//! The RuntimeManager handles instance creation, device selection, queue management,
//! and frame synchronization. It replaces 80+ lines of CORE boilerplate with a single
//! 5-line setup.
//!
//! ## Example
//!
//! ```rust,no_run
//! use shdrlib::ex::*;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Create RuntimeManager with defaults
//! let mut runtime = RuntimeManager::new(RuntimeConfig::default())?;
//!
//! // Access underlying CORE objects when needed
//! let device = runtime.device();
//! let graphics_family = runtime.graphics_family();
//!
//! // Frame loop
//! loop {
//!     let frame = runtime.begin_frame()?;
//!     
//!     // Record commands with frame.command_buffer
//!     frame.command_buffer.begin(&frame.device, ash::vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT)?;
//!     // ... record rendering commands ...
//!     frame.command_buffer.end(&frame.device)?;
//!     
//!     runtime.end_frame(&SubmitInfo::default())?;
//! }
//! # Ok(())
//! # }
//! ```

use crate::core::{
    self, CommandBuffer, CommandPool, Device, Fence, Instance, InstanceCreateInfo, Queue, Semaphore,
};
use crate::ex::errors::RuntimeError;
use ash::vk;
use std::sync::Arc;

/// Configuration for RuntimeManager
///
/// Provides explicit control over instance/device creation while offering sensible defaults.
pub struct RuntimeConfig {
    /// Application name (shown in Vulkan tools)
    pub app_name: String,

    /// Application version (major.minor.patch encoded as u32)
    pub app_version: u32,

    /// Enable Vulkan validation layers (auto-enabled in debug builds)
    pub enable_validation: bool,

    /// Number of frames that can be in-flight simultaneously
    ///
    /// Default: 2 (double buffering)
    pub in_flight_frames: usize,

    /// Required device extensions (e.g., "VK_KHR_swapchain")
    pub device_extensions: Vec<String>,

    /// Optional physical device selector
    ///
    /// If None, selects first discrete GPU or falls back to first available device.
    /// Provide a custom selector to choose based on specific requirements.
    ///
    /// Note: This type is complex by design to allow flexible device selection callbacks.
    #[allow(clippy::type_complexity)]
    pub physical_device_selector: Option<Box<dyn Fn(&core::PhysicalDeviceInfo) -> bool>>,
}

impl Default for RuntimeConfig {
    fn default() -> Self {
        Self {
            app_name: "shdrlib application".to_string(),
            app_version: 1,
            enable_validation: cfg!(debug_assertions),
            in_flight_frames: 2,
            device_extensions: vec![],
            physical_device_selector: None,
        }
    }
}

/// Frame rendering context
///
/// Borrowed mutably during frame recording. Provides access to the current
/// command buffer and device.
pub struct FrameContext<'a> {
    /// Shared device reference
    pub device: Arc<Device>,

    /// Command buffer for current frame
    pub command_buffer: CommandBuffer,

    /// Current frame index
    pub frame_index: usize,

    /// Reference to runtime manager (for internal state access)
    _runtime: &'a mut RuntimeManager,
}

impl<'a> FrameContext<'a> {
    /// Get a convenient reference to the command buffer
    #[inline]
    pub fn cmd(&self) -> &CommandBuffer {
        &self.command_buffer
    }

    /// Get the image available semaphore for this frame
    #[inline]
    pub fn image_available_semaphore(&self) -> vk::Semaphore {
        self._runtime.image_available_semaphore()
    }

    /// Get the render finished semaphore for this frame
    #[inline]
    pub fn render_finished_semaphore(&self) -> vk::Semaphore {
        self._runtime.render_finished_semaphore()
    }
}

/// Submit information for frame presentation
#[derive(Default)]
pub struct SubmitInfo {
    /// Wait semaphores (beyond image_available)
    pub wait_semaphores: Vec<vk::Semaphore>,

    /// Signal semaphores (beyond render_finished)
    pub signal_semaphores: Vec<vk::Semaphore>,

    /// Pipeline stages to wait at
    pub wait_stages: Vec<vk::PipelineStageFlags>,
}

/// RuntimeManager - Owns fundamental Vulkan resources
///
/// Encapsulates Instance, Device, Queue, Synchronization, and Command buffers.
/// Handles frame scheduling and resource lifetime management.
pub struct RuntimeManager {
    // CORE objects - drop order matters!
    // Rust drops fields in declaration order, so we declare in reverse destruction order
    /// Command buffers (one per in-flight frame)
    command_buffers: Vec<CommandBuffer>,

    /// Command pool for graphics commands
    command_pool: CommandPool,

    /// Semaphores signaled when render is finished (one per frame)
    render_finished: Vec<Semaphore>,

    /// Semaphores signaled when image is available (one per frame)
    image_available: Vec<Semaphore>,

    /// Fences for CPU-GPU sync (one per frame)
    in_flight_fences: Vec<Fence>,

    /// Graphics queue
    graphics_queue: Queue,

    /// Logical device (Arc'd for sharing with ShaderManager)
    device: Arc<Device>,

    /// Physical device handle
    physical_device: vk::PhysicalDevice,

    /// Vulkan instance (kept for potential cleanup or queries)
    #[allow(dead_code)]
    instance: Instance,

    // Frame tracking state
    /// Current frame index (cycles 0..in_flight_frames)
    current_frame: usize,

    /// Graphics queue family index
    graphics_family_index: u32,

    /// Number of in-flight frames
    in_flight_frames: usize,
}

impl RuntimeManager {
    /// Create a new RuntimeManager with the given configuration
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Instance creation fails
    /// - No suitable physical device found
    /// - Device creation fails
    /// - Graphics queue not available
    /// - Synchronization primitive creation fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use shdrlib::ex::*;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // With defaults
    /// let runtime = RuntimeManager::new(RuntimeConfig::default())?;
    ///
    /// // With custom config
    /// let runtime = RuntimeManager::new(RuntimeConfig {
    ///     app_name: "My Renderer".to_string(),
    ///     enable_validation: true,
    ///     device_extensions: vec!["VK_KHR_swapchain".to_string()],
    ///     ..Default::default()
    /// })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(config: RuntimeConfig) -> Result<Self, RuntimeError> {
        // 1. Create Vulkan instance
        let instance = Instance::new(InstanceCreateInfo {
            app_name: config.app_name.clone(),
            app_version: config.app_version,
            enable_validation: config.enable_validation,
            extensions: vec![], // Will be extended as needed
        })?;

        // 2. Select physical device
        let physical_devices = instance.enumerate_physical_devices()?;
        if physical_devices.is_empty() {
            return Err(RuntimeError::NoSuitableDevice(0));
        }

        let physical_device = Self::select_physical_device(
            &instance,
            &physical_devices,
            config.physical_device_selector.as_ref(),
        )?;

        // 3. Find graphics queue family
        let queue_families =
            unsafe { instance.get_physical_device_queue_family_properties(physical_device) };
        let graphics_family_index = queue_families
            .iter()
            .position(|qf| qf.queue_flags.contains(vk::QueueFlags::GRAPHICS))
            .ok_or(RuntimeError::NoGraphicsQueue)? as u32;

        // 4. Create logical device
        let device = Device::new(
            &instance,
            physical_device,
            core::DeviceCreateInfo {
                extensions: config.device_extensions.clone(),
                features: Default::default(),
                queue_create_infos: vec![core::QueueCreateInfo {
                    queue_family_index: graphics_family_index,
                    queue_count: 1,
                    queue_priorities: vec![1.0],
                }],
            },
        )?;

        // Wrap device in Arc for sharing
        let device = Arc::new(device);

        // 5. Get graphics queue
        let graphics_queue = Queue::get(&device, graphics_family_index, 0);

        // 6. Create synchronization primitives (one set per in-flight frame)
        let mut in_flight_fences = Vec::with_capacity(config.in_flight_frames);
        let mut image_available = Vec::with_capacity(config.in_flight_frames);
        let mut render_finished = Vec::with_capacity(config.in_flight_frames);

        for _ in 0..config.in_flight_frames {
            in_flight_fences.push(Fence::new(&device, true)?); // Start signaled
            image_available.push(Semaphore::new(&device)?);
            render_finished.push(Semaphore::new(&device)?);
        }

        // 7. Create command pool and buffers
        let command_pool = CommandPool::new(
            &device,
            graphics_family_index,
            vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER,
        )?;

        let command_buffers = command_pool.allocate(
            &device,
            vk::CommandBufferLevel::PRIMARY,
            config.in_flight_frames as u32,
        )?;

        Ok(Self {
            instance,
            physical_device,
            device,
            graphics_queue,
            graphics_family_index,
            in_flight_fences,
            image_available,
            render_finished,
            command_pool,
            command_buffers,
            current_frame: 0,
            in_flight_frames: config.in_flight_frames,
        })
    }

    /// Select a physical device based on the provided selector
    #[allow(clippy::type_complexity)]
    fn select_physical_device(
        instance: &Instance,
        devices: &[vk::PhysicalDevice],
        selector: Option<&Box<dyn Fn(&core::PhysicalDeviceInfo) -> bool>>,
    ) -> Result<vk::PhysicalDevice, RuntimeError> {
        match selector {
            Some(selector_fn) => {
                // Use custom selector
                for &device in devices {
                    let info = core::PhysicalDeviceInfo {
                        device,
                        properties: unsafe { instance.get_physical_device_properties(device) },
                        features: unsafe { instance.get_physical_device_features(device) },
                        memory_properties: unsafe {
                            instance.get_physical_device_memory_properties(device)
                        },
                        queue_families: unsafe {
                            instance.get_physical_device_queue_family_properties(device)
                        },
                    };
                    if selector_fn(&info) {
                        return Ok(device);
                    }
                }
                Err(RuntimeError::NoSuitableDevice(devices.len()))
            }
            None => {
                // Default: prefer discrete GPU, fallback to first device
                let discrete = devices.iter().find(|&&device| {
                    let props = unsafe { instance.get_physical_device_properties(device) };
                    props.device_type == vk::PhysicalDeviceType::DISCRETE_GPU
                });

                match discrete {
                    Some(&device) => Ok(device),
                    None => devices
                        .first()
                        .copied()
                        .ok_or(RuntimeError::NoSuitableDevice(0)),
                }
            }
        }
    }

    /// Begin a new frame
    ///
    /// Returns a FrameContext for recording commands. You must call `end_frame()`
    /// after recording to submit the commands.
    ///
    /// # Errors
    ///
    /// Returns error if fence wait/reset fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use shdrlib::ex::*;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let mut runtime = RuntimeManager::new(RuntimeConfig::default())?;
    /// let frame = runtime.begin_frame()?;
    ///
    /// frame.command_buffer.begin(&frame.device, ash::vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT)?;
    /// // ... record commands ...
    /// frame.command_buffer.end(&frame.device)?;
    ///
    /// runtime.end_frame(&SubmitInfo::default())?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn begin_frame(&mut self) -> Result<FrameContext<'_>, RuntimeError> {
        // Wait for this frame's fence
        let fence = &self.in_flight_fences[self.current_frame];
        fence.wait(&self.device, u64::MAX)?;
        fence.reset(&self.device)?;

        // Get command buffer handle (not move)
        let command_buffer = self.command_buffers[self.current_frame].handle();

        Ok(FrameContext {
            device: Arc::clone(&self.device),
            command_buffer: CommandBuffer::from_handle(
                command_buffer,
                vk::CommandBufferLevel::PRIMARY,
            ),
            frame_index: self.current_frame,
            _runtime: self,
        })
    }

    /// End the current frame and submit commands
    ///
    /// # Errors
    ///
    /// Returns error if queue submission fails.
    pub fn end_frame(&mut self, submit_info: &SubmitInfo) -> Result<(), RuntimeError> {
        let command_buffer_handle = self.command_buffers[self.current_frame].handle();
        let fence = &self.in_flight_fences[self.current_frame];

        // Build wait semaphores and stages
        let mut wait_semaphores = vec![self.image_available[self.current_frame].handle()];
        wait_semaphores.extend(&submit_info.wait_semaphores);

        let mut wait_stages = if submit_info.wait_stages.is_empty() {
            vec![vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT; wait_semaphores.len()]
        } else {
            submit_info.wait_stages.clone()
        };

        // Ensure wait_stages matches wait_semaphores length
        while wait_stages.len() < wait_semaphores.len() {
            wait_stages.push(vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT);
        }

        // Build signal semaphores
        let mut signal_semaphores = vec![self.render_finished[self.current_frame].handle()];
        signal_semaphores.extend(&submit_info.signal_semaphores);

        // Submit to graphics queue
        self.graphics_queue.submit(
            &self.device,
            &[command_buffer_handle],
            &wait_semaphores,
            &wait_stages,
            &signal_semaphores,
            Some(fence.handle()),
        )?;

        // Advance to next frame
        self.current_frame = (self.current_frame + 1) % self.in_flight_frames;

        Ok(())
    }

    /// Get a shared reference to the device
    ///
    /// This Arc can be cloned and shared with ShaderManager and other EX components.
    #[inline]
    pub fn device(&self) -> Arc<Device> {
        Arc::clone(&self.device)
    }

    /// Get the physical device handle
    #[inline]
    pub fn physical_device(&self) -> vk::PhysicalDevice {
        self.physical_device
    }

    /// Get the graphics queue family index
    #[inline]
    pub fn graphics_family(&self) -> u32 {
        self.graphics_family_index
    }

    /// Get a reference to the graphics queue
    #[inline]
    pub fn graphics_queue(&self) -> &Queue {
        &self.graphics_queue
    }

    /// Get the current command buffer (without borrowing the manager)
    #[inline]
    pub fn current_command_buffer(&self) -> vk::CommandBuffer {
        self.command_buffers[self.current_frame].handle()
    }

    /// Get the instance (useful for surface creation)
    #[inline]
    pub fn instance(&self) -> &Instance {
        &self.instance
    }

    /// Get the image available semaphore for the current frame
    #[inline]
    pub fn image_available_semaphore(&self) -> vk::Semaphore {
        self.image_available[self.current_frame].handle()
    }

    /// Get the render finished semaphore for the current frame
    #[inline]
    pub fn render_finished_semaphore(&self) -> vk::Semaphore {
        self.render_finished[self.current_frame].handle()
    }

    /// Wait for device to become idle
    ///
    /// Useful for cleanup or synchronization points.
    pub fn wait_idle(&self) -> Result<(), RuntimeError> {
        self.device.wait_idle()?;
        Ok(())
    }
}

impl Drop for RuntimeManager {
    fn drop(&mut self) {
        // Wait for device to be idle before cleanup
        let _ = self.device.wait_idle();

        // Destroy synchronization primitives manually (need device reference)
        for fence in &mut self.in_flight_fences {
            fence.destroy(&self.device);
        }
        for semaphore in &mut self.image_available {
            semaphore.destroy(&self.device);
        }
        for semaphore in &mut self.render_finished {
            semaphore.destroy(&self.device);
        }

        // Destroy command pool manually
        self.command_pool.destroy(&self.device);

        // Device, Instance drop automatically in correct order (declared last)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test_config() -> RuntimeConfig {
        RuntimeConfig {
            enable_validation: false, // Disable validation in tests
            ..Default::default()
        }
    }

    #[test]
    fn test_runtime_manager_creation_with_defaults() {
        let runtime = RuntimeManager::new(test_config());
        assert!(runtime.is_ok(), "RuntimeManager creation should succeed");
    }

    #[test]
    fn test_runtime_manager_device_access() {
        let runtime = RuntimeManager::new(test_config()).unwrap();
        let device = runtime.device();
        assert!(Arc::strong_count(&device) >= 1);
    }

    #[test]
    fn test_runtime_manager_custom_config() {
        let config = RuntimeConfig {
            app_name: "Test App".to_string(),
            app_version: 42,
            enable_validation: false,
            in_flight_frames: 3,
            ..Default::default()
        };

        let runtime = RuntimeManager::new(config);
        assert!(runtime.is_ok());
    }

    #[test]
    fn test_frame_begin_end_cycle() {
        let mut runtime = RuntimeManager::new(test_config()).unwrap();

        // Begin frame
        let frame = runtime.begin_frame();
        assert!(frame.is_ok());
        let frame = frame.unwrap();
        assert_eq!(frame.frame_index, 0);

        // Record empty commands
        frame
            .command_buffer
            .begin(&frame.device, vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT)
            .unwrap();
        frame.command_buffer.end(&frame.device).unwrap();

        // End frame
        let result = runtime.end_frame(&SubmitInfo::default());
        assert!(result.is_ok());

        // Frame index should advance
        assert_eq!(runtime.current_frame, 1);
    }
}