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
use {
    crate::graphics::GraphicsError,
    ash::vk,
    ccthw_ash_instance::{
        LogicalDevice, PhysicalDevice, PhysicalDeviceFeatures, VulkanInstance,
    },
    indoc::indoc,
    std::sync::Mutex,
};

mod queue;
mod queue_finder;
mod window_surface;

use {
    self::queue_finder::QueueFinder, ccthw_ash_allocator::MemoryAllocator,
    ccthw_ash_instance::VulkanHandle, window_surface::WindowSurface,
};

pub use self::queue::Queue;

/// A combination of the VulkanInstance, LogicalDevice, and queues required by
/// this application.
#[derive(Debug)]
pub struct RenderDevice {
    graphics_queue: Queue,
    presentation_queue: Queue,
    window_surface: WindowSurface,
    logical_device: LogicalDevice,
    instance: VulkanInstance,
    allocator: Mutex<MemoryAllocator>,
}

// Public Api
// ----------

impl RenderDevice {
    /// Create a new render device.
    ///
    /// # Params
    ///
    /// * `instance` - the VulkanInstance used to create all application
    ///   resources. The RenderDevice takes ownership of the vulkan instance so
    ///   it can be destroyed in the correct order.
    /// * `features` - the physical device features required by this
    ///   application.
    /// * `surface` - the surface this application will use for swapchain
    ///   presentation. Typically provided by the windowing system.
    ///
    /// # Safety
    ///
    /// Unsafe because the application must destroy the render device before
    /// exit. The application must also destroy all resources created by the
    /// logical device before destroying the render device.
    pub unsafe fn new(
        instance: VulkanInstance,
        features: PhysicalDeviceFeatures,
        surface: vk::SurfaceKHR,
    ) -> Result<Self, GraphicsError> {
        let window_surface = WindowSurface::new(&instance, surface);
        let physical_device =
            Self::pick_physical_device(&instance, features, &window_surface)?;
        let queue_finder = QueueFinder::new(&physical_device, &window_surface);
        let logical_device = unsafe {
            // SAFE because the RenderDevice takes ownership of the instance
            // along with the LogicalDevice.
            LogicalDevice::new(
                &instance,
                physical_device.clone(),
                &[ash::extensions::khr::Swapchain::name()
                    .to_owned()
                    .into_string()
                    .unwrap()],
                &queue_finder.queue_family_infos(),
            )?
        };
        let (graphics_queue, presentation_queue) =
            queue_finder.get_queues_from_device(&logical_device);

        let allocator = ccthw_ash_allocator::create_system_allocator(
            instance.ash(),
            logical_device.raw().clone(),
            *physical_device.raw(),
        );

        let render_device = Self {
            graphics_queue,
            presentation_queue,
            window_surface,
            logical_device,
            instance,
            allocator: Mutex::new(allocator),
        };
        render_device.set_debug_name(
            *render_device.presentation_queue().raw(),
            vk::ObjectType::QUEUE,
            "presentation queue",
        );
        render_device.set_debug_name(
            *render_device.graphics_queue.raw(),
            vk::ObjectType::QUEUE,
            "graphics queue",
        );

        Ok(render_device)
    }

    /// Borrow the device memory allocator.
    pub fn memory(&self) -> std::sync::MutexGuard<MemoryAllocator> {
        self.allocator.lock().unwrap()
    }

    /// Set the name that shows up in Vulkan debug logs for a given resource.
    ///
    /// # Params
    ///
    /// * `handle` - a Vulkan resource represented by the Ash library
    /// * `object_type` - the Vulkan object type
    /// * `name` - a human-readable name for the object. This will show up in
    ///   debug logs if the object is referenced.
    #[cfg(debug_assertions)]
    pub fn set_debug_name(
        &self,
        handle: impl ash::vk::Handle,
        object_type: vk::ObjectType,
        name: impl Into<String>,
    ) {
        let owned_name = name.into();
        let c_name = std::ffi::CString::new(owned_name).unwrap();
        let name_info = vk::DebugUtilsObjectNameInfoEXT {
            object_type,
            object_handle: handle.as_raw(),
            p_object_name: c_name.as_ptr(),
            ..Default::default()
        };
        self.instance.debug_utils_set_object_name(
            unsafe { self.logical_device.raw() },
            &name_info,
        );
    }

    /// Set the name that shows up in Vulkan debug logs for a given resource.
    ///
    /// # Params
    ///
    /// * `handle` - a Vulkan resource represented by the Ash library
    /// * `object_type` - the Vulkan object type
    /// * `name` - a human-readable name for the object. This will show up in
    ///   debug logs if the object is referenced.
    #[cfg(not(debug_assertions))]
    pub fn set_debug_name(
        &self,
        _handle: impl ash::vk::Handle,
        _object_type: vk::ObjectType,
        _name: impl Into<String>,
    ) {
        // no-op on release builds
    }

