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
//! RAII wrappers for Vulkan objects that extend the Vulkan device.

use {
    crate::{graphics::vulkan::raii, trace},
    anyhow::{Context, Result},
    ash::vk,
    std::sync::Arc,
};

macro_rules! device_extension {
    (
        $name: ident,
        $ext_type: ty,
        $raw_type: ty,
        $destroy: ident
    ) => {
        /// RAII wrapper that destroys itself when Dropped.
        ///
        /// The owner is responsible for dropping Vulkan resources in the
        /// correct order.
        pub struct $name {
            pub ext: $ext_type,
            pub raw: $raw_type,
            pub device: Arc<raii::Device>,
        }

        impl std::fmt::Debug for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_struct(stringify!($name))
                    .field("ext", &"<extension loader>")
                    .field("raw", &self.raw)
                    .field("device", &self.device)
                    .finish()
            }
        }

        impl std::ops::Deref for $name {
            type Target = $raw_type;

            fn deref(&self) -> &Self::Target {
                &self.raw
            }
        }

        impl Drop for $name {
            fn drop(&mut self) {
                unsafe { self.ext.$destroy(self.raw, None) }
            }
        }
    };
}

device_extension!(
    Swapchain,
    ash::khr::swapchain::Device,
    vk::SwapchainKHR,
    destroy_swapchain
);

impl Swapchain {
    pub fn new(
        device: Arc<raii::Device>,
        create_info: &vk::SwapchainCreateInfoKHR,
    ) -> Result<Arc<Self>> {
        let ext = ash::khr::swapchain::Device::new(&device.ash, &device);
        let raw = unsafe {
            ext.create_swapchain(create_info, None)
                .with_context(trace!("Error while creating swapchain!"))?
        };
        Ok(Arc::new(Self { ext, raw, device }))
    }
}