forked from LunarG/VulkanSamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil_init.cpp
More file actions
2201 lines (1896 loc) · 82.1 KB
/
Copy pathutil_init.cpp
File metadata and controls
2201 lines (1896 loc) · 82.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Vulkan Samples
*
* Copyright (C) 2015-2016 Valve Corporation
* Copyright (C) 2015-2016 LunarG, Inc.
* Copyright (C) 2015-2016 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
VULKAN_SAMPLE_DESCRIPTION
samples "init" utility functions
*/
#include <cstdlib>
#include <assert.h>
#include <string.h>
#include "util_init.hpp"
#include "cube_data.h"
using namespace std;
/*
* TODO: function description here
*/
VkResult init_global_extension_properties(layer_properties &layer_props) {
VkExtensionProperties *instance_extensions;
uint32_t instance_extension_count;
VkResult res;
char *layer_name = NULL;
layer_name = layer_props.properties.layerName;
do {
res = vkEnumerateInstanceExtensionProperties(
layer_name, &instance_extension_count, NULL);
if (res)
return res;
if (instance_extension_count == 0) {
return VK_SUCCESS;
}
layer_props.extensions.resize(instance_extension_count);
instance_extensions = layer_props.extensions.data();
res = vkEnumerateInstanceExtensionProperties(
layer_name, &instance_extension_count, instance_extensions);
} while (res == VK_INCOMPLETE);
return res;
}
/*
* TODO: function description here
*/
VkResult init_global_layer_properties(struct sample_info &info) {
uint32_t instance_layer_count;
VkLayerProperties *vk_props = NULL;
VkResult res;
#ifdef __ANDROID__
// This place is the first place for samples to use Vulkan APIs.
// Here, we are going to open Vulkan.so on the device and retrieve function pointers using
// vulkan_wrapper helper.
if (!InitVulkan()) {
LOGE("Failied initializing Vulkan APIs!");
return VK_ERROR_INITIALIZATION_FAILED;
}
LOGI("Loaded Vulkan APIs.");
#endif
/*
* It's possible, though very rare, that the number of
* instance layers could change. For example, installing something
* could include new layers that the loader would pick up
* between the initial query for the count and the
* request for VkLayerProperties. The loader indicates that
* by returning a VK_INCOMPLETE status and will update the
* the count parameter.
* The count parameter will be updated with the number of
* entries loaded into the data pointer - in case the number
* of layers went down or is smaller than the size given.
*/
do {
res = vkEnumerateInstanceLayerProperties(&instance_layer_count, NULL);
if (res)
return res;
if (instance_layer_count == 0) {
return VK_SUCCESS;
}
vk_props = (VkLayerProperties *)realloc(
vk_props, instance_layer_count * sizeof(VkLayerProperties));
res =
vkEnumerateInstanceLayerProperties(&instance_layer_count, vk_props);
} while (res == VK_INCOMPLETE);
/*
* Now gather the extension list for each instance layer.
*/
for (uint32_t i = 0; i < instance_layer_count; i++) {
layer_properties layer_props;
layer_props.properties = vk_props[i];
res = init_global_extension_properties(layer_props);
if (res)
return res;
info.instance_layer_properties.push_back(layer_props);
}
free(vk_props);
return res;
}
VkResult init_device_extension_properties(struct sample_info &info,
layer_properties &layer_props) {
VkExtensionProperties *device_extensions;
uint32_t device_extension_count;
VkResult res;
char *layer_name = NULL;
layer_name = layer_props.properties.layerName;
do {
res = vkEnumerateDeviceExtensionProperties(
info.gpus[0], layer_name, &device_extension_count, NULL);
if (res)
return res;
if (device_extension_count == 0) {
return VK_SUCCESS;
}
layer_props.extensions.resize(device_extension_count);
device_extensions = layer_props.extensions.data();
res = vkEnumerateDeviceExtensionProperties(info.gpus[0], layer_name,
&device_extension_count,
device_extensions);
} while (res == VK_INCOMPLETE);
return res;
}
/*
* TODO: function description here
*/
VkResult init_device_layer_properties(struct sample_info &info) {
uint32_t device_layer_count;
VkLayerProperties *vk_props = NULL;
VkResult res;
/*
* It's possible, though very rare, that the number of
* instance layers could change. For example, installing something
* could include new layers that the loader would pick up
* between the initial query for the count and the
* request for VkLayerProperties. The loader indicates that
* by returning a VK_INCOMPLETE status and will update the
* the count parameter.
* The count parameter will be updated with the number of
* entries loaded into the data pointer - in case the number
* of layers went down or is smaller than the size given.
*/
do {
res = vkEnumerateDeviceLayerProperties(info.gpus[0],
&device_layer_count, NULL);
if (res)
return res;
if (device_layer_count == 0) {
return VK_SUCCESS;
}
vk_props = (VkLayerProperties *)realloc(
vk_props, device_layer_count * sizeof(VkLayerProperties));
res = vkEnumerateDeviceLayerProperties(info.gpus[0],
&device_layer_count, vk_props);
} while (res == VK_INCOMPLETE);
/*
* Now gather the extension list for each device layer.
*/
for (uint32_t i = 0; i < device_layer_count; i++) {
layer_properties layer_props;
layer_props.properties = vk_props[i];
res = init_device_extension_properties(info, layer_props);
if (res)
return res;
info.device_layer_properties.push_back(layer_props);
}
free(vk_props);
return res;
}
/*
* Return 1 (true) if all layer names specified in check_names
* can be found in given layer properties.
*/
VkBool32 demo_check_layers(const std::vector<layer_properties> &layer_props,
const std::vector<const char *> &layer_names) {
uint32_t check_count = layer_names.size();
uint32_t layer_count = layer_props.size();
for (uint32_t i = 0; i < check_count; i++) {
VkBool32 found = 0;
for (uint32_t j = 0; j < layer_count; j++) {
if (!strcmp(layer_names[i], layer_props[j].properties.layerName)) {
found = 1;
}
}
if (!found) {
std::cout << "Cannot find layer: " << layer_names[i] << std::endl;
return 0;
}
}
return 1;
}
void init_instance_extension_names(struct sample_info &info) {
info.instance_extension_names.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
#ifdef __ANDROID__
info.instance_extension_names.push_back(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME);
#elif defined(_WIN32)
info.instance_extension_names.push_back(
VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
#else
info.instance_extension_names.push_back(VK_KHR_XCB_SURFACE_EXTENSION_NAME);
#endif
}
VkResult init_instance(struct sample_info &info,
char const *const app_short_name) {
VkApplicationInfo app_info = {};
app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app_info.pNext = NULL;
app_info.pApplicationName = app_short_name;
app_info.applicationVersion = 1;
app_info.pEngineName = app_short_name;
app_info.engineVersion = 1;
app_info.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo inst_info = {};
inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
inst_info.pNext = NULL;
inst_info.flags = 0;
inst_info.pApplicationInfo = &app_info;
inst_info.enabledLayerCount = info.instance_layer_names.size();
inst_info.ppEnabledLayerNames = info.instance_layer_names.size()
? info.instance_layer_names.data()
: NULL;
inst_info.enabledExtensionCount = info.instance_extension_names.size();
inst_info.ppEnabledExtensionNames = info.instance_extension_names.data();
VkResult res = vkCreateInstance(&inst_info, NULL, &info.inst);
assert(res == VK_SUCCESS);
return res;
}
void init_device_extension_names(struct sample_info &info) {
info.device_extension_names.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
}
VkResult init_device(struct sample_info &info) {
VkResult res;
VkDeviceQueueCreateInfo queue_info = {};
float queue_priorities[1] = {0.0};
queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_info.pNext = NULL;
queue_info.queueCount = 1;
queue_info.pQueuePriorities = queue_priorities;
queue_info.queueFamilyIndex = info.graphics_queue_family_index;
VkDeviceCreateInfo device_info = {};
device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_info.pNext = NULL;
device_info.queueCreateInfoCount = 1;
device_info.pQueueCreateInfos = &queue_info;
device_info.enabledLayerCount = info.device_layer_names.size();
device_info.ppEnabledLayerNames =
device_info.enabledLayerCount ? info.device_layer_names.data() : NULL;
device_info.enabledExtensionCount = info.device_extension_names.size();
device_info.ppEnabledExtensionNames =
device_info.enabledExtensionCount ? info.device_extension_names.data()
: NULL;
device_info.pEnabledFeatures = NULL;
res = vkCreateDevice(info.gpus[0], &device_info, NULL, &info.device);
assert(res == VK_SUCCESS);
return res;
}
VkResult init_enumerate_device(struct sample_info &info, uint32_t gpu_count) {
uint32_t const U_ASSERT_ONLY req_count = gpu_count;
VkResult res = vkEnumeratePhysicalDevices(info.inst, &gpu_count, NULL);
assert(gpu_count);
info.gpus.resize(gpu_count);
res = vkEnumeratePhysicalDevices(info.inst, &gpu_count, info.gpus.data());
assert(!res && gpu_count >= req_count);
vkGetPhysicalDeviceQueueFamilyProperties(info.gpus[0], &info.queue_count,
NULL);
assert(info.queue_count >= 1);
info.queue_props.resize(info.queue_count);
vkGetPhysicalDeviceQueueFamilyProperties(info.gpus[0], &info.queue_count,
info.queue_props.data());
assert(info.queue_count >= 1);
/* This is as good a place as any to do this */
vkGetPhysicalDeviceMemoryProperties(info.gpus[0], &info.memory_properties);
vkGetPhysicalDeviceProperties(info.gpus[0], &info.gpu_props);
return res;
}
void init_queue_family_index(struct sample_info &info) {
/* This routine simply finds a graphics queue for a later vkCreateDevice,
* without consideration for which queue family can present an image.
* Do not use this if your intent is to present later in your sample,
* instead use the init_connection, init_window, init_swapchain_extension,
* init_device call sequence to get a graphics and present compatible queue
* family
*/
vkGetPhysicalDeviceQueueFamilyProperties(info.gpus[0], &info.queue_count,
NULL);
assert(info.queue_count >= 1);
info.queue_props.resize(info.queue_count);
vkGetPhysicalDeviceQueueFamilyProperties(info.gpus[0], &info.queue_count,
info.queue_props.data());
assert(info.queue_count >= 1);
bool found = false;
for (unsigned int i = 0; i < info.queue_count; i++) {
if (info.queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
info.graphics_queue_family_index = i;
found = true;
break;
}
}
assert(found);
}
VkResult init_debug_report_callback(struct sample_info &info,
PFN_vkDebugReportCallbackEXT dbgFunc) {
VkResult res;
VkDebugReportCallbackEXT debug_report_callback;
info.dbgCreateDebugReportCallback =
(PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(
info.inst, "vkCreateDebugReportCallbackEXT");
if (!info.dbgCreateDebugReportCallback) {
std::cout << "GetInstanceProcAddr: Unable to find "
"vkCreateDebugReportCallbackEXT function." << std::endl;
return VK_ERROR_INITIALIZATION_FAILED;
}
std::cout << "Got dbgCreateDebugReportCallback function\n";
info.dbgDestroyDebugReportCallback =
(PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(
info.inst, "vkDestroyDebugReportCallbackEXT");
if (!info.dbgDestroyDebugReportCallback) {
std::cout << "GetInstanceProcAddr: Unable to find "
"vkDestroyDebugReportCallbackEXT function." << std::endl;
return VK_ERROR_INITIALIZATION_FAILED;
}
std::cout << "Got dbgDestroyDebugReportCallback function\n";
VkDebugReportCallbackCreateInfoEXT create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
create_info.pNext = NULL;
create_info.flags =
VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
create_info.pfnCallback = dbgFunc;
create_info.pUserData = NULL;
res = info.dbgCreateDebugReportCallback(info.inst, &create_info, NULL,
&debug_report_callback);
switch (res) {
case VK_SUCCESS:
std::cout << "Successfully created debug report callback object\n";
info.debug_report_callbacks.push_back(debug_report_callback);
break;
case VK_ERROR_OUT_OF_HOST_MEMORY:
std::cout
<< "dbgCreateDebugReportCallback: out of host memory pointer\n"
<< std::endl;
return VK_ERROR_INITIALIZATION_FAILED;
break;
default:
std::cout << "dbgCreateDebugReportCallback: unknown failure\n"
<< std::endl;
return VK_ERROR_INITIALIZATION_FAILED;
break;
}
return res;
}
void destroy_debug_report_callback(struct sample_info &info) {
while (info.debug_report_callbacks.size() > 0) {
info.dbgDestroyDebugReportCallback(
info.inst, info.debug_report_callbacks.back(), NULL);
info.debug_report_callbacks.pop_back();
}
}
void init_connection(struct sample_info &info) {
#ifdef __ANDROID__
// Do nothing on Android.
#elif !defined(_WIN32)
const xcb_setup_t *setup;
xcb_screen_iterator_t iter;
int scr;
info.connection = xcb_connect(NULL, &scr);
if (info.connection == NULL) {
std::cout << "Cannot find a compatible Vulkan ICD.\n";
exit(-1);
}
setup = xcb_get_setup(info.connection);
iter = xcb_setup_roots_iterator(setup);
while (scr-- > 0)
xcb_screen_next(&iter);
info.screen = iter.data;
#endif //__Android__
}
#ifdef _WIN32
static void run(struct sample_info *info) {
/* Placeholder for samples that want to show dynamic content */
}
// MS-Windows event handling function:
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
struct sample_info *info = reinterpret_cast<struct sample_info *>(
GetWindowLongPtr(hWnd, GWLP_USERDATA));
switch (uMsg) {
case WM_CLOSE:
PostQuitMessage(0);
break;
case WM_PAINT:
run(info);
return 0;
default:
break;
}
return (DefWindowProc(hWnd, uMsg, wParam, lParam));
}
void init_window(struct sample_info &info) {
WNDCLASSEX win_class;
assert(info.width > 0);
assert(info.height > 0);
info.connection = GetModuleHandle(NULL);
sprintf(info.name, "Sample");
// Initialize the window class structure:
win_class.cbSize = sizeof(WNDCLASSEX);
win_class.style = CS_HREDRAW | CS_VREDRAW;
win_class.lpfnWndProc = WndProc;
win_class.cbClsExtra = 0;
win_class.cbWndExtra = 0;
win_class.hInstance = info.connection; // hInstance
win_class.hIcon = LoadIcon(NULL, IDI_APPLICATION);
win_class.hCursor = LoadCursor(NULL, IDC_ARROW);
win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
win_class.lpszMenuName = NULL;
win_class.lpszClassName = info.name;
win_class.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
// Register window class:
if (!RegisterClassEx(&win_class)) {
// It didn't work, so try to give a useful error:
printf("Unexpected error trying to start the application!\n");
fflush(stdout);
exit(1);
}
// Create window with the registered class:
RECT wr = {0, 0, info.width, info.height};
AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
info.window = CreateWindowEx(0,
info.name, // class name
info.name, // app name
WS_OVERLAPPEDWINDOW | // window style
WS_VISIBLE | WS_SYSMENU,
100, 100, // x/y coords
wr.right - wr.left, // width
wr.bottom - wr.top, // height
NULL, // handle to parent
NULL, // handle to menu
info.connection, // hInstance
NULL); // no extra parameters
if (!info.window) {
// It didn't work, so try to give a useful error:
printf("Cannot create a window in which to draw!\n");
fflush(stdout);
exit(1);
}
SetWindowLongPtr(info.window, GWLP_USERDATA, (LONG_PTR)&info);
}
void destroy_window(struct sample_info &info) {
vkDestroySurfaceKHR(info.inst, info.surface, NULL);
DestroyWindow(info.window);
}
#elif defined(__ANDROID__)
// Android implementation.
void init_window(struct sample_info &info) {
}
void destroy_window(struct sample_info &info) {
}
#else
void init_window(struct sample_info &info) {
assert(info.width > 0);
assert(info.height > 0);
uint32_t value_mask, value_list[32];
info.window = xcb_generate_id(info.connection);
value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
value_list[0] = info.screen->black_pixel;
value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE;
xcb_create_window(info.connection, XCB_COPY_FROM_PARENT, info.window,
info.screen->root, 0, 0, info.width, info.height, 0,
XCB_WINDOW_CLASS_INPUT_OUTPUT, info.screen->root_visual,
value_mask, value_list);
/* Magic code that will send notification when window is destroyed */
xcb_intern_atom_cookie_t cookie =
xcb_intern_atom(info.connection, 1, 12, "WM_PROTOCOLS");
xcb_intern_atom_reply_t *reply =
xcb_intern_atom_reply(info.connection, cookie, 0);
xcb_intern_atom_cookie_t cookie2 =
xcb_intern_atom(info.connection, 0, 16, "WM_DELETE_WINDOW");
info.atom_wm_delete_window =
xcb_intern_atom_reply(info.connection, cookie2, 0);
xcb_change_property(info.connection, XCB_PROP_MODE_REPLACE, info.window,
(*reply).atom, 4, 32, 1,
&(*info.atom_wm_delete_window).atom);
free(reply);
xcb_map_window(info.connection, info.window);
// Force the x/y coordinates to 100,100 results are identical in consecutive
// runs
const uint32_t coords[] = {100, 100};
xcb_configure_window(info.connection, info.window,
XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
xcb_flush(info.connection);
xcb_generic_event_t *e;
while ((e = xcb_wait_for_event(info.connection))) {
if ((e->response_type & ~0x80) == XCB_EXPOSE)
break;
}
}
void destroy_window(struct sample_info &info) {
vkDestroySurfaceKHR(info.inst, info.surface, NULL);
xcb_destroy_window(info.connection, info.window);
xcb_disconnect(info.connection);
}
#endif // _WIN32
void init_window_size(struct sample_info &info, int32_t default_width,
int32_t default_height) {
#ifdef __ANDROID__
AndroidGetWindowSize(&info.width, &info.height);
#else
info.width = default_width;
info.height = default_height;
#endif
}
void init_depth_buffer(struct sample_info &info) {
VkResult U_ASSERT_ONLY res;
bool U_ASSERT_ONLY pass;
VkImageCreateInfo image_info = {};
/* allow custom depth formats */
if (info.depth.format == VK_FORMAT_UNDEFINED)
info.depth.format = VK_FORMAT_D16_UNORM;
#ifdef __ANDROID__
// Depth format needs to be VK_FORMAT_D24_UNORM_S8_UINT on Android.
const VkFormat depth_format = VK_FORMAT_D24_UNORM_S8_UINT;
#else
const VkFormat depth_format = info.depth.format;
#endif
VkFormatProperties props;
vkGetPhysicalDeviceFormatProperties(info.gpus[0], depth_format, &props);
if (props.linearTilingFeatures &
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) {
image_info.tiling = VK_IMAGE_TILING_LINEAR;
} else if (props.optimalTilingFeatures &
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) {
image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
} else {
/* Try other depth formats? */
std::cout << "depth_format " << depth_format << " Unsupported.\n";
exit(-1);
}
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info.pNext = NULL;
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.format = depth_format;
image_info.extent.width = info.width;
image_info.extent.height = info.height;
image_info.extent.depth = 1;
image_info.mipLevels = 1;
image_info.arrayLayers = 1;
image_info.samples = NUM_SAMPLES;
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
image_info.queueFamilyIndexCount = 0;
image_info.pQueueFamilyIndices = NULL;
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
image_info.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
image_info.flags = 0;
VkMemoryAllocateInfo mem_alloc = {};
mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
mem_alloc.pNext = NULL;
mem_alloc.allocationSize = 0;
mem_alloc.memoryTypeIndex = 0;
VkImageViewCreateInfo view_info = {};
view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
view_info.pNext = NULL;
view_info.image = VK_NULL_HANDLE;
view_info.format = depth_format;
view_info.components.r = VK_COMPONENT_SWIZZLE_R;
view_info.components.g = VK_COMPONENT_SWIZZLE_G;
view_info.components.b = VK_COMPONENT_SWIZZLE_B;
view_info.components.a = VK_COMPONENT_SWIZZLE_A;
view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
view_info.subresourceRange.baseMipLevel = 0;
view_info.subresourceRange.levelCount = 1;
view_info.subresourceRange.baseArrayLayer = 0;
view_info.subresourceRange.layerCount = 1;
view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
view_info.flags = 0;
if (depth_format == VK_FORMAT_D16_UNORM_S8_UINT ||
depth_format == VK_FORMAT_D24_UNORM_S8_UINT ||
depth_format == VK_FORMAT_D32_SFLOAT_S8_UINT) {
view_info.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
}
VkMemoryRequirements mem_reqs;
/* Create image */
res = vkCreateImage(info.device, &image_info, NULL, &info.depth.image);
assert(res == VK_SUCCESS);
vkGetImageMemoryRequirements(info.device, info.depth.image, &mem_reqs);
mem_alloc.allocationSize = mem_reqs.size;
/* Use the memory properties to determine the type of memory required */
pass = memory_type_from_properties(info, mem_reqs.memoryTypeBits,
0, /* No requirements */
&mem_alloc.memoryTypeIndex);
assert(pass);
/* Allocate memory */
res = vkAllocateMemory(info.device, &mem_alloc, NULL, &info.depth.mem);
assert(res == VK_SUCCESS);
/* Bind memory */
res = vkBindImageMemory(info.device, info.depth.image, info.depth.mem, 0);
assert(res == VK_SUCCESS);
/* Set the image layout to depth stencil optimal */
set_image_layout(info, info.depth.image,
view_info.subresourceRange.aspectMask,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
/* Create image view */
view_info.image = info.depth.image;
res = vkCreateImageView(info.device, &view_info, NULL, &info.depth.view);
assert(res == VK_SUCCESS);
}
void init_swapchain_extension(struct sample_info &info) {
/* DEPENDS on init_connection() and init_window() */
VkResult U_ASSERT_ONLY res;
// Construct the surface description:
#ifdef _WIN32
VkWin32SurfaceCreateInfoKHR createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
createInfo.pNext = NULL;
createInfo.hinstance = info.connection;
createInfo.hwnd = info.window;
res = vkCreateWin32SurfaceKHR(info.inst, &createInfo,
NULL, &info.surface);
#elif defined(__ANDROID__)
GET_INSTANCE_PROC_ADDR(info.inst, CreateAndroidSurfaceKHR);
VkAndroidSurfaceCreateInfoKHR createInfo;
createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
createInfo.pNext = nullptr;
createInfo.flags = 0;
createInfo.window = AndroidGetApplicationWindow();
res = info.fpCreateAndroidSurfaceKHR(info.inst, &createInfo, nullptr, &info.surface);
#else // !__ANDROID__ && !_WIN32
VkXcbSurfaceCreateInfoKHR createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR;
createInfo.pNext = NULL;
createInfo.connection = info.connection;
createInfo.window = info.window;
res = vkCreateXcbSurfaceKHR(info.inst, &createInfo,
NULL, &info.surface);
#endif // __ANDROID__ && _WIN32
assert(res == VK_SUCCESS);
// Iterate over each queue to learn whether it supports presenting:
VkBool32 *supportsPresent =
(VkBool32 *)malloc(info.queue_count * sizeof(VkBool32));
for (uint32_t i = 0; i < info.queue_count; i++) {
vkGetPhysicalDeviceSurfaceSupportKHR(info.gpus[0], i, info.surface,
&supportsPresent[i]);
}
// Search for a graphics queue and a present queue in the array of queue
// families, try to find one that supports both
uint32_t graphicsQueueNodeIndex = UINT32_MAX;
for (uint32_t i = 0; i < info.queue_count; i++) {
if ((info.queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) {
if (supportsPresent[i] == VK_TRUE) {
graphicsQueueNodeIndex = i;
break;
}
}
}
free(supportsPresent);
// Generate error if could not find a queue that supports both a graphics
// and present
if (graphicsQueueNodeIndex == UINT32_MAX) {
std::cout
<< "Could not find a queue that supports both graphics and present";
exit(-1);
}
info.graphics_queue_family_index = graphicsQueueNodeIndex;
// Get the list of VkFormats that are supported:
uint32_t formatCount;
res = vkGetPhysicalDeviceSurfaceFormatsKHR(info.gpus[0], info.surface,
&formatCount, NULL);
assert(res == VK_SUCCESS);
VkSurfaceFormatKHR *surfFormats =
(VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR));
res = vkGetPhysicalDeviceSurfaceFormatsKHR(info.gpus[0], info.surface,
&formatCount, surfFormats);
assert(res == VK_SUCCESS);
// If the format list includes just one entry of VK_FORMAT_UNDEFINED,
// the surface has no preferred format. Otherwise, at least one
// supported format will be returned.
if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) {
info.format = VK_FORMAT_B8G8R8A8_UNORM;
} else {
assert(formatCount >= 1);
info.format = surfFormats[0].format;
}
free(surfFormats);
}
void init_presentable_image(struct sample_info &info) {
/* DEPENDS on init_swap_chain() */
VkResult U_ASSERT_ONLY res;
VkSemaphoreCreateInfo presentCompleteSemaphoreCreateInfo;
presentCompleteSemaphoreCreateInfo.sType =
VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
presentCompleteSemaphoreCreateInfo.pNext = NULL;
presentCompleteSemaphoreCreateInfo.flags = 0;
res = vkCreateSemaphore(info.device, &presentCompleteSemaphoreCreateInfo,
NULL, &info.presentCompleteSemaphore);
assert(!res);
// Get the index of the next available swapchain image:
res = vkAcquireNextImageKHR(info.device, info.swap_chain, UINT64_MAX,
info.presentCompleteSemaphore, VK_NULL_HANDLE,
&info.current_buffer);
// TODO: Deal with the VK_SUBOPTIMAL_KHR and VK_ERROR_OUT_OF_DATE_KHR
// return codes
assert(!res);
set_image_layout(info, info.buffers[info.current_buffer].image,
VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
}
void execute_queue_cmdbuf(struct sample_info &info,
const VkCommandBuffer *cmd_bufs,
VkFence &fence) {
VkResult U_ASSERT_ONLY res;
VkPipelineStageFlags pipe_stage_flags =
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
VkSubmitInfo submit_info[1] = {};
submit_info[0].pNext = NULL;
submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info[0].waitSemaphoreCount = 1;
submit_info[0].pWaitSemaphores = &info.presentCompleteSemaphore;
submit_info[0].pWaitDstStageMask = NULL;
submit_info[0].commandBufferCount = 1;
submit_info[0].pCommandBuffers = cmd_bufs;
submit_info[0].pWaitDstStageMask = &pipe_stage_flags;
submit_info[0].signalSemaphoreCount = 0;
submit_info[0].pSignalSemaphores = NULL;
/* Queue the command buffer for execution */
res = vkQueueSubmit(info.queue, 1, submit_info, fence);
assert(!res);
}
void execute_pre_present_barrier(struct sample_info &info) {
/* DEPENDS on init_swap_chain() */
/* Add mem barrier to change layout to present */
VkImageMemoryBarrier prePresentBarrier = {};
prePresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
prePresentBarrier.pNext = NULL;
prePresentBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
prePresentBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
prePresentBarrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
prePresentBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
prePresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
prePresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
prePresentBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
prePresentBarrier.subresourceRange.baseMipLevel = 0;
prePresentBarrier.subresourceRange.levelCount = 1;
prePresentBarrier.subresourceRange.baseArrayLayer = 0;
prePresentBarrier.subresourceRange.layerCount = 1;
prePresentBarrier.image = info.buffers[info.current_buffer].image;
vkCmdPipelineBarrier(info.cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0,
NULL, 1, &prePresentBarrier);
}
void execute_present_image(struct sample_info &info) {
/* DEPENDS on init_presentable_image() and init_swap_chain()*/
/* Present the image in the window */
VkResult U_ASSERT_ONLY res;
VkPresentInfoKHR present;
present.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
present.pNext = NULL;
present.swapchainCount = 1;
present.pSwapchains = &info.swap_chain;
present.pImageIndices = &info.current_buffer;
present.pWaitSemaphores = NULL;
present.waitSemaphoreCount = 0;
present.pResults = NULL;
res = vkQueuePresentKHR(info.queue, &present);
// TODO: Deal with the VK_SUBOPTIMAL_WSI and VK_ERROR_OUT_OF_DATE_WSI
// return codes
assert(!res);
}
void init_swap_chain(struct sample_info &info, VkImageUsageFlags usageFlags) {
/* DEPENDS on info.cmd and info.queue initialized */
VkResult U_ASSERT_ONLY res;
VkSurfaceCapabilitiesKHR surfCapabilities;
res = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(info.gpus[0], info.surface,
&surfCapabilities);
assert(res == VK_SUCCESS);
uint32_t presentModeCount;
res = vkGetPhysicalDeviceSurfacePresentModesKHR(info.gpus[0], info.surface,
&presentModeCount, NULL);
assert(res == VK_SUCCESS);
VkPresentModeKHR *presentModes =
(VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR));
assert(presentModes);
res = vkGetPhysicalDeviceSurfacePresentModesKHR(
info.gpus[0], info.surface, &presentModeCount, presentModes);
assert(res == VK_SUCCESS);
VkExtent2D swapChainExtent;
// width and height are either both -1, or both not -1.
if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
// If the surface size is undefined, the size is set to
// the size of the images requested.
swapChainExtent.width = info.width;
swapChainExtent.height = info.height;
} else {
// If the surface size is defined, the swap chain size must match
swapChainExtent = surfCapabilities.currentExtent;
}
// If mailbox mode is available, use it, as is the lowest-latency non-
// tearing mode. If not, try IMMEDIATE which will usually be available,
// and is fastest (though it tears). If not, fall back to FIFO which is
// always available.
VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
for (size_t i = 0; i < presentModeCount; i++) {
if (presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR) {
swapchainPresentMode = VK_PRESENT_MODE_MAILBOX_KHR;
break;
}
if ((swapchainPresentMode != VK_PRESENT_MODE_MAILBOX_KHR) &&
(presentModes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR)) {
swapchainPresentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
}
}
#ifdef __ANDROID__
// Current driver only support VK_PRESENT_MODE_FIFO_KHR.
swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
#endif
// Determine the number of VkImage's to use in the swap chain (we desire to
// own only 1 image at a time, besides the images being displayed and
// queued for display):
uint32_t desiredNumberOfSwapChainImages =
surfCapabilities.minImageCount + 1;
if ((surfCapabilities.maxImageCount > 0) &&
(desiredNumberOfSwapChainImages > surfCapabilities.maxImageCount)) {
// Application must settle for fewer images than desired:
desiredNumberOfSwapChainImages = surfCapabilities.maxImageCount;
}
VkSurfaceTransformFlagBitsKHR preTransform;
if (surfCapabilities.supportedTransforms &
VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) {
preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
} else {
preTransform = surfCapabilities.currentTransform;
}
VkSwapchainCreateInfoKHR swap_chain = {};
swap_chain.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swap_chain.pNext = NULL;
swap_chain.surface = info.surface;
swap_chain.minImageCount = desiredNumberOfSwapChainImages;
swap_chain.imageFormat = info.format;
swap_chain.imageExtent.width = swapChainExtent.width;
swap_chain.imageExtent.height = swapChainExtent.height;
swap_chain.preTransform = preTransform;
swap_chain.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
swap_chain.imageArrayLayers = 1;
swap_chain.presentMode = swapchainPresentMode;
swap_chain.oldSwapchain = VK_NULL_HANDLE;
#ifndef __ANDROID__
swap_chain.clipped = true;
#else
swap_chain.clipped = false;
#endif
swap_chain.imageColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
swap_chain.imageUsage = usageFlags;
swap_chain.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
swap_chain.queueFamilyIndexCount = 0;
swap_chain.pQueueFamilyIndices = NULL;
res =
vkCreateSwapchainKHR(info.device, &swap_chain, NULL, &info.swap_chain);
assert(res == VK_SUCCESS);
res = vkGetSwapchainImagesKHR(info.device, info.swap_chain,
&info.swapchainImageCount, NULL);
assert(res == VK_SUCCESS);
VkImage *swapchainImages =
(VkImage *)malloc(info.swapchainImageCount * sizeof(VkImage));
assert(swapchainImages);
res = vkGetSwapchainImagesKHR(info.device, info.swap_chain,
&info.swapchainImageCount, swapchainImages);