-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
HelloTriangle.cpp
1918 lines (1547 loc) · 69.4 KB
/
HelloTriangle.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
// Vulkan hello world triangle rendering demo
// Global header settings
//////////////////////////////////////////////////////////////////////////////////
#include "VulkanEnvironment.h" // first include must be before vulkan.h and platform header
// Includes
//////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <fstream>
#include <functional>
#include <iterator>
#include <stdexcept>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include <vulkan/vulkan.h> // also assume core+WSI commands are loaded
static_assert( VK_HEADER_VERSION >= REQUIRED_HEADER_VERSION, "Update your SDK! This app is written against Vulkan header version " STRINGIZE(REQUIRED_HEADER_VERSION) "." );
#include "EnumerateScheme.h"
#include "ErrorHandling.h"
#include "ExtensionLoader.h"
#include "Vertex.h"
#include "Wsi.h"
using std::exception;
using std::runtime_error;
using std::string;
using std::to_string;
using std::vector;
// Config
//////////////////////////////////////////////////////////////////////////////////
const char appName[] = u8"Hello Vulkan Triangle -- Vertex Offset";
// layers and debug
#if VULKAN_VALIDATION
constexpr VkDebugUtilsMessageSeverityFlagsEXT debugSeverity =
0
//| VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT
//| VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT
| VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT
| VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT
;
constexpr VkDebugUtilsMessageTypeFlagsEXT debugType =
0
| VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT
| VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT
| VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT
;
constexpr bool useAssistantLayer = false;
#endif
constexpr bool fpsCounter = true;
// window and swapchain
constexpr uint32_t initialWindowWidth = 800;
constexpr uint32_t initialWindowHeight = 800;
//constexpr VkPresentModeKHR presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR; // better not be used often because of coil whine
constexpr VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR;
//constexpr VkPresentModeKHR presentMode = VK_PRESENT_MODE_MAILBOX_KHR;
// pipeline settings
constexpr VkClearValue clearColor = { { {0.1f, 0.1f, 0.1f, 1.0f} } };
// Makes present queue from different Queue Family than Graphics, for testing purposes
constexpr bool forceSeparatePresentQueue = false;
// needed stuff for main() -- forward declarations
//////////////////////////////////////////////////////////////////////////////////
bool isLayerSupported( const char* layer, const vector<VkLayerProperties>& supportedLayers );
bool isExtensionSupported( const char* extension, const vector<VkExtensionProperties>& supportedExtensions );
// treat layers as optional; app can always run without em -- i.e. return those supported
vector<const char*> checkInstanceLayerSupport( const vector<const char*>& requestedLayers, const vector<VkLayerProperties>& supportedLayers );
vector<VkExtensionProperties> getSupportedInstanceExtensions( const vector<const char*>& providingLayers );
bool checkExtensionSupport( const vector<const char*>& extensions, const vector<VkExtensionProperties>& supportedExtensions );
VkInstance initInstance( const vector<const char*>& layers = {}, const vector<const char*>& extensions = {} );
void killInstance( VkInstance instance );
VkPhysicalDevice getPhysicalDevice( VkInstance instance, VkSurfaceKHR surface = VK_NULL_HANDLE /*seek presentation support if !NULL*/ ); // destroyed with instance
VkPhysicalDeviceProperties getPhysicalDeviceProperties( VkPhysicalDevice physicalDevice );
VkPhysicalDeviceMemoryProperties getPhysicalDeviceMemoryProperties( VkPhysicalDevice physicalDevice );
std::pair<uint32_t, uint32_t> getQueueFamilies( VkPhysicalDevice physDevice, VkSurfaceKHR surface );
vector<VkQueueFamilyProperties> getQueueFamilyProperties( VkPhysicalDevice device );
VkDevice initDevice(
VkPhysicalDevice physDevice,
const VkPhysicalDeviceFeatures& features,
uint32_t graphicsQueueFamily,
uint32_t presentQueueFamily,
const vector<const char*>& layers = {},
const vector<const char*>& extensions = {}
);
void killDevice( VkDevice device );
VkQueue getQueue( VkDevice device, uint32_t queueFamily, uint32_t queueIndex );
enum class ResourceType{ Buffer, Image };
template< ResourceType resourceType, class T >
VkDeviceMemory initMemory(
VkDevice device,
VkPhysicalDeviceMemoryProperties physicalDeviceMemoryProperties,
T resource,
const std::vector<VkMemoryPropertyFlags>& memoryTypePriority
);
void setMemoryData( VkDevice device, VkDeviceMemory memory, void* begin, size_t size );
void killMemory( VkDevice device, VkDeviceMemory memory );
VkBuffer initBuffer( VkDevice device, VkDeviceSize size, VkBufferUsageFlags usage );
void killBuffer( VkDevice device, VkBuffer buffer );
VkImage initImage(
VkDevice device,
VkFormat format,
uint32_t width, uint32_t height,
VkSampleCountFlagBits samples,
VkImageUsageFlags usage
);
void killImage( VkDevice device, VkImage image );
VkImageView initImageView( VkDevice device, VkImage image, VkFormat format );
void killImageView( VkDevice device, VkImageView imageView );
// initSurface() is platform dependent
void killSurface( VkInstance instance, VkSurfaceKHR surface );
VkSurfaceCapabilitiesKHR getSurfaceCapabilities( VkPhysicalDevice physicalDevice, VkSurfaceKHR surface );
VkSurfaceFormatKHR getSurfaceFormat( VkPhysicalDevice physicalDevice, VkSurfaceKHR surface );
VkSwapchainKHR initSwapchain(
VkPhysicalDevice physicalDevice,
VkDevice device,
VkSurfaceKHR surface,
VkSurfaceFormatKHR surfaceFormat,
VkSurfaceCapabilitiesKHR capabilities,
uint32_t graphicsQueueFamily,
uint32_t presentQueueFamily,
VkSwapchainKHR oldSwapchain = VK_NULL_HANDLE
);
void killSwapchain( VkDevice device, VkSwapchainKHR swapchain );
uint32_t getNextImageIndex( VkDevice device, VkSwapchainKHR swapchain, VkSemaphore imageReadyS );
vector<VkImageView> initSwapchainImageViews( VkDevice device, vector<VkImage> images, VkFormat format );
void killSwapchainImageViews( VkDevice device, vector<VkImageView>& imageViews );
VkRenderPass initRenderPass( VkDevice device, VkSurfaceFormatKHR surfaceFormat );
void killRenderPass( VkDevice device, VkRenderPass renderPass );
vector<VkFramebuffer> initFramebuffers(
VkDevice device,
VkRenderPass renderPass,
vector<VkImageView> imageViews,
uint32_t width, uint32_t height
);
void killFramebuffers( VkDevice device, vector<VkFramebuffer>& framebuffers );
VkShaderModule initShaderModule( VkDevice device, const vector<uint32_t>& shaderCode );
VkShaderModule initShaderModule( VkDevice device, string filename );
void killShaderModule( VkDevice device, VkShaderModule shaderModule );
VkPipelineLayout initPipelineLayout( VkDevice device );
void killPipelineLayout( VkDevice device, VkPipelineLayout pipelineLayout );
VkPipeline initPipeline(
VkDevice device,
VkPhysicalDeviceLimits limits,
VkPipelineLayout pipelineLayout,
VkRenderPass renderPass,
VkShaderModule vertexShader,
VkShaderModule fragmentShader,
const uint32_t vertexBufferBinding,
uint32_t width, uint32_t height
);
void killPipeline( VkDevice device, VkPipeline pipeline );
void setVertexData( VkDevice device, VkDeviceMemory memory, vector<Vertex2D_ColorF_pack> vertices );
VkSemaphore initSemaphore( VkDevice device );
vector<VkSemaphore> initSemaphores( VkDevice device, size_t count );
void killSemaphore( VkDevice device, VkSemaphore semaphore );
void killSemaphores( VkDevice device, vector<VkSemaphore>& semaphores );
VkCommandPool initCommandPool( VkDevice device, const uint32_t queueFamily );
void killCommandPool( VkDevice device, VkCommandPool commandPool );
vector<VkFence> initFences( VkDevice device, size_t count, VkFenceCreateFlags flags = 0 );
void killFences( VkDevice device, vector<VkFence>& fences );
void acquireCommandBuffers( VkDevice device, VkCommandPool commandPool, uint32_t count, vector<VkCommandBuffer>& commandBuffers );
void beginCommandBuffer( VkCommandBuffer commandBuffer );
void endCommandBuffer( VkCommandBuffer commandBuffer );
void recordBeginRenderPass(
VkCommandBuffer commandBuffer,
VkRenderPass renderPass,
VkFramebuffer framebuffer,
VkClearValue clearValue,
uint32_t width, uint32_t height
);
void recordEndRenderPass( VkCommandBuffer commandBuffer );
void recordBindPipeline( VkCommandBuffer commandBuffer, VkPipeline pipeline );
void recordBindVertexBuffer( VkCommandBuffer commandBuffer, const uint32_t vertexBufferBinding, VkBuffer vertexBuffer, VkDeviceSize offset );
void recordDraw( VkCommandBuffer commandBuffer, uint32_t vertexCount );
void submitToQueue( VkQueue queue, VkCommandBuffer commandBuffer, VkSemaphore imageReadyS, VkSemaphore renderDoneS, VkFence fence = VK_NULL_HANDLE );
void present( VkQueue queue, VkSwapchainKHR swapchain, uint32_t swapchainImageIndex, VkSemaphore renderDoneS );
// cleanup dangerous semaphore with signal pending from vkAcquireNextImageKHR
void cleanupUnsafeSemaphore( VkQueue queue, VkSemaphore semaphore );
// main()!
//////////////////////////////////////////////////////////////////////////////////
int helloTriangle() try{
const uint32_t vertexBufferBinding = 0;
const float triangleSize = 1.6f;
const vector<Vertex2D_ColorF_pack> triangle = {
{ /*unused*/{ { 0.0f, 0.0f} }, { {0.0f, 0.0f, 0.0f} } },
{ /*rb*/ { { 0.5f * triangleSize, sqrtf( 3.0f ) * 0.25f * triangleSize} }, /*R*/{ {1.0f, 0.0f, 0.0f} } },
{ /* t*/ { { 0.0f, -sqrtf( 3.0f ) * 0.25f * triangleSize} }, /*G*/{ {0.0f, 1.0f, 0.0f} } },
{ /*lb*/ { {-0.5f * triangleSize, sqrtf( 3.0f ) * 0.25f * triangleSize} }, /*B*/{ {0.0f, 0.0f, 1.0f} } }
};
const auto supportedLayers = enumerate<VkInstance, VkLayerProperties>();
vector<const char*> requestedLayers;
#if VULKAN_VALIDATION
if( isLayerSupported( "VK_LAYER_KHRONOS_validation", supportedLayers ) ) requestedLayers.push_back( "VK_LAYER_KHRONOS_validation" );
else throw "VULKAN_VALIDATION is enabled but VK_LAYER_KHRONOS_validation layers are not supported!";
if( ::useAssistantLayer ){
if( isLayerSupported( "VK_LAYER_LUNARG_assistant_layer", supportedLayers ) ) requestedLayers.push_back( "VK_LAYER_LUNARG_assistant_layer" );
else throw "VULKAN_VALIDATION is enabled but VK_LAYER_LUNARG_assistant_layer layer is not supported!";
}
#endif
if( ::fpsCounter ) requestedLayers.push_back( "VK_LAYER_LUNARG_monitor" );
requestedLayers = checkInstanceLayerSupport( requestedLayers, supportedLayers );
const auto supportedInstanceExtensions = getSupportedInstanceExtensions( requestedLayers );
const auto platformSurfaceExtension = getPlatformSurfaceExtensionName();
vector<const char*> requestedInstanceExtensions = {
VK_KHR_SURFACE_EXTENSION_NAME,
platformSurfaceExtension.c_str()
};
#if VULKAN_VALIDATION
DebugObjectType debugExtensionTag;
if( isExtensionSupported( VK_EXT_DEBUG_UTILS_EXTENSION_NAME, supportedInstanceExtensions ) ){
debugExtensionTag = DebugObjectType::debugUtils;
requestedInstanceExtensions.push_back( VK_EXT_DEBUG_UTILS_EXTENSION_NAME );
}
else if( isExtensionSupported( VK_EXT_DEBUG_REPORT_EXTENSION_NAME, supportedInstanceExtensions ) ){
debugExtensionTag = DebugObjectType::debugReport;
requestedInstanceExtensions.push_back( VK_EXT_DEBUG_REPORT_EXTENSION_NAME );
}
else throw "VULKAN_VALIDATION is enabled but neither VK_EXT_debug_utils nor VK_EXT_debug_report extension is supported!";
#endif
checkExtensionSupport( requestedInstanceExtensions, supportedInstanceExtensions );
const VkInstance instance = initInstance( requestedLayers, requestedInstanceExtensions );
#if VULKAN_VALIDATION
const auto debugHandle = initDebug( instance, debugExtensionTag, ::debugSeverity, ::debugType );
const int32_t uncoded = 0;
const char* introMsg = "Validation Layers are enabled!";
if( debugExtensionTag == DebugObjectType::debugUtils ){
VkDebugUtilsObjectNameInfoEXT object = {
VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT,
nullptr, // pNext
VK_OBJECT_TYPE_INSTANCE,
handleToUint64(instance),
"instance"
};
const VkDebugUtilsMessengerCallbackDataEXT dumcd = {
VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT,
nullptr, // pNext
0, // flags
"VULKAN_VALIDATION", // VUID
0, // VUID hash
introMsg,
0, nullptr, 0, nullptr,
1, &object
};
vkSubmitDebugUtilsMessageEXT( instance, VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT, VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT, &dumcd );
}
else if( debugExtensionTag == DebugObjectType::debugReport ){
vkDebugReportMessageEXT( instance, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT, (uint64_t)instance, __LINE__, uncoded, "Application", introMsg );
}
#endif
const PlatformWindow window = initWindow( ::appName, ::initialWindowWidth, ::initialWindowHeight );
const VkSurfaceKHR surface = initSurface( instance, window );
const VkPhysicalDevice physicalDevice = getPhysicalDevice( instance, surface );
const VkPhysicalDeviceProperties physicalDeviceProperties = getPhysicalDeviceProperties( physicalDevice );
const VkPhysicalDeviceMemoryProperties physicalDeviceMemoryProperties = getPhysicalDeviceMemoryProperties( physicalDevice );
uint32_t graphicsQueueFamily, presentQueueFamily;
std::tie( graphicsQueueFamily, presentQueueFamily ) = getQueueFamilies( physicalDevice, surface );
const VkPhysicalDeviceFeatures features = {}; // don't need any special feature for this demo
const vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME };
const VkDevice device = initDevice( physicalDevice, features, graphicsQueueFamily, presentQueueFamily, requestedLayers, deviceExtensions );
const VkQueue graphicsQueue = getQueue( device, graphicsQueueFamily, 0 );
const VkQueue presentQueue = getQueue( device, presentQueueFamily, 0 );
VkSurfaceFormatKHR surfaceFormat = getSurfaceFormat( physicalDevice, surface );
VkRenderPass renderPass = initRenderPass( device, surfaceFormat );
vector<uint32_t> vertexShaderBinary = {
#include "shaders/hello_triangle.vert.spv.inl"
};
vector<uint32_t> fragmentShaderBinary = {
#include "shaders/hello_triangle.frag.spv.inl"
};
VkShaderModule vertexShader = initShaderModule( device, vertexShaderBinary );
VkShaderModule fragmentShader = initShaderModule( device, fragmentShaderBinary );
VkPipelineLayout pipelineLayout = initPipelineLayout( device );
VkBuffer vertexBuffer = initBuffer( device, sizeof( decltype( triangle )::value_type ) * triangle.size(), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT );
const std::vector<VkMemoryPropertyFlags> memoryTypePriority{
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, // preferably wanna device-side memory that can be updated from host without hassle
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT // guaranteed to allways be supported
};
VkDeviceMemory vertexBufferMemory = initMemory<ResourceType::Buffer>(
device,
physicalDeviceMemoryProperties,
vertexBuffer,
memoryTypePriority
);
setVertexData( device, vertexBufferMemory, triangle ); // Writes throug memory map. Synchronization is implicit for any subsequent vkQueueSubmit batches.
VkCommandPool commandPool = initCommandPool( device, graphicsQueueFamily );
// might need synchronization if init is more advanced than this
//VkResult errorCode = vkDeviceWaitIdle( device ); RESULT_HANDLER( errorCode, "vkDeviceWaitIdle" );
// place-holder swapchain dependent objects
VkSwapchainKHR swapchain = VK_NULL_HANDLE; // has to be NULL -- signifies that there's no swapchain
vector<VkImageView> swapchainImageViews;
vector<VkFramebuffer> framebuffers;
VkPipeline pipeline = VK_NULL_HANDLE; // has to be NULL for the case the app ends before even first swapchain
vector<VkCommandBuffer> commandBuffers;
vector<VkSemaphore> imageReadySs;
vector<VkSemaphore> renderDoneSs;
// workaround for validation layer "memory leak" + might also help the driver to cleanup old resources
// this should not be needed for a real-word app, because they are likely to use fences naturaly (e.g. responding to user input )
// read https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/issues/1628
const uint32_t maxInflightSubmissions = 2; // more than 2 probably does not make much sense
uint32_t submissionNr = 0; // index of the current submission modulo maxInflightSubmission
vector<VkFence> submissionFences;
const std::function<bool(void)> recreateSwapchain = [&](){
// swapchain recreation -- will be done before the first frame too;
TODO( "This may be triggered from many sources (e.g. WM_SIZE event, and VK_ERROR_OUT_OF_DATE_KHR too). Should prevent duplicate swapchain recreation." )
const VkSwapchainKHR oldSwapchain = swapchain;
swapchain = VK_NULL_HANDLE;
VkSurfaceCapabilitiesKHR capabilities = getSurfaceCapabilities( physicalDevice, surface );
if( capabilities.currentExtent.width == UINT32_MAX && capabilities.currentExtent.height == UINT32_MAX ){
capabilities.currentExtent.width = getWindowWidth( window );
capabilities.currentExtent.height = getWindowHeight( window );
}
VkExtent2D surfaceSize = { capabilities.currentExtent.width, capabilities.currentExtent.height };
const bool swapchainCreatable = {
surfaceSize.width >= capabilities.minImageExtent.width
&& surfaceSize.width <= capabilities.maxImageExtent.width
&& surfaceSize.width > 0
&& surfaceSize.height >= capabilities.minImageExtent.height
&& surfaceSize.height <= capabilities.maxImageExtent.height
&& surfaceSize.height > 0
};
// cleanup old
vector<VkSemaphore> oldImageReadySs = imageReadySs; imageReadySs.clear();
if( oldSwapchain ){
{VkResult errorCode = vkDeviceWaitIdle( device ); RESULT_HANDLER( errorCode, "vkDeviceWaitIdle" );}
// fences might be in unsignaled state, so kill them too to get fresh signaled
killFences( device, submissionFences );
// semaphores might be in signaled state, so kill them too to get fresh unsignaled
killSemaphores( device, renderDoneSs );
// kill imageReadySs later when oldSwapchain is destroyed
// only reset + later reuse already allocated and create new only if needed
{VkResult errorCode = vkResetCommandPool( device, commandPool, 0 ); RESULT_HANDLER( errorCode, "vkResetCommandPool" );}
killPipeline( device, pipeline );
killFramebuffers( device, framebuffers );
killSwapchainImageViews( device, swapchainImageViews );
// kill oldSwapchain later, after it is potentially used by vkCreateSwapchainKHR
}
// creating new
if( swapchainCreatable ){
// reuses & destroys the oldSwapchain
swapchain = initSwapchain( physicalDevice, device, surface, surfaceFormat, capabilities, graphicsQueueFamily, presentQueueFamily, oldSwapchain );
vector<VkImage> swapchainImages = enumerate<VkImage>( device, swapchain );
swapchainImageViews = initSwapchainImageViews( device, swapchainImages, surfaceFormat.format );
framebuffers = initFramebuffers( device, renderPass, swapchainImageViews, surfaceSize.width, surfaceSize.height );
pipeline = initPipeline(
device,
physicalDeviceProperties.limits,
pipelineLayout,
renderPass,
vertexShader,
fragmentShader,
vertexBufferBinding,
surfaceSize.width, surfaceSize.height
);
acquireCommandBuffers( device, commandPool, static_cast<uint32_t>( swapchainImages.size() ), commandBuffers );
for( size_t i = 0; i < swapchainImages.size(); ++i ){
beginCommandBuffer( commandBuffers[i] );
recordBeginRenderPass( commandBuffers[i], renderPass, framebuffers[i], ::clearColor, surfaceSize.width, surfaceSize.height );
recordBindPipeline( commandBuffers[i], pipeline );
recordBindVertexBuffer( commandBuffers[i], vertexBufferBinding, vertexBuffer, 1 * sizeof( Vertex2D_ColorF_pack ) );
recordDraw( commandBuffers[i], static_cast<uint32_t>( triangle.size() - 1 ) );
recordEndRenderPass( commandBuffers[i] );
endCommandBuffer( commandBuffers[i] );
}
imageReadySs = initSemaphores( device, maxInflightSubmissions );
// per https://github.com/KhronosGroup/Vulkan-Docs/issues/1150 need upto swapchain-image count
renderDoneSs = initSemaphores( device, swapchainImages.size());
submissionFences = initFences( device, maxInflightSubmissions, VK_FENCE_CREATE_SIGNALED_BIT ); // signaled fence means previous execution finished, so we start rendering presignaled
submissionNr = 0;
}
if( oldSwapchain ){
killSwapchain( device, oldSwapchain );
// per current spec, we can't really be sure these are not used :/ at least kill them after the swapchain
// https://github.com/KhronosGroup/Vulkan-Docs/issues/152
killSemaphores( device, oldImageReadySs );
}
return swapchain != VK_NULL_HANDLE;
};
// Finally, rendering! Yay!
const std::function<void(void)> render = [&](){
assert( swapchain ); // should be always true; should have yielded CPU if false
// vkAcquireNextImageKHR produces unsafe semaphore that needs extra cleanup. Track that with this variable.
bool unsafeSemaphore = false;
try{
// remove oldest frame from being in flight before starting new one
// refer to doc/, which talks about the cycle of how the synch primitives are (re)used here
{VkResult errorCode = vkWaitForFences( device, 1, &submissionFences[submissionNr], VK_TRUE, UINT64_MAX ); RESULT_HANDLER( errorCode, "vkWaitForFences" );}
{VkResult errorCode = vkResetFences( device, 1, &submissionFences[submissionNr] ); RESULT_HANDLER( errorCode, "vkResetFences" );}
unsafeSemaphore = true;
uint32_t nextSwapchainImageIndex = getNextImageIndex( device, swapchain, imageReadySs[submissionNr] );
unsafeSemaphore = false;
submitToQueue( graphicsQueue, commandBuffers[nextSwapchainImageIndex], imageReadySs[submissionNr], renderDoneSs[nextSwapchainImageIndex], submissionFences[submissionNr] );
present( presentQueue, swapchain, nextSwapchainImageIndex, renderDoneSs[nextSwapchainImageIndex] );
submissionNr = (submissionNr + 1) % maxInflightSubmissions;
}
catch( VulkanResultException ex ){
if( ex.result == VK_SUBOPTIMAL_KHR || ex.result == VK_ERROR_OUT_OF_DATE_KHR ){
if( unsafeSemaphore && ex.result == VK_SUBOPTIMAL_KHR ){
cleanupUnsafeSemaphore( graphicsQueue, imageReadySs[submissionNr] );
// no way to sanitize vkQueuePresentKHR semaphores, really
}
recreateSwapchain();
// we need to start over...
render();
}
else throw;
}
};
setSizeEventHandler( recreateSwapchain );
setPaintEventHandler( render );
// Finally start the main message loop (and so render too)
showWindow( window );
int exitStatus = messageLoop( window );
// proper Vulkan cleanup
VkResult errorCode = vkDeviceWaitIdle( device ); RESULT_HANDLER( errorCode, "vkDeviceWaitIdle" );
// kill swapchain
killSemaphores( device, renderDoneSs );
// imageReadySs killed after the swapchain
// command buffers killed with pool
killPipeline( device, pipeline );
killFramebuffers( device, framebuffers );
killSwapchainImageViews( device, swapchainImageViews );
killSwapchain( device, swapchain );
// per current spec, we can't really be sure these are not used :/ at least kill them after the swapchain
// https://github.com/KhronosGroup/Vulkan-Docs/issues/152
killSemaphores( device, imageReadySs );
// kill vulkan
killFences( device, submissionFences );
killCommandPool( device, commandPool );
killMemory( device, vertexBufferMemory );
killBuffer( device, vertexBuffer );
killPipelineLayout( device, pipelineLayout );
killShaderModule( device, fragmentShader );
killShaderModule( device, vertexShader );
killRenderPass( device, renderPass );
killDevice( device );
killSurface( instance, surface );
killWindow( window );
#if VULKAN_VALIDATION
killDebug( instance, debugHandle );
#endif
killInstance( instance );
return exitStatus;
}
catch( VulkanResultException vkE ){
logger << "ERROR: Terminated due to an uncaught VkResult exception: "
<< vkE.file << ":" << vkE.line << ":" << vkE.func << "() " << vkE.source << "() returned " << to_string( vkE.result )
<< std::endl;
return EXIT_FAILURE;
}
catch( const char* e ){
logger << "ERROR: Terminated due to an uncaught exception: " << e << std::endl;
return EXIT_FAILURE;
}
catch( string e ){
logger << "ERROR: Terminated due to an uncaught exception: " << e << std::endl;
return EXIT_FAILURE;
}
catch( std::exception e ){
logger << "ERROR: Terminated due to an uncaught exception: " << e.what() << std::endl;
return EXIT_FAILURE;
}
catch( ... ){
logger << "ERROR: Terminated due to an unrecognized uncaught exception." << std::endl;
return EXIT_FAILURE;
}
#if defined(_WIN32) && !defined(_CONSOLE)
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int ){
return helloTriangle();
}
#else
int main(){
return helloTriangle();
}
#endif
// Implementation
//////////////////////////////////////////////////////////////////////////////////
bool isLayerSupported( const char* layer, const vector<VkLayerProperties>& supportedLayers ){
const auto isSupportedPred = [layer]( const VkLayerProperties& prop ) -> bool{
return std::strcmp( layer, prop.layerName ) == 0;
};
return std::any_of( supportedLayers.begin(), supportedLayers.end(), isSupportedPred );
}
bool isExtensionSupported( const char* extension, const vector<VkExtensionProperties>& supportedExtensions ){
const auto isSupportedPred = [extension]( const VkExtensionProperties& prop ) -> bool{
return std::strcmp( extension, prop.extensionName ) == 0;
};
return std::any_of( supportedExtensions.begin(), supportedExtensions.end(), isSupportedPred );
}
vector<const char*> checkInstanceLayerSupport( const vector<const char*>& requestedLayers, const vector<VkLayerProperties>& supportedLayers ){
vector<const char*> compiledLayerList;
for( const auto layer : requestedLayers ){
if( isLayerSupported( layer, supportedLayers ) ) compiledLayerList.push_back( layer );
else logger << "WARNING: Requested layer " << layer << " is not supported. It will not be enabled." << std::endl;
}
return compiledLayerList;
}
vector<const char*> checkInstanceLayerSupport( const vector<const char*>& optionalLayers ){
return checkInstanceLayerSupport( optionalLayers, enumerate<VkInstance, VkLayerProperties>() );
}
vector<VkExtensionProperties> getSupportedInstanceExtensions( const vector<const char*>& providingLayers ){
auto supportedExtensions = enumerate<VkInstance, VkExtensionProperties>();
for( const auto pl : providingLayers ){
const auto providedExtensions = enumerate<VkInstance, VkExtensionProperties>( pl );
supportedExtensions.insert( supportedExtensions.end(), providedExtensions.begin(), providedExtensions.end() );
}
return supportedExtensions;
}
vector<VkExtensionProperties> getSupportedDeviceExtensions( const VkPhysicalDevice physDevice, const vector<const char*>& providingLayers ){
auto supportedExtensions = enumerate<VkExtensionProperties>( physDevice );
for( const auto pl : providingLayers ){
const auto providedExtensions = enumerate<VkExtensionProperties>( physDevice, pl );
supportedExtensions.insert( supportedExtensions.end(), providedExtensions.begin(), providedExtensions.end() );
}
return supportedExtensions;
}
bool checkExtensionSupport( const vector<const char*>& extensions, const vector<VkExtensionProperties>& supportedExtensions ){
bool allSupported = true;
for( const auto extension : extensions ){
if( !isExtensionSupported( extension, supportedExtensions ) ){
allSupported = false;
logger << "WARNING: Requested extension " << extension << " is not supported. Trying to enable it will likely fail." << std::endl;
}
}
return allSupported;
}
bool checkDeviceExtensionSupport( const VkPhysicalDevice physDevice, const vector<const char*>& extensions, const vector<const char*>& providingLayers ){
return checkExtensionSupport( extensions, getSupportedDeviceExtensions( physDevice, providingLayers ) );
}
VkInstance initInstance( const vector<const char*>& layers, const vector<const char*>& extensions ){
const VkApplicationInfo appInfo = {
VK_STRUCTURE_TYPE_APPLICATION_INFO,
nullptr, // pNext
::appName, // Nice to meetcha, and what's your name driver?
0, // app version
nullptr, // engine name
0, // engine version
VK_API_VERSION_1_0 // this app is written against the Vulkan 1.0 spec
};
#if VULKAN_VALIDATION
// in effect during vkCreateInstance and vkDestroyInstance duration (because callback object cannot be created without instance)
const VkDebugReportCallbackCreateInfoEXT debugReportCreateInfo{
VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT,
nullptr, // pNext
translateFlags( ::debugSeverity, ::debugType ),
::genericDebugReportCallback,
nullptr // pUserData
};
const VkDebugUtilsMessengerCreateInfoEXT debugUtilsCreateInfo = {
VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
nullptr, // pNext
0, // flags
debugSeverity,
debugType,
::genericDebugUtilsCallback,
nullptr // pUserData
};
bool debugUtils = std::find_if( extensions.begin(), extensions.end(), [](const char* e){ return std::strcmp( e, VK_EXT_DEBUG_UTILS_EXTENSION_NAME ) == 0; } ) != extensions.end();
bool debugReport = std::find_if( extensions.begin(), extensions.end(), [](const char* e){ return std::strcmp( e, VK_EXT_DEBUG_REPORT_EXTENSION_NAME ) == 0; } ) != extensions.end();
if( !debugUtils && !debugReport ) throw "VULKAN_VALIDATION is enabled but neither VK_EXT_debug_utils nor VK_EXT_debug_report extension is being enabled!";
const void* debugpNext = debugUtils ? (void*)&debugUtilsCreateInfo : (void*)&debugReportCreateInfo;
#endif
const VkInstanceCreateInfo instanceInfo{
VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
#if VULKAN_VALIDATION
debugpNext,
#else
nullptr, // pNext
#endif
0, // flags - reserved for future use
&appInfo,
static_cast<uint32_t>( layers.size() ),
layers.data(),
static_cast<uint32_t>( extensions.size() ),
extensions.data()
};
VkInstance instance;
const VkResult errorCode = vkCreateInstance( &instanceInfo, nullptr, &instance ); RESULT_HANDLER( errorCode, "vkCreateInstance" );
loadInstanceExtensionsCommands( instance, extensions );
return instance;
}
void killInstance( const VkInstance instance ){
unloadInstanceExtensionsCommands( instance );
vkDestroyInstance( instance, nullptr );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool isPresentationSupported( const VkPhysicalDevice physDevice, const uint32_t queueFamily, const VkSurfaceKHR surface ){
VkBool32 supported;
const VkResult errorCode = vkGetPhysicalDeviceSurfaceSupportKHR( physDevice, queueFamily, surface, &supported ); RESULT_HANDLER( errorCode, "vkGetPhysicalDeviceSurfaceSupportKHR" );
return supported == VK_TRUE;
}
bool isPresentationSupported( const VkPhysicalDevice physDevice, const VkSurfaceKHR surface ){
uint32_t qfCount;
vkGetPhysicalDeviceQueueFamilyProperties( physDevice, &qfCount, nullptr );
for( uint32_t qf = 0; qf < qfCount; ++qf ){
if( isPresentationSupported( physDevice, qf, surface ) ) return true;
}
return false;
}
VkPhysicalDevice getPhysicalDevice( const VkInstance instance, const VkSurfaceKHR surface ){
vector<VkPhysicalDevice> devices = enumerate<VkPhysicalDevice>( instance );
if( surface ){
for( auto it = devices.begin(); it != devices.end(); ){
const auto& pd = *it;
if( !isPresentationSupported( pd, surface ) ) it = devices.erase( it );
else ++it;
}
}
if( devices.empty() ) throw string("ERROR: No Physical Devices (GPUs) ") + (surface ? "with presentation support " : "") + "detected!";
else if( devices.size() == 1 ){
return devices[0];
}
else{
for( const auto pd : devices ){
const VkPhysicalDeviceProperties pdp = getPhysicalDeviceProperties( pd );
if( pdp.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU ){
#if VULKAN_VALIDATION
vkDebugReportMessageEXT(
instance, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT, handleToUint64(instance), __LINE__,
1, u8"application", u8"More than one Physical Devices (GPU) found. Choosing the first dedicated one."
);
#endif
return pd;
}
}
#if VULKAN_VALIDATION
vkDebugReportMessageEXT(
instance, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT, handleToUint64(instance), __LINE__,
1, u8"application", u8"More than one Physical Devices (GPU) found. Just choosing the first one."
);
#endif
return devices[0];
}
}
VkPhysicalDeviceProperties getPhysicalDeviceProperties( VkPhysicalDevice physicalDevice ){
VkPhysicalDeviceProperties properties;
vkGetPhysicalDeviceProperties( physicalDevice, &properties );
return properties;
}
VkPhysicalDeviceMemoryProperties getPhysicalDeviceMemoryProperties( VkPhysicalDevice physicalDevice ){
VkPhysicalDeviceMemoryProperties memoryInfo;
vkGetPhysicalDeviceMemoryProperties( physicalDevice, &memoryInfo );
return memoryInfo;
}
vector<VkQueueFamilyProperties> getQueueFamilyProperties( VkPhysicalDevice device ){
uint32_t queueFamiliesCount;
vkGetPhysicalDeviceQueueFamilyProperties( device, &queueFamiliesCount, nullptr );
vector<VkQueueFamilyProperties> queueFamilies( queueFamiliesCount );
vkGetPhysicalDeviceQueueFamilyProperties( device, &queueFamiliesCount, queueFamilies.data() );
return queueFamilies;
}
std::pair<uint32_t, uint32_t> getQueueFamilies( const VkPhysicalDevice physDevice, const VkSurfaceKHR surface ){
constexpr uint32_t notFound = VK_QUEUE_FAMILY_IGNORED;
const auto qfps = getQueueFamilyProperties( physDevice );
const auto findQueueFamilyThat = [&qfps, notFound](std::function<bool (const VkQueueFamilyProperties&, const uint32_t)> predicate) -> uint32_t{
for( uint32_t qf = 0; qf < qfps.size(); ++qf ) if( predicate(qfps[qf], qf) ) return qf;
return notFound;
};
const auto isGraphics = [](const VkQueueFamilyProperties& props, const uint32_t = 0){
return props.queueFlags & VK_QUEUE_GRAPHICS_BIT;
};
const auto isPresent = [=](const VkQueueFamilyProperties&, const uint32_t queueFamily){
return isPresentationSupported( physDevice, queueFamily, surface );
};
const auto isFusedGraphicsAndPresent = [=](const VkQueueFamilyProperties& props, const uint32_t queueFamily){
return isGraphics( props ) && isPresent( props, queueFamily );
};
uint32_t graphicsQueueFamily = notFound;
uint32_t presentQueueFamily = notFound;
if( ::forceSeparatePresentQueue ){
graphicsQueueFamily = findQueueFamilyThat( isGraphics );
const auto isSeparatePresent = [graphicsQueueFamily, isPresent](const VkQueueFamilyProperties& props, const uint32_t queueFamily){
return queueFamily != graphicsQueueFamily && isPresent( props, queueFamily );
};
presentQueueFamily = findQueueFamilyThat( isSeparatePresent );
}
else{
graphicsQueueFamily = presentQueueFamily = findQueueFamilyThat( isFusedGraphicsAndPresent );
if( graphicsQueueFamily == notFound || presentQueueFamily == notFound ){
graphicsQueueFamily = findQueueFamilyThat( isGraphics );
presentQueueFamily = findQueueFamilyThat( isPresent );
}
}
if( graphicsQueueFamily == notFound ) throw "Cannot find a graphics queue family!";
if( presentQueueFamily == notFound ) throw "Cannot find a presentation queue family!";
return std::make_pair( graphicsQueueFamily, presentQueueFamily );
}
VkDevice initDevice(
const VkPhysicalDevice physDevice,
const VkPhysicalDeviceFeatures& features,
const uint32_t graphicsQueueFamily,
const uint32_t presentQueueFamily,
const vector<const char*>& layers,
const vector<const char*>& extensions
){
checkDeviceExtensionSupport( physDevice, extensions, layers );
const float priority[] = {1.0f};
vector<VkDeviceQueueCreateInfo> queues = {
{
VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
nullptr, // pNext
0, // flags
graphicsQueueFamily,
1, // queue count
priority
}
};
if( presentQueueFamily != graphicsQueueFamily ){
queues.push_back({
VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
nullptr, // pNext
0, // flags
presentQueueFamily,
1, // queue count
priority
});
}
const VkDeviceCreateInfo deviceInfo{
VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
nullptr, // pNext
0, // flags
static_cast<uint32_t>( queues.size() ),
queues.data(),
static_cast<uint32_t>( layers.size() ),
layers.data(),
static_cast<uint32_t>( extensions.size() ),
extensions.data(),
&features
};
VkDevice device;
const VkResult errorCode = vkCreateDevice( physDevice, &deviceInfo, nullptr, &device ); RESULT_HANDLER( errorCode, "vkCreateDevice" );
loadDeviceExtensionsCommands( device, extensions );
return device;
}
void killDevice( const VkDevice device ){
unloadDeviceExtensionsCommands( device );
vkDestroyDevice( device, nullptr );
}
VkQueue getQueue( const VkDevice device, const uint32_t queueFamily, const uint32_t queueIndex ){
VkQueue queue;
vkGetDeviceQueue( device, queueFamily, queueIndex, &queue );
return queue;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template< ResourceType resourceType, class T >
VkMemoryRequirements getMemoryRequirements( VkDevice device, T resource );
template<>
VkMemoryRequirements getMemoryRequirements< ResourceType::Buffer >( VkDevice device, VkBuffer buffer ){
VkMemoryRequirements memoryRequirements;
vkGetBufferMemoryRequirements( device, buffer, &memoryRequirements );
return memoryRequirements;
}
template<>
VkMemoryRequirements getMemoryRequirements< ResourceType::Image >( VkDevice device, VkImage image ){
VkMemoryRequirements memoryRequirements;
vkGetImageMemoryRequirements( device, image, &memoryRequirements );
return memoryRequirements;
}
template< ResourceType resourceType, class T >
void bindMemory( VkDevice device, T buffer, VkDeviceMemory memory, VkDeviceSize offset );
template<>
void bindMemory< ResourceType::Buffer >( VkDevice device, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize offset ){
VkResult errorCode = vkBindBufferMemory( device, buffer, memory, offset ); RESULT_HANDLER( errorCode, "vkBindBufferMemory" );
}
template<>
void bindMemory< ResourceType::Image >( VkDevice device, VkImage image, VkDeviceMemory memory, VkDeviceSize offset ){
VkResult errorCode = vkBindImageMemory( device, image, memory, offset ); RESULT_HANDLER( errorCode, "vkBindImageMemory" );
}
template< ResourceType resourceType, class T >
VkDeviceMemory initMemory(
VkDevice device,
VkPhysicalDeviceMemoryProperties physicalDeviceMemoryProperties,
T resource,
const std::vector<VkMemoryPropertyFlags>& memoryTypePriority
){
const VkMemoryRequirements memoryRequirements = getMemoryRequirements<resourceType>( device, resource );