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
use {
    super::{DriverError, Instance},
    archery::{SharedPointer, SharedPointerKind},
    ash::{extensions::khr, vk},
    log::warn,
    raw_window_handle::HasRawWindowHandle,
    std::{
        fmt::{Debug, Formatter},
        ops::Deref,
        thread::panicking,
    },
};

pub struct Surface<P>
where
    P: SharedPointerKind,
{
    _instance: SharedPointer<Instance, P>,
    surface: vk::SurfaceKHR,
    surface_ext: khr::Surface,
}

impl<P> Surface<P>
where
    P: SharedPointerKind,
{
    pub fn new(
        instance: &SharedPointer<Instance, P>,
        window: &impl HasRawWindowHandle,
    ) -> Result<Self, DriverError> {
        let instance = SharedPointer::clone(instance);
        let surface_ext = khr::Surface::new(&instance.entry, &instance);
        let surface =
            unsafe { ash_window::create_surface(&instance.entry, &instance, window, None) }
                .map_err(|err| {
                    warn!("{err}");

                    DriverError::Unsupported
                })?;

        Ok(Self {
            _instance: instance,
            surface,
            surface_ext,
        })
    }
}

impl<P> Debug for Surface<P>
where
    P: SharedPointerKind,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str("Surface")
    }
}

impl<P> Deref for Surface<P>
where
    P: SharedPointerKind,
{
    type Target = vk::SurfaceKHR;

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

impl<P> Drop for Surface<P>
where
    P: SharedPointerKind,
{
    fn drop(&mut self) {
        if panicking() {
            return;
        }

        unsafe {
            self.surface_ext.destroy_surface(self.surface, None);
        }
    }
}