-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1662 lines (1384 loc) · 73.6 KB
/
main.cpp
File metadata and controls
1662 lines (1384 loc) · 73.6 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 <fstream>
#include <filesystem>
#include <sstream>
#include <GLFW/glfw3.h>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <cstdint>
#include <limits>
#include <optional>
#include <set>
#include <iostream>
#include <unistd.h>
#include <limits.h>
#include <array>
#include <glm/glm.hpp>
#include <sys/stat.h>
#include "/Users/colinleary/Desktop/VulkanSDK/KTX-Software/include/ktx.h"
#include "/Users/colinleary/Desktop/VulkanSDK/KTX-Software/include/ktxvulkan.h"
struct Vertex {
glm::vec2 pos; // Position (x, y)
glm::vec2 texCoord; // Texture Coordinates (u, v)
};
#include <glm/glm.hpp>
void printWorkingDirectory() {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != nullptr) {
std::cout << "Current Working Directory: " << cwd << std::endl;
} else {
perror("getcwd() error");
}
}
const uint32_t WIDTH = 800;
const uint32_t HEIGHT = 600;
const std::vector<const char*> validationLayers = {
"VK_LAYER_KHRONOS_validation"
};
const std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME,
"VK_KHR_portability_subset"
};
#ifdef NDEBUG
const bool enableValidationLayers = false;
#else
const bool enableValidationLayers = true;
#endif
bool checkExtensionSupport(VkPhysicalDevice device, const char* extensionName) {
uint32_t extensionCount;
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
std::vector<VkExtensionProperties> availableExtensions(extensionCount);
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
for (const auto& ext : availableExtensions) {
if (strcmp(ext.extensionName, extensionName) == 0) {
return true;
}
}
return false;
}
VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pDebugMessenger) {
auto func = (PFN_vkCreateDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
if (func != nullptr) {
return func(instance, pCreateInfo, pAllocator, pDebugMessenger);
} else {
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, const VkAllocationCallbacks* pAllocator) {
auto func = (PFN_vkDestroyDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
if (func != nullptr) {
func(instance, debugMessenger, pAllocator);
}
}
struct QueueFamilyIndices {
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool isComplete() {
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class HelloTriangleApplication {
void createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer &buffer, VkDeviceMemory &bufferMemory) {
VkBufferCreateInfo bufferInfo{};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) {
throw std::runtime_error("❌ ERROR: Failed to create buffer!");
}
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(device, buffer, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) {
throw std::runtime_error("❌ ERROR: Failed to allocate buffer memory!");
}
vkBindBufferMemory(device, buffer, bufferMemory, 0);
}
uint32_t findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties) {
VkPhysicalDeviceMemoryProperties memProperties;
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) {
std::cout << "🔍 Checking Memory Type " << i << ": Flags=" << memProperties.memoryTypes[i].propertyFlags << std::endl;
if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) {
return i;
}
}
throw std::runtime_error("❌ ERROR: Failed to find suitable memory type!");
}
const std::string TEXTURE_PATH = "/Users/colinleary/Downloads/RoomONE.ktx2";
void loadTexture() {
std::cout << "🛠 Entering loadTexture()...\n";
ktxTexture* texture;
KTX_error_code result = ktxTexture_CreateFromNamedFile(TEXTURE_PATH.c_str(), KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, &texture);
if (result != KTX_SUCCESS) {
std::cerr << "❌ ERROR: Failed to load KTX texture: " << TEXTURE_PATH << "\n";
assert(false && "🔴 CRASH: Failed to load KTX texture!");
}
std::cout << "✅ KTX2 Texture loaded successfully!\n";
std::cout << "🔍 Texture Dimensions: " << texture->baseWidth << " x " << texture->baseHeight << "\n";
std::cout << "🔍 Mip Levels: " << texture->numLevels << "\n";
// **Force RGBA8 format to ensure Metal compatibility**
ktx_transcode_fmt_e targetFormat = KTX_TTF_RGBA32;
VkFormat textureFormat = VK_FORMAT_R8G8B8A8_UNORM; // ✅ Vulkan equivalent for RGBA8
// **Handle VK_FORMAT_UNDEFINED case**
if (ktxTexture_GetVkFormat(texture) == VK_FORMAT_UNDEFINED) {
std::cerr << "❌ ERROR: KTX2 file has VK_FORMAT_UNDEFINED! Attempting to transcode...\n";
if (ktxTexture2_TranscodeBasis(reinterpret_cast<ktxTexture2*>(texture), targetFormat, 0) != KTX_SUCCESS) {
throw std::runtime_error("❌ ERROR: Transcoding failed!");
}
std::cout << "✅ Transcoded Format: VK_FORMAT_R8G8B8A8_UNORM (RGBA8)\n";
}
// **Create Vulkan Image with RGBA8 format**
createImage(texture->baseWidth, texture->baseHeight,
textureFormat, // ✅ Using RGBA8 format
VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
textureImage, textureImageMemory);
vkBindImageMemory(device, textureImage, textureImageMemory, 0);
// 🔥 Debugging Step: Print final Vulkan image format
std::cout << "🔍 Final Vulkan Image Format: " << textureFormat << std::endl;
// Create Vulkan image with the processed texture
createTextureImageView();
ktxTexture_Destroy(texture);
}
void createTextureImageView() {
std::cout << "🛠 Entering createTextureImageView()..." << std::endl;
std::cout << "🔍 textureImage: " << textureImage << std::endl;
if (textureImage == VK_NULL_HANDLE) {
std::cerr << "❌ ERROR: textureImage is NULL before creating textureImageView!" << std::endl;
assert(false && "🔴 CRASH: textureImage is NULL!");
}
// Print the Vulkan memory properties of textureImage
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(device, textureImage, &memRequirements);
std::cout << "🔍 Texture Image Memory Requirements: Size = " << memRequirements.size
<< " | Alignment = " << memRequirements.alignment
<< " | Memory Type Bits = " << memRequirements.memoryTypeBits << std::endl;
textureImageView = createImageView(textureImage, VK_FORMAT_R8G8B8A8_UNORM);
if (textureImageView == VK_NULL_HANDLE) {
std::cerr << "❌ ERROR: textureImageView creation failed!" << std::endl;
assert(false && "🔴 CRASH: textureImageView creation failed!");
}
std::cout << "✅ textureImageView created successfully!" << std::endl;
}
void createTextureSampler() {
std::cout << "🛠 Creating Texture Sampler...\n";
VkSamplerCreateInfo samplerInfo{};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_TRUE;
samplerInfo.maxAnisotropy = 16;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
VkResult result = vkCreateSampler(device, &samplerInfo, nullptr, &textureSampler);
if (result != VK_SUCCESS) {
std::cerr << "❌ ERROR: Failed to create Vulkan texture sampler! VkResult = " << result << "\n";
assert(false && "🔴 CRASH: Failed to create Vulkan texture sampler!");
}
std::cout << "✅ Texture Sampler Created: " << textureSampler << "\n";
}
void createDescriptorSet() {
std::cout << "🛠 Entering createDescriptorSet()..." << std::endl << std::flush;
// 🔍 Step 1: Ensure descriptorPool is created
std::cout << "🔍 Creating descriptor pool..." << std::endl << std::flush;
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
poolSize.descriptorCount = 1;
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = 1;
poolInfo.pPoolSizes = &poolSize;
poolInfo.maxSets = 1;
VkResult poolResult = vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool);
if (poolResult != VK_SUCCESS) {
std::cerr << "❌ ERROR: Failed to create descriptor pool! VkResult = " << poolResult << std::endl << std::flush;
assert(false && "🔴 CRASH: Failed to create descriptor pool!");
}
std::cout << "✅ descriptorPool created successfully: " << descriptorPool << std::endl << std::flush;
// 🔍 Step 2: Allocate Descriptor Set
std::cout << "🔍 Allocating descriptor set..." << std::endl << std::flush;
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
VkResult allocResult = vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet);
if (allocResult != VK_SUCCESS) {
std::cerr << "❌ ERROR: Failed to allocate descriptor set! VkResult = " << allocResult << std::endl << std::flush;
assert(false && "🔴 CRASH: Failed to allocate descriptor set!");
}
std::cout << "✅ descriptorSet allocated successfully: " << descriptorSet << std::endl << std::flush;
// 🔍 Step 3: Validate Texture Image View & Sampler
if (textureImageView == VK_NULL_HANDLE) {
std::cerr << "❌ ERROR: textureImageView is NULL before writing descriptor!" << std::endl << std::flush;
assert(false && "🔴 CRASH: textureImageView is NULL!");
}
if (textureSampler == VK_NULL_HANDLE) {
std::cerr << "❌ ERROR: textureSampler is NULL before writing descriptor!" << std::endl << std::flush;
assert(false && "🔴 CRASH: textureSampler is NULL!");
}
// 🔍 Step 4: Prepare Descriptor Write
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = textureImageView;
imageInfo.sampler = textureSampler;
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0; // Ensure this matches shader binding!
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pImageInfo = &imageInfo;
// Debugging output for descriptor info
std::cout << "🔍 descriptorSet: " << descriptorSet << std::endl;
std::cout << "🔍 descriptorWrite.dstBinding: " << descriptorWrite.dstBinding << std::endl;
std::cout << "🔍 descriptorWrite.descriptorType: " << descriptorWrite.descriptorType << std::endl;
std::cout << "🔍 descriptorWrite.descriptorCount: " << descriptorWrite.descriptorCount << std::endl;
std::cout << "🔍 descriptorWrite.pImageInfo: " << descriptorWrite.pImageInfo << std::endl;
if (descriptorWrite.pImageInfo) {
std::cout << "🔍 imageInfo.imageView: " << descriptorWrite.pImageInfo->imageView << std::endl;
std::cout << "🔍 imageInfo.sampler: " << descriptorWrite.pImageInfo->sampler << std::endl;
std::cout << "🔍 imageInfo.imageLayout: " << descriptorWrite.pImageInfo->imageLayout << std::endl;
}
// 🔍 Step 5: Update Descriptor Set
std::cout << "🔍 Updating descriptor set..." << std::endl << std::flush;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
std::cout << "✅ Descriptor set updated successfully!" << std::endl << std::flush;
// 🔍 Step 6: Additional Debugging After Update
if (descriptorSet == VK_NULL_HANDLE) {
std::cerr << "❌ ERROR: descriptorSet is NULL after vkUpdateDescriptorSets!" << std::endl << std::flush;
assert(false && "🔴 CRASH: descriptorSet is NULL after update!");
} else {
std::cout << "✅ Post-update descriptorSet is valid: " << descriptorSet << std::endl << std::flush;
}
}
VkSemaphore imageAvailableSemaphore;
VkSemaphore renderFinishedSemaphore;
void createSyncObjects() {
VkSemaphoreCreateInfo semaphoreInfo{};
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphore) != VK_SUCCESS ||
vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphore) != VK_SUCCESS) {
throw std::runtime_error("❌ ERROR: Failed to create semaphores!");
}
std::cout << "✅ Semaphores created successfully!" << std::endl;
}
void recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIndex) {
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
// ✅ Ensure the command buffer is valid before beginning
if (commandBuffer == VK_NULL_HANDLE) {
throw std::runtime_error("❌ ERROR: Command buffer is NULL before recording!");
}
if (vkBeginCommandBuffer(commandBuffer, &beginInfo) != VK_SUCCESS) {
throw std::runtime_error("❌ ERROR: Failed to begin recording command buffer!");
}
VkRenderPassBeginInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = renderPass;
renderPassInfo.framebuffer = swapChainFramebuffers[imageIndex];
renderPassInfo.renderArea.offset = {0, 0};
renderPassInfo.renderArea.extent = swapChainExtent;
VkClearValue clearColor = {{{0.0f, 0.0f, 0.0f, 1.0f}}};
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(commandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline);
// ✅ Ensure vertex buffer exists before binding
if (vertexBuffer == VK_NULL_HANDLE) {
throw std::runtime_error("❌ ERROR: vertexBuffer is NULL before binding!");
}
std::cout << "🔍 Binding Vertex Buffer: " << vertexBuffer << std::endl;
VkBuffer vertexBuffers[] = {vertexBuffer};
VkDeviceSize offsets[] = {0};
vkCmdBindVertexBuffers(commandBuffer, 0, 1, vertexBuffers, offsets);
// ✅ Ensure descriptor set exists before binding
if (descriptorSet == VK_NULL_HANDLE) {
throw std::runtime_error("❌ ERROR: descriptorSet is NULL before binding!");
}
vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSet, 0, nullptr);
std::cout << "🟢 Calling vkCmdDraw()" << std::endl;
vkCmdDraw(commandBuffer, 6, 1, 0, 0);
vkCmdEndRenderPass(commandBuffer);
if (vkEndCommandBuffer(commandBuffer) != VK_SUCCESS) {
throw std::runtime_error("❌ ERROR: Failed to record command buffer!");
}
}
void drawFrame() {
uint32_t imageIndex;
VkResult result = vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphore, VK_NULL_HANDLE, &imageIndex);
if (result != VK_SUCCESS) {
throw std::runtime_error("❌ ERROR: Failed to acquire swap chain image!");
}
// ✅ Ensure command buffer is valid before submitting
if (commandBuffers[imageIndex] == VK_NULL_HANDLE) {
throw std::runtime_error("❌ ERROR: commandBuffers[imageIndex] is NULL before vkQueueSubmit!");
}
// 🛠 **Record the command buffer before submitting**
recordCommandBuffer(commandBuffers[imageIndex], imageIndex);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.waitSemaphoreCount = 1;
VkSemaphore waitSemaphores[] = {imageAvailableSemaphore};
VkPipelineStageFlags waitStages[] = {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT};
submitInfo.pWaitSemaphores = waitSemaphores;
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
VkSemaphore signalSemaphores[] = {renderFinishedSemaphore};
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphores;
// ✅ Ensure graphicsQueue is valid
if (graphicsQueue == VK_NULL_HANDLE) {
throw std::runtime_error("❌ ERROR: graphicsQueue is NULL before submission!");
}
// ✅ Ensure semaphores are valid
if (imageAvailableSemaphore == VK_NULL_HANDLE || renderFinishedSemaphore == VK_NULL_HANDLE) {
throw std::runtime_error("❌ ERROR: Semaphore is NULL before vkQueueSubmit!");
}
std::cout << "🟢 Submitting Command Buffer: " << commandBuffers[imageIndex] << std::endl;
std::cout << "🟢 Using graphicsQueue: " << graphicsQueue << std::endl;
std::cout << "🟢 Image Available Semaphore: " << imageAvailableSemaphore << std::endl;
std::cout << "🟢 Render Finished Semaphore: " << renderFinishedSemaphore << std::endl;
if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE) != VK_SUCCESS) {
throw std::runtime_error("❌ ERROR: Failed to submit draw command buffer!");
}
VkPresentInfoKHR presentInfo{};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = signalSemaphores;
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = &swapChain;
presentInfo.pImageIndices = &imageIndex;
vkQueuePresentKHR(presentQueue, &presentInfo);
}
VkShaderModule createShaderModule(const std::vector<char>& code) {
VkShaderModuleCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
createInfo.codeSize = code.size();
createInfo.pCode = reinterpret_cast<const uint32_t*>(code.data());
VkShaderModule shaderModule;
VkResult result = vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule);
if (result != VK_SUCCESS) {
std::cerr << "❌ ERROR: Failed to create shader module! Error Code: " << result << std::endl;
throw std::runtime_error("failed to create shader module!");
}
std::cout << "✅ Shader module created successfully!" << std::endl;
return shaderModule;
}
std::vector<char> readFile(const std::string& filename) {
// 🔹 Debug: Print the full file path
std::cout << "Attempting to open file: " << filename << std::endl;
// 🕒 Check last modified time before opening the file
struct stat result;
if (stat(filename.c_str(), &result) == 0) {
std::cout << "🕒 Shader Last Modified: " << ctime(&result.st_mtime);
} else {
std::cerr << "❌ ERROR: Could not retrieve file modification time!" << std::endl;
}
std::ifstream file(filename, std::ios::ate | std::ios::binary);
if (!file.is_open()) {
throw std::runtime_error("failed to open file: " + filename);
}
size_t fileSize = (size_t)file.tellg();
std::vector<char> buffer(fileSize);
file.seekg(0);
file.read(buffer.data(), fileSize);
file.close();
return buffer;
}
VkVertexInputBindingDescription getBindingDescription() {
VkVertexInputBindingDescription bindingDescription{};
bindingDescription.binding = 0;
bindingDescription.stride = sizeof(Vertex);
bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return bindingDescription;
}
std::array<VkVertexInputAttributeDescription, 2> getAttributeDescriptions() {
std::array<VkVertexInputAttributeDescription, 2> attributeDescriptions{};
// Position (vec2) -> Location 0
attributeDescriptions[0].binding = 0;
attributeDescriptions[0].location = 0;
attributeDescriptions[0].format = VK_FORMAT_R32G32_SFLOAT;
attributeDescriptions[0].offset = offsetof(Vertex, pos);
// Texture Coordinates (vec2) -> Location 1
attributeDescriptions[1].binding = 0;
attributeDescriptions[1].location = 1;
attributeDescriptions[1].format = VK_FORMAT_R32G32_SFLOAT;
attributeDescriptions[1].offset = offsetof(Vertex, texCoord);
return attributeDescriptions;
}
public:
VkCommandBuffer beginSingleTimeCommands() {
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
if (vkBeginCommandBuffer(commandBuffer, &beginInfo) != VK_SUCCESS) {
throw std::runtime_error("❌ ERROR: Failed to begin command buffer!");
}
return commandBuffer;
}
void endSingleTimeCommands(VkCommandBuffer commandBuffer) {
if (vkEndCommandBuffer(commandBuffer) != VK_SUCCESS) {
throw std::runtime_error("❌ ERROR: Failed to end command buffer!");
}
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
void run() {
initWindow();
initVulkan();
mainLoop();
cleanup();
}
private:
VkDescriptorPool descriptorPool; // Declare descriptor pool
VkDescriptorSetLayout descriptorSetLayout;
VkDescriptorSet descriptorSet;
VkBuffer vertexBuffer;
VkDeviceMemory vertexBufferMemory;
VkPipeline graphicsPipeline;
VkPipelineLayout pipelineLayout;
VkCommandPool commandPool;
std::vector<VkCommandBuffer> commandBuffers;
std::vector<VkFramebuffer> swapChainFramebuffers;
VkImage textureImage;
VkDeviceMemory textureImageMemory;
VkImageView textureImageView;
VkSampler textureSampler;
uint32_t textureWidth;
uint32_t textureHeight;
void createImage(uint32_t width, uint32_t height, VkFormat format, VkImageTiling tiling,
VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage& image, VkDeviceMemory& imageMemory);
void transitionImageLayout(VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout);
void copyBufferToImage(VkBuffer buffer, VkImage image, uint32_t width, uint32_t height);
VkImageView createImageView(VkImage image, VkFormat format);
void copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size) {
VkCommandBuffer commandBuffer = beginSingleTimeCommands();
VkBufferCopy copyRegion{};
copyRegion.srcOffset = 0;
copyRegion.dstOffset = 0;
copyRegion.size = size;
vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, ©Region);
endSingleTimeCommands(commandBuffer);
}
void createFramebuffers() {
std::cout << "🛠 Entering createFramebuffers()...\n";
if (!swapChainFramebuffers.empty()) {
std::cout << "🗑 Destroying existing framebuffers...\n";
for (auto framebuffer : swapChainFramebuffers) {
vkDestroyFramebuffer(device, framebuffer, nullptr);
}
swapChainFramebuffers.clear();
}
swapChainFramebuffers.resize(swapChainImageViews.size(), VK_NULL_HANDLE);
std::cout << "🔍 Resized swapChainFramebuffers to " << swapChainFramebuffers.size() << " entries.\n";
for (size_t i = 0; i < swapChainImageViews.size(); i++) {
VkImageView attachments[] = { swapChainImageViews[i] };
VkFramebufferCreateInfo framebufferInfo{};
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebufferInfo.renderPass = renderPass;
framebufferInfo.attachmentCount = 1;
framebufferInfo.pAttachments = attachments;
framebufferInfo.width = swapChainExtent.width;
framebufferInfo.height = swapChainExtent.height;
framebufferInfo.layers = 1;
VkResult result = vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]);
if (result != VK_SUCCESS) {
throw std::runtime_error("❌ ERROR: Failed to create framebuffer " + std::to_string(i) + "!");
}
std::cout << "✅ Framebuffer " << i << " created successfully! Handle: " << swapChainFramebuffers[i] << std::endl;
}
}
void createCommandPool() {
QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice);
if (!queueFamilyIndices.graphicsFamily.has_value()) {
throw std::runtime_error("❌ ERROR: No valid graphics queue family found!");
}
VkCommandPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
VkResult result = vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool);
if (result != VK_SUCCESS) {
throw std::runtime_error("❌ ERROR: Failed to create command pool! VkResult: " + std::to_string(result));
}
if (commandPool == VK_NULL_HANDLE) {
throw std::runtime_error("❌ ERROR: commandPool is NULL after creation!");
}
std::cout << "✅ Command Pool Created Successfully!\n";
}
void createCommandBuffers(VkDevice device, VkCommandPool commandPool, std::vector<VkCommandBuffer>& commandBuffers, uint32_t bufferCount) {
if (commandPool == VK_NULL_HANDLE) {
throw std::runtime_error("❌ ERROR: Command pool is NULL before allocating command buffers!");
}
if (!commandBuffers.empty()) {
vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
commandBuffers.clear();
}
commandBuffers.resize(bufferCount);
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.commandPool = commandPool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = bufferCount;
VkResult result = vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data());
if (result != VK_SUCCESS) {
throw std::runtime_error("❌ ERROR: Failed to allocate command buffers!");
}
std::cout << "✅ Command Buffers Allocated Successfully!" << std::endl;
}
VkRenderPass renderPass;
GLFWwindow* window;
VkInstance instance;
VkDebugUtilsMessengerEXT debugMessenger;
VkSurfaceKHR surface;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device;
VkQueue graphicsQueue;
VkQueue presentQueue;
VkSwapchainKHR swapChain;
std::vector<VkImage> swapChainImages;
VkFormat swapChainImageFormat;
VkExtent2D swapChainExtent;
std::vector<VkImageView> swapChainImageViews;
void initWindow() {
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
window = glfwCreateWindow(WIDTH, HEIGHT, "Vulkan", nullptr, nullptr);
}
std::vector<Vertex> tileVertices; // Store tile vertices globally in the class
void createVertexBuffer() {
std::cout << "🛠 Entering createVertexBuffer()..." << std::endl;
// Define a fullscreen quad with texture coordinates
std::vector<Vertex> quadVertices = {
{{-1.0f, -1.0f}, {0.0f, 1.0f}}, // Bottom-left
{{1.0f, -1.0f}, {1.0f, 1.0f}}, // Bottom-right
{{-1.0f, 1.0f}, {0.0f, 0.0f}}, // Top-left
{{1.0f, 1.0f}, {1.0f, 0.0f}}, // Top-right
};
VkDeviceSize bufferSize = sizeof(quadVertices[0]) * quadVertices.size();
// Create Vulkan buffer
VkBufferCreateInfo bufferInfo{};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = bufferSize;
bufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VkResult bufferResult = vkCreateBuffer(device, &bufferInfo, nullptr, &vertexBuffer);
if (bufferResult != VK_SUCCESS) {
std::cerr << "❌ ERROR: Failed to create vertex buffer! VkResult: " << bufferResult << std::endl;
throw std::runtime_error("❌ ERROR: Failed to create vertex buffer!");
}
std::cout << "✅ vertexBuffer Created: " << vertexBuffer << std::endl;
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(device, vertexBuffer, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
VkResult allocResult = vkAllocateMemory(device, &allocInfo, nullptr, &vertexBufferMemory);
if (allocResult != VK_SUCCESS) {
std::cerr << "❌ ERROR: Failed to allocate vertex buffer memory! VkResult: " << allocResult << std::endl;
throw std::runtime_error("❌ ERROR: Failed to allocate vertex buffer memory!");
}
std::cout << "✅ vertexBufferMemory Allocated: " << vertexBufferMemory << std::endl;
vkBindBufferMemory(device, vertexBuffer, vertexBufferMemory, 0);
if (vertexBuffer == VK_NULL_HANDLE) {
throw std::runtime_error("❌ ERROR: vertexBuffer is NULL after binding!");
}
std::cout << "✅ vertexBuffer Memory Bound Successfully!\n";
// Copy vertex data to buffer memory
void* data;
vkMapMemory(device, vertexBufferMemory, 0, bufferSize, 0, &data);
memcpy(data, quadVertices.data(), (size_t) bufferSize); // 🔹 Copy quad vertices into Vulkan memory
vkUnmapMemory(device, vertexBufferMemory);
std::cout << "✅ Vulkan Vertex Buffer Updated Successfully with Fullscreen Quad!\n";
}
void initVulkan() {
std::cout << "🛠 Entering initVulkan..." << std::endl;
createInstance();
setupDebugMessenger();
createSurface();
pickPhysicalDevice();
createLogicalDevice();
createSwapChain();
createImageViews();
createRenderPass();
createPipelineLayout();
createGraphicsPipeline();
std::cout << "🟡 Checking BC7 Format Support Before Loading Texture..." << std::endl;
// 🔍 Check if GPU supports BC7 before attempting to load texture
VkFormatProperties formatProperties;
vkGetPhysicalDeviceFormatProperties(physicalDevice, VK_FORMAT_BC7_UNORM_BLOCK, &formatProperties);
if (!(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) {
std::cerr << "❌ ERROR: GPU does NOT support BC7. Trying ASTC instead..." << std::endl;
vkGetPhysicalDeviceFormatProperties(physicalDevice, VK_FORMAT_ASTC_4x4_UNORM_BLOCK, &formatProperties);
if (!(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) {
throw std::runtime_error("❌ ERROR: GPU does NOT support BC7 or ASTC! Cannot load texture.");
}
std::cout << "✅ GPU supports ASTC. Using ASTC instead of BC7.\n";
} else {
std::cout << "✅ GPU supports BC7. Proceeding with BC7 format.\n";
}
std::cout << "🟡 Calling loadTexture() before descriptor set creation..." << std::endl;
loadTexture(); // ✅ Now safe to load the texture
std::cout << "🔍 Calling createTextureImageView()..." << std::endl;
createTextureImageView();
std::cout << "🔍 Calling createTextureSampler()..." << std::endl;
createTextureSampler();
std::cout << "🟡 BEFORE createDescriptorSet()" << std::endl;
createDescriptorSet();
std::cout << "🟡 Calling createVertexBuffer()..." << std::endl;
createVertexBuffer(); // ✅ Ensures vertex buffer is created
std::cout << "🔍 Calling createCommandBuffers()...\n";
createFramebuffers();
createCommandPool();
if (commandPool == VK_NULL_HANDLE) {
throw std::runtime_error("❌ ERROR: commandPool was not created! Did createCommandPool() run?");
}
std::cout << "🔍 Creating command buffers...\n";
uint32_t bufferCount = 3; // Adjust based on the number of frames in flight
createCommandBuffers(device, commandPool, commandBuffers, bufferCount);
std::cout << "🔍 Creating synchronization objects...\n";
createSyncObjects();
std::cout << "✅ Vulkan initialization complete!\n";
}
void 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;
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorAttachmentRef;
VkRenderPassCreateInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = 1;
renderPassInfo.pAttachments = &colorAttachment;
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
VkResult renderPassResult = vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass);
if (renderPassResult != VK_SUCCESS) {
throw std::runtime_error("ERROR: Failed to create render pass!");
}
// **Debug Check**
if (renderPass == VK_NULL_HANDLE) {
throw std::runtime_error("ERROR: renderPass is NULL after creation!");
} else {
std::cout << "✅ Render Pass Created Successfully: " << renderPass << std::endl;
}
}
void createPipelineLayout() {
// Define the sampler descriptor layout binding
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 0; // Matches the binding in the fragment shader
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
// Define descriptor set layout creation
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = 1;
layoutInfo.pBindings = &samplerLayoutBinding;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("❌ ERROR: Failed to create descriptor set layout!");
}
// Define pipeline layout
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout; // Use the descriptor set layout
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("❌ ERROR: Failed to create pipeline layout!");
}
}
// Function to convert VkResult to a human-readable string
std::string getVkResultString(VkResult result) {
switch (result) {
case VK_SUCCESS: return "VK_SUCCESS";
case VK_NOT_READY: return "VK_NOT_READY";
case VK_TIMEOUT: return "VK_TIMEOUT";
case VK_EVENT_SET: return "VK_EVENT_SET";
case VK_EVENT_RESET: return "VK_EVENT_RESET";
case VK_INCOMPLETE: return "VK_INCOMPLETE";
case VK_ERROR_OUT_OF_HOST_MEMORY: return "VK_ERROR_OUT_OF_HOST_MEMORY";
case VK_ERROR_OUT_OF_DEVICE_MEMORY: return "VK_ERROR_OUT_OF_DEVICE_MEMORY";
case VK_ERROR_INITIALIZATION_FAILED: return "VK_ERROR_INITIALIZATION_FAILED";
case VK_ERROR_DEVICE_LOST: return "VK_ERROR_DEVICE_LOST";
case VK_ERROR_MEMORY_MAP_FAILED: return "VK_ERROR_MEMORY_MAP_FAILED";
case VK_ERROR_LAYER_NOT_PRESENT: return "VK_ERROR_LAYER_NOT_PRESENT";
case VK_ERROR_EXTENSION_NOT_PRESENT: return "VK_ERROR_EXTENSION_NOT_PRESENT";
case VK_ERROR_FEATURE_NOT_PRESENT: return "VK_ERROR_FEATURE_NOT_PRESENT";
case VK_ERROR_INCOMPATIBLE_DRIVER: return "VK_ERROR_INCOMPATIBLE_DRIVER";
case VK_ERROR_TOO_MANY_OBJECTS: return "VK_ERROR_TOO_MANY_OBJECTS";
case VK_ERROR_FORMAT_NOT_SUPPORTED: return "VK_ERROR_FORMAT_NOT_SUPPORTED";
case VK_ERROR_FRAGMENTED_POOL: return "VK_ERROR_FRAGMENTED_POOL";
case VK_ERROR_UNKNOWN: return "VK_ERROR_UNKNOWN";
default: return "UNKNOWN_VK_RESULT";
}
}
void createGraphicsPipeline() {
VkVertexInputBindingDescription bindingDescription = getBindingDescription();
std::array<VkVertexInputAttributeDescription, 2> attributeDescriptions = getAttributeDescriptions();
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputInfo.vertexBindingDescriptionCount = 1;
vertexInputInfo.pVertexBindingDescriptions = &bindingDescription; // Now valid
vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size());
vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data();
std::cout << "🛠 Entering createGraphicsPipeline()...\n";
if (graphicsPipeline != VK_NULL_HANDLE) {
std::cout << "🗑 Destroying old graphics pipeline before recreation...\n";
vkDestroyPipeline(device, graphicsPipeline, nullptr);
graphicsPipeline = VK_NULL_HANDLE;
}
std::string vertShaderPath = "/Users/colinleary/desktop/VulkanSDK/LittleVulkanEngine/shaders/triangle.vert.spv";
std::string fragShaderPath = "/Users/colinleary/desktop/VulkanSDK/LittleVulkanEngine/shaders/triangle.frag.spv";
std::cout << "🔍 Loading Vertex Shader: " << vertShaderPath << "\n";
std::cout << "🔍 Loading Fragment Shader: " << fragShaderPath << "\n";
auto vertShaderCode = readFile(vertShaderPath);
auto fragShaderCode = readFile(fragShaderPath);
std::cout << "Vertex Shader Size: " << vertShaderCode.size() << " bytes\n";
std::cout << "Fragment Shader Size: " << fragShaderCode.size() << " bytes\n";
VkShaderModule vertShaderModule = createShaderModule(vertShaderCode);
VkShaderModule fragShaderModule = createShaderModule(fragShaderCode);
if (vertShaderModule == VK_NULL_HANDLE || fragShaderModule == VK_NULL_HANDLE) {
throw std::runtime_error("❌ ERROR: Shader modules were not created successfully!");
}
VkPipelineShaderStageCreateInfo shaderStages[] = {