forked from unknownue/vulkan-tutorial-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
06_swap_chain_creation.rs
579 lines (500 loc) · 19.8 KB
/
06_swap_chain_creation.rs
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
use vulkan_tutorial_rust::{
utility, // the mod define some fixed functions that have been learned before.
utility::constants::*,
utility::debug::ValidationInfo,
utility::share,
utility::structures::*,
};
use ash::version::DeviceV1_0;
use ash::version::InstanceV1_0;
use ash::vk;
use winit::event::{Event, VirtualKeyCode, ElementState, KeyboardInput, WindowEvent};
use winit::event_loop::{EventLoop, ControlFlow};
use std::collections::HashSet;
use std::ffi::CString;
use std::os::raw::c_char;
use std::ptr;
// Constants
const WINDOW_TITLE: &'static str = "06.Swap Chain Creation";
const DEVICE_EXTENSIONS: DeviceExtension = DeviceExtension {
names: ["VK_KHR_swapchain"],
};
struct QueueFamilyIndices {
graphics_family: Option<u32>,
present_family: Option<u32>,
}
impl QueueFamilyIndices {
pub fn new() -> QueueFamilyIndices {
QueueFamilyIndices {
graphics_family: None,
present_family: None,
}
}
pub fn is_complete(&self) -> bool {
self.graphics_family.is_some() && self.present_family.is_some()
}
}
struct SurfaceStuff {
surface_loader: ash::extensions::khr::Surface,
surface: vk::SurfaceKHR,
}
struct SwapChainStuff {
swapchain_loader: ash::extensions::khr::Swapchain,
swapchain: vk::SwapchainKHR,
swapchain_images: Vec<vk::Image>,
swapchain_format: vk::Format,
swapchain_extent: vk::Extent2D,
}
struct SwapChainSupportDetail {
capabilities: vk::SurfaceCapabilitiesKHR,
formats: Vec<vk::SurfaceFormatKHR>,
present_modes: Vec<vk::PresentModeKHR>,
}
struct VulkanApp {
_entry: ash::Entry,
instance: ash::Instance,
surface_loader: ash::extensions::khr::Surface,
surface: vk::SurfaceKHR,
debug_utils_loader: ash::extensions::ext::DebugUtils,
debug_merssager: vk::DebugUtilsMessengerEXT,
_physical_device: vk::PhysicalDevice,
device: ash::Device,
_graphics_queue: vk::Queue,
_present_queue: vk::Queue,
swapchain_loader: ash::extensions::khr::Swapchain,
swapchain: vk::SwapchainKHR,
_swapchain_images: Vec<vk::Image>,
_swapchain_format: vk::Format,
_swapchain_extent: vk::Extent2D,
}
impl VulkanApp {
pub fn new(window: &winit::window::Window) -> VulkanApp {
let entry = ash::Entry::new().unwrap();
let instance = share::create_instance(
&entry,
WINDOW_TITLE,
VALIDATION.is_enable,
&VALIDATION.required_validation_layers.to_vec(),
);
let surface_stuff = VulkanApp::create_surface(&entry, &instance, &window);
let (debug_utils_loader, debug_merssager) =
utility::debug::setup_debug_utils(VALIDATION.is_enable, &entry, &instance);
let physical_device = VulkanApp::pick_physical_device(&instance, &surface_stuff);
let (device, family_indices) = VulkanApp::create_logical_device(
&instance,
physical_device,
&VALIDATION,
&surface_stuff,
);
let graphics_queue =
unsafe { device.get_device_queue(family_indices.graphics_family.unwrap(), 0) };
let present_queue =
unsafe { device.get_device_queue(family_indices.present_family.unwrap(), 0) };
let swapchain_stuff = VulkanApp::create_swapchain(
&instance,
&device,
physical_device,
&surface_stuff,
&family_indices,
);
// cleanup(); the 'drop' function will take care of it.
VulkanApp {
_entry: entry,
instance,
surface: surface_stuff.surface,
surface_loader: surface_stuff.surface_loader,
debug_utils_loader,
debug_merssager,
_physical_device: physical_device,
device,
_graphics_queue: graphics_queue,
_present_queue: present_queue,
swapchain_loader: swapchain_stuff.swapchain_loader,
swapchain: swapchain_stuff.swapchain,
_swapchain_format: swapchain_stuff.swapchain_format,
_swapchain_images: swapchain_stuff.swapchain_images,
_swapchain_extent: swapchain_stuff.swapchain_extent,
}
}
fn create_surface(
entry: &ash::Entry,
instance: &ash::Instance,
window: &winit::window::Window,
) -> SurfaceStuff {
let surface = unsafe {
utility::platforms::create_surface(entry, instance, window)
.expect("Failed to create surface.")
};
let surface_loader = ash::extensions::khr::Surface::new(entry, instance);
SurfaceStuff {
surface_loader,
surface,
}
}
fn pick_physical_device(
instance: &ash::Instance,
surface_stuff: &SurfaceStuff,
) -> vk::PhysicalDevice {
let physical_devices = unsafe {
instance
.enumerate_physical_devices()
.expect("Failed to enumerate Physical Devices!")
};
let result = physical_devices.iter().find(|physical_device| {
VulkanApp::is_physical_device_suitable(
instance,
**physical_device,
surface_stuff,
)
});
match result {
Some(p_physical_device) => *p_physical_device,
None => panic!("Failed to find a suitable GPU!"),
}
}
fn is_physical_device_suitable(
instance: &ash::Instance,
physical_device: vk::PhysicalDevice,
surface_stuff: &SurfaceStuff,
) -> bool {
let _device_features = unsafe { instance.get_physical_device_features(physical_device) };
let indices = VulkanApp::find_queue_family(instance, physical_device, surface_stuff);
let is_queue_family_supported = indices.is_complete();
let is_device_extension_supported =
VulkanApp::check_device_extension_support(instance, physical_device);
let is_swapchain_supported = if is_device_extension_supported {
let swapchain_support = VulkanApp::query_swapchain_support(physical_device, surface_stuff);
!swapchain_support.formats.is_empty() && !swapchain_support.present_modes.is_empty()
} else {
false
};
return is_queue_family_supported
&& is_device_extension_supported
&& is_swapchain_supported;
}
fn create_logical_device(
instance: &ash::Instance,
physical_device: vk::PhysicalDevice,
validation: &ValidationInfo,
surface_stuff: &SurfaceStuff,
) -> (ash::Device, QueueFamilyIndices) {
let indices = VulkanApp::find_queue_family(instance, physical_device, surface_stuff);
let mut unique_queue_families = HashSet::new();
unique_queue_families.insert(indices.graphics_family.unwrap());
unique_queue_families.insert(indices.present_family.unwrap());
let queue_priorities = [1.0_f32];
let mut queue_create_infos = vec![];
for &queue_family in unique_queue_families.iter() {
let queue_create_info = vk::DeviceQueueCreateInfo {
s_type: vk::StructureType::DEVICE_QUEUE_CREATE_INFO,
p_next: ptr::null(),
flags: vk::DeviceQueueCreateFlags::empty(),
queue_family_index: queue_family,
p_queue_priorities: queue_priorities.as_ptr(),
queue_count: queue_priorities.len() as u32,
};
queue_create_infos.push(queue_create_info);
}
let physical_device_features = vk::PhysicalDeviceFeatures {
..Default::default() // default just enable no feature.
};
let requred_validation_layer_raw_names: Vec<CString> = validation
.required_validation_layers
.iter()
.map(|layer_name| CString::new(*layer_name).unwrap())
.collect();
let enable_layer_names: Vec<*const c_char> = requred_validation_layer_raw_names
.iter()
.map(|layer_name| layer_name.as_ptr())
.collect();
let enable_extension_names = [
ash::extensions::khr::Swapchain::name().as_ptr(), // currently just enable the Swapchain extension.
];
let device_create_info = vk::DeviceCreateInfo {
s_type: vk::StructureType::DEVICE_CREATE_INFO,
p_next: ptr::null(),
flags: vk::DeviceCreateFlags::empty(),
queue_create_info_count: queue_create_infos.len() as u32,
p_queue_create_infos: queue_create_infos.as_ptr(),
enabled_layer_count: if validation.is_enable {
enable_layer_names.len()
} else {
0
} as u32,
pp_enabled_layer_names: if validation.is_enable {
enable_layer_names.as_ptr()
} else {
ptr::null()
},
enabled_extension_count: enable_extension_names.len() as u32,
pp_enabled_extension_names: enable_extension_names.as_ptr(),
p_enabled_features: &physical_device_features,
};
let device: ash::Device = unsafe {
instance
.create_device(physical_device, &device_create_info, None)
.expect("Failed to create logical device!")
};
(device, indices)
}
fn find_queue_family(
instance: &ash::Instance,
physical_device: vk::PhysicalDevice,
surface_stuff: &SurfaceStuff,
) -> QueueFamilyIndices {
let queue_families =
unsafe { instance.get_physical_device_queue_family_properties(physical_device) };
let mut queue_family_indices = QueueFamilyIndices::new();
let mut index = 0;
for queue_family in queue_families.iter() {
if queue_family.queue_count > 0
&& queue_family.queue_flags.contains(vk::QueueFlags::GRAPHICS)
{
queue_family_indices.graphics_family = Some(index);
}
let is_present_support = unsafe {
surface_stuff
.surface_loader
.get_physical_device_surface_support(
physical_device,
index as u32,
surface_stuff.surface,
)
};
if queue_family.queue_count > 0 && is_present_support {
queue_family_indices.present_family = Some(index);
}
if queue_family_indices.is_complete() {
break;
}
index += 1;
}
queue_family_indices
}
fn check_device_extension_support(
instance: &ash::Instance,
physical_device: vk::PhysicalDevice,
) -> bool {
let available_extensions = unsafe {
instance
.enumerate_device_extension_properties(physical_device)
.expect("Failed to get device extension properties.")
};
let mut available_extension_names = vec![];
println!("\tAvailable Device Extensions: ");
for extension in available_extensions.iter() {
let extension_name = utility::tools::vk_to_string(&extension.extension_name);
println!(
"\t\tName: {}, Version: {}",
extension_name, extension.spec_version
);
available_extension_names.push(extension_name);
}
let mut required_extensions = HashSet::new();
for extension in DEVICE_EXTENSIONS.names.iter() {
required_extensions.insert(extension.to_string());
}
for extension_name in available_extension_names.iter() {
required_extensions.remove(extension_name);
}
return required_extensions.is_empty();
}
fn query_swapchain_support(
physical_device: vk::PhysicalDevice,
surface_stuff: &SurfaceStuff,
) -> SwapChainSupportDetail {
unsafe {
let capabilities = surface_stuff
.surface_loader
.get_physical_device_surface_capabilities(physical_device, surface_stuff.surface)
.expect("Failed to query for surface capabilities.");
let formats = surface_stuff
.surface_loader
.get_physical_device_surface_formats(physical_device, surface_stuff.surface)
.expect("Failed to query for surface formats.");
let present_modes = surface_stuff
.surface_loader
.get_physical_device_surface_present_modes(physical_device, surface_stuff.surface)
.expect("Failed to query for surface present mode.");
SwapChainSupportDetail {
capabilities,
formats,
present_modes,
}
}
}
fn create_swapchain(
instance: &ash::Instance,
device: &ash::Device,
physical_device: vk::PhysicalDevice,
surface_stuff: &SurfaceStuff,
queue_family: &QueueFamilyIndices,
) -> SwapChainStuff {
let swapchain_support = VulkanApp::query_swapchain_support(physical_device, surface_stuff);
let surface_format = VulkanApp::choose_swapchain_format(&swapchain_support.formats);
let present_mode =
VulkanApp::choose_swapchain_present_mode(&swapchain_support.present_modes);
let extent = VulkanApp::choose_swapchain_extent(&swapchain_support.capabilities);
let image_count = swapchain_support.capabilities.min_image_count + 1;
let image_count = if swapchain_support.capabilities.max_image_count > 0 {
image_count.min(swapchain_support.capabilities.max_image_count)
} else {
image_count
};
let (image_sharing_mode, queue_family_index_count, queue_family_indices) =
if queue_family.graphics_family != queue_family.present_family {
(
vk::SharingMode::EXCLUSIVE,
2,
vec![
queue_family.graphics_family.unwrap(),
queue_family.present_family.unwrap(),
],
)
} else {
(vk::SharingMode::EXCLUSIVE, 0, vec![])
};
let swapchain_create_info = vk::SwapchainCreateInfoKHR {
s_type: vk::StructureType::SWAPCHAIN_CREATE_INFO_KHR,
p_next: ptr::null(),
flags: vk::SwapchainCreateFlagsKHR::empty(),
surface: surface_stuff.surface,
min_image_count: image_count,
image_color_space: surface_format.color_space,
image_format: surface_format.format,
image_extent: extent,
image_usage: vk::ImageUsageFlags::COLOR_ATTACHMENT,
image_sharing_mode,
p_queue_family_indices: queue_family_indices.as_ptr(),
queue_family_index_count,
pre_transform: swapchain_support.capabilities.current_transform,
composite_alpha: vk::CompositeAlphaFlagsKHR::OPAQUE,
present_mode,
clipped: vk::TRUE,
old_swapchain: vk::SwapchainKHR::null(),
image_array_layers: 1,
};
let swapchain_loader = ash::extensions::khr::Swapchain::new(instance, device);
let swapchain = unsafe {
swapchain_loader
.create_swapchain(&swapchain_create_info, None)
.expect("Failed to create Swapchain!")
};
let swapchain_images = unsafe {
swapchain_loader
.get_swapchain_images(swapchain)
.expect("Failed to get Swapchain Images.")
};
SwapChainStuff {
swapchain_loader,
swapchain,
swapchain_format: surface_format.format,
swapchain_extent: extent,
swapchain_images,
}
}
fn choose_swapchain_format(
available_formats: &Vec<vk::SurfaceFormatKHR>,
) -> vk::SurfaceFormatKHR {
// check if list contains most widely used R8G8B8A8 format with nonlinear color space
for available_format in available_formats {
if available_format.format == vk::Format::B8G8R8A8_SRGB
&& available_format.color_space == vk::ColorSpaceKHR::SRGB_NONLINEAR
{
return available_format.clone();
}
}
// return the first format from the list
return available_formats.first().unwrap().clone();
}
fn choose_swapchain_present_mode(
available_present_modes: &Vec<vk::PresentModeKHR>,
) -> vk::PresentModeKHR {
for &available_present_mode in available_present_modes.iter() {
if available_present_mode == vk::PresentModeKHR::MAILBOX {
return available_present_mode;
}
}
vk::PresentModeKHR::FIFO
}
fn choose_swapchain_extent(capabilities: &vk::SurfaceCapabilitiesKHR) -> vk::Extent2D {
if capabilities.current_extent.width != u32::max_value() {
capabilities.current_extent
} else {
use num::clamp;
vk::Extent2D {
width: clamp(
WINDOW_WIDTH,
capabilities.min_image_extent.width,
capabilities.max_image_extent.width,
),
height: clamp(
WINDOW_HEIGHT,
capabilities.min_image_extent.height,
capabilities.max_image_extent.height,
),
}
}
}
fn draw_frame(&mut self) {
// Drawing will be here
}
}
impl Drop for VulkanApp {
fn drop(&mut self) {
unsafe {
self.swapchain_loader
.destroy_swapchain(self.swapchain, None);
self.device.destroy_device(None);
self.surface_loader.destroy_surface(self.surface, None);
if VALIDATION.is_enable {
self.debug_utils_loader
.destroy_debug_utils_messenger(self.debug_merssager, None);
}
self.instance.destroy_instance(None);
}
}
}
// Fix content -------------------------------------------------------------------------------
impl VulkanApp {
pub fn main_loop(mut self, event_loop: EventLoop<()>, window: winit::window::Window) {
event_loop.run(move |event, _, control_flow| {
match event {
| Event::WindowEvent { event, .. } => {
match event {
| WindowEvent::CloseRequested => {
*control_flow = ControlFlow::Exit
},
| WindowEvent::KeyboardInput { input, .. } => {
match input {
| KeyboardInput { virtual_keycode, state, .. } => {
match (virtual_keycode, state) {
| (Some(VirtualKeyCode::Escape), ElementState::Pressed) => {
*control_flow = ControlFlow::Exit
},
| _ => {},
}
},
}
},
| _ => {},
}
},
| Event::MainEventsCleared => {
window.request_redraw();
},
| Event::RedrawRequested(_window_id) => {
self.draw_frame();
},
_ => (),
}
})
}
}
fn main() {
let event_loop = EventLoop::new();
let window = utility::window::init_window(&event_loop, WINDOW_TITLE, WINDOW_WIDTH, WINDOW_HEIGHT);
let vulkan_app = VulkanApp::new(&window);
vulkan_app.main_loop(event_loop, window);
}
// -------------------------------------------------------------------------------------------