-
Notifications
You must be signed in to change notification settings - Fork 0
/
vulkan-example.c
2301 lines (1976 loc) · 84.2 KB
/
vulkan-example.c
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 _GNU_SOURCE
#include <assert.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linmath.h"
#include "object_type_string_helper.h"
#include <vulkan/vulkan.h>
#include "gettime.h"
#include "inttypes.h"
#define MILLION 1000000L
#define BILLION 1000000000L
#define DEMO_TEXTURE_COUNT 1
#define APP_SHORT_NAME "vkcube"
#define APP_LONG_NAME "Vulkan Cube"
// Allow a maximum of two outstanding presentation operations.
#define FRAME_LAG 2
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
/*
* structure to track all objects related to a texture.
*/
struct texture_object
{
VkSampler sampler;
VkImage image;
VkBuffer buffer;
VkImageLayout imageLayout;
VkMemoryAllocateInfo mem_alloc;
VkDeviceMemory mem;
VkImageView view;
int32_t tex_width, tex_height;
};
static char* tex_files[] = { "lunarg.ppm" };
static int validation_error = 0;
struct vktexcube_vs_uniform
{
// Must start with MVP
float mvp[4][4];
float position[12 * 3][4];
float attr[12 * 3][4];
};
//--------------------------------------------------------------------------------------
// Mesh and VertexFormat Data
//--------------------------------------------------------------------------------------
// clang-format off
static const float g_vertex_buffer_data[] = {
-1.0f,-1.0f,-1.0f, // -X side
-1.0f,-1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f, // -Z side
1.0f, 1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
-1.0f,-1.0f,-1.0f, // -Y side
1.0f,-1.0f,-1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f,-1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
-1.0f, 1.0f,-1.0f, // +Y side
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f,-1.0f,
1.0f, 1.0f,-1.0f, // +X side
1.0f, 1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
-1.0f, 1.0f, 1.0f, // +Z side
-1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
};
static const float g_uv_buffer_data[] = {
0.0f, 1.0f, // -X side
1.0f, 1.0f,
1.0f, 0.0f,
1.0f, 0.0f,
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f, // -Z side
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
0.0f, 0.0f,
1.0f, 0.0f, // -Y side
1.0f, 1.0f,
0.0f, 1.0f,
1.0f, 0.0f,
0.0f, 1.0f,
0.0f, 0.0f,
1.0f, 0.0f, // +Y side
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f, // +X side
0.0f, 0.0f,
0.0f, 1.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
0.0f, 0.0f, // +Z side
0.0f, 1.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
};
// clang-format on
typedef struct
{
VkImage image;
VkCommandBuffer cmd;
VkCommandBuffer graphics_to_present_cmd;
VkImageView view;
VkBuffer uniform_buffer;
VkDeviceMemory uniform_memory;
VkFramebuffer framebuffer;
VkDescriptorSet descriptor_set;
} SwapchainImageResources;
struct demo
{
VkSurfaceKHR surface;
bool prepared;
bool use_staging_buffer;
bool separate_present_queue;
bool is_minimized;
VkInstance inst;
VkPhysicalDevice gpu;
VkDevice device;
VkQueue graphics_queue;
VkQueue present_queue;
uint32_t graphics_queue_family_index;
uint32_t present_queue_family_index;
VkSemaphore image_acquired_semaphores[FRAME_LAG];
VkSemaphore draw_complete_semaphores[FRAME_LAG];
VkSemaphore image_ownership_semaphores[FRAME_LAG];
VkPhysicalDeviceProperties gpu_props;
VkQueueFamilyProperties* queue_props;
VkPhysicalDeviceMemoryProperties memory_properties;
uint32_t enabled_extension_count;
uint32_t enabled_layer_count;
char* extension_names[64];
char* enabled_layers[64];
int width, height;
VkFormat format;
VkColorSpaceKHR color_space;
uint32_t swapchainImageCount;
VkSwapchainKHR swapchain;
SwapchainImageResources* swapchain_image_resources;
VkPresentModeKHR presentMode;
VkFence fences[FRAME_LAG];
int frame_index;
VkCommandPool cmd_pool;
VkCommandPool present_cmd_pool;
struct
{
VkFormat format;
VkImage image;
VkMemoryAllocateInfo mem_alloc;
VkDeviceMemory mem;
VkImageView view;
} depth;
struct texture_object textures[DEMO_TEXTURE_COUNT];
struct texture_object staging_texture;
VkCommandBuffer cmd; // Buffer for initialization commands
VkPipelineLayout pipeline_layout;
VkDescriptorSetLayout desc_layout;
VkPipelineCache pipelineCache;
VkRenderPass render_pass;
VkPipeline pipeline;
mat4x4 projection_matrix;
mat4x4 view_matrix;
mat4x4 model_matrix;
float spin_angle;
float spin_increment;
bool pause;
VkShaderModule vert_shader_module;
VkShaderModule frag_shader_module;
VkDescriptorPool desc_pool;
bool quit;
bool validate;
bool validate_checks_disabled;
bool use_break;
bool suppress_popups;
uint32_t current_buffer;
uint32_t queue_family_count;
};
// Forward declaration:
static void
demo_resize(struct demo* demo);
static bool
memory_type_from_properties(struct demo* demo, uint32_t typeBits, VkFlags requirements_mask,
uint32_t* typeIndex)
{
// Search memtypes to find first index with those properties
for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
if ((typeBits & 1) == 1) {
// Type is available, does it match user properties?
if ((demo->memory_properties.memoryTypes[i].propertyFlags & requirements_mask) ==
requirements_mask) {
*typeIndex = i;
return true;
}
}
typeBits >>= 1;
}
// No memory types matched, return failure
return false;
}
static void
demo_flush_init_cmd(struct demo* demo)
{
VkResult U_ASSERT_ONLY err;
// This function could get called twice if the texture uses a staging buffer
// In that case the second call should be ignored
if (demo->cmd == VK_NULL_HANDLE)
return;
err = vkEndCommandBuffer(demo->cmd);
assert(!err);
VkFence fence;
VkFenceCreateInfo fence_ci = { .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = 0 };
err = vkCreateFence(demo->device, &fence_ci, NULL, &fence);
assert(!err);
const VkCommandBuffer cmd_bufs[] = { demo->cmd };
VkSubmitInfo submit_info = { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.pNext = NULL,
.waitSemaphoreCount = 0,
.pWaitSemaphores = NULL,
.pWaitDstStageMask = NULL,
.commandBufferCount = 1,
.pCommandBuffers = cmd_bufs,
.signalSemaphoreCount = 0,
.pSignalSemaphores = NULL };
err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, fence);
assert(!err);
err = vkWaitForFences(demo->device, 1, &fence, VK_TRUE, UINT64_MAX);
assert(!err);
vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, cmd_bufs);
vkDestroyFence(demo->device, fence, NULL);
demo->cmd = VK_NULL_HANDLE;
}
static void
demo_set_image_layout(struct demo* demo, VkImage image, VkImageAspectFlags aspectMask,
VkImageLayout old_image_layout, VkImageLayout new_image_layout,
VkAccessFlagBits srcAccessMask, VkPipelineStageFlags src_stages,
VkPipelineStageFlags dest_stages)
{
assert(demo->cmd);
VkImageMemoryBarrier image_memory_barrier = { .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.pNext = NULL,
.srcAccessMask = srcAccessMask,
.dstAccessMask = 0,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.oldLayout = old_image_layout,
.newLayout = new_image_layout,
.image = image,
.subresourceRange = { aspectMask, 0, 1, 0, 1 } };
switch (new_image_layout) {
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
/* Make sure anything that was copying from this image has completed */
image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
image_memory_barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
image_memory_barrier.dstAccessMask =
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
image_memory_barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
break;
default:
image_memory_barrier.dstAccessMask = 0;
break;
}
VkImageMemoryBarrier* pmemory_barrier = &image_memory_barrier;
vkCmdPipelineBarrier(demo->cmd, src_stages, dest_stages, 0, 0, NULL, 0, NULL, 1, pmemory_barrier);
}
static void
demo_draw_build_cmd(struct demo* demo, VkCommandBuffer cmd_buf)
{
VkDebugUtilsLabelEXT label;
memset(&label, 0, sizeof(label));
const VkCommandBufferBeginInfo cmd_buf_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.pNext = NULL,
.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
.pInheritanceInfo = NULL,
};
const VkClearValue clear_values[2] = {
[0] = { .color.float32 = { 0.2f, 0.2f, 0.2f, 0.2f } },
[1] = { .depthStencil = { 1.0f, 0 } },
};
const VkRenderPassBeginInfo rp_begin = {
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
.pNext = NULL,
.renderPass = demo->render_pass,
.framebuffer = demo->swapchain_image_resources[demo->current_buffer].framebuffer,
.renderArea.offset.x = 0,
.renderArea.offset.y = 0,
.renderArea.extent.width = demo->width,
.renderArea.extent.height = demo->height,
.clearValueCount = 2,
.pClearValues = clear_values,
};
VkResult U_ASSERT_ONLY err;
err = vkBeginCommandBuffer(cmd_buf, &cmd_buf_info);
if (demo->validate) {
// Set a name for the command buffer
VkDebugUtilsObjectNameInfoEXT cmd_buf_name = {
.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT,
.pNext = NULL,
.objectType = VK_OBJECT_TYPE_COMMAND_BUFFER,
.objectHandle = (uint64_t)cmd_buf,
.pObjectName = "CubeDrawCommandBuf",
};
demo->SetDebugUtilsObjectNameEXT(demo->device, &cmd_buf_name);
label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
label.pNext = NULL;
label.pLabelName = "DrawBegin";
label.color[0] = 0.4f;
label.color[1] = 0.3f;
label.color[2] = 0.2f;
label.color[3] = 0.1f;
demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
}
assert(!err);
vkCmdBeginRenderPass(cmd_buf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
if (demo->validate) {
label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
label.pNext = NULL;
label.pLabelName = "InsideRenderPass";
label.color[0] = 8.4f;
label.color[1] = 7.3f;
label.color[2] = 6.2f;
label.color[3] = 7.1f;
demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
}
vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline);
vkCmdBindDescriptorSets(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline_layout, 0, 1,
&demo->swapchain_image_resources[demo->current_buffer].descriptor_set, 0, NULL);
VkViewport viewport;
memset(&viewport, 0, sizeof(viewport));
viewport.height = (float)demo->height;
viewport.width = (float)demo->width;
viewport.minDepth = (float)0.0f;
viewport.maxDepth = (float)1.0f;
vkCmdSetViewport(cmd_buf, 0, 1, &viewport);
VkRect2D scissor;
memset(&scissor, 0, sizeof(scissor));
scissor.extent.width = demo->width;
scissor.extent.height = demo->height;
scissor.offset.x = 0;
scissor.offset.y = 0;
vkCmdSetScissor(cmd_buf, 0, 1, &scissor);
if (demo->validate) {
label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
label.pNext = NULL;
label.pLabelName = "ActualDraw";
label.color[0] = -0.4f;
label.color[1] = -0.3f;
label.color[2] = -0.2f;
label.color[3] = -0.1f;
demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
}
vkCmdDraw(cmd_buf, 12 * 3, 1, 0, 0);
if (demo->validate) {
demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
}
// Note that ending the renderpass changes the image's layout from
// COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
vkCmdEndRenderPass(cmd_buf);
if (demo->validate) {
demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
}
if (demo->separate_present_queue) {
// We have to transfer ownership from the graphics queue family to the
// present queue family to be able to present. Note that we don't have
// to transfer from present queue family back to graphics queue family at
// the start of the next frame because we don't care about the image's
// contents at that point.
VkImageMemoryBarrier image_ownership_barrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.pNext = NULL,
.srcAccessMask = 0,
.dstAccessMask = 0,
.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.srcQueueFamilyIndex = demo->graphics_queue_family_index,
.dstQueueFamilyIndex = demo->present_queue_family_index,
.image = demo->swapchain_image_resources[demo->current_buffer].image,
.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }
};
vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1,
&image_ownership_barrier);
}
if (demo->validate) {
demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
}
err = vkEndCommandBuffer(cmd_buf);
assert(!err);
}
void
demo_build_image_ownership_cmd(struct demo* demo, int i)
{
VkResult U_ASSERT_ONLY err;
const VkCommandBufferBeginInfo cmd_buf_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.pNext = NULL,
.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
.pInheritanceInfo = NULL,
};
err = vkBeginCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd, &cmd_buf_info);
assert(!err);
VkImageMemoryBarrier image_ownership_barrier = { .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.pNext = NULL,
.srcAccessMask = 0,
.dstAccessMask = 0,
.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.srcQueueFamilyIndex = demo->graphics_queue_family_index,
.dstQueueFamilyIndex = demo->present_queue_family_index,
.image = demo->swapchain_image_resources[i].image,
.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0,
1 } };
vkCmdPipelineBarrier(demo->swapchain_image_resources[i].graphics_to_present_cmd,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0,
NULL, 0, NULL, 1, &image_ownership_barrier);
err = vkEndCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd);
assert(!err);
}
void
demo_update_data_buffer(struct demo* demo)
{
mat4x4 MVP, Model, VP;
int matrixSize = sizeof(MVP);
uint8_t* pData;
VkResult U_ASSERT_ONLY err;
mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
// Rotate around the Y axis
mat4x4_dup(Model, demo->model_matrix);
mat4x4_rotate(demo->model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(demo->spin_angle));
mat4x4_mul(MVP, VP, demo->model_matrix);
err = vkMapMemory(demo->device, demo->swapchain_image_resources[demo->current_buffer].uniform_memory, 0,
VK_WHOLE_SIZE, 0, (void**)&pData);
assert(!err);
memcpy(pData, (const void*)&MVP[0][0], matrixSize);
vkUnmapMemory(demo->device, demo->swapchain_image_resources[demo->current_buffer].uniform_memory);
}
static void
demo_draw(struct demo* demo)
{
VkResult U_ASSERT_ONLY err;
// Ensure no more than FRAME_LAG renderings are outstanding
vkWaitForFences(demo->device, 1, &demo->fences[demo->frame_index], VK_TRUE, UINT64_MAX);
vkResetFences(demo->device, 1, &demo->fences[demo->frame_index]);
do {
// Get the index of the next available swapchain image:
err = vkAcquireNextImageKHR(demo->device, demo->swapchain, UINT64_MAX,
demo->image_acquired_semaphores[demo->frame_index], VK_NULL_HANDLE,
&demo->current_buffer);
if (err == VK_ERROR_OUT_OF_DATE_KHR) {
// demo->swapchain is out of date (e.g. the window was resized) and
// must be recreated:
demo_resize(demo);
} else if (err == VK_SUBOPTIMAL_KHR) {
// demo->swapchain is not as optimal as it could be, but the platform's
// presentation engine will still present the image correctly.
break;
} else {
assert(!err);
}
} while (err != VK_SUCCESS);
demo_update_data_buffer(demo);
// Wait for the image acquired semaphore to be signaled to ensure
// that the image won't be rendered to until the presentation
// engine has fully released ownership to the application, and it is
// okay to render to the image.
VkPipelineStageFlags pipe_stage_flags;
VkSubmitInfo submit_info;
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.pNext = NULL;
submit_info.pWaitDstStageMask = &pipe_stage_flags;
pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
submit_info.waitSemaphoreCount = 1;
submit_info.pWaitSemaphores = &demo->image_acquired_semaphores[demo->frame_index];
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &demo->swapchain_image_resources[demo->current_buffer].cmd;
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = &demo->draw_complete_semaphores[demo->frame_index];
err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, demo->fences[demo->frame_index]);
assert(!err);
if (demo->separate_present_queue) {
// If we are using separate queues, change image ownership to the
// present queue before presenting, waiting for the draw complete
// semaphore and signalling the ownership released semaphore when finished
VkFence nullFence = VK_NULL_HANDLE;
pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
submit_info.waitSemaphoreCount = 1;
submit_info.pWaitSemaphores = &demo->draw_complete_semaphores[demo->frame_index];
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers =
&demo->swapchain_image_resources[demo->current_buffer].graphics_to_present_cmd;
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = &demo->image_ownership_semaphores[demo->frame_index];
err = vkQueueSubmit(demo->present_queue, 1, &submit_info, nullFence);
assert(!err);
}
// If we are using separate queues we have to wait for image ownership,
// otherwise wait for draw complete
VkPresentInfoKHR present = {
.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
.pNext = NULL,
.waitSemaphoreCount = 1,
.pWaitSemaphores = (demo->separate_present_queue)
? &demo->image_ownership_semaphores[demo->frame_index]
: &demo->draw_complete_semaphores[demo->frame_index],
.swapchainCount = 1,
.pSwapchains = &demo->swapchain,
.pImageIndices = &demo->current_buffer,
};
VkRectLayerKHR rect;
VkPresentRegionKHR region;
VkPresentRegionsKHR regions;
err = vkQueuePresentKHR(demo->present_queue, &present);
demo->frame_index += 1;
demo->frame_index %= FRAME_LAG;
if (err == VK_ERROR_OUT_OF_DATE_KHR) {
// demo->swapchain is out of date (e.g. the window was resized) and
// must be recreated:
demo_resize(demo);
} else if (err == VK_SUBOPTIMAL_KHR) {
// demo->swapchain is not as optimal as it could be, but the platform's
// presentation engine will still present the image correctly.
} else {
assert(!err);
}
}
static void
demo_prepare_buffers(struct demo* demo)
{
VkResult U_ASSERT_ONLY err;
VkSwapchainKHR oldSwapchain = demo->swapchain;
// Check the surface capabilities and formats
VkSurfaceCapabilitiesKHR surfCapabilities;
err = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(demo->gpu, demo->surface, &surfCapabilities);
assert(!err);
uint32_t presentModeCount;
err = vkGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, NULL);
assert(!err);
VkPresentModeKHR* presentModes = (VkPresentModeKHR*)malloc(presentModeCount * sizeof(VkPresentModeKHR));
assert(presentModes);
err =
vkGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, presentModes);
assert(!err);
VkExtent2D swapchainExtent;
// width and height are either both 0xFFFFFFFF, or both not 0xFFFFFFFF.
if (surfCapabilities.currentExtent.width == 0xFFFFFFFF) {
// If the surface size is undefined, the size is set to the size
// of the images requested, which must fit within the minimum and
// maximum values.
swapchainExtent.width = demo->width;
swapchainExtent.height = demo->height;
if (swapchainExtent.width < surfCapabilities.minImageExtent.width) {
swapchainExtent.width = surfCapabilities.minImageExtent.width;
} else if (swapchainExtent.width > surfCapabilities.maxImageExtent.width) {
swapchainExtent.width = surfCapabilities.maxImageExtent.width;
}
if (swapchainExtent.height < surfCapabilities.minImageExtent.height) {
swapchainExtent.height = surfCapabilities.minImageExtent.height;
} else if (swapchainExtent.height > surfCapabilities.maxImageExtent.height) {
swapchainExtent.height = surfCapabilities.maxImageExtent.height;
}
} else {
// If the surface size is defined, the swap chain size must match
swapchainExtent = surfCapabilities.currentExtent;
demo->width = surfCapabilities.currentExtent.width;
demo->height = surfCapabilities.currentExtent.height;
}
if (demo->width == 0 || demo->height == 0) {
demo->is_minimized = true;
return;
} else {
demo->is_minimized = false;
}
// The FIFO present mode is guaranteed by the spec to be supported
// and to have no tearing. It's a great default present mode to use.
VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
// There are times when you may wish to use another present mode. The
// following code shows how to select them, and the comments provide some
// reasons you may wish to use them.
//
// It should be noted that Vulkan 1.0 doesn't provide a method for
// synchronizing rendering with the presentation engine's display. There
// is a method provided for throttling rendering with the display, but
// there are some presentation engines for which this method will not work.
// If an application doesn't throttle its rendering, and if it renders much
// faster than the refresh rate of the display, this can waste power on
// mobile devices. That is because power is being spent rendering images
// that may never be seen.
// VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care about
// tearing, or have some way of synchronizing their rendering with the
// display.
// VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
// generally render a new presentable image every refresh cycle, but are
// occasionally early. In this case, the application wants the new image
// to be displayed instead of the previously-queued-for-presentation image
// that has not yet been displayed.
// VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
// render a new presentable image every refresh cycle, but are occasionally
// late. In this case (perhaps because of stuttering/latency concerns),
// the application wants the late image to be immediately displayed, even
// though that may mean some tearing.
if (demo->presentMode != swapchainPresentMode) {
for (size_t i = 0; i < presentModeCount; ++i) {
if (presentModes[i] == demo->presentMode) {
swapchainPresentMode = demo->presentMode;
break;
}
}
}
if (swapchainPresentMode != demo->presentMode) {
ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
}
// Determine the number of VkImages to use in the swap chain.
// Application desires to acquire 3 images at a time for triple
// buffering
uint32_t desiredNumOfSwapchainImages = 3;
if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
}
// If maxImageCount is 0, we can ask for as many images as we want;
// otherwise we're limited to maxImageCount
if ((surfCapabilities.maxImageCount > 0) &&
(desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
// Application must settle for fewer images than desired:
desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
}
VkSurfaceTransformFlagsKHR preTransform;
if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) {
preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
} else {
preTransform = surfCapabilities.currentTransform;
}
// Find a supported composite alpha mode - one of these is guaranteed to be set
VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
VkCompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR,
VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
};
for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
compositeAlpha = compositeAlphaFlags[i];
break;
}
}
VkSwapchainCreateInfoKHR swapchain_ci = {
.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
.pNext = NULL,
.surface = demo->surface,
.minImageCount = desiredNumOfSwapchainImages,
.imageFormat = demo->format,
.imageColorSpace = demo->color_space,
.imageExtent =
{
.width = swapchainExtent.width,
.height = swapchainExtent.height,
},
.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
.preTransform = preTransform,
.compositeAlpha = compositeAlpha,
.imageArrayLayers = 1,
.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = NULL,
.presentMode = swapchainPresentMode,
.oldSwapchain = oldSwapchain,
.clipped = true,
};
uint32_t i;
err = vkCreateSwapchainKHR(demo->device, &swapchain_ci, NULL, &demo->swapchain);
assert(!err);
// If we just re-created an existing swapchain, we should destroy the old
// swapchain at this point.
// Note: destroying the swapchain also cleans up all its associated
// presentable images once the platform is done with them.
if (oldSwapchain != VK_NULL_HANDLE) {
vkDestroySwapchainKHR(demo->device, oldSwapchain, NULL);
}
err = vkGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, NULL);
assert(!err);
VkImage* swapchainImages = (VkImage*)malloc(demo->swapchainImageCount * sizeof(VkImage));
assert(swapchainImages);
err = vkGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, swapchainImages);
assert(!err);
demo->swapchain_image_resources =
(SwapchainImageResources*)malloc(sizeof(SwapchainImageResources) * demo->swapchainImageCount);
assert(demo->swapchain_image_resources);
for (i = 0; i < demo->swapchainImageCount; i++) {
VkImageViewCreateInfo color_image_view = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = NULL,
.format = demo->format,
.components =
{
.r = VK_COMPONENT_SWIZZLE_R,
.g = VK_COMPONENT_SWIZZLE_G,
.b = VK_COMPONENT_SWIZZLE_B,
.a = VK_COMPONENT_SWIZZLE_A,
},
.subresourceRange = { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1 },
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.flags = 0,
};
demo->swapchain_image_resources[i].image = swapchainImages[i];
color_image_view.image = demo->swapchain_image_resources[i].image;
err = vkCreateImageView(demo->device, &color_image_view, NULL,
&demo->swapchain_image_resources[i].view);
assert(!err);
}
if (NULL != swapchainImages) {
free(swapchainImages);
}
if (NULL != presentModes) {
free(presentModes);
}
}
static void
demo_prepare_depth(struct demo* demo)
{
const VkFormat depth_format = VK_FORMAT_D16_UNORM;
const VkImageCreateInfo image = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.pNext = NULL,
.imageType = VK_IMAGE_TYPE_2D,
.format = depth_format,
.extent = { demo->width, demo->height, 1 },
.mipLevels = 1,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
.flags = 0,
};
VkImageViewCreateInfo view = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = NULL,
.image = VK_NULL_HANDLE,
.format = depth_format,
.subresourceRange = { .aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1 },
.flags = 0,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
};
VkMemoryRequirements mem_reqs;
VkResult U_ASSERT_ONLY err;
bool U_ASSERT_ONLY pass;
demo->depth.format = depth_format;
/* create image */
err = vkCreateImage(demo->device, &image, NULL, &demo->depth.image);
assert(!err);
vkGetImageMemoryRequirements(demo->device, demo->depth.image, &mem_reqs);
assert(!err);
demo->depth.mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
demo->depth.mem_alloc.pNext = NULL;
demo->depth.mem_alloc.allocationSize = mem_reqs.size;
demo->depth.mem_alloc.memoryTypeIndex = 0;
pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
&demo->depth.mem_alloc.memoryTypeIndex);
assert(pass);
/* allocate memory */
err = vkAllocateMemory(demo->device, &demo->depth.mem_alloc, NULL, &demo->depth.mem);
assert(!err);
/* bind memory */
err = vkBindImageMemory(demo->device, demo->depth.image, demo->depth.mem, 0);
assert(!err);
/* create image view */
view.image = demo->depth.image;
err = vkCreateImageView(demo->device, &view, NULL, &demo->depth.view);
assert(!err);
}
/* Convert ppm image data from header file into RGBA texture image */
#include "lunarg.ppm.h"
bool
loadTexture(const char* filename, uint8_t* rgba_data, VkSubresourceLayout* layout, int32_t* width,
int32_t* height)
{
(void)filename;
char* cPtr;
cPtr = (char*)lunarg_ppm;
if ((unsigned char*)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
return false;
}
while (strncmp(cPtr++, "\n", 1))
;
sscanf(cPtr, "%u %u", width, height);
if (rgba_data == NULL) {
return true;
}
while (strncmp(cPtr++, "\n", 1))
;
if ((unsigned char*)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
return false;
}
while (strncmp(cPtr++, "\n", 1))
;
for (int y = 0; y < *height; y++) {
uint8_t* rowPtr = rgba_data;
for (int x = 0; x < *width; x++) {
memcpy(rowPtr, cPtr, 3);
rowPtr[3] = 255; /* Alpha of 1 */
rowPtr += 4;
cPtr += 3;
}
rgba_data += layout->rowPitch;
}
return true;
}
static void
demo_prepare_texture_buffer(struct demo* demo, const char* filename, struct texture_object* tex_obj)
{
int32_t tex_width;
int32_t tex_height;
VkResult U_ASSERT_ONLY err;
bool U_ASSERT_ONLY pass;
if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
ERR_EXIT("Failed to load textures", "Load Texture Failure");
}
tex_obj->tex_width = tex_width;
tex_obj->tex_height = tex_height;