-
Notifications
You must be signed in to change notification settings - Fork 0
/
VulkanRenderer.cpp
1733 lines (1427 loc) · 73.6 KB
/
VulkanRenderer.cpp
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
#include "VulkanRenderer.h"
VulkanRenderer::VulkanRenderer()
{
}
int VulkanRenderer::init(GLFWwindow * newWindow)
{
window = newWindow;
try {
createInstance();
createSurface();
getPhysicalDevice();
createLogicalDevice();
createSwapChain();
createRenderPass();
createDescriptorSetLayout();
createPushConstantRange();
createGraphicsPipeline();
createDepthBufferImage();
createFramebuffers();
createCommandPool();
createCommandBuffers();
createTextureSampler();
//allocateDynamicBufferTransferSpace();
createUniformBuffers();
createDescriptorPool();
createDescriptorSets();
createSynchronisation();
uboViewProjection.projection = glm::perspective(glm::radians(45.0f), (float)swapChainExtent.width / (float)swapChainExtent.height, 0.1f, 100.0f);
uboViewProjection.view = glm::lookAt(glm::vec3(50.0f, 40.0f, 60.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
uboViewProjection.projection[1][1] *= -1;
// create default "no texture" fallback
createTexture("plain.png");
}
catch (const std::runtime_error &e) {
printf("ERROR: %s\n", e.what());
return EXIT_FAILURE;
}
return 0;
}
void VulkanRenderer::updateModel(int modelId, glm::mat4 newModel)
{
if (modelId >= modelList.size()) return;
modelList[modelId].setModel(newModel);
}
void VulkanRenderer::draw()
{
// -- GET NEXT IMAGE --
// Wait for given fence to signal (open) from last draw before continuing
vkWaitForFences(mainDevice.logicalDevice, 1, &drawFences[currentFrame], VK_TRUE, std::numeric_limits<uint64_t>::max());
// Manually reset (close) fences
vkResetFences(mainDevice.logicalDevice, 1, &drawFences[currentFrame]);
// Get index of next image to be drawn to, and signal semaphore when ready to be drawn to
uint32_t imageIndex;
vkAcquireNextImageKHR(mainDevice.logicalDevice, swapchain, std::numeric_limits<uint64_t>::max(), imageAvailable[currentFrame], VK_NULL_HANDLE, &imageIndex);
recordCommands(imageIndex);
updateUniformBuffers(imageIndex);
// -- SUBMIT COMMAND BUFFER TO RENDER --
// Queue submission information
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.waitSemaphoreCount = 1; // Number of semaphores to wait on
submitInfo.pWaitSemaphores = &imageAvailable[currentFrame]; // List of semaphores to wait on
VkPipelineStageFlags waitStages[] = {
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT
};
submitInfo.pWaitDstStageMask = waitStages; // Stages to check semaphores at
submitInfo.commandBufferCount = 1; // Number of command buffers to submit
submitInfo.pCommandBuffers = &commandBuffers[imageIndex]; // Command buffer to submit
submitInfo.signalSemaphoreCount = 1; // Number of semaphores to signal
submitInfo.pSignalSemaphores = &renderFinished[currentFrame]; // Semaphores to signal when command buffer finishes
// Submit command buffer to queue
VkResult result = vkQueueSubmit(graphicsQueue, 1, &submitInfo, drawFences[currentFrame]);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to submit Command Buffer to Queue!");
}
// -- PRESENT RENDERED IMAGE TO SCREEN --
VkPresentInfoKHR presentInfo = {};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1; // Number of semaphores to wait on
presentInfo.pWaitSemaphores = &renderFinished[currentFrame]; // Semaphores to wait on
presentInfo.swapchainCount = 1; // Number of swapchains to present to
presentInfo.pSwapchains = &swapchain; // Swapchains to present images to
presentInfo.pImageIndices = &imageIndex; // Index of images in swapchains to present
// Present image
result = vkQueuePresentKHR(presentationQueue, &presentInfo);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to present Image!");
}
// Get next frame (use % swapChainImages.size() to keep value below swapChainImages.size())
currentFrame = (currentFrame + 1) % MAX_FRAME_DRAWS;
}
void VulkanRenderer::cleanup()
{
// Wait until no actions being run on device before destroying
vkDeviceWaitIdle(mainDevice.logicalDevice);
//_aligned_free(modelTransferSpace);
for (size_t i = 0; i < modelList.size(); i++) {
modelList[i].destroyMeshModel();
}
vkDestroyDescriptorPool(mainDevice.logicalDevice, samplerDescriptorPool, nullptr);
vkDestroyDescriptorSetLayout(mainDevice.logicalDevice, samplerSetLayout, nullptr);
vkDestroySampler(mainDevice.logicalDevice, textureSampler, nullptr);
for (size_t i = 0; i < textureImages.size(); i++)
{
vkDestroyImageView(mainDevice.logicalDevice, textureImageViews[i], nullptr);
vkDestroyImage(mainDevice.logicalDevice, textureImages[i], nullptr);
vkFreeMemory(mainDevice.logicalDevice, textureImageMemory[i], nullptr);
}
vkDestroyImageView(mainDevice.logicalDevice, depthBufferImageView, nullptr);
vkDestroyImage(mainDevice.logicalDevice, depthBufferImage, nullptr);
vkFreeMemory(mainDevice.logicalDevice, depthBufferImageMemory, nullptr);
vkDestroyDescriptorPool(mainDevice.logicalDevice, descriptorPool, nullptr);
vkDestroyDescriptorSetLayout(mainDevice.logicalDevice, descriptorSetLayout, nullptr);
for (size_t i = 0; i < swapChainImages.size(); i++)
{
vkDestroyBuffer(mainDevice.logicalDevice, vpUniformBuffer[i], nullptr);
vkFreeMemory(mainDevice.logicalDevice, vpUniformBufferMemory[i], nullptr);
//vkDestroyBuffer(mainDevice.logicalDevice, modelDUniformBuffer[i], nullptr);
//vkFreeMemory(mainDevice.logicalDevice, modelDUniformBufferMemory[i], nullptr);
}
for (size_t i = 0; i < MAX_FRAME_DRAWS; i++)
{
vkDestroySemaphore(mainDevice.logicalDevice, renderFinished[i], nullptr);
vkDestroySemaphore(mainDevice.logicalDevice, imageAvailable[i], nullptr);
vkDestroyFence(mainDevice.logicalDevice, drawFences[i], nullptr);
}
vkDestroyCommandPool(mainDevice.logicalDevice, graphicsCommandPool, nullptr);
for (auto framebuffer : swapChainFramebuffers)
{
vkDestroyFramebuffer(mainDevice.logicalDevice, framebuffer, nullptr);
}
vkDestroyPipeline(mainDevice.logicalDevice, graphicsPipeline, nullptr);
vkDestroyPipelineLayout(mainDevice.logicalDevice, pipelineLayout, nullptr);
vkDestroyRenderPass(mainDevice.logicalDevice, renderPass, nullptr);
for (auto image : swapChainImages)
{
vkDestroyImageView(mainDevice.logicalDevice, image.imageView, nullptr);
}
vkDestroySwapchainKHR(mainDevice.logicalDevice, swapchain, nullptr);
vkDestroySurfaceKHR(instance, surface, nullptr);
vkDestroyDevice(mainDevice.logicalDevice, nullptr);
vkDestroyInstance(instance, nullptr);
}
VulkanRenderer::~VulkanRenderer()
{
}
void VulkanRenderer::createInstance()
{
// Information about the application itself
// Most data here doesn't affect the program and is for developer convenience
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Vulkan App"; // Custom name of the application
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); // Custom version of the application
appInfo.pEngineName = "No Engine"; // Custom engine name
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); // Custom engine version
appInfo.apiVersion = VK_API_VERSION_1_0; // The Vulkan Version
// Creation information for a VkInstance (Vulkan Instance)
VkInstanceCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
// Create list to hold instance extensions
std::vector<const char*> instanceExtensions = std::vector<const char*>();
// Set up extensions Instance will use
uint32_t glfwExtensionCount = 0; // GLFW may require multiple extensions
const char** glfwExtensions; // Extensions passed as array of cstrings, so need pointer (the array) to pointer (the cstring)
// Get GLFW extensions
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
// Add GLFW extensions to list of extensions
for (size_t i = 0; i < glfwExtensionCount; i++)
{
instanceExtensions.push_back(glfwExtensions[i]);
}
// Check Instance Extensions supported...
if (!checkInstanceExtensionSupport(&instanceExtensions))
{
throw std::runtime_error("VkInstance does not support required extensions!");
}
createInfo.enabledExtensionCount = static_cast<uint32_t>(instanceExtensions.size());
createInfo.ppEnabledExtensionNames = instanceExtensions.data();
createInfo.enabledLayerCount = 0;
createInfo.ppEnabledLayerNames = nullptr;
// Create instance
VkResult result = vkCreateInstance(&createInfo, nullptr, &instance);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a Vulkan Instance!");
}
}
void VulkanRenderer::createLogicalDevice()
{
//Get the queue family indices for the chosen Physical Device
QueueFamilyIndices indices = getQueueFamilies(mainDevice.physicalDevice);
// Vector for queue creation information, and set for family indices
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
std::set<int> queueFamilyIndices = { indices.graphicsFamily, indices.presentationFamily };
// Queues the logical device needs to create and info to do so
for (int queueFamilyIndex : queueFamilyIndices)
{
VkDeviceQueueCreateInfo queueCreateInfo = {};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queueFamilyIndex; // The index of the family to create a queue from
queueCreateInfo.queueCount = 1; // Number of queues to create
float priority = 1.0f;
queueCreateInfo.pQueuePriorities = &priority; // Vulkan needs to know how to handle multiple queues, so decide priority (1 = highest priority)
queueCreateInfos.push_back(queueCreateInfo);
}
// Information to create logical device (sometimes called "device")
VkDeviceCreateInfo deviceCreateInfo = {};
deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceCreateInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); // Number of Queue Create Infos
deviceCreateInfo.pQueueCreateInfos = queueCreateInfos.data(); // List of queue create infos so device can create required queues
deviceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()); // Number of enabled logical device extensions
deviceCreateInfo.ppEnabledExtensionNames = deviceExtensions.data(); // List of enabled logical device extensions
// Physical Device Features the Logical Device will be using
VkPhysicalDeviceFeatures deviceFeatures = {};
deviceFeatures.samplerAnisotropy = VK_TRUE; // Enable Anisotropy
deviceCreateInfo.pEnabledFeatures = &deviceFeatures; // Physical Device features Logical Device will use
// Create the logical device for the given physical device
VkResult result = vkCreateDevice(mainDevice.physicalDevice, &deviceCreateInfo, nullptr, &mainDevice.logicalDevice);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a Logical Device!");
}
// Queues are created at the same time as the device...
// So we want handle to queues
// From given logical device, of given Queue Family, of given Queue Index (0 since only one queue), place reference in given VkQueue
vkGetDeviceQueue(mainDevice.logicalDevice, indices.graphicsFamily, 0, &graphicsQueue);
vkGetDeviceQueue(mainDevice.logicalDevice, indices.presentationFamily, 0, &presentationQueue);
}
void VulkanRenderer::createSurface()
{
// Create Surface (creates a surface create info struct, runs the create surface function, returns result)
VkResult result = glfwCreateWindowSurface(instance, window, nullptr, &surface);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a surface!");
}
}
void VulkanRenderer::createSwapChain()
{
// Get Swap Chain details so we can pick best settings
SwapChainDetails swapChainDetails = getSwapChainDetails(mainDevice.physicalDevice);
// Find optimal surface values for our swap chain
VkSurfaceFormatKHR surfaceFormat = chooseBestSurfaceFormat(swapChainDetails.formats);
VkPresentModeKHR presentMode = chooseBestPresentationMode(swapChainDetails.presentationModes);
VkExtent2D extent = chooseSwapExtent(swapChainDetails.surfaceCapabilities);
// How many images are in the swap chain? Get 1 more than the minimum to allow triple buffering
uint32_t imageCount = swapChainDetails.surfaceCapabilities.minImageCount + 1;
// If imageCount higher than max, then clamp down to max
// If 0, then limitless
if (swapChainDetails.surfaceCapabilities.maxImageCount > 0
&& swapChainDetails.surfaceCapabilities.maxImageCount < imageCount)
{
imageCount = swapChainDetails.surfaceCapabilities.maxImageCount;
}
// Creation information for swap chain
VkSwapchainCreateInfoKHR swapChainCreateInfo = {};
swapChainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapChainCreateInfo.surface = surface; // Swapchain surface
swapChainCreateInfo.imageFormat = surfaceFormat.format; // Swapchain format
swapChainCreateInfo.imageColorSpace = surfaceFormat.colorSpace; // Swapchain colour space
swapChainCreateInfo.presentMode = presentMode; // Swapchain presentation mode
swapChainCreateInfo.imageExtent = extent; // Swapchain image extents
swapChainCreateInfo.minImageCount = imageCount; // Minimum images in swapchain
swapChainCreateInfo.imageArrayLayers = 1; // Number of layers for each image in chain
swapChainCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; // What attachment images will be used as
swapChainCreateInfo.preTransform = swapChainDetails.surfaceCapabilities.currentTransform; // Transform to perform on swap chain images
swapChainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; // How to handle blending images with external graphics (e.g. other windows)
swapChainCreateInfo.clipped = VK_TRUE; // Whether to clip parts of image not in view (e.g. behind another window, off screen, etc)
// Get Queue Family Indices
QueueFamilyIndices indices = getQueueFamilies(mainDevice.physicalDevice);
// If Graphics and Presentation families are different, then swapchain must let images be shared between families
if (indices.graphicsFamily != indices.presentationFamily)
{
// Queues to share between
uint32_t queueFamilyIndices[] = {
(uint32_t)indices.graphicsFamily,
(uint32_t)indices.presentationFamily
};
swapChainCreateInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; // Image share handling
swapChainCreateInfo.queueFamilyIndexCount = 2; // Number of queues to share images between
swapChainCreateInfo.pQueueFamilyIndices = queueFamilyIndices; // Array of queues to share between
}
else
{
swapChainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
swapChainCreateInfo.queueFamilyIndexCount = 0;
swapChainCreateInfo.pQueueFamilyIndices = nullptr;
}
// IF old swap chain been destroyed and this one replaces it, then link old one to quickly hand over responsibilities
swapChainCreateInfo.oldSwapchain = VK_NULL_HANDLE;
// Create Swapchain
VkResult result = vkCreateSwapchainKHR(mainDevice.logicalDevice, &swapChainCreateInfo, nullptr, &swapchain);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a Swapchain!");
}
// Store for later reference
swapChainImageFormat = surfaceFormat.format;
swapChainExtent = extent;
// Get swap chain images (first count, then values)
uint32_t swapChainImageCount;
vkGetSwapchainImagesKHR(mainDevice.logicalDevice, swapchain, &swapChainImageCount, nullptr);
std::vector<VkImage> images(swapChainImageCount);
vkGetSwapchainImagesKHR(mainDevice.logicalDevice, swapchain, &swapChainImageCount, images.data());
for (VkImage image : images)
{
// Store image handle
SwapchainImage swapChainImage = {};
swapChainImage.image = image;
swapChainImage.imageView = createImageView(image, swapChainImageFormat, VK_IMAGE_ASPECT_COLOR_BIT);
// Add to swapchain image list
swapChainImages.push_back(swapChainImage);
}
}
void VulkanRenderer::createRenderPass()
{
// ATTACHMENTS
// Colour attachment of render pass
VkAttachmentDescription colourAttachment = {};
colourAttachment.format = swapChainImageFormat; // Format to use for attachment
colourAttachment.samples = VK_SAMPLE_COUNT_1_BIT; // Number of samples to write for multisampling
colourAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; // Describes what to do with attachment before rendering
colourAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; // Describes what to do with attachment after rendering
colourAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; // Describes what to do with stencil before rendering
colourAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; // Describes what to do with stencil after rendering
// Framebuffer data will be stored as an image, but images can be given different data layouts
// to give optimal use for certain operations
colourAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // Image data layout before render pass starts
colourAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; // Image data layout after render pass (to change to)
// Depth attachment of render pass
VkAttachmentDescription depthAttachment = {};
depthAttachment.format = chooseSupportedFormat(
{ VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D32_SFLOAT, VK_FORMAT_D24_UNORM_S8_UINT },
VK_IMAGE_TILING_OPTIMAL,
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT);
depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
// REFERENCES
// Attachment reference uses an attachment index that refers to index in the attachment list passed to renderPassCreateInfo
VkAttachmentReference colourAttachmentReference = {};
colourAttachmentReference.attachment = 0;
colourAttachmentReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
// Depth Attachment Reference
VkAttachmentReference depthAttachmentReference = {};
depthAttachmentReference.attachment = 1;
depthAttachmentReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
// Information about a particular subpass the Render Pass is using
VkSubpassDescription subpass = {};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; // Pipeline type subpass is to be bound to
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colourAttachmentReference;
subpass.pDepthStencilAttachment = &depthAttachmentReference;
// Need to determine when layout transitions occur using subpass dependencies
std::array<VkSubpassDependency, 2> subpassDependencies;
// Conversion from VK_IMAGE_LAYOUT_UNDEFINED to VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
// Transition must happen after...
subpassDependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; // Subpass index (VK_SUBPASS_EXTERNAL = Special value meaning outside of renderpass)
subpassDependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; // Pipeline stage
subpassDependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; // Stage access mask (memory access)
// But must happen before...
subpassDependencies[0].dstSubpass = 0;
subpassDependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
subpassDependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
subpassDependencies[0].dependencyFlags = 0;
// Conversion from VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL to VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
// Transition must happen after...
subpassDependencies[1].srcSubpass = 0;
subpassDependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
subpassDependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;;
// But must happen before...
subpassDependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL;
subpassDependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
subpassDependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
subpassDependencies[1].dependencyFlags = 0;
std::array<VkAttachmentDescription, 2> renderPassAttachments = { colourAttachment, depthAttachment };
// Create info for Render Pass
VkRenderPassCreateInfo renderPassCreateInfo = {};
renderPassCreateInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassCreateInfo.attachmentCount = static_cast<uint32_t>(renderPassAttachments.size());
renderPassCreateInfo.pAttachments = renderPassAttachments.data();
renderPassCreateInfo.subpassCount = 1;
renderPassCreateInfo.pSubpasses = &subpass;
renderPassCreateInfo.dependencyCount = static_cast<uint32_t>(subpassDependencies.size());
renderPassCreateInfo.pDependencies = subpassDependencies.data();
VkResult result = vkCreateRenderPass(mainDevice.logicalDevice, &renderPassCreateInfo, nullptr, &renderPass);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a Render Pass!");
}
}
void VulkanRenderer::createDescriptorSetLayout()
{
// UNIFORM VALUES DESCRIPTOR SET LAYOUT
// UboViewProjection Binding Info
VkDescriptorSetLayoutBinding vpLayoutBinding = {};
vpLayoutBinding.binding = 0; // Binding point in shader (designated by binding number in shader)
vpLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; // Type of descriptor (uniform, dynamic uniform, image sampler, etc)
vpLayoutBinding.descriptorCount = 1; // Number of descriptors for binding
vpLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; // Shader stage to bind to
vpLayoutBinding.pImmutableSamplers = nullptr; // For Texture: Can make sampler data unchangeable (immutable) by specifying in layout
// Model Binding Info
/*VkDescriptorSetLayoutBinding modelLayoutBinding = {};
modelLayoutBinding.binding = 1;
modelLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
modelLayoutBinding.descriptorCount = 1;
modelLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
modelLayoutBinding.pImmutableSamplers = nullptr;*/
std::vector<VkDescriptorSetLayoutBinding> layoutBindings = { vpLayoutBinding };
// Create Descriptor Set Layout with given bindings
VkDescriptorSetLayoutCreateInfo layoutCreateInfo = {};
layoutCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutCreateInfo.bindingCount = static_cast<uint32_t>(layoutBindings.size()); // Number of binding infos
layoutCreateInfo.pBindings = layoutBindings.data(); // Array of binding infos
// Create Descriptor Set Layout
VkResult result = vkCreateDescriptorSetLayout(mainDevice.logicalDevice, &layoutCreateInfo, nullptr, &descriptorSetLayout);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a Descriptor Set Layout!");
}
// CREATE TEXTURE SAMPLER DESCRIPTOR SET LAYOUT
// Texture binding info
VkDescriptorSetLayoutBinding samplerLayoutBinding = {};
samplerLayoutBinding.binding = 0;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
// Create a Descriptor Set Layout with given bindings for texture
VkDescriptorSetLayoutCreateInfo textureLayoutCreateInfo = {};
textureLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
textureLayoutCreateInfo.bindingCount = 1;
textureLayoutCreateInfo.pBindings = &samplerLayoutBinding;
// Create Descriptor Set Layout
result = vkCreateDescriptorSetLayout(mainDevice.logicalDevice, &textureLayoutCreateInfo, nullptr, &samplerSetLayout);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a Descriptor Set Layout!");
}
}
void VulkanRenderer::createPushConstantRange()
{
// Define push constant values (no 'create' needed!)
pushConstantRange.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; // Shader stage push constant will go to
pushConstantRange.offset = 0; // Offset into given data to pass to push constant
pushConstantRange.size = sizeof(Model); // Size of data being passed
}
void VulkanRenderer::createGraphicsPipeline()
{
// Read in SPIR-V code of shaders
auto vertexShaderCode = readFile("Shaders/vert.spv");
auto fragmentShaderCode = readFile("Shaders/frag.spv");
// Create Shader Modules
VkShaderModule vertexShaderModule = createShaderModule(vertexShaderCode);
VkShaderModule fragmentShaderModule = createShaderModule(fragmentShaderCode);
// -- SHADER STAGE CREATION INFORMATION --
// Vertex Stage creation information
VkPipelineShaderStageCreateInfo vertexShaderCreateInfo = {};
vertexShaderCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vertexShaderCreateInfo.stage = VK_SHADER_STAGE_VERTEX_BIT; // Shader Stage name
vertexShaderCreateInfo.module = vertexShaderModule; // Shader module to be used by stage
vertexShaderCreateInfo.pName = "main"; // Entry point in to shader
// Fragment Stage creation information
VkPipelineShaderStageCreateInfo fragmentShaderCreateInfo = {};
fragmentShaderCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
fragmentShaderCreateInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT; // Shader Stage name
fragmentShaderCreateInfo.module = fragmentShaderModule; // Shader module to be used by stage
fragmentShaderCreateInfo.pName = "main"; // Entry point in to shader
// Put shader stage creation info in to array
// Graphics Pipeline creation info requires array of shader stage creates
VkPipelineShaderStageCreateInfo shaderStages[] = { vertexShaderCreateInfo, fragmentShaderCreateInfo };
// How the data for a single vertex (including info such as position, colour, texture coords, normals, etc) is as a whole
VkVertexInputBindingDescription bindingDescription = {};
bindingDescription.binding = 0; // Can bind multiple streams of data, this defines which one
bindingDescription.stride = sizeof(Vertex); // Size of a single vertex object
bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; // How to move between data after each vertex.
// VK_VERTEX_INPUT_RATE_INDEX : Move on to the next vertex
// VK_VERTEX_INPUT_RATE_INSTANCE : Move to a vertex for the next instance
// How the data for an attribute is defined within a vertex
std::array<VkVertexInputAttributeDescription, 3> attributeDescriptions;
// Position Attribute
attributeDescriptions[0].binding = 0; // Which binding the data is at (should be same as above)
attributeDescriptions[0].location = 0; // Location in shader where data will be read from
attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT; // Format the data will take (also helps define size of data)
attributeDescriptions[0].offset = offsetof(Vertex, pos); // Where this attribute is defined in the data for a single vertex
// Colour Attribute
attributeDescriptions[1].binding = 0;
attributeDescriptions[1].location = 1;
attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[1].offset = offsetof(Vertex, col);
// Texture Attribute
attributeDescriptions[2].binding = 0;
attributeDescriptions[2].location = 2;
attributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT;
attributeDescriptions[2].offset = offsetof(Vertex, tex);
// -- VERTEX INPUT --
VkPipelineVertexInputStateCreateInfo vertexInputCreateInfo = {};
vertexInputCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputCreateInfo.vertexBindingDescriptionCount = 1;
vertexInputCreateInfo.pVertexBindingDescriptions = &bindingDescription; // List of Vertex Binding Descriptions (data spacing/stride information)
vertexInputCreateInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size());
vertexInputCreateInfo.pVertexAttributeDescriptions = attributeDescriptions.data(); // List of Vertex Attribute Descriptions (data format and where to bind to/from)
// -- INPUT ASSEMBLY --
VkPipelineInputAssemblyStateCreateInfo inputAssembly = {};
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; // Primitive type to assemble vertices as
inputAssembly.primitiveRestartEnable = VK_FALSE; // Allow overriding of "strip" topology to start new primitives
// -- VIEWPORT & SCISSOR --
// Create a viewport info struct
VkViewport viewport = {};
viewport.x = 0.0f; // x start coordinate
viewport.y = 0.0f; // y start coordinate
viewport.width = (float)swapChainExtent.width; // width of viewport
viewport.height = (float)swapChainExtent.height; // height of viewport
viewport.minDepth = 0.0f; // min framebuffer depth
viewport.maxDepth = 1.0f; // max framebuffer depth
// Create a scissor info struct
VkRect2D scissor = {};
scissor.offset = { 0,0 }; // Offset to use region from
scissor.extent = swapChainExtent; // Extent to describe region to use, starting at offset
VkPipelineViewportStateCreateInfo viewportStateCreateInfo = {};
viewportStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportStateCreateInfo.viewportCount = 1;
viewportStateCreateInfo.pViewports = &viewport;
viewportStateCreateInfo.scissorCount = 1;
viewportStateCreateInfo.pScissors = &scissor;
// -- DYNAMIC STATES --
// Dynamic states to enable
//std::vector<VkDynamicState> dynamicStateEnables;
//dynamicStateEnables.push_back(VK_DYNAMIC_STATE_VIEWPORT); // Dynamic Viewport : Can resize in command buffer with vkCmdSetViewport(commandbuffer, 0, 1, &viewport);
//dynamicStateEnables.push_back(VK_DYNAMIC_STATE_SCISSOR); // Dynamic Scissor : Can resize in command buffer with vkCmdSetScissor(commandbuffer, 0, 1, &scissor);
//// Dynamic State creation info
//VkPipelineDynamicStateCreateInfo dynamicStateCreateInfo = {};
//dynamicStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
//dynamicStateCreateInfo.dynamicStateCount = static_cast<uint32_t>(dynamicStateEnables.size());
//dynamicStateCreateInfo.pDynamicStates = dynamicStateEnables.data();
// -- RASTERIZER --
VkPipelineRasterizationStateCreateInfo rasterizerCreateInfo = {};
rasterizerCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizerCreateInfo.depthClampEnable = VK_FALSE; // Change if fragments beyond near/far planes are clipped (default) or clamped to plane
rasterizerCreateInfo.rasterizerDiscardEnable = VK_FALSE; // Whether to discard data and skip rasterizer. Never creates fragments, only suitable for pipeline without framebuffer output
rasterizerCreateInfo.polygonMode = VK_POLYGON_MODE_FILL; // How to handle filling points between vertices
rasterizerCreateInfo.lineWidth = 1.0f; // How thick lines should be when drawn
rasterizerCreateInfo.cullMode = VK_CULL_MODE_BACK_BIT; // Which face of a tri to cull
rasterizerCreateInfo.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; // Winding to determine which side is front
rasterizerCreateInfo.depthBiasEnable = VK_FALSE; // Whether to add depth bias to fragments (good for stopping "shadow acne" in shadow mapping)
// -- MULTISAMPLING --
VkPipelineMultisampleStateCreateInfo multisamplingCreateInfo = {};
multisamplingCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisamplingCreateInfo.sampleShadingEnable = VK_FALSE; // Enable multisample shading or not
multisamplingCreateInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; // Number of samples to use per fragment
// -- BLENDING --
// Blending decides how to blend a new colour being written to a fragment, with the old value
// Blend Attachment State (how blending is handled)
VkPipelineColorBlendAttachmentState colourState = {};
colourState.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT // Colours to apply blending to
| VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
colourState.blendEnable = VK_TRUE; // Enable blending
// Blending uses equation: (srcColorBlendFactor * new colour) colorBlendOp (dstColorBlendFactor * old colour)
colourState.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
colourState.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
colourState.colorBlendOp = VK_BLEND_OP_ADD;
// Summarised: (VK_BLEND_FACTOR_SRC_ALPHA * new colour) + (VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA * old colour)
// (new colour alpha * new colour) + ((1 - new colour alpha) * old colour)
colourState.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
colourState.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
colourState.alphaBlendOp = VK_BLEND_OP_ADD;
// Summarised: (1 * new alpha) + (0 * old alpha) = new alpha
VkPipelineColorBlendStateCreateInfo colourBlendingCreateInfo = {};
colourBlendingCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
colourBlendingCreateInfo.logicOpEnable = VK_FALSE; // Alternative to calculations is to use logical operations
colourBlendingCreateInfo.attachmentCount = 1;
colourBlendingCreateInfo.pAttachments = &colourState;
// -- PIPELINE LAYOUT --
std::array<VkDescriptorSetLayout, 2> descriptorSetLayouts = { descriptorSetLayout, samplerSetLayout };
VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = {};
pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutCreateInfo.setLayoutCount = static_cast<uint32_t>(descriptorSetLayouts.size());
pipelineLayoutCreateInfo.pSetLayouts = descriptorSetLayouts.data();
pipelineLayoutCreateInfo.pushConstantRangeCount = 1;
pipelineLayoutCreateInfo.pPushConstantRanges = &pushConstantRange;
// Create Pipeline Layout
VkResult result = vkCreatePipelineLayout(mainDevice.logicalDevice, &pipelineLayoutCreateInfo, nullptr, &pipelineLayout);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to create Pipeline Layout!");
}
// -- DEPTH STENCIL TESTING --
VkPipelineDepthStencilStateCreateInfo depthStencilCreateInfo = {};
depthStencilCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
depthStencilCreateInfo.depthTestEnable = VK_TRUE; // Enable checking depth to determine fragment write
depthStencilCreateInfo.depthWriteEnable = VK_TRUE; // Enable writing to depth buffer (to replace old values)
depthStencilCreateInfo.depthCompareOp = VK_COMPARE_OP_LESS; // Comparison operation that allows an overwrite (is in front)
depthStencilCreateInfo.depthBoundsTestEnable = VK_FALSE; // Depth Bounds Test: Does the depth value exist between two bounds
depthStencilCreateInfo.stencilTestEnable = VK_FALSE; // Enable Stencil Test
// -- GRAPHICS PIPELINE CREATION --
VkGraphicsPipelineCreateInfo pipelineCreateInfo = {};
pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineCreateInfo.stageCount = 2; // Number of shader stages
pipelineCreateInfo.pStages = shaderStages; // List of shader stages
pipelineCreateInfo.pVertexInputState = &vertexInputCreateInfo; // All the fixed function pipeline states
pipelineCreateInfo.pInputAssemblyState = &inputAssembly;
pipelineCreateInfo.pViewportState = &viewportStateCreateInfo;
pipelineCreateInfo.pDynamicState = nullptr;
pipelineCreateInfo.pRasterizationState = &rasterizerCreateInfo;
pipelineCreateInfo.pMultisampleState = &multisamplingCreateInfo;
pipelineCreateInfo.pColorBlendState = &colourBlendingCreateInfo;
pipelineCreateInfo.pDepthStencilState = &depthStencilCreateInfo;
pipelineCreateInfo.layout = pipelineLayout; // Pipeline Layout pipeline should use
pipelineCreateInfo.renderPass = renderPass; // Render pass description the pipeline is compatible with
pipelineCreateInfo.subpass = 0; // Subpass of render pass to use with pipeline
// Pipeline Derivatives : Can create multiple pipelines that derive from one another for optimisation
pipelineCreateInfo.basePipelineHandle = VK_NULL_HANDLE; // Existing pipeline to derive from...
pipelineCreateInfo.basePipelineIndex = -1; // or index of pipeline being created to derive from (in case creating multiple at once)
// Create Graphics Pipeline
result = vkCreateGraphicsPipelines(mainDevice.logicalDevice, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &graphicsPipeline);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a Graphics Pipeline!");
}
// Destroy Shader Modules, no longer needed after Pipeline created
vkDestroyShaderModule(mainDevice.logicalDevice, fragmentShaderModule, nullptr);
vkDestroyShaderModule(mainDevice.logicalDevice, vertexShaderModule, nullptr);
}
void VulkanRenderer::createDepthBufferImage()
{
// Get supported format for depth buffer
VkFormat depthFormat = chooseSupportedFormat(
{ VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D32_SFLOAT, VK_FORMAT_D24_UNORM_S8_UINT },
VK_IMAGE_TILING_OPTIMAL,
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT);
// Create Depth Buffer Image
depthBufferImage = createImage(swapChainExtent.width, swapChainExtent.height, depthFormat, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &depthBufferImageMemory);
// Create Depth Buffer Image View
depthBufferImageView = createImageView(depthBufferImage, depthFormat, VK_IMAGE_ASPECT_DEPTH_BIT);
}
void VulkanRenderer::createFramebuffers()
{
// Resize framebuffer count to equal swap chain image count
swapChainFramebuffers.resize(swapChainImages.size());
// Create a framebuffer for each swap chain image
for (size_t i = 0; i < swapChainFramebuffers.size(); i++)
{
std::array<VkImageView, 2> attachments = {
swapChainImages[i].imageView,
depthBufferImageView
};
VkFramebufferCreateInfo framebufferCreateInfo = {};
framebufferCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebufferCreateInfo.renderPass = renderPass; // Render Pass layout the Framebuffer will be used with
framebufferCreateInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
framebufferCreateInfo.pAttachments = attachments.data(); // List of attachments (1:1 with Render Pass)
framebufferCreateInfo.width = swapChainExtent.width; // Framebuffer width
framebufferCreateInfo.height = swapChainExtent.height; // Framebuffer height
framebufferCreateInfo.layers = 1; // Framebuffer layers
VkResult result = vkCreateFramebuffer(mainDevice.logicalDevice, &framebufferCreateInfo, nullptr, &swapChainFramebuffers[i]);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a Framebuffer!");
}
}
}
void VulkanRenderer::createCommandPool()
{
// Get indices of queue families from device
QueueFamilyIndices queueFamilyIndices = getQueueFamilies(mainDevice.physicalDevice);
VkCommandPoolCreateInfo poolInfo = {};
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily; // Queue Family type that buffers from this command pool will use
// Create a Graphics Queue Family Command Pool
VkResult result = vkCreateCommandPool(mainDevice.logicalDevice, &poolInfo, nullptr, &graphicsCommandPool);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a Command Pool!");
}
}
void VulkanRenderer::createCommandBuffers()
{
// Resize command buffer count to have one for each framebuffer
commandBuffers.resize(swapChainFramebuffers.size());
VkCommandBufferAllocateInfo cbAllocInfo = {};
cbAllocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
cbAllocInfo.commandPool = graphicsCommandPool;
cbAllocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; // VK_COMMAND_BUFFER_LEVEL_PRIMARY : Buffer you submit directly to queue. Cant be called by other buffers.
// VK_COMMAND_BUFFER_LEVEL_SECONARY : Buffer can't be called directly. Can be called from other buffers via "vkCmdExecuteCommands" when recording commands in primary buffer
cbAllocInfo.commandBufferCount = static_cast<uint32_t>(commandBuffers.size());
// Allocate command buffers and place handles in array of buffers
VkResult result = vkAllocateCommandBuffers(mainDevice.logicalDevice, &cbAllocInfo, commandBuffers.data());
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate Command Buffers!");
}
}
void VulkanRenderer::createSynchronisation()
{
imageAvailable.resize(MAX_FRAME_DRAWS);
renderFinished.resize(MAX_FRAME_DRAWS);
drawFences.resize(MAX_FRAME_DRAWS);
// Semaphore creation information
VkSemaphoreCreateInfo semaphoreCreateInfo = {};
semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
// Fence creation information
VkFenceCreateInfo fenceCreateInfo = {};
fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceCreateInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
for (size_t i = 0; i < MAX_FRAME_DRAWS; i++)
{
if (vkCreateSemaphore(mainDevice.logicalDevice, &semaphoreCreateInfo, nullptr, &imageAvailable[i]) != VK_SUCCESS ||
vkCreateSemaphore(mainDevice.logicalDevice, &semaphoreCreateInfo, nullptr, &renderFinished[i]) != VK_SUCCESS ||
vkCreateFence(mainDevice.logicalDevice, &fenceCreateInfo, nullptr, &drawFences[i]) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a Semaphore and/or Fence!");
}
}
}
void VulkanRenderer::createTextureSampler()
{
// Sampler Creation Info
VkSamplerCreateInfo samplerCreateInfo = {};
samplerCreateInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerCreateInfo.magFilter = VK_FILTER_LINEAR; // How to render when image is magnified on screen
samplerCreateInfo.minFilter = VK_FILTER_LINEAR; // How to render when image is minified on screen
samplerCreateInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; // How to handle texture wrap in U (x) direction
samplerCreateInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; // How to handle texture wrap in V (y) direction
samplerCreateInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; // How to handle texture wrap in W (z) direction
samplerCreateInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; // Border beyond texture (only workds for border clamp)
samplerCreateInfo.unnormalizedCoordinates = VK_FALSE; // Whether coords should be normalized (between 0 and 1)
samplerCreateInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; // Mipmap interpolation mode
samplerCreateInfo.mipLodBias = 0.0f; // Level of Details bias for mip level
samplerCreateInfo.minLod = 0.0f; // Minimum Level of Detail to pick mip level
samplerCreateInfo.maxLod = 0.0f; // Maximum Level of Detail to pick mip level
samplerCreateInfo.anisotropyEnable = VK_TRUE; // Enable Anisotropy
samplerCreateInfo.maxAnisotropy = 16; // Anisotropy sample level
VkResult result = vkCreateSampler(mainDevice.logicalDevice, &samplerCreateInfo, nullptr, &textureSampler);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Filed to create a Texture Sampler!");
}
}
void VulkanRenderer::createUniformBuffers()
{
// ViewProjection buffer size
VkDeviceSize vpBufferSize = sizeof(UboViewProjection);
// Model buffer size
//VkDeviceSize modelBufferSize = modelUniformAlignment * MAX_OBJECTS;
// One uniform buffer for each image (and by extension, command buffer)
vpUniformBuffer.resize(swapChainImages.size());
vpUniformBufferMemory.resize(swapChainImages.size());
//modelDUniformBuffer.resize(swapChainImages.size());
//modelDUniformBufferMemory.resize(swapChainImages.size());
// Create Uniform buffers
for (size_t i = 0; i < swapChainImages.size(); i++)
{
createBuffer(mainDevice.physicalDevice, mainDevice.logicalDevice, vpBufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &vpUniformBuffer[i], &vpUniformBufferMemory[i]);
/*createBuffer(mainDevice.physicalDevice, mainDevice.logicalDevice, modelBufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &modelDUniformBuffer[i], &modelDUniformBufferMemory[i]);*/
}
}
void VulkanRenderer::createDescriptorPool()
{
// CREATE UNIFORM DESCRIPTOR POOL
// Type of descriptors + how many DESCRIPTORS, not Descriptor Sets (combined makes the pool size)
// ViewProjection Pool
VkDescriptorPoolSize vpPoolSize = {};
vpPoolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
vpPoolSize.descriptorCount = static_cast<uint32_t>(vpUniformBuffer.size());
// Model Pool (DYNAMIC)
/*VkDescriptorPoolSize modelPoolSize = {};
modelPoolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
modelPoolSize.descriptorCount = static_cast<uint32_t>(modelDUniformBuffer.size());*/
// List of pool sizes
std::vector<VkDescriptorPoolSize> descriptorPoolSizes = { vpPoolSize };
// Data to create Descriptor Pool
VkDescriptorPoolCreateInfo poolCreateInfo = {};
poolCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolCreateInfo.maxSets = static_cast<uint32_t>(swapChainImages.size()); // Maximum number of Descriptor Sets that can be created from pool
poolCreateInfo.poolSizeCount = static_cast<uint32_t>(descriptorPoolSizes.size()); // Amount of Pool Sizes being passed
poolCreateInfo.pPoolSizes = descriptorPoolSizes.data(); // Pool Sizes to create pool with
// Create Descriptor Pool
VkResult result = vkCreateDescriptorPool(mainDevice.logicalDevice, &poolCreateInfo, nullptr, &descriptorPool);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a Descriptor Pool!");
}
// CREATE SAMPLER DESCRIPTOR POOL
// Texture sampler pool
VkDescriptorPoolSize samplerPoolSize = {};
samplerPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerPoolSize.descriptorCount = MAX_OBJECTS;
VkDescriptorPoolCreateInfo samplerPoolCreateInfo = {};
samplerPoolCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
samplerPoolCreateInfo.maxSets = MAX_OBJECTS;
samplerPoolCreateInfo.poolSizeCount = 1;
samplerPoolCreateInfo.pPoolSizes = &samplerPoolSize;
result = vkCreateDescriptorPool(mainDevice.logicalDevice, &samplerPoolCreateInfo, nullptr, &samplerDescriptorPool);
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a Descriptor Pool!");
}
}
void VulkanRenderer::createDescriptorSets()
{
// Resize Descriptor Set list so one for every buffer
descriptorSets.resize(swapChainImages.size());
std::vector<VkDescriptorSetLayout> setLayouts(swapChainImages.size(), descriptorSetLayout);
// Descriptor Set Allocation Info
VkDescriptorSetAllocateInfo setAllocInfo = {};
setAllocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
setAllocInfo.descriptorPool = descriptorPool; // Pool to allocate Descriptor Set from
setAllocInfo.descriptorSetCount = static_cast<uint32_t>(swapChainImages.size());// Number of sets to allocate
setAllocInfo.pSetLayouts = setLayouts.data(); // Layouts to use to allocate sets (1:1 relationship)
// Allocate descriptor sets (multiple)
VkResult result = vkAllocateDescriptorSets(mainDevice.logicalDevice, &setAllocInfo, descriptorSets.data());
if (result != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate Descriptor Sets!");
}
// Update all of descriptor set buffer bindings
for (size_t i = 0; i < swapChainImages.size(); i++)
{