-
Notifications
You must be signed in to change notification settings - Fork 4
/
vktriangle_vertex.cpp
1382 lines (1194 loc) · 54.1 KB
/
vktriangle_vertex.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
/**
* Single file Vulkan triangle example with minimal "helper" methods.
* The example renders in memory then copies it to a "readable" image and
* saves the result into a binary PPM image file.
*
* The example uses a single vertex input.
* Look for the "V.X." comments to see the vertex input handling ("X" is a number).
*
* Compile without shaderc:
* $ g++ vktriangle_vertex.cpp -o triangle_vertex -lvulkan -std=c++11
*
* Re-Compile shaders (optional):
* $ glslangValidator -V passthrough.vert -o passthrough.vert.spv
* $ glslangValidator -V passthrough.frag -o passthrough.frag.spv
*
* Compile with shaderc:
* $ g++ vktriangle_vertex.cpp -o triangle_vertex -lvulkan -lshaderc_shared -std=c++11 -DHAVE_SHADERC=1
*
* Run: the "passthrough.{vert,frag}*" files must be in the same dir.
* $ ./triangle_vertex
*
* Env variables:
* DEMO_USE_VALIDATION: Enables (1) or disables (0) the usage of validation layers. Default: 0
* DEMO_OUTPUT: Output PPM file name. Default: out.ppm
*
* Dependencies:
* * C++11
* * Vulkan 1.0
* * Vulkan loader
* * One of the following:
* * glslangValidator (HAVE_SHADERC=0)
* * shaderc with glslang (HAVE_SHADERC=1)
*
* Includes:
* * Validation layer enable.
* * PPM image output.
*
* Excludes:
* * No swapchain.
*
* MIT License
* Copyright (c) 2020 elecro
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* OFTWARE.
*/
#include <fstream>
#include <cstring>
#include <stdexcept>
#include <vector>
#include <vulkan/vulkan.h>
#ifndef HAVE_SHADERC
#define HAVE_SHADERC 0
#endif
#if HAVE_SHADERC
#include <shaderc/shaderc.hpp>
#endif
const std::vector<const char*> g_validationLayers = {
"VK_LAYER_KHRONOS_validation",
};
static uint32_t FindQueueFamily(const VkPhysicalDevice device, bool *hasIdx);
static uint32_t FindMemoryType(const VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties);
#if HAVE_SHADERC
static std::vector<char> LoadGLSL(const std::string name);
static std::vector<uint32_t> CompileGLSL(shaderc_shader_kind shaderType, const std::vector<char> &vertSrc);
#else
static std::vector<uint32_t> LoadSPIRV(const std::string name);
#endif
static void CopyImageToLinearImage(const VkPhysicalDevice physicalDevice,
const VkDevice device,
const VkQueue queue,
const VkCommandPool cmdPool,
const VkImage renderImage,
float renderImageWidth,
float renderImageHeight,
VkImage *outImage,
VkDeviceMemory *outMemory);
int main(int argc, char **argv) {
(void)argc;
(void)argv;
const char *envValidation = getenv("DEMO_USE_VALIDATION");
const char *envOutputName = getenv("DEMO_OUTPUT");
bool enableValidationLayers = ((envValidation != NULL) && (strncmp("1", envValidation, 2) == 0));
const char *outputFileName = "out.ppm";
if (envOutputName != NULL) {
outputFileName = envOutputName;
}
printf("Validation: %s\n", (enableValidationLayers ? "ON" : "OFF"));
printf("Using shaderc: %s\n", (HAVE_SHADERC ? "YES" : "NO"));
printf("Output: %s\n", outputFileName);
// 1. Create Vulkan Instance.
// A Vulkan instance is the base for all other Vulkan API calls.
// This is similar an the OpenGL context.
VkInstance instance;
{
std::vector<const char*> extensions{};
// 1.1. Specify the application infromation.
// One important info is the "apiVersion"
VkApplicationInfo appInfo;
{
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pNext = NULL;
appInfo.pApplicationName = "MinimalVkTriangle";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "RAW";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;
}
// 1.2. Specify the Instance creation information.
// The Instance level Validation and debug layers must be specified here.
VkInstanceCreateInfo createInfo;
{
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pNext = NULL;
createInfo.flags = 0;
createInfo.pApplicationInfo = &appInfo;
createInfo.enabledLayerCount = 0;
if (enableValidationLayers) {
createInfo.enabledLayerCount = static_cast<uint32_t>(g_validationLayers.size());
createInfo.ppEnabledLayerNames = g_validationLayers.data();
// If a debug callbacks should be enabled:
// * The extension must be specified and
// * The "pNext" should point to a valid "VkDebugUtilsMessengerCreateInfoEXT" struct.
// extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
//createInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT*) &debugInfo;
}
createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
createInfo.ppEnabledExtensionNames = extensions.data();
}
// 1.3. Create the Vulkan instance.
if (vkCreateInstance(&createInfo, NULL, &instance) != VK_SUCCESS) {
throw std::runtime_error("failed to create instance!");
}
}
// 2. Select PhysicalDevice and Queue Family Index.
VkPhysicalDevice physicalDevice;
uint32_t graphicsQueueFamilyIdx;
{
// 2.1 Query the number of physical devices.
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0) {
throw std::runtime_error("failed to find GPUs with Vulkan support!");
}
// 2.2. Get all avaliable physical devices.
std::vector<VkPhysicalDevice> devices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
// 2.3. Select a physical device (based on some info).
// Currently the first physical device is selected if it supports Graphics Queue.
for (const VkPhysicalDevice& device : devices) {
bool hasIdx;
graphicsQueueFamilyIdx = FindQueueFamily(device, &hasIdx);
if (hasIdx) {
physicalDevice = device;
break;
}
}
if (physicalDevice == VK_NULL_HANDLE) {
throw std::runtime_error("failed to find a suitable GPU!");
}
}
// 3. Create a logical Vulkan Device.
// Most Vulkan API calls require a logical device.
// To use device level layer, they should be provided here.
VkDevice device;
{
// 3.1. Build the device queue create info data (use only a singe queue).
float queuePriority = 1.0f;
VkDeviceQueueCreateInfo queueCreateInfo;
{
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.pNext = NULL;
queueCreateInfo.flags = 0;
queueCreateInfo.queueFamilyIndex = graphicsQueueFamilyIdx;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
}
// 3.2. The queue family/families must be provided to allow the device to use them.
std::vector<uint32_t> uniqueQueueFamilies = { graphicsQueueFamilyIdx };
// 3.3. Specify the device creation information.
VkDeviceCreateInfo createInfo;
{
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.pNext = NULL;
createInfo.flags = 0;
createInfo.queueCreateInfoCount = 1;
createInfo.pQueueCreateInfos = &queueCreateInfo;
createInfo.pEnabledFeatures = NULL;
createInfo.enabledExtensionCount = 0;
createInfo.ppEnabledExtensionNames = NULL;
createInfo.enabledLayerCount = 0;
if (enableValidationLayers) {
// To have device level validation information, the layers are added here.
createInfo.enabledLayerCount = static_cast<uint32_t>(g_validationLayers.size());
createInfo.ppEnabledLayerNames = g_validationLayers.data();
}
}
// 3.4. Create the logical device.
if (vkCreateDevice(physicalDevice, &createInfo, NULL, &device) != VK_SUCCESS) {
throw std::runtime_error("failed to create logical device!");
}
}
// 4. Get the selected Queue family's first queue.
// A Queue is used to issue recorded command buffers to the GPU for execution.
VkQueue queue;
{
vkGetDeviceQueue(device, graphicsQueueFamilyIdx, 0, &queue);
}
// 5. Create a 256x256 2D Image to draw onto.
// This will be the render target image.
// Note: An Image by itself does not allocate memory on the GPU.
uint32_t renderImageWidth = 256;
uint32_t renderImageHeight = 256;
VkFormat renderImageFormat = VK_FORMAT_R8G8B8A8_UNORM;
VkImage renderImage;
{
// 5.1. Specify the image creation information.
VkImageCreateInfo imageInfo;
{
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.pNext = NULL;
imageInfo.flags = 0;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.format = renderImageFormat;
imageInfo.extent = { renderImageWidth, renderImageHeight, 1 };
imageInfo.mipLevels = 1;
imageInfo.arrayLayers = 1;
imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
// Tiling optimal means that the image is in a GPU optimal mode.
// Usually this means that it should not be accessed from the CPU side directly as
// the image color channels can be in any order.
imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
// Specifying the usage is important:
// * VK_IMAGE_USAGE_TRANSFER_SRC_BIT: the image can be used as a source for a transfer/copy operation.
// * VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT: the image can be used as a color attachment (aka can render on it).
imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; // | VK_IMAGE_USAGE_SAMPLED_BIT;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.queueFamilyIndexCount = 0;
imageInfo.pQueueFamilyIndices = NULL;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
}
// 5.2. Create the image.
if (vkCreateImage(device, &imageInfo, NULL, &renderImage) != VK_SUCCESS) {
throw std::runtime_error("failed to create 2D image!");
}
}
// 6. Allocate and bind the memory for the render target image.
// For each Image (or Buffer) a memory should be allocated on the GPU otherwise it can't be used.
VkDeviceMemory renderImageMemory;
{
// 6.1 Query the memory requirments for the image.
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(device, renderImage, &memRequirements);
// 6.2 Find a memory type based on the requirements.
// Here a device (gpu) local memory type is requested (VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT).
uint32_t memoryTypeIndex = FindMemoryType(physicalDevice,
memRequirements.memoryTypeBits,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
// 6.3. Based on the memory requirements specify the allocation information.
VkMemoryAllocateInfo allocInfo;
{
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.pNext = NULL;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = memoryTypeIndex;
}
// 6.3 Allocate the memory.
if (vkAllocateMemory(device, &allocInfo, NULL, &renderImageMemory) != VK_SUCCESS) {
throw std::runtime_error("failed to allocate image memory!");
}
// 6.4 "Connect" the image with the allocated memory.
vkBindImageMemory(device, renderImage, renderImageMemory, 0);
}
// 7. Create an Image View for the Render Target Image.
// Will be used by the Framebuffer as Color Attachment.
VkImageView renderImageView;
{
// 7.1. Specify the view information.
VkImageViewCreateInfo createInfo;
{
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
createInfo.pNext = NULL;
createInfo.flags = 0;
createInfo.image = renderImage;
createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
createInfo.format = renderImageFormat;
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 = VK_IMAGE_ASPECT_COLOR_BIT;
createInfo.subresourceRange.baseMipLevel = 0;
createInfo.subresourceRange.levelCount = 1;
createInfo.subresourceRange.baseArrayLayer = 0;
createInfo.subresourceRange.layerCount = 1;
}
// 7.2. Create the Image View.
if (vkCreateImageView(device, &createInfo, NULL, &renderImageView) != VK_SUCCESS) {
throw std::runtime_error("failed to create image views!");
}
}
// V.0. Prepare the Vertex Coordinates.
std::vector<float> vertexCoordinates = {
0.0, -0.5,
0.5, 0.5,
-0.5, 0.5
};
// V.1. Create the Vulkan buffer which will hold the Vertex Input data.
// This buffer will hold the Vertex coordinates in a vec2 like format.
VkBuffer vertexBuffer;
{
VkBufferCreateInfo bufferInfo;
{
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.pNext = NULL;
bufferInfo.flags = 0;
bufferInfo.size = sizeof(float) * vertexCoordinates.size();
// The buffer will be used as a Vertex Input attribute.
bufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
bufferInfo.queueFamilyIndexCount = 0;
bufferInfo.pQueueFamilyIndices = NULL;
}
if (vkCreateBuffer(device, &bufferInfo, NULL, &vertexBuffer) != VK_SUCCESS) {
throw std::runtime_error("failed to create vertex buffer!");
}
}
// V.2. Allocate and bind the memory for the Vertex Buffer.
// For each Buffer a memory should be allocated on the GPU otherwise it can't be used.
VkDeviceMemory vertexBufferMemory;
{
// 6.1 Query the memory requirments for the image.
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(device, vertexBuffer, &memRequirements);
// 6.2 Find a memory type based on the requirements.
// Here a device (gpu) local memory type is requested (VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT).
uint32_t memoryTypeIndex = FindMemoryType(physicalDevice,
memRequirements.memoryTypeBits,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
// 6.3. Based on the memory requirements specify the allocation information.
VkMemoryAllocateInfo allocInfo;
{
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.pNext = NULL;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = memoryTypeIndex;
}
// 6.3 Allocate the memory.
if (vkAllocateMemory(device, &allocInfo, NULL, &vertexBufferMemory) != VK_SUCCESS) {
throw std::runtime_error("failed to allocate image memory!");
}
// 6.4 "Connect" the Vertex buffer with the allocated memory.
vkBindBufferMemory(device, vertexBuffer, vertexBufferMemory, 0);
}
// V.3. Upload the Vertex Buffer data.
{
// V.3.1. Map buffer memory to "data" pointer.
void *data;
if (vkMapMemory(device, vertexBufferMemory, 0, VK_WHOLE_SIZE, 0, &data) != VK_SUCCESS) {
throw std::runtime_error("failed to map vertex buffer!");
}
// V.3.2. Copy data into the "data".
::memcpy(data, vertexCoordinates.data(), sizeof(float) * vertexCoordinates.size());
// V.3.3. Flush the data.
// This is required as a non-coherent buffer was created.
VkMappedMemoryRange memoryRange;
{
memoryRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
memoryRange.pNext = NULL;
memoryRange.memory = vertexBufferMemory;
memoryRange.offset = 0;
memoryRange.size = VK_WHOLE_SIZE;
}
vkFlushMappedMemoryRanges(device, 1, &memoryRange);
// V.3.4. Unmap the mapped vertex buffer.
// After this the "data" pointer is a non-valid pointer.
vkUnmapMemory(device, vertexBufferMemory);
}
// 8. Create a Render Pass.
// A Render Pass is required to use vkCmdDraw* commands.
VkRenderPass renderPass;
{
VkAttachmentDescription colorAttachment;
{
colorAttachment.flags = 0;
colorAttachment.format = renderImageFormat;
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_COLOR_ATTACHMENT_OPTIMAL;
}
VkAttachmentReference colorAttachmentRef;
{
colorAttachmentRef.attachment = 0;
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
}
VkSubpassDescription subpass;
{
subpass.flags = 0;
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.inputAttachmentCount = 0;
subpass.pInputAttachments = NULL;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorAttachmentRef;
subpass.pResolveAttachments = NULL;
subpass.pDepthStencilAttachment = NULL;
subpass.preserveAttachmentCount = 0;
subpass.pPreserveAttachments = NULL;
}
VkRenderPassCreateInfo renderPassInfo;
{
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.pNext = NULL;
renderPassInfo.flags = 0;
renderPassInfo.attachmentCount = 1;
renderPassInfo.pAttachments = &colorAttachment;
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
renderPassInfo.dependencyCount = 0;
renderPassInfo.pDependencies = NULL;
}
if (vkCreateRenderPass(device, &renderPassInfo, NULL, &renderPass) != VK_SUCCESS) {
throw std::runtime_error("failed to create render pass!");
}
}
// 9. Create Vertex shader.
VkShaderModule vertShaderModule;
{
// 9.1. Load the GLSL shader from file and compile it with shaderc.
#if HAVE_SHADERC
std::vector<char> vertSrc = LoadGLSL("passthrough.vert");
std::vector<uint32_t> vertCode = CompileGLSL(shaderc_vertex_shader, vertSrc);
#else
std::vector<uint32_t> vertCode = LoadSPIRV("passthrough.vert.spv");
#endif
if (vertCode.size() == 0) {
throw std::runtime_error("failed to load vertex shader!");
}
// 9.2. Specify the vertex shader module information.
// Notes:
// * "codeSize" is in bytes.
// * "pCode" points to an array of SPIR-V opcodes.
VkShaderModuleCreateInfo vertInfo;
{
vertInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
vertInfo.pNext = NULL;
vertInfo.flags = 0;
vertInfo.codeSize = vertCode.size() * sizeof(uint32_t);
vertInfo.pCode = reinterpret_cast<uint32_t*>(vertCode.data());
}
// 9.3. Create the Vertex Shader Module.
if (vkCreateShaderModule(device, &vertInfo, NULL, &vertShaderModule) != VK_SUCCESS) {
throw std::runtime_error("failed to create shader module!");
}
}
// 10. Create Fragment shader.
VkShaderModule fragShaderModule;
{
// 10.1. Load the GLSL shader from file and compile it with shaderc.
#if HAVE_SHADERC
std::vector<char> fragSrc = LoadGLSL("passthrough.frag");
std::vector<uint32_t> fragCode = CompileGLSL(shaderc_fragment_shader, fragSrc);
#else
std::vector<uint32_t> fragCode = LoadSPIRV("passthrough.frag.spv");
#endif
if (fragCode.size() == 0) {
throw std::runtime_error("failed to load fragment shader!");
}
// 10.2. Specify the fragment shader module information.
VkShaderModuleCreateInfo fragInfo;
{
fragInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
fragInfo.pNext = NULL;
fragInfo.flags = 0;
fragInfo.codeSize = fragCode.size() * sizeof(uint32_t);
fragInfo.pCode = reinterpret_cast<uint32_t*>(fragCode.data());
}
// 10.3. Create the Fragment Shader Module.
if (vkCreateShaderModule(device, &fragInfo, NULL, &fragShaderModule) != VK_SUCCESS) {
throw std::runtime_error("failed to create shader module!");
}
}
// 11. Create Pipeline Layout.
// Currently there are no descriptors added (no uniforms).
VkPipelineLayout pipelineLayout;
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo;
{
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.pNext = NULL;
pipelineLayoutInfo.flags = 0;
pipelineLayoutInfo.setLayoutCount = 0;
pipelineLayoutInfo.pSetLayouts = NULL;
pipelineLayoutInfo.pushConstantRangeCount = 0;
}
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, NULL, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("failed to create pipeline layout!");
}
}
// 12. Create the Rendering Pipeline
VkPipeline pipeline;
{
VkPipelineShaderStageCreateInfo vertShaderStageInfo;
{
vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vertShaderStageInfo.pNext = NULL;
vertShaderStageInfo.flags = 0;
vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
vertShaderStageInfo.module = vertShaderModule;
vertShaderStageInfo.pName = "main";
vertShaderStageInfo.pSpecializationInfo = NULL;
}
VkPipelineShaderStageCreateInfo fragShaderStageInfo;
{
fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
fragShaderStageInfo.pNext = NULL;
fragShaderStageInfo.flags = 0;
fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
fragShaderStageInfo.module = fragShaderModule;
fragShaderStageInfo.pName = "main";
fragShaderStageInfo.pSpecializationInfo = NULL;
}
VkPipelineShaderStageCreateInfo shaderStages[] = { vertShaderStageInfo, fragShaderStageInfo };
// V.4. Describe the Vertex input binding information.
VkVertexInputBindingDescription vec2VertexBinding;
{
// The binding information is mapped to the VkVertexInputAttributeDescription.binding.
vec2VertexBinding.binding = 0;
// The stride information is based on the vertex input type: vec2. (see shader)
vec2VertexBinding.stride = sizeof(float) * 2;
vec2VertexBinding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
}
// V.5. Describe the Vertex input attribute information.
VkVertexInputAttributeDescription positionVertexAttribute;
{
positionVertexAttribute.binding = 0;
// The attribute location is from the Vertex shader.
positionVertexAttribute.location = 0;
// Format and offset is used during the data read from the buffer.
positionVertexAttribute.format = VK_FORMAT_R32G32_SFLOAT;
positionVertexAttribute.offset = 0;
}
// V.6. Connect the Attribute and Binding infors to the VertexInputState.
VkPipelineVertexInputStateCreateInfo vertexInputInfo;
{
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputInfo.pNext = NULL;
vertexInputInfo.flags = 0;
vertexInputInfo.vertexBindingDescriptionCount = 1;
vertexInputInfo.pVertexBindingDescriptions = &vec2VertexBinding;
vertexInputInfo.vertexAttributeDescriptionCount = 1;
vertexInputInfo.pVertexAttributeDescriptions = &positionVertexAttribute;
}
VkPipelineInputAssemblyStateCreateInfo inputAssembly;
{
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssembly.pNext = NULL;
inputAssembly.flags = 0;
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
inputAssembly.primitiveRestartEnable = VK_FALSE;
}
VkViewport viewport;
{
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = (float) renderImageWidth;
viewport.height = (float) renderImageHeight;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
}
VkRect2D scissor;
{
scissor.offset = { 0, 0 };
scissor.extent = { (uint32_t)viewport.width, (uint32_t)viewport.height };
}
VkPipelineViewportStateCreateInfo viewportState{};
{
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportState.viewportCount = 1;
viewportState.pViewports = &viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &scissor;
}
VkPipelineRasterizationStateCreateInfo rasterizer;
{
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.pNext = NULL;
rasterizer.flags = 0;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;
rasterizer.depthBiasEnable = VK_FALSE;
rasterizer.depthBiasConstantFactor = 0.0;
rasterizer.depthBiasClamp = 0.0;
rasterizer.depthBiasSlopeFactor = 0.0;
rasterizer.lineWidth = 1.0f;
}
VkPipelineMultisampleStateCreateInfo multisampling;
{
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.pNext = NULL;
multisampling.flags = 0;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.minSampleShading = 0.0;
multisampling.pSampleMask = NULL;
multisampling.alphaToCoverageEnable = VK_FALSE;
multisampling.alphaToOneEnable = VK_FALSE;
}
VkPipelineColorBlendAttachmentState colorBlendAttachment;
{
colorBlendAttachment.blendEnable = VK_FALSE;
colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE;
colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE;
colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT
| VK_COLOR_COMPONENT_G_BIT
| VK_COLOR_COMPONENT_B_BIT
| VK_COLOR_COMPONENT_A_BIT;
}
VkPipelineColorBlendStateCreateInfo colorBlending;
{
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
colorBlending.pNext = NULL;
colorBlending.flags = 0;
colorBlending.logicOpEnable = VK_FALSE;
colorBlending.logicOp = VK_LOGIC_OP_COPY;
colorBlending.attachmentCount = 1;
colorBlending.pAttachments = &colorBlendAttachment;
colorBlending.blendConstants[0] = 0.0f;
colorBlending.blendConstants[1] = 0.0f;
colorBlending.blendConstants[2] = 0.0f;
colorBlending.blendConstants[3] = 0.0f;
}
VkGraphicsPipelineCreateInfo pipelineInfo;
{
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineInfo.pNext = NULL;
pipelineInfo.flags = 0;
pipelineInfo.stageCount = 2;
pipelineInfo.pStages = shaderStages;
pipelineInfo.pVertexInputState = &vertexInputInfo;
pipelineInfo.pInputAssemblyState = &inputAssembly;
pipelineInfo.pTessellationState = NULL;
pipelineInfo.pViewportState = &viewportState;
pipelineInfo.pRasterizationState = &rasterizer;
pipelineInfo.pMultisampleState = &multisampling;
pipelineInfo.pDepthStencilState = NULL;
pipelineInfo.pColorBlendState = &colorBlending;
pipelineInfo.pDynamicState = NULL;
pipelineInfo.layout = pipelineLayout;
pipelineInfo.renderPass = renderPass;
pipelineInfo.subpass = 0;
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
pipelineInfo.basePipelineIndex = 0;
}
if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, NULL, &pipeline) != VK_SUCCESS) {
throw std::runtime_error("failed to create graphics pipeline!");
}
}
// 13. Create Framebuffer.
// Frame buffer is the render target.
VkFramebuffer framebuffer;
{
VkFramebufferCreateInfo framebufferInfo;
{
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebufferInfo.pNext = NULL;
framebufferInfo.flags = 0;
framebufferInfo.renderPass = renderPass;
framebufferInfo.attachmentCount = 1;
framebufferInfo.pAttachments = &renderImageView;
framebufferInfo.width = renderImageWidth;
framebufferInfo.height = renderImageHeight;
framebufferInfo.layers = 1;
}
if (vkCreateFramebuffer(device, &framebufferInfo, NULL, &framebuffer) != VK_SUCCESS) {
throw std::runtime_error("failed to create framebuffer!");
}
}
// 14. Create Command Pool.
// Required to create Command buffers.
VkCommandPool cmdPool;
{
VkCommandPoolCreateInfo poolInfo;
{
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
poolInfo.pNext = NULL;
poolInfo.flags = 0;
poolInfo.queueFamilyIndex = graphicsQueueFamilyIdx;
}
if (vkCreateCommandPool(device, &poolInfo, NULL, &cmdPool) != VK_SUCCESS) {
throw std::runtime_error("failed to create command pool!");
}
}
// 15. Create Command Buffer to record draw commands.
VkCommandBuffer cmdBuffer;
{
VkCommandBufferAllocateInfo allocInfo;
{
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.pNext = NULL;
allocInfo.commandPool = cmdPool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = 1;
}
if (vkAllocateCommandBuffers(device, &allocInfo, &cmdBuffer) != VK_SUCCESS) {
throw std::runtime_error("failed to allocate command buffers!");
}
}
// Start recording draw commands.
// 16. Start Command Buffer
{
VkCommandBufferBeginInfo beginInfo;
{
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.pNext = NULL;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
beginInfo.pInheritanceInfo = NULL;
}
if (vkBeginCommandBuffer(cmdBuffer, &beginInfo) != VK_SUCCESS) {
throw std::runtime_error("failed to begin recording command buffer!");
}
}
// 17. Insert draw commands into Command Buffer.
{
// 17.1. Add Begin RenderPass command
// This makes it possible to use the vmCmdDraw* calls.
VkClearValue clearColor = { { { 0.0f, 0.0f, 0.0f, 1.0f } } };
VkRenderPassBeginInfo renderPassInfo;
{
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.pNext = NULL;
renderPassInfo.renderPass = renderPass;
renderPassInfo.framebuffer = framebuffer;
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = { (uint32_t)renderImageWidth, (uint32_t)renderImageHeight };
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
}
vkCmdBeginRenderPass(cmdBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
// 17.2. Bind the Graphics pipeline inside the Current Render Pass.
vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
// V.7. Bind the Vertex buffers as specified by the pipeline.
VkDeviceSize bufferOffsets[] = { 0 };
vkCmdBindVertexBuffers(cmdBuffer, 0, 1, &vertexBuffer, bufferOffsets);
// 17.3. Add a Draw command.
// Draw 3 vertices using the pipeline bound previously.
uint32_t vertexCount = 3;
uint32_t instanceCount = 1;
vkCmdDraw(cmdBuffer, vertexCount, instanceCount, 0, 0);
// 17.4. End the Render Pass.
vkCmdEndRenderPass(cmdBuffer);
}
// 18. End the Command Buffer recording.
{
if (vkEndCommandBuffer(cmdBuffer) != VK_SUCCESS) {
throw std::runtime_error("failed to record command buffer!");
}
}
// Recording of the draw commands into the Command Buffer is done.
// Now the Command Buffer should be sent to the GPU.
// 19. Create a Fence.
// This Fence will be used to synchronize between CPU and GPU.
// The Fence is created in an unsignaled state, thus no need to reset it.
VkFence fence;
{
VkFenceCreateInfo fenceInfo;
{
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceInfo.pNext = 0;
//fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
fenceInfo.flags = 0;
}
if (vkCreateFence(device, &fenceInfo, NULL, &fence) != VK_SUCCESS) {
throw std::runtime_error("failed to create synchronization objects for a frame!");
}
//vkResetFences(device, 1, &fence);
}
// 20. Submit the recorded Command Buffer to the Queue.
{
VkSubmitInfo submitInfo;
{
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.pNext = NULL;
submitInfo.waitSemaphoreCount = 0;
submitInfo.pWaitSemaphores = NULL;
submitInfo.pWaitDstStageMask = NULL;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &cmdBuffer;
submitInfo.signalSemaphoreCount = 0;
submitInfo.pSignalSemaphores = NULL;
}
// A fence is provided to have a CPU side sync point.
if (vkQueueSubmit(queue, 1, &submitInfo, fence) != VK_SUCCESS) {
throw std::runtime_error("failed to submit command buffer!");
}
}
// 21. Wait the submitted Command Buffer to finish.
{
// -1 means to wait for ever to finish.
if (vkWaitForFences(device, 1, &fence, VK_TRUE, -1) != VK_SUCCESS) {
throw std::runtime_error("failed to wait for fence!");
}
}
// At this point the image is rendered into the Framebuffer's attachment which is an ImageView.
// The ImageView is created for the "renderImage" thus the image is rendered into that.
{
// Start readback process of the rendered image.
// 22. Copy the rendered image into a buffer which can be mapped and read.
// Note: this is the most basic process to the the image into a readeable memory.
VkImage readableImage;
VkDeviceMemory readableImageMemory;
CopyImageToLinearImage(physicalDevice, device, queue, cmdPool, renderImage, renderImageWidth, renderImageHeight, &readableImage, &readableImageMemory);
// 23. Get layout of the readable image (including row pitch).
VkImageSubresource subResource;
{
subResource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
subResource.mipLevel = 0;
subResource.arrayLayer = 0;
}
VkSubresourceLayout subResourceLayout;
vkGetImageSubresourceLayout(device, readableImage, &subResource, &subResourceLayout);
// 24. Map image memory so we can start copying from it.
const uint8_t* data;
{
vkMapMemory(device, readableImageMemory, 0, VK_WHOLE_SIZE, 0, (void**)&data);
data += subResourceLayout.offset;
}
// 25. Write out the image to a ppm file.
{
std::ofstream file(outputFileName, std::ios::out | std::ios::binary);
// ppm header
file << "P6\n" << renderImageWidth << "\n" << renderImageHeight << "\n" << 255 << "\n";
// ppm binary pixel data
// As the image format is R8G8B8A8 one "pixel" size is 4 bytes (uint32_t)
for (uint32_t y = 0; y < renderImageHeight; y++) {
uint32_t *row = (uint32_t*)data;
for (uint32_t x = 0; x < renderImageWidth; x++) {
// Only copy the RGB values (3)
file.write((const char*)row, 3);
row++;
}
data += subResourceLayout.rowPitch;
}
file.close();
}
// 26. UnMap the readable image memory.
vkUnmapMemory(device, readableImageMemory);
// XX. Free linear image's memory.
vkFreeMemory(device, readableImageMemory, NULL);
// XX. Destory linar image memory.
vkDestroyImage(device, readableImage, NULL);
}
// XX. Destroy Fence.
vkDestroyFence(device, fence, NULL);
// XX. Free Command Buffer.
vkFreeCommandBuffers(device, cmdPool, 1, &cmdBuffer);
// XX. Destroy Command Pool
vkDestroyCommandPool(device, cmdPool, NULL);