-
Notifications
You must be signed in to change notification settings - Fork 0
/
HelloTriangleApplication.cpp
1587 lines (1338 loc) · 66.4 KB
/
HelloTriangleApplication.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
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
//#include <vulkan/vulkan.h>
#include <iostream>
#include <stdexcept>
#include <functional> // lambda functions
#include <cstdlib> // EXIT_FAILURE / SUCCESS
#include <optional> // used in QueueFamilyIndices struct
#include <set>
#include <cstdint> // Necessary for UINT32_MAX
#include <algorithm> // std::clamp
#include <fstream> // to load in shader files
#include <glm/glm.hpp> // linear algrebra stuff
#include <array>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <chrono>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#define TINYOBJLOADER_IMPLEMENTATION
#include <tiny_obj_loader.h>
#include "Vertex.h"
#include "RenderObject.h"
const uint32_t WIDTH = 800;
const uint32_t HEIGHT = 600;
//const std::string MODEL_PATH = "models/water.obj";
//const std::string TEXTURE_PATH = "textures/water_texture.png";
const std::vector<const char*> validationLayers = {
"VK_LAYER_KHRONOS_validation"
};
const std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
#ifdef NDEBUG
const bool enableValidationLayers = false;
#else
const bool enableValidationLayers = true;
#endif
//struct Vertex {
// glm::vec3 pos;
// glm::vec3 color;
// glm::vec2 texCoord;
//
// static VkVertexInputBindingDescription getBindingDescription() {
// VkVertexInputBindingDescription bindingDescription{};
// bindingDescription.binding = 0; // start index
// bindingDescription.stride = sizeof(Vertex);
// bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; // move per vertex (or per instance)
// return bindingDescription;
// }
//
// static std::array<VkVertexInputAttributeDescription, 3> getAttributeDescriptions() {
// std::array<VkVertexInputAttributeDescription, 3> attributeDescriptions{};
//
// attributeDescriptions[0].binding = 0;
// attributeDescriptions[0].location = 0;
// attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;
// attributeDescriptions[0].offset = offsetof(Vertex, pos);
//
// attributeDescriptions[1].binding = 0;
// attributeDescriptions[1].location = 1;
// attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
// attributeDescriptions[1].offset = offsetof(Vertex, color);
//
// attributeDescriptions[2].binding = 0;
// attributeDescriptions[2].location = 2;
// attributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT;
// attributeDescriptions[2].offset = offsetof(Vertex, texCoord);
//
// return attributeDescriptions;
// }
//};
struct UniformBufferObject {
glm::mat4 model;
glm::mat4 view;
glm::mat4 proj;
};
class HelloTriangleApplication {
public:
void run() {
std::cout << "started program\n";
initWindow();
initVulkan();
mainLoop();
cleanup();
std::cout << "closed program\n";
}
private:
GLFWwindow* window;
VkInstance instance;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; // physical gpu, implicitly cleaned
VkDevice device; // logical gpu to interface to physical
VkQueue graphicsQueue; // graphics pipeline command queue / implicitly cleaned
VkSurfaceKHR surface; // abstract surface to display rendered images
VkQueue presentQueue;
VkSwapchainKHR swapChain;
std::vector<VkImage> swapChainImages; // handles of swap chain images for rendering / implicitly cleaned
VkFormat swapChainImageFormat; // color format (32bit rgba)
VkExtent2D swapChainExtent; // swap chain image resolution
std::vector<VkImageView> swapChainImageViews;
VkRenderPass renderPass;
VkDescriptorSetLayout descriptorSetLayout;
VkPipelineLayout pipelineLayout;
VkPipeline graphicsPipeline;
std::vector<VkFramebuffer> swapChainFramebuffers;
VkCommandPool commandPool;
std::vector<VkCommandBuffer> commandBuffers; // command buffer for rendering / one for every Framebuffer
const int MAX_FRAMES_IN_FLIGHT = 2; // frames to process concurrently
size_t currentFrame = 0;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences; // to sync cpu / gpu
std::vector<VkFence> imagesInFlight; // keep images in order
std::vector<RenderObject> renderObjects;
VkImage depthImage;
VkDeviceMemory depthImageMemory;
VkImageView depthImageView;
float zoomLevel = 3.0f;
int whichMolecule = 0;
bool framebufferResized = false; // flag if window resized (will recreate swapchain)
bool keysHeld[1024];
std::chrono::steady_clock::time_point prevTime;
std::chrono::steady_clock::time_point currTime;
// initialize desktop window (glfw)
void initWindow() {
glfwInit(); //initialize glfw library
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); //dont create opengl context
//glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); //disable window resize
window = glfwCreateWindow(WIDTH, HEIGHT, "Vulkan", nullptr, nullptr);
glfwSetWindowUserPointer(window, this);
glfwSetFramebufferSizeCallback(window, framebufferResizeCallback);
glfwSetKeyCallback(window, key_callback);
}
static void framebufferResizeCallback(GLFWwindow* window, int width, int height) {
auto app = reinterpret_cast<HelloTriangleApplication*>(glfwGetWindowUserPointer(window));
app->framebufferResized = true;
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
auto app = reinterpret_cast<HelloTriangleApplication*>(glfwGetWindowUserPointer(window));
if (key >= 0 && key < 1024)
{
if (action == GLFW_PRESS)
{
app->keysHeld[key] = true;
}
else if (action == GLFW_RELEASE)
app->keysHeld[key] = false;
}
}
// initialize vulkan library
void initVulkan() {
createInstance();
createSurface();
pickPhysicalDevice();
createLogicalDevice();
createSwapChain();
createImageViews();
createRenderPass();
createDescriptorSetLayout();
createGraphicsPipeline();
createCommandPool();
createDepthResources();
createFramebuffers();
createResources();
createCommandBuffers();
createSyncObjects();
}
void createResources() {
RenderObject water_molecule = createRenderObject("models/water.obj", "textures/water_texture.png");
water_molecule.shouldRender = true;
renderObjects.push_back(water_molecule);
RenderObject water_desc = createRenderObject("models/quad.obj", "textures/water_desc.png");
water_desc.modelMatrix = glm::scale(water_desc.modelMatrix, glm::vec3(0.25f));
water_desc.modelMatrix = glm::translate(water_desc.modelMatrix, glm::vec3(0.0, -3.0, 0.0));
water_desc.shouldRender = true;
renderObjects.push_back(water_desc);
RenderObject propane_molecule = createRenderObject("models/propane.obj", "textures/propane_texture.png");
renderObjects.push_back(propane_molecule);
RenderObject propane_desc = createRenderObject("models/quad.obj", "textures/propane_desc.png");
propane_desc.modelMatrix = glm::scale(propane_desc.modelMatrix, glm::vec3(0.25f));
propane_desc.modelMatrix = glm::translate(propane_desc.modelMatrix, glm::vec3(0.0, -3.0, 0.0));
renderObjects.push_back(propane_desc);
RenderObject bernstein_molecule = createRenderObject("models/bernstein.obj", "textures/bernstein_texture.png");
renderObjects.push_back(bernstein_molecule);
RenderObject bernstein_desc = createRenderObject("models/quad.obj", "textures/bernstein_desc.png");
bernstein_desc.modelMatrix = glm::scale(bernstein_desc.modelMatrix, glm::vec3(0.25f));
bernstein_desc.modelMatrix = glm::translate(bernstein_desc.modelMatrix, glm::vec3(0.0, -3.0, 0.0));
renderObjects.push_back(bernstein_desc);
std::cout << "created " << renderObjects.size() << " render objects\n";
}
RenderObject createRenderObject(std::string modelPath, std::string texturePath) {
RenderObject renderObject;
createTextureImage(renderObject.textureImage, renderObject.textureImageMemory, texturePath);
createTextureImageView(renderObject.textureImageView, renderObject.textureImage);
createTextureSampler(renderObject.textureSampler);
loadModel(renderObject.vertices, renderObject.indices, modelPath);
createVertexBuffer(renderObject.vertexBuffer, renderObject.vertexBufferMemory, renderObject.vertices);
createIndexBuffer(renderObject.indexBuffer, renderObject.indexBufferMemory, renderObject.indices);
createUniformBuffers(renderObject.uniformBuffers, renderObject.uniformBuffersMemory);
createDescriptorPool(renderObject.descriptorPool);
createDescriptorSets(renderObject.descriptorSets, renderObject.descriptorPool, renderObject.uniformBuffers, renderObject.textureImageView, renderObject.textureSampler);
renderObject.modelMatrix = glm::mat4(1.0f);
return renderObject;
}
void mainLoop() {
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
gameLogic();
drawFrame();
}
vkDeviceWaitIdle(device);
}
void gameLogic() {
prevTime = currTime;
currTime = std::chrono::high_resolution_clock::now();
float time = std::chrono::duration<float, std::chrono::seconds::period>(currTime - prevTime).count();
if (keysHeld[GLFW_KEY_D])
renderObjects[whichMolecule].modelMatrix = glm::rotate(renderObjects[whichMolecule].modelMatrix, time * glm::radians(45.0f), glm::vec3(0.0f, 1.0f, 0.0f));
if (keysHeld[GLFW_KEY_A])
renderObjects[whichMolecule].modelMatrix = glm::rotate(renderObjects[whichMolecule].modelMatrix, time * glm::radians(-45.0f), glm::vec3(0.0f, 1.0f, 0.0f));
if (keysHeld[GLFW_KEY_W])
renderObjects[whichMolecule].modelMatrix = glm::rotate(renderObjects[whichMolecule].modelMatrix, time * glm::radians(-45.0f), glm::vec3(1.0f, 0.0f, 0.0f));
if (keysHeld[GLFW_KEY_S])
renderObjects[whichMolecule].modelMatrix = glm::rotate(renderObjects[whichMolecule].modelMatrix, time * glm::radians(45.0f), glm::vec3(1.0f, 0.0f, 0.0f));
if (keysHeld[GLFW_KEY_Q])
renderObjects[whichMolecule].modelMatrix = glm::rotate(renderObjects[whichMolecule].modelMatrix, time * glm::radians(45.0f), glm::vec3(0.0f, 0.0f, 1.0f));
if (keysHeld[GLFW_KEY_E])
renderObjects[whichMolecule].modelMatrix = glm::rotate(renderObjects[whichMolecule].modelMatrix, time * glm::radians(-45.0f), glm::vec3(0.0f, 0.0f, 1.0f));
if (keysHeld[GLFW_KEY_Z])
zoomLevel += 0.1;
if (keysHeld[GLFW_KEY_X])
zoomLevel -= 0.1;
if (keysHeld[GLFW_KEY_1]) {
renderObjects[0].shouldRender = true;
renderObjects[1].shouldRender = true;
renderObjects[2].shouldRender = false;
renderObjects[3].shouldRender = false;
renderObjects[4].shouldRender = false;
renderObjects[5].shouldRender = false;
whichMolecule = 0;
}
else if (keysHeld[GLFW_KEY_2]) {
renderObjects[0].shouldRender = false;
renderObjects[1].shouldRender = false;
renderObjects[2].shouldRender = true;
renderObjects[3].shouldRender = true;
renderObjects[4].shouldRender = false;
renderObjects[5].shouldRender = false;
whichMolecule = 2;
}
else if (keysHeld[GLFW_KEY_3]) {
renderObjects[0].shouldRender = false;
renderObjects[1].shouldRender = false;
renderObjects[2].shouldRender = false;
renderObjects[3].shouldRender = false;
renderObjects[4].shouldRender = true;
renderObjects[5].shouldRender = true;
whichMolecule = 4;
}
}
void drawFrame() {
// wait for frame to be finished
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
uint32_t imageIndex;
VkResult result = vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
// check if swapchain needs to be recreated
if (result == VK_ERROR_OUT_OF_DATE_KHR) {
recreateSwapChain();
return;
}
else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR)
throw std::runtime_error("failed to acquire swapchain image!");
if (imagesInFlight[imageIndex] != VK_NULL_HANDLE) // check if previous frame is using this image (if there is fence to wait on)
vkWaitForFences(device, 1, &imagesInFlight[imageIndex], VK_TRUE, UINT64_MAX);
imagesInFlight[imageIndex] = inFlightFences[currentFrame]; // mark image as now being in use by this frame
updateUniformBuffer(imageIndex, renderObjects[0]);
updateUniformBufferUI(imageIndex, renderObjects[1]);
updateUniformBuffer(imageIndex, renderObjects[2]);
updateUniformBufferUI(imageIndex, renderObjects[3]);
updateUniformBuffer(imageIndex, renderObjects[4]);
updateUniformBufferUI(imageIndex, renderObjects[5]);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkSemaphore waitSemaphores[] = { imageAvailableSemaphores[currentFrame] };
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = waitSemaphores;
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
VkSemaphore signalSemaphores[] = { renderFinishedSemaphores[currentFrame] };
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphores;
vkResetFences(device, 1, &inFlightFences[currentFrame]);
if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]) != VK_SUCCESS)
throw std::runtime_error("failed to submit draw command buffer!");
// submit result back to swap chain
VkPresentInfoKHR presentInfo{};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = signalSemaphores;
VkSwapchainKHR swapChains[] = { swapChain };
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
presentInfo.pResults = nullptr;
result = vkQueuePresentKHR(presentQueue, &presentInfo);
// remake swapchain before presenting if needed
if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) {
framebufferResized = false;
recreateSwapChain();
}
else if (result != VK_SUCCESS)
throw std::runtime_error("failed to present swap chain image!");
vkQueueWaitIdle(presentQueue);
currentFrame = (currentFrame + 1) & MAX_FRAMES_IN_FLIGHT;
}
void updateUniformBuffer(uint32_t currentImage, RenderObject renderObject) {
UniformBufferObject ubo{};
ubo.model = renderObject.modelMatrix;
ubo.view = glm::lookAt(glm::vec3(0.0f, 0.0f, zoomLevel), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
ubo.proj = glm::perspective(glm::radians(45.0f), swapChainExtent.width / (float)swapChainExtent.height, 0.1f, 10.0f);
ubo.proj[1][1] *= -1; // was made for opengl which has Y coord inverted vs Vulkan
if (!renderObject.shouldRender)
ubo.model = glm::mat4(0.0f);
void* data;
vkMapMemory(device, renderObject.uniformBuffersMemory[currentImage], 0, sizeof(ubo), 0, &data);
memcpy(data, &ubo, sizeof(ubo));
vkUnmapMemory(device, renderObject.uniformBuffersMemory[currentImage]);
}
void updateUniformBufferUI(uint32_t currentImage, RenderObject renderObject) {
float aspect = (float)swapChainExtent.width / (float)swapChainExtent.height;
UniformBufferObject ubo{};
ubo.model = glm::rotate(renderObject.modelMatrix, glm::radians(180.0f), glm::vec3(0.0f, 0.0f, 1.0f));
ubo.view = glm::mat4(1.0f);
ubo.proj = glm::ortho(-aspect, aspect, -1.0f, 1.0f);
ubo.proj[1][1] *= -1; // was made for opengl which has Y coord inverted vs Vulkan
if (!renderObject.shouldRender)
ubo.model = glm::mat4(0.0f);
void* data;
vkMapMemory(device, renderObject.uniformBuffersMemory[currentImage], 0, sizeof(ubo), 0, &data);
memcpy(data, &ubo, sizeof(ubo));
vkUnmapMemory(device, renderObject.uniformBuffersMemory[currentImage]);
}
void cleanup() {
cleanupSwapChain();
for (int i = 0; i < renderObjects.size(); i++) {
vkDestroySampler(device, renderObjects[i].textureSampler, nullptr);
vkDestroyImageView(device, renderObjects[i].textureImageView, nullptr);
vkDestroyImage(device, renderObjects[i].textureImage, nullptr);
vkFreeMemory(device, renderObjects[i].textureImageMemory, nullptr);
vkDestroyBuffer(device, renderObjects[i].indexBuffer, nullptr);
vkFreeMemory(device, renderObjects[i].indexBufferMemory, nullptr);
vkDestroyBuffer(device, renderObjects[i].vertexBuffer, nullptr);
vkFreeMemory(device, renderObjects[i].vertexBufferMemory, nullptr);
}
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
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);
}
vkDestroyCommandPool(device, commandPool, nullptr);
vkDestroyDevice(device, nullptr);
vkDestroySurfaceKHR(instance, surface, nullptr);
vkDestroyInstance(instance, nullptr);
glfwDestroyWindow(window);
glfwTerminate();
}
void cleanupSwapChain() {
vkDestroyImageView(device, depthImageView, nullptr);
vkDestroyImage(device, depthImage, nullptr);
vkFreeMemory(device, depthImageMemory, nullptr);
for (size_t i = 0; i < swapChainFramebuffers.size(); i++)
vkDestroyFramebuffer(device, swapChainFramebuffers[i], nullptr);
vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
vkDestroyPipeline(device, graphicsPipeline, nullptr);
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
vkDestroyRenderPass(device, renderPass, nullptr);
for (auto imageView : swapChainImageViews)
vkDestroyImageView(device, imageView, nullptr);
vkDestroySwapchainKHR(device, swapChain, nullptr);
for (int x = 0; x < renderObjects.size(); x++) {
for (size_t i = 0; i < swapChainImages.size(); i++) {
vkDestroyBuffer(device, renderObjects[x].uniformBuffers[i], nullptr);
vkFreeMemory(device, renderObjects[x].uniformBuffersMemory[i], nullptr);
}
vkDestroyDescriptorPool(device, renderObjects[x].descriptorPool, nullptr);
}
}
// create vulkan instance
void createInstance() {
if (enableValidationLayers && !checkValidationLayerSupport())
throw std::runtime_error("validation layers requested, but not available!");
VkApplicationInfo appInfo = {}; //info to driver to optimize app
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Hello Triangle";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "No Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo createInfo = {}; //which global ext and avlidation layers to use
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
createInfo.enabledExtensionCount = glfwExtensionCount;
createInfo.ppEnabledExtensionNames = glfwExtensions;
createInfo.enabledLayerCount = 0;
if (enableValidationLayers) {
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
}
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS)
throw std::runtime_error("failed to create instance!");
//uint32_t extensionCount = 0;
//vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr);
//std::vector<VkExtensionProperties> extensions(extensionCount);
//vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, extensions.data());
//std::cout << "available extensions:" << std::endl;
//for (const auto& extension : extensions) {
// std::cout << "\t" << extension.extensionName << std::endl;
//}
}
// check for all validation layers in vulkan to use in debugging
bool checkValidationLayerSupport() {
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
// check if all of the layers in validationLayers exist in the availableLayers list
for (const char* layerName : validationLayers) {
bool layerFound = false;
for (const auto& layerProperties : availableLayers) {
if (strcmp(layerName, layerProperties.layerName) == 0) {
layerFound = true;
break;
}
}
if (!layerFound) {
return false;
}
}
return true;
}
void createSurface() {
if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS)
throw std::runtime_error("failed to create window surface!");
}
// pick gpu to use for vulkan
void pickPhysicalDevice() {
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0)
throw std::runtime_error("failed to find GPUs with Vulkan support!");
std::vector<VkPhysicalDevice> devices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
for (const auto& device : devices) { // select first gpu that supports vulkan
if (isDeviceSuitable(device)) { // check device support for command queues and features
physicalDevice = device;
break;
}
}
if (physicalDevice == VK_NULL_HANDLE)
throw std::runtime_error("failed to find a suitable GPU!");
}
bool isDeviceSuitable(VkPhysicalDevice device) {
QueueFamilyIndices indices = findQueueFamilies(device);
bool extensionsSupported = checkDeviceExtensionSupport(device);
bool swapChainAdequate = false;
if (extensionsSupported) {
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device);
swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
}
VkPhysicalDeviceFeatures supportedFeatures;
vkGetPhysicalDeviceFeatures(device, &supportedFeatures);
return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
}
struct QueueFamilyIndices {
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool isComplete() {
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
// check if device supports input command queues (graphics queue)
QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device) {
QueueFamilyIndices indices;
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
int i = 0;
for (const auto& queueFamily : queueFamilies) {
if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT)
indices.graphicsFamily = i;
VkBool32 presentSupport = false;
vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
if (presentSupport)
indices.presentFamily = i;
i++;
}
return indices;
}
// check for swapchain compatibility
bool checkDeviceExtensionSupport(VkPhysicalDevice device) {
uint32_t extensionCount;
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
std::vector<VkExtensionProperties> availableExtensions(extensionCount);
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
for (const auto& extension : availableExtensions)
requiredExtensions.erase(extension.extensionName);
return requiredExtensions.empty();
}
void createLogicalDevice() {
QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
std::set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
float queuePriority = 1.0f; // scheduling priority of queue [0.0, 1.0]
for (uint32_t queueFamily : uniqueQueueFamilies) {
VkDeviceQueueCreateInfo queueCreateInfo = {};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queueFamily;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
queueCreateInfos.push_back(queueCreateInfo);
}
VkPhysicalDeviceFeatures deviceFeatures = {}; // will be used for checking features
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;
createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
createInfo.ppEnabledExtensionNames = deviceExtensions.data();
createInfo.enabledLayerCount = 0;
if (enableValidationLayers) {
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
}
if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS)
throw std::runtime_error("failed to create logical device!");
vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
}
void createSwapChain() {
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);
VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities);
uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; // images in swap chain ( +1 for no waiting if minimum)
if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) // dont exceed max ( 0 == no limit)
imageCount = swapChainSupport.capabilities.maxImageCount;
VkSwapchainCreateInfoKHR createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
createInfo.surface = surface;
createInfo.minImageCount = imageCount;
createInfo.imageFormat = surfaceFormat.format;
createInfo.imageColorSpace = surfaceFormat.colorSpace;
createInfo.imageExtent = extent;
createInfo.imageArrayLayers = 1; // layers in image (always 1 unless steroscopic 3D)
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; // specify operation on images (render directly to them)
QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
if (indices.graphicsFamily != indices.presentFamily) { // if not same, draw in graphics queue and submit to present queue
createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; // images can be used across queues without ownership transfer
createInfo.queueFamilyIndexCount = 2;
createInfo.pQueueFamilyIndices = queueFamilyIndices;
} else {
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; // image must be explicitly transfered to another queue family (best performance)
createInfo.queueFamilyIndexCount = 0; // optional
createInfo.pQueueFamilyIndices = nullptr; // optional
}
createInfo.preTransform = swapChainSupport.capabilities.currentTransform; // can specify transformations (leave current)
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; // can make window transparent (dont/opaque)
createInfo.presentMode = presentMode;
createInfo.clipped = VK_TRUE; // dont care about obscured pixels (window in front of it)
createInfo.oldSwapchain = VK_NULL_HANDLE; // if swapchain becomes invalid (resize) recreate (we omit this functionality)
if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS)
throw std::runtime_error("failed to create swap chain!");
// retrieve swap chain image handles
vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
swapChainImages.resize(imageCount);
vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
swapChainImageFormat = surfaceFormat.format;
swapChainExtent = extent;
}
void recreateSwapChain() {
// pause if window is minimized
int width = 0, height = 0;
glfwGetFramebufferSize(window, &width, &height);
while (width == 0 || height == 0) { // if minimized width/height == 0
glfwGetFramebufferSize(window, &width, &height);
glfwWaitEvents();
}
vkDeviceWaitIdle(device); // dont touch resources that may still be in use
cleanupSwapChain();
createSwapChain();
createImageViews(); // based directly on swap chain
createRenderPass(); // based on swap chain image format
createGraphicsPipeline(); // viewport and scissor rect are changed
createDepthResources();
createFramebuffers(); // depend directly on swapchain images
for (int i = 0; i < renderObjects.size(); i++) {
createUniformBuffers(renderObjects[i].uniformBuffers, renderObjects[i].uniformBuffersMemory); // depends on number of swapchain images
createDescriptorPool(renderObjects[i].descriptorPool); // depends on number of swapchain images
createDescriptorSets(renderObjects[i].descriptorSets,
renderObjects[i].descriptorPool,
renderObjects[i].uniformBuffers,
renderObjects[i].textureImageView,
renderObjects[i].textureSampler); // depends on number of swapchain images
}
createCommandBuffers(); // depend directly on swapchain images
}
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
// check device for swapchain support
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device) {
SwapChainSupportDetails details;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
uint32_t formatCount;
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
if (formatCount != 0) {
details.formats.resize(formatCount);
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
}
uint32_t presentModeCount;
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
if (presentModeCount != 0) {
details.presentModes.resize(presentModeCount);
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
}
return details;
}
// choose 32 bit rgba color format if possible, else just get the first format in list
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) {
for (const auto& availableFormat : availableFormats) {
if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
return availableFormat;
}
}
return availableFormats[0];
}
// choose v-sync (garuanteed) or triple buffer if available
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) {
for (const auto& availablePresentMode : availablePresentModes) {
if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
return availablePresentMode;
}
}
return VK_PRESENT_MODE_FIFO_KHR;
}
// set resolution of swap chain images (size of window)
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities) {
if (capabilities.currentExtent.width != UINT32_MAX) {
return capabilities.currentExtent;
} else {
int width, height;
glfwGetFramebufferSize(window, &width, &height);
VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) };
actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width);
actualExtent.height = std::clamp(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height);
return actualExtent;
}
}
void createImageViews() {
swapChainImageViews.resize(swapChainImages.size());
for (size_t i = 0; i < swapChainImages.size(); i++) {
swapChainImageViews[i] = createImageView(swapChainImages[i], swapChainImageFormat, VK_IMAGE_ASPECT_COLOR_BIT);
}
}
// specify framebuffer attachments for rendering wrapped in renderPass object
void createRenderPass() {
VkAttachmentDescription colorAttachment{};
colorAttachment.format = swapChainImageFormat;
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; // clear values to constant at start
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; // renders stored in memory and can be read later
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; // we're not using stencil buffer
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; // we're not using stencil buffer
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; // images to be presented in swap chain
VkAttachmentReference colorAttachmentRef{};
colorAttachmentRef.attachment = 0; // references index 0 of VkAttachmentDescription
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentDescription depthAttachment{};
depthAttachment.format = findDepthFormat();
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;
VkAttachmentReference depthAttachmentRef{};
depthAttachmentRef.attachment = 1;
depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorAttachmentRef;
subpass.pDepthStencilAttachment = &depthAttachmentRef;
VkSubpassDependency dependency{}; // wait on swap chain to finish reading before accessing
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.srcAccessMask = 0;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
std::array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
VkRenderPassCreateInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());;
renderPassInfo.pAttachments = attachments.data();
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
renderPassInfo.dependencyCount = 1;
renderPassInfo.pDependencies = &dependency;
if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS)
throw std::runtime_error("failed to create render pass!");
}
void createDescriptorSetLayout() {
VkDescriptorSetLayoutBinding uboLayoutBinding{};
uboLayoutBinding.binding = 0; // the binding from shader
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBinding.descriptorCount = 1;
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; // which shader stage it will be referenced
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 1;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.pImmutableSamplers = nullptr;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding };
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS)
throw std::runtime_error("failed to create descriptor set layout!");
}
// create graphics pipeline by loading shader files
void createGraphicsPipeline() {
auto vertShaderCode = readFile("shaders/vert.spv");
auto fragShaderCode = readFile("shaders/frag.spv");
VkShaderModule vertShaderModule = createShaderModule(vertShaderCode);
VkShaderModule fragShaderModule = createShaderModule(fragShaderCode);
VkPipelineShaderStageCreateInfo vertShaderStageInfo = {};
vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
vertShaderStageInfo.module = vertShaderModule;
vertShaderStageInfo.pName = "main"; // entry point
VkPipelineShaderStageCreateInfo fragShaderStageInfo = {};
fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
fragShaderStageInfo.module = fragShaderModule;
fragShaderStageInfo.pName = "main";
VkPipelineShaderStageCreateInfo shaderStages[] = { vertShaderStageInfo, fragShaderStageInfo };
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
auto bindingDescription = Vertex::getBindingDescription();
auto attributeDescriptions = Vertex::getAttributeDescriptions();
vertexInputInfo.vertexBindingDescriptionCount = 1;
vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size());
vertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data();
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
inputAssembly.primitiveRestartEnable = VK_FALSE;
VkViewport viewport{};
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = (float)swapChainExtent.width;
viewport.height = (float)swapChainExtent.height;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor{};
scissor.offset = { 0, 0 };
scissor.extent = swapChainExtent;
VkPipelineViewportStateCreateInfo viewportState{};
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportState.viewportCount = 1;
viewportState.pViewports = &viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &scissor;
VkPipelineRasterizationStateCreateInfo rasterizer{};
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE; // if true clamp z depth frags instead of discard
rasterizer.rasterizerDiscardEnable = VK_FALSE; // if true disable rasterizer
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.lineWidth = 1.0f; // wider than 1.0f requies wideLines gpu feature
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rasterizer.depthBiasEnable = VK_FALSE;
VkPipelineMultisampleStateCreateInfo multisampling{}; // left disabled so far
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineDepthStencilStateCreateInfo depthStencil{};
depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
depthStencil.depthTestEnable = VK_TRUE;
depthStencil.depthWriteEnable = VK_TRUE;
depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
depthStencil.depthBoundsTestEnable = VK_FALSE;
depthStencil.minDepthBounds = 0.0f; // Optional
depthStencil.maxDepthBounds = 1.0f; // Optional
depthStencil.stencilTestEnable = VK_FALSE;
VkPipelineColorBlendAttachmentState colorBlendAttachment{}; // left disabled, blends new and old rasterized pixel per framebuffer
colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
colorBlendAttachment.blendEnable = VK_FALSE;
VkPipelineColorBlendStateCreateInfo colorBlending{}; // left disabled, blends new and old rasterized pixel for every frambuffer, overrides prev blend
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
colorBlending.logicOpEnable = VK_FALSE;
colorBlending.logicOp = VK_LOGIC_OP_COPY; // Optional
colorBlending.attachmentCount = 1;
colorBlending.pAttachments = &colorBlendAttachment;
colorBlending.blendConstants[0] = 0.0f; // Optional
colorBlending.blendConstants[1] = 0.0f; // Optional
colorBlending.blendConstants[2] = 0.0f; // Optional
colorBlending.blendConstants[3] = 0.0f; // Optional
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS)
throw std::runtime_error("failed to create pipeline layout!");
VkGraphicsPipelineCreateInfo pipelineInfo{};
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineInfo.stageCount = 2;
pipelineInfo.pStages = shaderStages;
pipelineInfo.pVertexInputState = &vertexInputInfo;
pipelineInfo.pInputAssemblyState = &inputAssembly;
pipelineInfo.pViewportState = &viewportState;
pipelineInfo.pRasterizationState = &rasterizer;
pipelineInfo.pMultisampleState = &multisampling;
pipelineInfo.pDepthStencilState = &depthStencil;
pipelineInfo.pColorBlendState = &colorBlending;
pipelineInfo.layout = pipelineLayout;
pipelineInfo.renderPass = renderPass;
pipelineInfo.subpass = 0;
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; // for deriving new pipeline from another
pipelineInfo.basePipelineIndex = -1; // for deriving new pipeline from another
if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &graphicsPipeline) != VK_SUCCESS)
throw std::runtime_error("failed to create graphics pipeline!");
vkDestroyShaderModule(device, vertShaderModule, nullptr);
vkDestroyShaderModule(device, fragShaderModule, nullptr);