-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
3823 lines (3129 loc) · 151 KB
/
main.cpp
File metadata and controls
3823 lines (3129 loc) · 151 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/vec4.hpp>
#include <glm/mat4x4.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#define GLM_ENABLE_EXPERIMENTAL
#include "glm/gtx/hash.hpp"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <iostream>
#include <vector>
#include <string.h>
#include <algorithm>
#include <fstream>
#include <functional>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <ios>
#include <sys/time.h>
#include "UI_system.h"
#include "geometry.h"
#include "physics.h"
#include "main.h"
#include "tinyfiledialogs.h"
struct MatricesUBO{
alignas(16) glm::mat4 view;
alignas(16) glm::mat4 proj;
alignas(16) glm::vec4 camPos;
};
struct LightUBO{
alignas(16) glm::vec4 dir;
alignas(16) glm::vec4 col;
};
struct PerObjectData{
alignas(16) glm::mat4 model;
};
struct VoxelMetaData {
alignas(16) glm::vec4 minCorner;//w not used min corner of whole voxel grid
alignas(16) glm::vec4 maxCorner;//w not used max corner of whole voxel grid
alignas(16) glm::ivec4 stepDim;//w not used for data reading indexing into buffer increasing pos[i] by 1 increases data loc bby stepDim[i]
alignas(16) glm::ivec4 voxelDim;//w not used whole grid dimensions in voxel units
alignas(16) glm::vec4 voxelSize;//w not used used to work out cell pos of a id
};
struct CSGMetaData {
alignas(4) glm::ivec1 primitiveDataSize;
alignas(4) glm::ivec1 nodeDataSize;
alignas(4) glm::ivec1 root;
alignas(4) glm::ivec1 selected;
};
struct VoxelData{
alignas(4) uint type;
};
struct PrimitiveData{
alignas(16) glm::vec4 data;
};
struct NodeData{
alignas(16) glm::ivec4 data;
};
struct MatrixPushConstant{
alignas(16) glm::mat4 model;
};
struct UIPushConstant{
alignas(16) glm::mat4 model;
alignas(16) glm::mat4 texture;
};
class Program;
class CSG;
class Camera;
template <class T>
class MemoryManager;
class Model;
class InstancedModel;
class RigidBody;
class UIElement;
struct DesignState;
struct StructureDefinition;
Program::Program(bool useValidationLayers, const std::vector<const char*> validationLayersToUse, const std::vector<const char*> deviceExtensionsToUse){
enableValidationLayers = useValidationLayers;
for (const char* vLayer : validationLayersToUse){
validationLayers.push_back(vLayer);
}
for (const char* ext : deviceExtensionsToUse){
deviceExtensions.push_back(ext);
}
MAX_FRAMES_IN_FLIGHT = 2;
currentFrame = 0;
framebufferResized = false;
mainCamera = new Camera();
}
Program::~Program(){
for (int i = 0; i < rigidBodies.size(); i++){
delete rigidBodies[i];
rigidBodies[i] = nullptr;
}
for (int i = 0; i < models.size(); i++){// probably needed as otherwise may try to free its space from a destroyed memory block
delete models[i];
models[i] = nullptr;
}
for (int i = 0; i < instancedModels.size(); i++){// probably needed as otherwise may try to free its space from a destroyed memory block
delete instancedModels[i];
instancedModels[i] = nullptr;
}
delete mainCamera;
std::cout << "closing down\n";
cleanupSwapChain();
vkDestroySampler(logicalDevice, textureSampler, nullptr);
vkDestroyImageView(logicalDevice, textureImageView, nullptr);
vkDestroyImage(logicalDevice, textureImage, nullptr);
vkFreeMemory(logicalDevice, textureImageMemory, nullptr);
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
vkDestroySemaphore(logicalDevice, renderFinishedSemaphores[i], nullptr);
vkDestroySemaphore(logicalDevice, imageAvailableSemaphores[i], nullptr);
vkDestroyFence(logicalDevice, inFlightFences[i], nullptr);
}
delete verticesMemManager;
delete indicesMemManager;
vkDestroyCommandPool(logicalDevice, commandPool, nullptr);
vkDestroyDescriptorPool(logicalDevice, descriptorPool, nullptr);
vkDestroyDescriptorSetLayout(logicalDevice, descriptorSetLayout, nullptr);
vkDestroyDescriptorSetLayout(logicalDevice, perObjectDataDSLayout, nullptr);
vkDestroyDescriptorSetLayout(logicalDevice, uiDescriptorSetLayout, nullptr);
vkDestroyDescriptorSetLayout(logicalDevice, uiTextureDescriptorSetLayout, nullptr);
vkDestroyDescriptorSetLayout(logicalDevice, designDSLayout, nullptr);
vkDestroyDescriptorSetLayout(logicalDevice, designDataDSLayout, nullptr);
for (int i = 0; i < buffers.size(); i++){
vkDestroyBuffer(logicalDevice, buffers[i], nullptr);
vkFreeMemory(logicalDevice, buffersMemory[i], nullptr);
}
vkDestroyPipeline(logicalDevice, graphicsPipeline, nullptr);
vkDestroyPipelineLayout(logicalDevice, pipelineLayout, nullptr);
vkDestroyPipeline(logicalDevice, uiGraphicsPipeline, nullptr);
vkDestroyPipelineLayout(logicalDevice, uiPipeLineLayout, nullptr);
vkDestroyPipeline(logicalDevice, designGraphicsPipeline, nullptr);
vkDestroyPipelineLayout(logicalDevice, designPipelineLayout, nullptr);
vkDestroyRenderPass(logicalDevice, renderPass, nullptr);
vkDestroyImage(logicalDevice, depthImage, nullptr);
vkFreeMemory(logicalDevice, depthImageMemory, nullptr);
vkDestroyImageView(logicalDevice, depthImageView, nullptr);
vkDestroyDevice(logicalDevice, nullptr);
vkDestroySurfaceKHR(instance, surface, nullptr);
vkDestroyInstance(instance, nullptr);
glfwDestroyWindow(window);
glfwTerminate();
}
void Program::cleanupSwapChain(){
for (int i = 0; i < swapChainFramebuffers.size(); i++) {
vkDestroyFramebuffer(logicalDevice, swapChainFramebuffers[i], nullptr);
}
for (int i = 0; i < swapChainImageViews.size(); i++) {
vkDestroyImageView(logicalDevice, swapChainImageViews[i], nullptr);
}
vkDestroySwapchainKHR(logicalDevice, swapChain, nullptr);
}
void Program::makeWindow(){
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
//glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); // due to being able to recreate the swap chain is not needed
window = glfwCreateWindow(1080, 720, "Structural Simulator", nullptr, nullptr);
//glfwSetFramebufferSizeCallback(window, framebufferResizeCallback);
}
void Program::setUpVulkan(){
createInstance();
createSurface();
pickHardWareDevices();
createLogicalDevice();
createSwapChain();
createImageViews();
createCommandPool();
createRenderPass();
createDescriptorSetLayouts();// does all pipelines
createGraphicsPipeline();
createUIGraphicsPipeline();
createDesignRayCastingPipeline();
createDepthResources();
createFramebuffers();
createTextureImage();
createTextureImageView();
createTextureSampler();
verticesMemManager = new MemoryManager<Vertex>(65536*16,logicalDevice, this, Vertex{{0.0,0.0,0.0},{0.0,0.0,0.0},{0.0,0.0,0.0}},
VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
indicesMemManager = new MemoryManager<uint16_t>(65536*16,logicalDevice, this, 0,
VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
createBuffers();
createDescriptorPool();
createDescriptorSets();
createCommandBuffers();
createSyncObjects();
finishedSetUpBits();
}
void Program::createInstance(){
if (enableValidationLayers && !checkValidationLayerSupport()){
throw std::runtime_error("validation layers not available");
}
VkApplicationInfo appInfo{};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Structural simulator";
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_1;
VkInstanceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
if (enableValidationLayers) {
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
} else {
createInfo.enabledLayerCount = 0;
}
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
createInfo.enabledExtensionCount = glfwExtensionCount;
createInfo.ppEnabledExtensionNames = glfwExtensions;
VkResult result = vkCreateInstance(&createInfo, nullptr, &instance);
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
throw std::runtime_error("failed to create instance");
}
}
bool Program::checkValidationLayerSupport(){
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
for (const char* layerName : validationLayers){
bool layerFound = false;
for (const VkLayerProperties& layerProperties : availableLayers){
if (strcmp(layerName, layerProperties.layerName) == 0){// strcmp is asking are they equal from string.h
layerFound = true;
break;
}
}
if (!layerFound){// if any of wanted layers not available return false
return false;
}
}
return true;
}
void Program::createSurface(){
if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) {
throw std::runtime_error("failed to create window surface!");
}
}
void Program::pickHardWareDevices(){
physicalDevice = VK_NULL_HANDLE;
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0){
std::cout << "no gpus with vulkan support\n";
throw std::runtime_error("failed to find GPUs with Vulkan support!");
}
std::cout << deviceCount << " gpus\n";
std::vector<VkPhysicalDevice> devices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
for (const VkPhysicalDevice& device : devices) {
std::cout << devices.size() << "\n";
if (device == VK_NULL_HANDLE){
std::cout << "??\n";
}
if (validDevice(device)) {
physicalDevice = device;
break;
}
}
std::cout << "\n\n";
if (physicalDevice == VK_NULL_HANDLE) {
throw std::runtime_error("failed to find a suitable GPU!");
}
}
bool Program::validDevice(VkPhysicalDevice device){
std::cout << device << "\n";
// version supported and other stuff
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(device, &deviceProperties);
// what optional support is there
VkPhysicalDeviceFeatures deviceFeatures;
vkGetPhysicalDeviceFeatures(device, &deviceFeatures);
QueueStruct indcies = findQueues(device);
if (!indcies.isComplete()){
std::cout << "error missing vital queue\n";
return false;
}
std::cout << indcies.graphicsFamily << " graphic queue\n";
if (!hasNeededExtensions(device)){
return false;
}
bool swapChainAdequate = false;
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device);
swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
std::cout << swapChainSupport.formats.size() << " " << swapChainSupport.presentModes.size() << "\n";
if (!swapChainAdequate){
std::cout << "not swap chain adequate\n";
return false;
}
return true;
}
QueueStruct Program::findQueues(VkPhysicalDevice device){
QueueStruct indices;
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
for (int i = 0; i < queueFamilies.size(); i++){
const VkQueueFamilyProperties& queueFamily = queueFamilies[i];
std::cout << i << " queue\n";
if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT){
indices.graphicsFamily = i;
}
VkBool32 canPresent = false;
vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &canPresent);
if (canPresent){
indices.presentFamily = i;
}
if((queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) && (queueFamily.queueFlags & VK_QUEUE_COMPUTE_BIT)){
indices.graphicsAndComputeFamily = i;
}
if (indices.isComplete()){
//break;
}
}
return indices;
}
bool Program::hasNeededExtensions(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 VkExtensionProperties& extension : availableExtensions){ // for each of the availible extensions remove it from needed ones
requiredExtensions.erase(extension.extensionName);
}
return requiredExtensions.empty();// if any left means unavailable extension
}
SwapChainSupportDetails Program::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;
}
void Program::createLogicalDevice(){
QueueStruct indices = findQueues(physicalDevice);
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
std::set<uint32_t> uniqueQueueFamilies;
uniqueQueueFamilies.insert(indices.graphicsFamily);
uniqueQueueFamilies.insert(indices.presentFamily);
uniqueQueueFamilies.insert(indices.graphicsAndComputeFamily);
float queuePriority = 1.0f;
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{};
//vkGetPhysicalDeviceFeatures(physicalDevice, &deviceFeatures);
VkPhysicalDeviceShaderDrawParametersFeatures shaderDrawParameterFeatures{};
shaderDrawParameterFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES;
shaderDrawParameterFeatures.pNext = nullptr;
shaderDrawParameterFeatures.shaderDrawParameters = VK_TRUE;
VkPhysicalDeviceFeatures2 physicalFeatures2 = {};
physicalFeatures2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
physicalFeatures2.pNext = &shaderDrawParameterFeatures;
vkGetPhysicalDeviceFeatures2(physicalDevice, &physicalFeatures2);
if (shaderDrawParameterFeatures.shaderDrawParameters == VK_FALSE){throw;}
VkDeviceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
createInfo.pQueueCreateInfos = queueCreateInfos.data();
createInfo.pEnabledFeatures = nullptr;//&deviceFeatures;
createInfo.pNext = &physicalFeatures2;
createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
createInfo.ppEnabledExtensionNames = deviceExtensions.data();
if (enableValidationLayers) {
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
} else {
createInfo.enabledLayerCount = 0;
}
if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &logicalDevice) != VK_SUCCESS) {
throw std::runtime_error("failed to create logical device!");
}
vkGetDeviceQueue(logicalDevice, indices.graphicsFamily, 0, &graphicsQueue);
vkGetDeviceQueue(logicalDevice, indices.presentFamily, 0, &presentQueue);
vkGetDeviceQueue(logicalDevice, indices.graphicsAndComputeFamily, 0, &computeQueue);
}
void Program::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;// +1 so dont have to wait for driver to finish as much
if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {// 0 means no max
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;
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
QueueStruct indices = findQueues(physicalDevice);
uint32_t queueFamilyIndices[] = {static_cast<uint32_t>(indices.graphicsFamily),static_cast<uint32_t>(indices.presentFamily)};
if (indices.graphicsFamily != indices.presentFamily){
createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
createInfo.queueFamilyIndexCount = 2;
createInfo.pQueueFamilyIndices = queueFamilyIndices;
}
else{
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
createInfo.queueFamilyIndexCount = 0; // Optional
createInfo.pQueueFamilyIndices = nullptr; // Optional
}
createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
createInfo.presentMode = presentMode;
createInfo.clipped = VK_TRUE;
createInfo.oldSwapchain = VK_NULL_HANDLE;
if (vkCreateSwapchainKHR(logicalDevice, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
throw std::runtime_error("failed to create swap chain!");
}
vkGetSwapchainImagesKHR(logicalDevice, swapChain, &imageCount, nullptr);
swapChainImages.resize(imageCount);
vkGetSwapchainImagesKHR(logicalDevice, swapChain, &imageCount, swapChainImages.data());
swapChainImageFormat = surfaceFormat.format;
swapChainExtent = extent;
}
VkSurfaceFormatKHR Program::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) {
for (const VkSurfaceFormatKHR& availableFormat : availableFormats) {
if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
return availableFormat;
}
}
return availableFormats[0];
}
VkPresentModeKHR Program::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes){
for (const VkPresentModeKHR& availablePresentMode : availablePresentModes){
if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR){
return availablePresentMode;
}
}
return VK_PRESENT_MODE_FIFO_KHR;
}
VkExtent2D Program::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities){
if (capabilities.currentExtent.width != std::numeric_limits<uint32_t>::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 Program::createImageViews(){
swapChainImageViews.resize(swapChainImages.size());
for (int i = 0; i < swapChainImages.size(); i++) {
swapChainImageViews[i] = createImageView(swapChainImages[i],swapChainImageFormat,VK_IMAGE_ASPECT_COLOR_BIT);
}
}
VkImageView Program::createImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags){
VkImageViewCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
createInfo.image = image;
createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
createInfo.format = format;
createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.subresourceRange.aspectMask = aspectFlags;
createInfo.subresourceRange.baseMipLevel = 0;
createInfo.subresourceRange.levelCount = 1;
createInfo.subresourceRange.baseArrayLayer = 0;
createInfo.subresourceRange.layerCount = 1;
VkImageView imageView;
if (vkCreateImageView(logicalDevice, &createInfo, nullptr, &imageView) != VK_SUCCESS) {
throw std::runtime_error("failed to create image view");
}
return imageView;
}
void Program::createCommandPool(){
QueueStruct queueFamilyIndices = findQueues(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;
if (vkCreateCommandPool(logicalDevice, &poolInfo, nullptr, &commandPool) != VK_SUCCESS){
throw std::runtime_error("failed to create command pool!");
}
}
void Program::createRenderPass(){
VkAttachmentDescription colorAttachment{};
colorAttachment.format = swapChainImageFormat;
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference colorAttachmentRef{};
colorAttachmentRef.attachment = 0;
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{};
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
dependency.srcAccessMask = 0;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_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(logicalDevice, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
throw std::runtime_error("failed to create render pass");
}
}
VkFormat Program::findDepthFormat() {
return findSupportedFormat(
{VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT},
VK_IMAGE_TILING_OPTIMAL,
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
);
}
VkFormat Program::findSupportedFormat(const std::vector<VkFormat>& candidates, VkImageTiling tiling, VkFormatFeatureFlags features){
for (VkFormat format : candidates) {
VkFormatProperties props;
vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &props);
if (tiling == VK_IMAGE_TILING_LINEAR && (props.linearTilingFeatures & features) == features){
return format;
}
else if (tiling == VK_IMAGE_TILING_OPTIMAL && (props.optimalTilingFeatures & features) == features){
return format;
}
}
throw std::runtime_error("failed to find supported format!");
}
void Program::createDescriptorSetLayouts(){// makes all decriptor set layouts using below function
createDescriptorSetLayout({VK_SHADER_STAGE_VERTEX_BIT,VK_SHADER_STAGE_FRAGMENT_BIT},2,descriptorSetLayout,VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);// main ubo
createDescriptorSetLayout({},0,uiDescriptorSetLayout,VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);// ui ubo
createDescriptorSetLayout({VK_SHADER_STAGE_FRAGMENT_BIT},1,uiTextureDescriptorSetLayout,VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);// ui texture
createDescriptorSetLayout({VK_SHADER_STAGE_VERTEX_BIT},1,perObjectDataDSLayout,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);// main ssbo
createDescriptorSetLayout({VK_SHADER_STAGE_VERTEX_BIT|VK_SHADER_STAGE_FRAGMENT_BIT,VK_SHADER_STAGE_FRAGMENT_BIT,VK_SHADER_STAGE_FRAGMENT_BIT},3,designDSLayout,VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);// design ubo (like main ubo but with voxel/CSG meta data)
createDescriptorSetLayout({VK_SHADER_STAGE_FRAGMENT_BIT,VK_SHADER_STAGE_FRAGMENT_BIT},2,designDataDSLayout,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);// design ssbo(s?) the CSG version has an extra SSBO as it has 2 undefined size things
}
void Program::createDescriptorSetLayout(std::vector<int> stages, int numBuffers,VkDescriptorSetLayout& layout, VkDescriptorType type){// helper function
std::vector<VkDescriptorSetLayoutBinding> layoutBindings{};
for (int i = 0; i < numBuffers; i++){
layoutBindings.push_back(VkDescriptorSetLayoutBinding{});
layoutBindings[i].binding = i;
layoutBindings[i].descriptorType = type;
layoutBindings[i].descriptorCount = 1;
layoutBindings[i].stageFlags = stages[i];
layoutBindings[i].pImmutableSamplers = nullptr; // Optional
}
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = layoutBindings.size();
layoutInfo.pBindings = layoutBindings.data();
if (vkCreateDescriptorSetLayout(logicalDevice, &layoutInfo, nullptr, &layout) != VK_SUCCESS) {
throw std::runtime_error("failed to create descriptor set layout");
}
}
void Program::createGraphicsPipeline(){
std::vector<char> vertShaderCode = readFile("vulkan_shaders/shader_vert.spv");
std::vector<char> fragShaderCode = readFile("vulkan_shaders/shader_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";
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;
std::vector<VkDynamicState> dynamicStates = {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR
};
VkPipelineDynamicStateCreateInfo dynamicState{};
dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamicState.dynamicStateCount = static_cast<uint32_t>(dynamicStates.size());
dynamicState.pDynamicStates = dynamicStates.data();
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;
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;
depthStencil.front = {}; // Optional
depthStencil.back = {}; // Optional
VkPipelineRasterizationStateCreateInfo rasterizer{};
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.lineWidth = 1.0f; // cant be more than 1 without cahnging something
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rasterizer.depthBiasEnable = VK_FALSE;
rasterizer.depthBiasConstantFactor = 0.0f; // Optional
rasterizer.depthBiasClamp = 0.0f; // Optional
rasterizer.depthBiasSlopeFactor = 0.0f; // Optional
VkPipelineMultisampleStateCreateInfo multisampling{};
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
multisampling.minSampleShading = 1.0f; // Optional
multisampling.pSampleMask = nullptr; // Optional
multisampling.alphaToCoverageEnable = VK_FALSE; // Optional
multisampling.alphaToOneEnable = VK_FALSE; // Optional
VkPipelineColorBlendAttachmentState colorBlendAttachment{};
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;
colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; // Optional
colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; // Optional
VkPipelineColorBlendStateCreateInfo colorBlending{};
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
// added to send model matrix per object
VkPushConstantRange pushConstRange;
pushConstRange.offset = 0;// only 1 so use the start
pushConstRange.size = sizeof(MatrixPushConstant);//64;// 4 vec4 is 4 byte per float *16 = 64
pushConstRange.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;// needs to be in vertex shader
std::vector<VkDescriptorSetLayout> dsLayouts = {descriptorSetLayout, perObjectDataDSLayout};
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = dsLayouts.size();
pipelineLayoutInfo.pSetLayouts = dsLayouts.data();
pipelineLayoutInfo.pushConstantRangeCount = 1;
pipelineLayoutInfo.pPushConstantRanges = &pushConstRange;
if (vkCreatePipelineLayout(logicalDevice, &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 = nullptr; // Optional
pipelineInfo.pColorBlendState = &colorBlending;
pipelineInfo.pDynamicState = &dynamicState;
pipelineInfo.pDepthStencilState = &depthStencil;
pipelineInfo.layout = pipelineLayout;
pipelineInfo.renderPass = renderPass;
pipelineInfo.subpass = 0;
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; // Optional
pipelineInfo.basePipelineIndex = -1; // Optional
if (vkCreateGraphicsPipelines(logicalDevice, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &graphicsPipeline) != VK_SUCCESS) {
throw std::runtime_error("failed to create graphics pipeline!");
}
vkDestroyShaderModule(logicalDevice, fragShaderModule, nullptr);
vkDestroyShaderModule(logicalDevice, vertShaderModule, nullptr);
}
void Program::createUIGraphicsPipeline(){
std::vector<char> vertShaderCode = readFile("vulkan_shaders/shader_vert_ui.spv");
std::vector<char> fragShaderCode = readFile("vulkan_shaders/shader_frag_ui.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";
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";