Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
1923 lines (1542 loc) · 65.4 KB
/
Copy pathmain.cpp
File metadata and controls
1923 lines (1542 loc) · 65.4 KB
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <cstdint>
#include <limits>
#include <optional>
#include <set>
#include <fstream>
#ifdef NDEBUG
const bool enableValidationLayers = false; // boolean flag for release and debug. if debug then set false
#else
const bool enableValidationLayers = true; // boolean flag for release and debug. if debug then set true
#endif // NDEBUG
const uint32_t WIDTH = 800; // window width
const uint32_t HEIGHT = 600; // window height
const int MAX_FRAMES_IN_FLIGHT = 2; // max frames count
// extenstions
const std::vector<const char*> validationLayers = { "VK_LAYER_KHRONOS_validation" }; // validation layer
// List of device extensions required by our renderer.
// Currently we only require the Swapchain extension.
// Without this extension, Vulkan cannot present rendered
// images to the window.
const std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME };
/* Creates a Vulkan Debug Messenger.
Since vkCreateDebugUtilsMessengerEXT is part of an extension
(not Vulkan Core), we must first retrieve its function pointer
from the Vulkan driver before calling it.
*/
VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pDebugMessenger)
{
// Ask Vulkan for the address of the extension function.
// PFN_vkCreateDebugUtilsMessengerEXT is the correct
// function-pointer type for vkCreateDebugUtilsMessengerEXT.
auto func =
(PFN_vkCreateDebugUtilsMessengerEXT)
vkGetInstanceProcAddr(instance,
"vkCreateDebugUtilsMessengerEXT");
// If the function exists, call it just like a normal function.
if (func != nullptr)
{
return func(
instance,
pCreateInfo,
pAllocator,
pDebugMessenger);
}
else
{
// The extension was not enabled or is not supported.
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
/* Destroys the Vulkan Debug Messenger.
Like the create function, this is also an extension function,
so we must retrieve its address before calling it.
*/
void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, const VkAllocationCallbacks* pAllocator)
{
// Get the address of vkDestroyDebugUtilsMessengerEXT.
auto func =
(PFN_vkDestroyDebugUtilsMessengerEXT)
vkGetInstanceProcAddr(instance,
"vkDestroyDebugUtilsMessengerEXT");
// If the function exists, destroy the debug messenger.
if (func != nullptr)
{
func(
instance,
debugMessenger,
pAllocator);
}
}
/* Stores the indices of all queue families required by our renderer.
Each member is std::optional because we don't know its value
until we search the GPU's queue families. */
struct QueueFamilyIndices
{
// Index of the queue family that supports Graphics commands. Initially empty until a suitable graphics queue is found.
std::optional<uint32_t> graphicsFamily;
// Index of the queue family that supports presenting commands. Initially empty until a suitable present queue is found.
std::optional<uint32_t> presentFamily;
/*
Check whether all required queue families have been found.
Currently we require a Graphics Queue, present Queue.
Later this function will also check for Compute,
Transfer, and other queue families if needed.
*/
bool isComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value(); // Returns true if graphicsFamily contains a valid index. Returns false if no graphics queue has been found yet.
}
};
/* Stores all Swapchain information supported by a GPU
for a particular window surface. */
struct SwapChainSupportDetails
{
// General capabilities of the surface.
// Examples:
// - Minimum and maximum image count
// - Current window size
// - Supported image sizes
// - Supported transforms
VkSurfaceCapabilitiesKHR capabilities;
// List of all supported image formats
// (pixel format + color space).
std::vector<VkSurfaceFormatKHR> formats;
// List of all supported presentation modes
// (FIFO, MAILBOX, IMMEDIATE, etc.).
std::vector<VkPresentModeKHR> presentModes;
};
/* main class */
class HelloTriangleApplication {
public:
/* Main Run Loop */
void run() {
initWindow(); // create main window
initVulkan(); // initializing vulkan
mainLoop(); // main loop
cleanup(); // clean up delete all allocated memory
}
private:
// window
GLFWwindow* window; // main window
// vulkan instance
VkInstance instance; // instance object
VkDebugUtilsMessengerEXT debugMessenger; // Debuger object
VkSurfaceKHR surface;
// devices
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; // Physical device object creation.
VkDevice device; // logical device.
// queue
VkQueue graphicsQueue; // this stores the graphics queue data.
VkQueue presentQueue; // this stores the present queue data.
// swapchain
VkSwapchainKHR swapChain; // this is main swapchain.
std::vector<VkImage> swapChainImages; // stores and create image for swapchain.
VkFormat swapChainImageFormat; // this stores the swapchain image format.
VkExtent2D swapChainExtent; // this store the extend size.
std::vector<VkImageView> swapChainImageViews; // this stores image view.
// graphics
VkRenderPass renderPass; // rendere pass.
VkPipelineLayout pipelineLayout; // this stores pipline layout.
VkPipeline graphicsPipeline; // this is main graphcis object.
// framebuffer
std::vector<VkFramebuffer> swapChainFramebuffers; // this store framebuffer data.
// commands
VkCommandPool commandPool; // this store command pool.
std::vector<VkCommandBuffer> commandBuffers; // this store command buffer.
// synchronous
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
uint32_t currentFrame = 0;
/* Initialize Window */
void initWindow() {
if (!glfwInit()) { std::cout << "Failed to Initialize GLFW ! " << std::endl; } // initialize glew and also check that it was initialize correctly! best practice.
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); // set no api as glfw was initially made for opengl and now using for vulkan required to set that value to false. it is done but glfwwindowhint function.
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); // set resizable to flase as to make it resizable required some more code. for starting let it be false.
window = glfwCreateWindow(WIDTH, HEIGHT, "Vulkan", nullptr, nullptr); // creates main window assign width and height then assign name for app then rest can be nullptr.
}
/* Initializing Vulkan */
void initVulkan() {
// Instance
createInstance(); // now we will call createInstance to create vulkan instance this is main part and step 1 for vulkan.
setupDebugMessenger(); // now also call setupDebugMessager to see actual error waring for code and it will be disable automatically in release mode.
// window surface
createSurface(); // noew we will create an surface where we can present our rendering to screen.
// Devices
pickPhysicalDevice(); // now we will call pickphysicaldevice function to get a best physical device that is present in systema and use it.
createLogicalDevice(); // now we will create and logical device.
// swapchain
createSwapChain();
createImageViews(); // now we will create an image view.
// graphics pipline
createRenderPass(); // now we will render.
createGraphicsPipeline(); // now we will make our graphcis pipline.
// framebuffer
createFramebuffers(); // now we will create framebuufer
// commands
createCommandPool(); // now we will create command pool
createCommandBuffers(); // now we will creat command buffer
// synchronization
createSyncObjects(); // now we will create an synchronization Objects.
}
/* Main Loop */
void mainLoop() {
/* run code until window is not close */
while (!glfwWindowShouldClose(window)) {
glfwPollEvents(); // provide functionality like minimize resize and close window.
drawFrame();
}
// wait for device to finish its work.
vkDeviceWaitIdle(device);
}
/* clean up delets all memory allcated by program (required) */
void cleanup() {
// clear synchronization objects.
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
vkDestroyFence(device, inFlightFences[i], nullptr);
}
// clear command pool
vkDestroyCommandPool(device, commandPool, nullptr);
// destroy framebuffer
for (auto framebuffer : swapChainFramebuffers) {
vkDestroyFramebuffer(device, framebuffer, nullptr);
}
// graphics
vkDestroyPipeline(device, graphicsPipeline, nullptr);
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
vkDestroyRenderPass(device, renderPass, nullptr);
// swapchain images
for (auto imageView : swapChainImageViews) {
vkDestroyImageView(device, imageView, nullptr);
}
// swapchain destroys.
vkDestroySwapchainKHR(device, swapChain, nullptr); // destroy swapchain
// delete device.
vkDestroyDevice(device, nullptr); // destroy created device.
// delete debug message
if (enableValidationLayers) { DestroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr); } // if code run with debug mode then it needs to clear all allocation however in release mode it is not called.
// delete window surface.
vkDestroySurfaceKHR(instance, surface, nullptr);
// delete instance of vulkan
vkDestroyInstance(instance, nullptr); // Destroy VULKAN INSTANCE
// delete window
glfwDestroyWindow(window); // GLFW WINDOW DESTROY
// terminate program
glfwTerminate(); // TERMINATE PROGRAM
}
/* create an Instance for vulkan */
void createInstance() {
if (enableValidationLayers && !checkValidationLayerSupport()) { throw std::runtime_error("validation layers requested, but not available!"); } // check for validation layer if not found then throw error for it and it only happen when debug mode is on.
// Application Info
VkApplicationInfo appinfo{}; // creating object for application.
appinfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; // structure of object i.e application info.
appinfo.pApplicationName = "Hello Triangle"; // application name.
appinfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); // application version.
appinfo.pEngineName = "No Engine"; // engine name.
appinfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); // engine version.
appinfo.apiVersion = VK_API_VERSION_1_0; // api version.
// Instance
VkInstanceCreateInfo createInfo{}; // CREATING OBJECT FRO INSTANCE.
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; // CREATING STRUCTRUE FOR INSTANCE OBJECT.
createInfo.pApplicationInfo = &appinfo; // ASSIGN APPLICATION INFO WITH APPINFO.
// EXTENSTION.
uint32_t glfwExtensionCount = 0; // glfwExtension Counter initialize with zero.
const char** glfwExtensions; // pointer to glfw Extension.
#if 0 /* starter code */
// glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); // provide glfwrequiredinstanceextension with counts i.e glfwExtensionCount = 0;
// createInfo.enabledExtensionCount = glfwExtensionCount; // assgin glfwcount to enabling vk instance object . propertie i.e enable extension count with get enable with value of count.
// createInfo.ppEnabledExtensionNames = glfwExtensions; // enable all extesntion with name provide from glfwExtensions.
// createInfo.enabledLayerCount = 0; // enable layer count with 0.
#endif
auto extensions = getRequiredExtensions(); // this returns all required extensions.
createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size()); // enable extenstion count to extenstion size.
createInfo.ppEnabledExtensionNames = extensions.data(); // enable extension name with extension data.
VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo{}; // created an object for debuginfo.
if (enableValidationLayers) // check is debug is on. If it is true then only run validation code or else no need on runtime.
{
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); // enable layer count with all layer that are avaible and provided by validation layer.
createInfo.ppEnabledLayerNames = validationLayers.data(); // assign enabled layer with name, which is provided by validation data function.
populateDebugMessengerCreateInfo(debugCreateInfo); // for created debuginfo object we will populate it with messager.
createInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT*)&debugCreateInfo; // we will point to next debug info.
}
else
{
createInfo.enabledLayerCount = 0; // set layer count to 0 only if it not in debug as in release mode no need to check this validation any more.
}
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) { throw std::runtime_error("failed to create instance!"); } // CREATED INSTANCE AND ALSO CHECK IS THAT WAS PERFECT.
}
/* Create a Vulkan Surface.
A Surface connects the operating system's window (GLFW)
with Vulkan so rendered images can be displayed on screen.
*/
void createSurface()
{
// Ask GLFW to create a Vulkan-compatible surface
// for our existing window.
if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS)
{
throw std::runtime_error("failed to create window surface!");
}
}
/* Select a physical GPU from all Vulkan-compatible GPUs in the system. */
void pickPhysicalDevice()
{
uint32_t deviceCount = 0; // Stores how many Vulkan-compatible GPUs are available.
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); // First call: only retrieve the number of physical devices. Passing nullptr means "don't return the devices yet."
if (deviceCount == 0)
{
throw std::runtime_error("failed to find GPUs with Vulkan support!"); // No Vulkan-capable GPU was found.
}
std::vector<VkPhysicalDevice> devices(deviceCount); // Allocate enough space to store all GPU handles.
vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data()); // Second call: retrieve all physical device handles.
// Check every GPU until we find one that satisfies
// the requirements of our renderer.
for (const auto& device : devices)
{
if (isDeviceSuitable(device))
{
physicalDevice = device; // Save the selected GPU.
break;
}
}
if (physicalDevice == VK_NULL_HANDLE)
{
throw std::runtime_error("failed to find a suitable GPU!"); // Every GPU failed our suitability checks.
}
}
/*
Create the Logical Device and all required queues.
We now request both Graphics and Presentation queues.
If both use the same queue family, we create only one queue.
*/
void createLogicalDevice()
{
QueueFamilyIndices indices = findQueueFamilies(physicalDevice); // Find the Graphics and Presentation queue families.
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; // Store queue creation information.
// Store only unique queue families.
// If Graphics and Presentation are the same,
// std::set automatically removes duplicates.
std::set<uint32_t> uniqueQueueFamilies =
{
indices.graphicsFamily.value(),
indices.presentFamily.value()
};
float queuePriority = 1.0f;
// Create one queue description for every unique queue family.
for (uint32_t queueFamily : uniqueQueueFamilies)
{
VkDeviceQueueCreateInfo queueCreateInfo{};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queueFamily;
queueCreateInfo.queueCount = 1; // Create one queue from this family.
queueCreateInfo.pQueuePriorities = &queuePriority;
queueCreateInfos.push_back(queueCreateInfo);
}
// No GPU features enabled yet.
VkPhysicalDeviceFeatures deviceFeatures{};
// Describe the Logical Device.
VkDeviceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
createInfo.pQueueCreateInfos = queueCreateInfos.data();
createInfo.pEnabledFeatures = &deviceFeatures;
#if 0 // before swapchain
createInfo.enabledExtensionCount = 0;
#endif
// after swapchain
createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
createInfo.ppEnabledExtensionNames = deviceExtensions.data();
#if 0
if (enableValidationLayers)
{
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
}
else
{
createInfo.enabledLayerCount = 0;
}
#endif
// latest vulkan code
createInfo.enabledLayerCount = 0;
// Create the Logical Device.
if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS)
{
throw std::runtime_error("failed to create logical device!");
}
// Retrieve the Graphics Queue.
vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
// Retrieve the Presentation Queue.
vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
}
/* Create the Swapchain.
The Swapchain stores the images that will be rendered
and later presented (displayed) on the screen. */
void createSwapChain()
{
// Query all Swapchain support information from the selected GPU.
// This gives us:
// - Surface capabilities
// - Supported image formats
// - Supported presentation modes
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);
// Choose the best image format supported by the GPU.
// Example:
// VK_FORMAT_B8G8R8A8_SRGB
VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
// Choose the best presentation mode.
// Prefer MAILBOX, otherwise use FIFO.
VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
// Choose the image size (width and height)
// for every Swapchain image.
VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities);
// Request one more image than the minimum supported.
// This helps prevent the GPU from waiting while rendering.
uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
// If the GPU specifies a maximum image count,
// make sure we do not exceed it.
if (swapChainSupport.capabilities.maxImageCount > 0 &&
imageCount > swapChainSupport.capabilities.maxImageCount)
{
imageCount = swapChainSupport.capabilities.maxImageCount;
}
// Create the Swapchain creation structure.
VkSwapchainCreateInfoKHR createInfo{};
// Specify that this structure describes a Swapchain.
createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
// The window surface where the Swapchain images
// will eventually be presented.
createInfo.surface = surface;
// Number of images inside the Swapchain.
createInfo.minImageCount = imageCount;
// Pixel format for every Swapchain image.
createInfo.imageFormat = surfaceFormat.format;
// Color space used by the Swapchain images.
createInfo.imageColorSpace = surfaceFormat.colorSpace;
// Width and height of every Swapchain image.
createInfo.imageExtent = extent;
// Number of layers per image.
// Normal applications always use one layer.
createInfo.imageArrayLayers = 1;
// Specify how the images will be used.
// Here they are used as color attachments
// because we will render directly into them.
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
// Find the Graphics and Present queue families.
QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
// Store both queue family indices.
uint32_t queueFamilyIndices[] =
{
indices.graphicsFamily.value(),
indices.presentFamily.value()
};
// Check whether Graphics and Present queues
// belong to different queue families.
if (indices.graphicsFamily != indices.presentFamily)
{
// Allow both queue families to access
// the Swapchain images simultaneously.
createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
// Two queue families will share the images.
createInfo.queueFamilyIndexCount = 2;
// Pass both queue family indices.
createInfo.pQueueFamilyIndices = queueFamilyIndices;
}
else
{
// Graphics and Present use the same queue family.
// Exclusive mode gives better performance.
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
}
// Keep the current transformation of the window.
// (Example: rotation or orientation supplied by the OS.)
createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
// Ignore the alpha channel when blending
// the window with other windows.
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
// Selected presentation mode (MAILBOX or FIFO).
createInfo.presentMode = presentMode;
// We do not care about pixels that are hidden
// behind another window. Vulkan may discard them
// for better performance.
createInfo.clipped = VK_TRUE;
// No previous Swapchain exists.
// Used later when recreating the Swapchain after resizing.
createInfo.oldSwapchain = VK_NULL_HANDLE;
// Create the actual Swapchain.
if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS)
{
throw std::runtime_error("failed to create swap chain!");
}
// --------------------------------------------
// Retrieve all Swapchain Images
// --------------------------------------------
// First call:
// Retrieve only the number of Swapchain images.
vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
// Allocate enough space to store all image handles.
swapChainImages.resize(imageCount);
// Second call:
// Retrieve the handles of every Swapchain image.
vkGetSwapchainImagesKHR(
device,
swapChain,
&imageCount,
swapChainImages.data());
// Save the chosen image format for later use
// when creating Image Views and the Render Pass.
swapChainImageFormat = surfaceFormat.format;
// Save the image size for later use
// during rendering.
swapChainExtent = extent;
}
/* Create an Image View for every Swapchain Image.
Vulkan cannot use a VkImage directly for rendering.
An Image View describes how Vulkan should access that image. */
void createImageViews()
{
// Allocate space for one Image View
// for every Swapchain Image.
swapChainImageViews.resize(swapChainImages.size());
// Create an Image View for every image
// inside the Swapchain.
for (size_t i = 0; i < swapChainImages.size(); i++)
{
// Create the Image View description.
VkImageViewCreateInfo createInfo{};
// Specify that this structure describes
// an Image View.
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
// Select the Swapchain Image
// this Image View will represent.
createInfo.image = swapChainImages[i];
// This is a normal 2D image.
createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
// Use the same image format
// chosen when creating the Swapchain.
createInfo.format = swapChainImageFormat;
// Do not remap any color channels.
// Keep R→R, G→G, B→B, A→A.
createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
// This Image View represents the color aspect
// of the image.
createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
// Start from mip level 0.
createInfo.subresourceRange.baseMipLevel = 0;
// Use only one mip level.
createInfo.subresourceRange.levelCount = 1;
// Start from the first array layer.
createInfo.subresourceRange.baseArrayLayer = 0;
// Use only one array layer.
createInfo.subresourceRange.layerCount = 1;
// Create the Image View.
if (vkCreateImageView(device, &createInfo, nullptr,
&swapChainImageViews[i]) != VK_SUCCESS)
{
throw std::runtime_error("failed to create image views!");
}
}
}
/* Create a Render Pass.
A Render Pass describes:
- Which images will be rendered to.
- How those images should be handled before rendering.
- How they should be handled after rendering.
- Which subpasses will use those images. */
void createRenderPass()
{
// ==========================================================
// Color Attachment
// This describes the Swapchain Image that we will render into.
// ==========================================================
VkAttachmentDescription colorAttachment{};
// Image format must match the Swapchain Image format.
colorAttachment.format = swapChainImageFormat;
// Use one sample per pixel (No MSAA).
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
// Before rendering begins,
// clear the image to the clear color.
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
// After rendering,
// keep the rendered image.
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
// We are not using a stencil buffer.
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
// Previous contents of the image are ignored.
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
// After rendering,
// prepare the image for presentation on the screen.
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
// ==========================================================
// Attachment Reference
// Tell the Subpass which attachment to use.
// ==========================================================
VkAttachmentReference colorAttachmentRef{};
// Use attachment index 0.
colorAttachmentRef.attachment = 0;
// During rendering,
// this attachment acts as a Color Attachment.
colorAttachmentRef.layout =
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
// ==========================================================
// Subpass
// A Subpass is one stage of rendering inside the Render Pass.
// Here we create one Graphics Subpass.
// ==========================================================
VkSubpassDescription subpass{};
// This Subpass uses the Graphics Pipeline.
subpass.pipelineBindPoint =
VK_PIPELINE_BIND_POINT_GRAPHICS;
// One Color Attachment.
subpass.colorAttachmentCount = 1;
// Attach our Color Attachment Reference.
subpass.pColorAttachments = &colorAttachmentRef;
// ==========================================================
// Render Pass Creation Info
// Collect all attachments and subpasses together.
// ==========================================================
VkRenderPassCreateInfo renderPassInfo{};
renderPassInfo.sType =
VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
// Total number of attachments.
renderPassInfo.attachmentCount = 1;
// Pointer to attachment descriptions.
renderPassInfo.pAttachments = &colorAttachment;
// Total number of Subpasses.
renderPassInfo.subpassCount = 1;
// Pointer to Subpass descriptions.
renderPassInfo.pSubpasses = &subpass;
// ==========================================================
// Create the Vulkan Render Pass object.
// ==========================================================
if (vkCreateRenderPass(
device,
&renderPassInfo,
nullptr,
&renderPass) != VK_SUCCESS)
{
throw std::runtime_error("failed to create render pass!");
}
}
/* Prepare all states required for creating the Graphics Pipeline.
(The actual Graphics Pipeline will be created in a later chapter.) */
void createGraphicsPipeline()
{
// ==========================================================
// Read compiled SPIR-V shader files from disk.
// ==========================================================
auto vertShaderCode = readFile("shaders/vert.spv"); // Vertex Shader
auto fragShaderCode = readFile("shaders/frag.spv"); // Fragment Shader
// ==========================================================
// Create Vulkan Shader Modules from the SPIR-V bytecode.
// Shader Modules are Vulkan objects that store compiled shaders.
// ==========================================================
VkShaderModule vertShaderModule = createShaderModule(vertShaderCode);
VkShaderModule fragShaderModule = createShaderModule(fragShaderCode);
// ==========================================================
// Vertex Shader Stage
// Tell Vulkan which shader should execute during
// the Vertex Shader stage.
// ==========================================================
VkPipelineShaderStageCreateInfo vertShaderStageInfo{};
vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT; // Vertex Shader stage
vertShaderStageInfo.module = vertShaderModule; // Shader Module to execute
vertShaderStageInfo.pName = "main"; // Entry function inside shader
// ==========================================================
// Fragment Shader Stage
// Tell Vulkan which shader should execute during
// the Fragment Shader stage.
// ==========================================================
VkPipelineShaderStageCreateInfo fragShaderStageInfo{};
fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT; // Fragment Shader stage
fragShaderStageInfo.module = fragShaderModule; // Shader Module
fragShaderStageInfo.pName = "main"; // Entry function
// Store both shader stages together.
// This array will later be passed to vkCreateGraphicsPipelines().
VkPipelineShaderStageCreateInfo shaderStages[] =
{
vertShaderStageInfo,
fragShaderStageInfo
};
// ==========================================================
// Vertex Input State
// Describes how vertex data is read from Vertex Buffers.
//
// Currently we are NOT using Vertex Buffers,
// so there are no bindings or attributes.
// ==========================================================
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputInfo.vertexBindingDescriptionCount = 0;
vertexInputInfo.vertexAttributeDescriptionCount = 0;
// ==========================================================
// Input Assembly State
// Describes how Vulkan should connect vertices together.
// ==========================================================
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
// Every 3 vertices become one triangle.
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
// Primitive Restart is only useful for strips.
inputAssembly.primitiveRestartEnable = VK_FALSE;
// ==========================================================
// Viewport State
// Specifies how many Viewports and Scissor Rectangles
// this pipeline will use.
//
// Actual viewport/scissor values are set dynamically later.
// ==========================================================
VkPipelineViewportStateCreateInfo viewportState{};
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportState.viewportCount = 1;
viewportState.scissorCount = 1;
// ==========================================================
// Rasterizer State
// Converts triangles into fragments (pixels).
// Also controls culling and polygon drawing mode.
// ==========================================================
VkPipelineRasterizationStateCreateInfo rasterizer{};
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
// Don't clamp fragments beyond near/far planes.
rasterizer.depthClampEnable = VK_FALSE;
// Actually rasterize geometry.
// If TRUE, nothing would be drawn.
rasterizer.rasterizerDiscardEnable = VK_FALSE;
// Draw filled triangles.
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
// Line width (used when drawing lines).
rasterizer.lineWidth = 1.0f;
// Ignore back-facing triangles.
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
// Clockwise vertices are considered the front face.
rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;
// No depth bias.
// Used later for Shadow Mapping.
rasterizer.depthBiasEnable = VK_FALSE;
// ==========================================================
// Multisampling State
// Controls Anti-Aliasing (MSAA).
// ==========================================================
VkPipelineMultisampleStateCreateInfo multisampling{};
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
// Disable sample shading.
multisampling.sampleShadingEnable = VK_FALSE;
// Use only one sample per pixel.
// (No Anti-Aliasing)
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
// ==========================================================
// Color Blend Attachment
// Describes how one framebuffer attachment
// should receive color output.
// ==========================================================
VkPipelineColorBlendAttachmentState colorBlendAttachment{};
// Enable writing to all RGBA channels.
colorBlendAttachment.colorWriteMask =
VK_COLOR_COMPONENT_R_BIT |
VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT |
VK_COLOR_COMPONENT_A_BIT;
// Disable color blending.
// New pixel completely replaces old pixel.
colorBlendAttachment.blendEnable = VK_FALSE;
// ==========================================================
// Color Blend State
// Controls blending for the entire pipeline.
// ==========================================================
VkPipelineColorBlendStateCreateInfo colorBlending{};
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
// Disable logical operations.
colorBlending.logicOpEnable = VK_FALSE;
// Copy output color directly.
colorBlending.logicOp = VK_LOGIC_OP_COPY;
// One framebuffer attachment.
colorBlending.attachmentCount = 1;
colorBlending.pAttachments = &colorBlendAttachment;
// Blend constants.
// Used only for certain blend modes.
colorBlending.blendConstants[0] = 0.0f;
colorBlending.blendConstants[1] = 0.0f;
colorBlending.blendConstants[2] = 0.0f;
colorBlending.blendConstants[3] = 0.0f;
// ==========================================================
// Dynamic States
// These states will NOT be fixed inside the pipeline.
// They can be changed during rendering using Vulkan commands.
// ==========================================================
std::vector<VkDynamicState> dynamicStates =
{
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR
};
VkPipelineDynamicStateCreateInfo dynamicState{};
dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamicState.dynamicStateCount = static_cast<uint32_t>(dynamicStates.size());
dynamicState.pDynamicStates = dynamicStates.data();
// ==========================================================
// Pipeline Layout
// Defines how shaders receive resources like:
// - Uniform Buffers
// - Textures
// - Descriptor Sets
// - Push Constants
//
// Currently we are not using any of these.
// ==========================================================