    /// The queue this application uses for graphics operations.
    pub fn presentation_queue(&self) -> &Queue {
        &self.presentation_queue
    }

    /// The queue this application uses for graphics operations.
    pub fn graphics_queue(&self) -> &Queue {
        &self.graphics_queue
    }

    /// The Ash entry used by this RenderDevice.
    pub fn entry(&self) -> &ash::Entry {
        self.instance.entry()
    }

    /// The Ash instance used by this RenderDevice.
    pub fn ash(&self) -> &ash::Instance {
        self.instance.ash()
    }

    /// The Ash logical device used to interface with the underlying Vulkan
    /// hardware device.
    ///
    /// # Safety
    ///
    /// The caller must not keep copies of the device handle after the render
    /// device is dropped.
    pub unsafe fn device(&self) -> &ash::Device {
        self.logical_device.raw()
    }

    /// The KHR surface provided by the window system for rendering.
    ///
    /// # Safety
    ///
    /// The caller must not keep copies of the device handle after the render
    /// device is dropped.
    pub unsafe fn surface(&self) -> &vk::SurfaceKHR {
        self.window_surface.raw()
    }

    /// Get all of the surface formats supported by this device.
    pub fn get_surface_formats(
        &self,
    ) -> Result<Vec<vk::SurfaceFormatKHR>, GraphicsError> {
        unsafe {
            // Safe because the physical device is checked for support when
            // the Render Device is constructed.
            self.window_surface.get_physical_device_surface_formats(
                self.logical_device.physical_device(),
            )
        }
    }

    /// Get all of the presentation modes supported by this device.
    pub fn get_present_modes(
        &self,
    ) -> Result<Vec<vk::PresentModeKHR>, GraphicsError> {
        unsafe {
            // Safe because the physical device is checked for support when
            // the Render Device is constructed.
            self.window_surface
                .get_physical_device_surface_present_modes(
                    self.logical_device.physical_device(),
                )
        }
    }

    /// Get the surface capabilities for this device.
    pub fn get_surface_capabilities(
        &self,
    ) -> Result<vk::SurfaceCapabilitiesKHR, GraphicsError> {
        unsafe {
            // Safe because the physical device is checked for support when
            // the Render Device is constructed.
            self.window_surface
                .get_surface_capabilities(self.logical_device.physical_device())
        }
    }
}

impl Drop for RenderDevice {
    fn drop(&mut self) {
        unsafe {
            self.device().device_wait_idle().expect(
                "Error waiting for pending graphics operations to complete!",
            );
        }
    }
}

impl std::fmt::Display for RenderDevice {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_fmt(format_args!(
            indoc!(
                "
                RenderDevice Overview

                {}

                {}

                Graphics {}

                Presentation {}"
            ),
            self.instance,
            self.logical_device,
            self.graphics_queue(),
            self.presentation_queue()
        ))
    }
}

// Private API
// -----------

impl RenderDevice {
    /// Pick a physical device which is suitable for this application.
    ///
    /// # Params
    ///
    /// * `instance` - the Vulkan instance used to access devices on this
    ///   platform.
    /// * `features` - all features required by this application.
    fn pick_physical_device(
        instance: &VulkanInstance,
        features: PhysicalDeviceFeatures,
        window_surface: &WindowSurface,
    ) -> Result<PhysicalDevice, GraphicsError> {
        let all_devices =
            PhysicalDevice::enumerate_supported_devices(instance, &features)?;

        log::trace!("All available physical devices: {:?}", all_devices);

        let usable_devices: Vec<PhysicalDevice> = all_devices
            .into_iter()
            .filter(|device| {
                let has_required_queues =
                    QueueFinder::device_has_required_queues(
                        device,
                        window_surface,
                    );
                log::trace!(
                    "{} has required queues? {}",
                    device,
                    has_required_queues
                );
                has_required_queues
            })
            .filter(|device| {
                let has_extensions =
                    device.available_extension_names().contains(
                        &ash::extensions::khr::Swapchain::name()
                            .to_owned()
                            .into_string()
                            .unwrap(),
                    );
                log::trace!(
                    "{} has required extensions? {}",
                    device,
                    has_extensions
                );
                has_extensions
            })
            .collect();
        let find_device_type =
            |device_type: vk::PhysicalDeviceType| -> Option<&PhysicalDevice> {
                usable_devices.iter().find(|device| {
                    device.properties().properties().device_type == device_type
                })
            };

        if let Some(device) =
            find_device_type(vk::PhysicalDeviceType::DISCRETE_GPU)
        {
            return Ok(device.clone());
        }

        if let Some(device) =
            find_device_type(vk::PhysicalDeviceType::INTEGRATED_GPU)
        {
            return Ok(device.clone());
        }

        let device = usable_devices
            .first()
            .ok_or(GraphicsError::NoSuitablePhysicalDevice)?;
        Ok(device.clone())
    }
}