forked from SaschaWillems/Vulkan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvulkanexamplebase.cpp
2238 lines (2011 loc) · 63.4 KB
/
vulkanexamplebase.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Vulkan Example base class
*
* Copyright (C) by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include "vulkanexamplebase.h"
std::vector<const char*> VulkanExampleBase::args;
VkResult VulkanExampleBase::createInstance(bool enableValidation)
{
this->settings.validation = enableValidation;
// Validation can also be forced via a define
#if defined(_VALIDATION)
this->settings.validation = true;
#endif
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = name.c_str();
appInfo.pEngineName = name.c_str();
appInfo.apiVersion = apiVersion;
std::vector<const char*> instanceExtensions = { VK_KHR_SURFACE_EXTENSION_NAME };
// Enable surface extensions depending on os
#if defined(_WIN32)
instanceExtensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
instanceExtensions.push_back(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME);
#elif defined(_DIRECT2DISPLAY)
instanceExtensions.push_back(VK_KHR_DISPLAY_EXTENSION_NAME);
#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
instanceExtensions.push_back(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME);
#elif defined(VK_USE_PLATFORM_XCB_KHR)
instanceExtensions.push_back(VK_KHR_XCB_SURFACE_EXTENSION_NAME);
#elif defined(VK_USE_PLATFORM_IOS_MVK)
instanceExtensions.push_back(VK_MVK_IOS_SURFACE_EXTENSION_NAME);
#elif defined(VK_USE_PLATFORM_MACOS_MVK)
instanceExtensions.push_back(VK_MVK_MACOS_SURFACE_EXTENSION_NAME);
#endif
if (enabledInstanceExtensions.size() > 0) {
for (auto enabledExtension : enabledInstanceExtensions) {
instanceExtensions.push_back(enabledExtension);
}
}
VkInstanceCreateInfo instanceCreateInfo = {};
instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceCreateInfo.pNext = NULL;
instanceCreateInfo.pApplicationInfo = &appInfo;
if (instanceExtensions.size() > 0)
{
if (settings.validation)
{
instanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
instanceCreateInfo.enabledExtensionCount = (uint32_t)instanceExtensions.size();
instanceCreateInfo.ppEnabledExtensionNames = instanceExtensions.data();
}
if (settings.validation)
{
// The VK_LAYER_KHRONOS_validation contains all current validation functionality.
// Note that on Android this layer requires at least NDK r20
const char* validationLayerName = "VK_LAYER_KHRONOS_validation";
// Check if this layer is available at instance level
uint32_t instanceLayerCount;
vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr);
std::vector<VkLayerProperties> instanceLayerProperties(instanceLayerCount);
vkEnumerateInstanceLayerProperties(&instanceLayerCount, instanceLayerProperties.data());
bool validationLayerPresent = false;
for (VkLayerProperties layer : instanceLayerProperties) {
if (strcmp(layer.layerName, validationLayerName) == 0) {
validationLayerPresent = true;
break;
}
}
if (validationLayerPresent) {
instanceCreateInfo.ppEnabledLayerNames = &validationLayerName;
instanceCreateInfo.enabledLayerCount = 1;
} else {
std::cerr << "Validation layer VK_LAYER_KHRONOS_validation not present, validation is disabled";
}
}
return vkCreateInstance(&instanceCreateInfo, nullptr, &instance);
}
void VulkanExampleBase::renderFrame()
{
VulkanExampleBase::prepareFrame();
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VulkanExampleBase::submitFrame();
}
std::string VulkanExampleBase::getWindowTitle()
{
std::string device(deviceProperties.deviceName);
std::string windowTitle;
windowTitle = title + " - " + device;
if (!settings.overlay) {
windowTitle += " - " + std::to_string(frameCounter) + " fps";
}
return windowTitle;
}
void VulkanExampleBase::createCommandBuffers()
{
// Create one command buffer for each swap chain image and reuse for rendering
drawCmdBuffers.resize(swapChain.imageCount);
VkCommandBufferAllocateInfo cmdBufAllocateInfo =
vks::initializers::commandBufferAllocateInfo(
cmdPool,
VK_COMMAND_BUFFER_LEVEL_PRIMARY,
static_cast<uint32_t>(drawCmdBuffers.size()));
VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, drawCmdBuffers.data()));
}
void VulkanExampleBase::destroyCommandBuffers()
{
vkFreeCommandBuffers(device, cmdPool, static_cast<uint32_t>(drawCmdBuffers.size()), drawCmdBuffers.data());
}
std::string VulkanExampleBase::getShadersPath() const
{
return getAssetPath() + "shaders/" + shaderDir + "/";
}
void VulkanExampleBase::createPipelineCache()
{
VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
VK_CHECK_RESULT(vkCreatePipelineCache(device, &pipelineCacheCreateInfo, nullptr, &pipelineCache));
}
void VulkanExampleBase::prepare()
{
if (vulkanDevice->enableDebugMarkers) {
vks::debugmarker::setup(device);
}
initSwapchain();
createCommandPool();
setupSwapChain();
createCommandBuffers();
createSynchronizationPrimitives();
setupDepthStencil();
setupRenderPass();
createPipelineCache();
setupFrameBuffer();
settings.overlay = settings.overlay && (!benchmark.active);
if (settings.overlay) {
UIOverlay.device = vulkanDevice;
UIOverlay.queue = queue;
UIOverlay.shaders = {
loadShader(getShadersPath() + "base/uioverlay.vert.spv", VK_SHADER_STAGE_VERTEX_BIT),
loadShader(getShadersPath() + "base/uioverlay.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT),
};
UIOverlay.prepareResources();
UIOverlay.preparePipeline(pipelineCache, renderPass);
}
}
VkPipelineShaderStageCreateInfo VulkanExampleBase::loadShader(std::string fileName, VkShaderStageFlagBits stage)
{
VkPipelineShaderStageCreateInfo shaderStage = {};
shaderStage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStage.stage = stage;
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
shaderStage.module = vks::tools::loadShader(androidApp->activity->assetManager, fileName.c_str(), device);
#else
shaderStage.module = vks::tools::loadShader(fileName.c_str(), device);
#endif
shaderStage.pName = "main"; // todo : make param
assert(shaderStage.module != VK_NULL_HANDLE);
shaderModules.push_back(shaderStage.module);
return shaderStage;
}
void VulkanExampleBase::nextFrame()
{
auto tStart = std::chrono::high_resolution_clock::now();
if (viewUpdated)
{
viewUpdated = false;
viewChanged();
}
render();
frameCounter++;
auto tEnd = std::chrono::high_resolution_clock::now();
auto tDiff = std::chrono::duration<double, std::milli>(tEnd - tStart).count();
frameTimer = (float)tDiff / 1000.0f;
camera.update(frameTimer);
if (camera.moving())
{
viewUpdated = true;
}
// Convert to clamped timer value
if (!paused)
{
timer += timerSpeed * frameTimer;
if (timer > 1.0)
{
timer -= 1.0f;
}
}
float fpsTimer = (float)(std::chrono::duration<double, std::milli>(tEnd - lastTimestamp).count());
if (fpsTimer > 1000.0f)
{
lastFPS = static_cast<uint32_t>((float)frameCounter * (1000.0f / fpsTimer));
#if defined(_WIN32)
if (!settings.overlay) {
std::string windowTitle = getWindowTitle();
SetWindowText(window, windowTitle.c_str());
}
#endif
frameCounter = 0;
lastTimestamp = tEnd;
}
// TODO: Cap UI overlay update rates
updateOverlay();
}
void VulkanExampleBase::renderLoop()
{
if (benchmark.active) {
benchmark.run([=] { render(); }, vulkanDevice->properties);
vkDeviceWaitIdle(device);
if (benchmark.filename != "") {
benchmark.saveResults();
}
return;
}
destWidth = width;
destHeight = height;
lastTimestamp = std::chrono::high_resolution_clock::now();
#if defined(_WIN32)
MSG msg;
bool quitMessageReceived = false;
while (!quitMessageReceived) {
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
if (msg.message == WM_QUIT) {
quitMessageReceived = true;
break;
}
}
if (prepared && !IsIconic(window)) {
nextFrame();
}
}
#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
while (1)
{
int ident;
int events;
struct android_poll_source* source;
bool destroy = false;
focused = true;
while ((ident = ALooper_pollAll(focused ? 0 : -1, NULL, &events, (void**)&source)) >= 0)
{
if (source != NULL)
{
source->process(androidApp, source);
}
if (androidApp->destroyRequested != 0)
{
LOGD("Android app destroy requested");
destroy = true;
break;
}
}
// App destruction requested
// Exit loop, example will be destroyed in application main
if (destroy)
{
ANativeActivity_finish(androidApp->activity);
break;
}
// Render frame
if (prepared)
{
auto tStart = std::chrono::high_resolution_clock::now();
render();
frameCounter++;
auto tEnd = std::chrono::high_resolution_clock::now();
auto tDiff = std::chrono::duration<double, std::milli>(tEnd - tStart).count();
frameTimer = tDiff / 1000.0f;
camera.update(frameTimer);
// Convert to clamped timer value
if (!paused)
{
timer += timerSpeed * frameTimer;
if (timer > 1.0)
{
timer -= 1.0f;
}
}
float fpsTimer = std::chrono::duration<double, std::milli>(tEnd - lastTimestamp).count();
if (fpsTimer > 1000.0f)
{
lastFPS = (float)frameCounter * (1000.0f / fpsTimer);
frameCounter = 0;
lastTimestamp = tEnd;
}
// TODO: Cap UI overlay update rates/only issue when update requested
updateOverlay();
bool updateView = false;
// Check touch state (for movement)
if (touchDown) {
touchTimer += frameTimer;
}
if (touchTimer >= 1.0) {
camera.keys.up = true;
viewChanged();
}
// Check gamepad state
const float deadZone = 0.0015f;
// todo : check if gamepad is present
// todo : time based and relative axis positions
if (camera.type != Camera::CameraType::firstperson)
{
// Rotate
if (std::abs(gamePadState.axisLeft.x) > deadZone)
{
camera.rotate(glm::vec3(0.0f, gamePadState.axisLeft.x * 0.5f, 0.0f));
updateView = true;
}
if (std::abs(gamePadState.axisLeft.y) > deadZone)
{
camera.rotate(glm::vec3(gamePadState.axisLeft.y * 0.5f, 0.0f, 0.0f));
updateView = true;
}
// Zoom
if (std::abs(gamePadState.axisRight.y) > deadZone)
{
camera.translate(glm::vec3(0.0f, 0.0f, gamePadState.axisRight.y * 0.01f));
updateView = true;
}
if (updateView)
{
viewChanged();
}
}
else
{
updateView = camera.updatePad(gamePadState.axisLeft, gamePadState.axisRight, frameTimer);
if (updateView)
{
viewChanged();
}
}
}
}
#elif defined(_DIRECT2DISPLAY)
while (!quit)
{
auto tStart = std::chrono::high_resolution_clock::now();
if (viewUpdated)
{
viewUpdated = false;
viewChanged();
}
render();
frameCounter++;
auto tEnd = std::chrono::high_resolution_clock::now();
auto tDiff = std::chrono::duration<double, std::milli>(tEnd - tStart).count();
frameTimer = tDiff / 1000.0f;
camera.update(frameTimer);
if (camera.moving())
{
viewUpdated = true;
}
// Convert to clamped timer value
if (!paused)
{
timer += timerSpeed * frameTimer;
if (timer > 1.0)
{
timer -= 1.0f;
}
}
float fpsTimer = std::chrono::duration<double, std::milli>(tEnd - lastTimestamp).count();
if (fpsTimer > 1000.0f)
{
lastFPS = (float)frameCounter * (1000.0f / fpsTimer);
frameCounter = 0;
lastTimestamp = tEnd;
}
updateOverlay();
}
#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
while (!quit)
{
auto tStart = std::chrono::high_resolution_clock::now();
if (viewUpdated)
{
viewUpdated = false;
viewChanged();
}
while (!configured)
wl_display_dispatch(display);
while (wl_display_prepare_read(display) != 0)
wl_display_dispatch_pending(display);
wl_display_flush(display);
wl_display_read_events(display);
wl_display_dispatch_pending(display);
render();
frameCounter++;
auto tEnd = std::chrono::high_resolution_clock::now();
auto tDiff = std::chrono::duration<double, std::milli>(tEnd - tStart).count();
frameTimer = tDiff / 1000.0f;
camera.update(frameTimer);
if (camera.moving())
{
viewUpdated = true;
}
// Convert to clamped timer value
if (!paused)
{
timer += timerSpeed * frameTimer;
if (timer > 1.0)
{
timer -= 1.0f;
}
}
float fpsTimer = std::chrono::duration<double, std::milli>(tEnd - lastTimestamp).count();
if (fpsTimer > 1000.0f)
{
if (!settings.overlay)
{
std::string windowTitle = getWindowTitle();
xdg_toplevel_set_title(xdg_toplevel, windowTitle.c_str());
}
lastFPS = (float)frameCounter * (1000.0f / fpsTimer);
frameCounter = 0;
lastTimestamp = tEnd;
}
updateOverlay();
}
#elif defined(VK_USE_PLATFORM_XCB_KHR)
xcb_flush(connection);
while (!quit)
{
auto tStart = std::chrono::high_resolution_clock::now();
if (viewUpdated)
{
viewUpdated = false;
viewChanged();
}
xcb_generic_event_t *event;
while ((event = xcb_poll_for_event(connection)))
{
handleEvent(event);
free(event);
}
render();
frameCounter++;
auto tEnd = std::chrono::high_resolution_clock::now();
auto tDiff = std::chrono::duration<double, std::milli>(tEnd - tStart).count();
frameTimer = tDiff / 1000.0f;
camera.update(frameTimer);
if (camera.moving())
{
viewUpdated = true;
}
// Convert to clamped timer value
if (!paused)
{
timer += timerSpeed * frameTimer;
if (timer > 1.0)
{
timer -= 1.0f;
}
}
float fpsTimer = std::chrono::duration<double, std::milli>(tEnd - lastTimestamp).count();
if (fpsTimer > 1000.0f)
{
if (!settings.overlay)
{
std::string windowTitle = getWindowTitle();
xcb_change_property(connection, XCB_PROP_MODE_REPLACE,
window, XCB_ATOM_WM_NAME, XCB_ATOM_STRING, 8,
windowTitle.size(), windowTitle.c_str());
}
lastFPS = (float)frameCounter * (1000.0f / fpsTimer);
frameCounter = 0;
lastTimestamp = tEnd;
}
updateOverlay();
}
#endif
// Flush device to make sure all resources can be freed
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
}
void VulkanExampleBase::updateOverlay()
{
if (!settings.overlay)
return;
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = ImVec2((float)width, (float)height);
io.DeltaTime = frameTimer;
io.MousePos = ImVec2(mousePos.x, mousePos.y);
io.MouseDown[0] = mouseButtons.left;
io.MouseDown[1] = mouseButtons.right;
ImGui::NewFrame();
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0);
ImGui::SetNextWindowPos(ImVec2(10, 10));
ImGui::SetNextWindowSize(ImVec2(0, 0), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Vulkan Example", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove);
ImGui::TextUnformatted(title.c_str());
ImGui::TextUnformatted(deviceProperties.deviceName);
ImGui::Text("%.2f ms/frame (%.1d fps)", (1000.0f / lastFPS), lastFPS);
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 5.0f * UIOverlay.scale));
#endif
ImGui::PushItemWidth(110.0f * UIOverlay.scale);
OnUpdateUIOverlay(&UIOverlay);
ImGui::PopItemWidth();
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
ImGui::PopStyleVar();
#endif
ImGui::End();
ImGui::PopStyleVar();
ImGui::Render();
if (UIOverlay.update() || UIOverlay.updated) {
buildCommandBuffers();
UIOverlay.updated = false;
}
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
if (mouseButtons.left) {
mouseButtons.left = false;
}
#endif
}
void VulkanExampleBase::drawUI(const VkCommandBuffer commandBuffer)
{
if (settings.overlay) {
const VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f);
const VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0);
vkCmdSetViewport(commandBuffer, 0, 1, &viewport);
vkCmdSetScissor(commandBuffer, 0, 1, &scissor);
UIOverlay.draw(commandBuffer);
}
}
void VulkanExampleBase::prepareFrame()
{
// Acquire the next image from the swap chain
VkResult result = swapChain.acquireNextImage(semaphores.presentComplete, ¤tBuffer);
// Recreate the swapchain if it's no longer compatible with the surface (OUT_OF_DATE) or no longer optimal for presentation (SUBOPTIMAL)
if ((result == VK_ERROR_OUT_OF_DATE_KHR) || (result == VK_SUBOPTIMAL_KHR)) {
windowResize();
}
else {
VK_CHECK_RESULT(result);
}
}
void VulkanExampleBase::submitFrame()
{
VkResult result = swapChain.queuePresent(queue, currentBuffer, semaphores.renderComplete);
if (!((result == VK_SUCCESS) || (result == VK_SUBOPTIMAL_KHR))) {
if (result == VK_ERROR_OUT_OF_DATE_KHR) {
// Swap chain is no longer compatible with the surface and needs to be recreated
windowResize();
return;
} else {
VK_CHECK_RESULT(result);
}
}
VK_CHECK_RESULT(vkQueueWaitIdle(queue));
}
VulkanExampleBase::VulkanExampleBase(bool enableValidation)
{
#if !defined(VK_USE_PLATFORM_ANDROID_KHR)
// Check for a valid asset path
struct stat info;
if (stat(getAssetPath().c_str(), &info) != 0)
{
#if defined(_WIN32)
std::string msg = "Could not locate asset path in \"" + getAssetPath() + "\" !";
MessageBox(NULL, msg.c_str(), "Fatal error", MB_OK | MB_ICONERROR);
#else
std::cerr << "Error: Could not find asset path in " << getAssetPath() << std::endl;
#endif
exit(-1);
}
#endif
settings.validation = enableValidation;
char* numConvPtr;
// Parse command line arguments
for (size_t i = 0; i < args.size(); i++)
{
if (args[i] == std::string("-validation")) {
settings.validation = true;
}
if (args[i] == std::string("-vsync")) {
settings.vsync = true;
}
if ((args[i] == std::string("-f")) || (args[i] == std::string("--fullscreen"))) {
settings.fullscreen = true;
}
if ((args[i] == std::string("-w")) || (args[i] == std::string("-width"))) {
uint32_t w = strtol(args[i + 1], &numConvPtr, 10);
if (numConvPtr != args[i + 1]) { width = w; };
}
if ((args[i] == std::string("-h")) || (args[i] == std::string("-height"))) {
uint32_t h = strtol(args[i + 1], &numConvPtr, 10);
if (numConvPtr != args[i + 1]) { height = h; };
}
// Select between glsl and hlsl shaders
if ((args[i] == std::string("-s")) || (args[i] == std::string("--shaders"))) {
std::string type;
if (args.size() > i + 1) {
type = args[i + 1];
}
if (type == "glsl" || type == "hlsl") {
shaderDir = type;
} else {
std::cerr << args[i] << " must be one of 'glsl' or 'hlsl'" << std::endl;
}
}
// Benchmark
if ((args[i] == std::string("-b")) || (args[i] == std::string("--benchmark"))) {
benchmark.active = true;
vks::tools::errorModeSilent = true;
}
// Warmup time (in seconds)
if ((args[i] == std::string("-bw")) || (args[i] == std::string("--benchwarmup"))) {
if (args.size() > i + 1) {
uint32_t num = strtol(args[i + 1], &numConvPtr, 10);
if (numConvPtr != args[i + 1]) {
benchmark.warmup = num;
} else {
std::cerr << "Warmup time for benchmark mode must be specified as a number!" << std::endl;
}
}
}
// Benchmark runtime (in seconds)
if ((args[i] == std::string("-br")) || (args[i] == std::string("--benchruntime"))) {
if (args.size() > i + 1) {
uint32_t num = strtol(args[i + 1], &numConvPtr, 10);
if (numConvPtr != args[i + 1]) {
benchmark.duration = num;
}
else {
std::cerr << "Benchmark run duration must be specified as a number!" << std::endl;
}
}
}
// Bench result save filename (overrides default)
if ((args[i] == std::string("-bf")) || (args[i] == std::string("--benchfilename"))) {
if (args.size() > i + 1) {
if (args[i + 1][0] == '-') {
std::cerr << "Filename for benchmark results must not start with a hyphen!" << std::endl;
} else {
benchmark.filename = args[i + 1];
}
}
}
// Output frame times to benchmark result file
if ((args[i] == std::string("-bt")) || (args[i] == std::string("--benchframetimes"))) {
benchmark.outputFrameTimes = true;
}
}
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
// Vulkan library is loaded dynamically on Android
bool libLoaded = vks::android::loadVulkanLibrary();
assert(libLoaded);
#elif defined(_DIRECT2DISPLAY)
#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
initWaylandConnection();
#elif defined(VK_USE_PLATFORM_XCB_KHR)
initxcbConnection();
#endif
#if defined(_WIN32)
// Enable console if validation is active
// Debug message callback will output to it
if (this->settings.validation)
{
setupConsole("Vulkan validation output");
}
setupDPIAwareness();
#endif
}
VulkanExampleBase::~VulkanExampleBase()
{
// Clean up Vulkan resources
swapChain.cleanup();
if (descriptorPool != VK_NULL_HANDLE)
{
vkDestroyDescriptorPool(device, descriptorPool, nullptr);
}
destroyCommandBuffers();
vkDestroyRenderPass(device, renderPass, nullptr);
for (uint32_t i = 0; i < frameBuffers.size(); i++)
{
vkDestroyFramebuffer(device, frameBuffers[i], nullptr);
}
for (auto& shaderModule : shaderModules)
{
vkDestroyShaderModule(device, shaderModule, nullptr);
}
vkDestroyImageView(device, depthStencil.view, nullptr);
vkDestroyImage(device, depthStencil.image, nullptr);
vkFreeMemory(device, depthStencil.mem, nullptr);
vkDestroyPipelineCache(device, pipelineCache, nullptr);
vkDestroyCommandPool(device, cmdPool, nullptr);
vkDestroySemaphore(device, semaphores.presentComplete, nullptr);
vkDestroySemaphore(device, semaphores.renderComplete, nullptr);
for (auto& fence : waitFences) {
vkDestroyFence(device, fence, nullptr);
}
if (settings.overlay) {
UIOverlay.freeResources();
}
delete vulkanDevice;
if (settings.validation)
{
vks::debug::freeDebugCallback(instance);
}
vkDestroyInstance(instance, nullptr);
#if defined(_DIRECT2DISPLAY)
#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
xdg_toplevel_destroy(xdg_toplevel);
xdg_surface_destroy(xdg_surface);
wl_surface_destroy(surface);
if (keyboard)
wl_keyboard_destroy(keyboard);
if (pointer)
wl_pointer_destroy(pointer);
wl_seat_destroy(seat);
xdg_wm_base_destroy(shell);
wl_compositor_destroy(compositor);
wl_registry_destroy(registry);
wl_display_disconnect(display);
#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
// todo : android cleanup (if required)
#elif defined(VK_USE_PLATFORM_XCB_KHR)
xcb_destroy_window(connection, window);
xcb_disconnect(connection);
#endif
}
bool VulkanExampleBase::initVulkan()
{
VkResult err;
// Vulkan instance
err = createInstance(settings.validation);
if (err) {
vks::tools::exitFatal("Could not create Vulkan instance : \n" + vks::tools::errorString(err), err);
return false;
}
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
vks::android::loadVulkanFunctions(instance);
#endif
// If requested, we enable the default validation layers for debugging
if (settings.validation)
{
// The report flags determine what type of messages for the layers will be displayed
// For validating (debugging) an appplication the error and warning bits should suffice
VkDebugReportFlagsEXT debugReportFlags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
// Additional flags include performance info, loader and layer debug messages, etc.
vks::debug::setupDebugging(instance, debugReportFlags, VK_NULL_HANDLE);
}
// Physical device
uint32_t gpuCount = 0;
// Get number of available physical devices
VK_CHECK_RESULT(vkEnumeratePhysicalDevices(instance, &gpuCount, nullptr));
assert(gpuCount > 0);
// Enumerate devices
std::vector<VkPhysicalDevice> physicalDevices(gpuCount);
err = vkEnumeratePhysicalDevices(instance, &gpuCount, physicalDevices.data());
if (err) {
vks::tools::exitFatal("Could not enumerate physical devices : \n" + vks::tools::errorString(err), err);
return false;
}
// GPU selection
// Select physical device to be used for the Vulkan example
// Defaults to the first device unless specified by command line
uint32_t selectedDevice = 0;
#if !defined(VK_USE_PLATFORM_ANDROID_KHR)
// GPU selection via command line argument
for (size_t i = 0; i < args.size(); i++)
{
// Select GPU
if ((args[i] == std::string("-g")) || (args[i] == std::string("-gpu")))
{
char* endptr;
uint32_t index = strtol(args[i + 1], &endptr, 10);
if (endptr != args[i + 1])
{
if (index > gpuCount - 1)
{
std::cerr << "Selected device index " << index << " is out of range, reverting to device 0 (use -listgpus to show available Vulkan devices)" << std::endl;
}
else
{
std::cout << "Selected Vulkan device " << index << std::endl;
selectedDevice = index;
}
};
break;
}
// List available GPUs
if (args[i] == std::string("-listgpus"))
{
uint32_t gpuCount = 0;
VK_CHECK_RESULT(vkEnumeratePhysicalDevices(instance, &gpuCount, nullptr));
if (gpuCount == 0)
{
std::cerr << "No Vulkan devices found!" << std::endl;
}
else
{
// Enumerate devices
std::cout << "Available Vulkan devices" << std::endl;
std::vector<VkPhysicalDevice> devices(gpuCount);
VK_CHECK_RESULT(vkEnumeratePhysicalDevices(instance, &gpuCount, devices.data()));
for (uint32_t i = 0; i < gpuCount; i++) {
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(devices[i], &deviceProperties);
std::cout << "Device [" << i << "] : " << deviceProperties.deviceName << std::endl;
std::cout << " Type: " << vks::tools::physicalDeviceTypeString(deviceProperties.deviceType) << std::endl;
std::cout << " API: " << (deviceProperties.apiVersion >> 22) << "." << ((deviceProperties.apiVersion >> 12) & 0x3ff) << "." << (deviceProperties.apiVersion & 0xfff) << std::endl;
}
}
}
}
#endif
physicalDevice = physicalDevices[selectedDevice];
// Store properties (including limits), features and memory properties of the phyiscal device (so that examples can check against them)
vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
vkGetPhysicalDeviceFeatures(physicalDevice, &deviceFeatures);
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &deviceMemoryProperties);
// Derived examples can override this to set actual features (based on above readings) to enable for logical device creation
getEnabledFeatures();
// Vulkan device creation
// This is handled by a separate class that gets a logical device representation
// and encapsulates functions related to a device
vulkanDevice = new vks::VulkanDevice(physicalDevice);
VkResult res = vulkanDevice->createLogicalDevice(enabledFeatures, enabledDeviceExtensions, deviceCreatepNextChain);
if (res != VK_SUCCESS) {
vks::tools::exitFatal("Could not create Vulkan device: \n" + vks::tools::errorString(res), res);
return false;
}
device = vulkanDevice->logicalDevice;
// Get a graphics queue from the device
vkGetDeviceQueue(device, vulkanDevice->queueFamilyIndices.graphics, 0, &queue);
// Find a suitable depth format
VkBool32 validDepthFormat = vks::tools::getSupportedDepthFormat(physicalDevice, &depthFormat);
assert(validDepthFormat);
swapChain.connect(instance, physicalDevice, device);
// Create synchronization objects
VkSemaphoreCreateInfo semaphoreCreateInfo = vks::initializers::semaphoreCreateInfo();
// Create a semaphore used to synchronize image presentation
// Ensures that the image is displayed before we start submitting new commands to the queu
VK_CHECK_RESULT(vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphores.presentComplete));
// Create a semaphore used to synchronize command submission
// Ensures that the image is not presented until all commands have been sumbitted and executed
VK_CHECK_RESULT(vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphores.renderComplete));
// Set up submit info structure
// Semaphores will stay the same during application lifetime
// Command buffer submission info is set by each example
submitInfo = vks::initializers::submitInfo();
submitInfo.pWaitDstStageMask = &submitPipelineStages;
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &semaphores.presentComplete;
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = &semaphores.renderComplete;
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
// Get Android device name and manufacturer (to display along GPU name)
androidProduct = "";
char prop[PROP_VALUE_MAX+1];
int len = __system_property_get("ro.product.manufacturer", prop);
if (len > 0) {
androidProduct += std::string(prop) + " ";
};
len = __system_property_get("ro.product.model", prop);
if (len > 0) {
androidProduct += std::string(prop);
};
LOGD("androidProduct = %s", androidProduct.c_str());
#endif
return true;
}
#if defined(_WIN32)
// Win32 : Sets up a console window and redirects standard output to it
void VulkanExampleBase::setupConsole(std::string title)
{
AllocConsole();
AttachConsole(GetCurrentProcessId());
FILE *stream;
freopen_s(&stream, "CONOUT$", "w+", stdout);
freopen_s(&stream, "CONOUT$", "w+", stderr);
SetConsoleTitle(TEXT(title.c_str()));
}
void VulkanExampleBase::setupDPIAwareness()
{
typedef HRESULT *(__stdcall *SetProcessDpiAwarenessFunc)(PROCESS_DPI_AWARENESS);
HMODULE shCore = LoadLibraryA("Shcore.dll");
if (shCore)
{
SetProcessDpiAwarenessFunc setProcessDpiAwareness =
(SetProcessDpiAwarenessFunc)GetProcAddress(shCore, "SetProcessDpiAwareness");
if (setProcessDpiAwareness != nullptr)
{
setProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE);
}
FreeLibrary(shCore);
}
}
HWND VulkanExampleBase::setupWindow(HINSTANCE hinstance, WNDPROC wndproc)
{
this->windowInstance = hinstance;
WNDCLASSEX wndClass;
wndClass.cbSize = sizeof(WNDCLASSEX);
wndClass.style = CS_HREDRAW | CS_VREDRAW;
wndClass.lpfnWndProc = wndproc;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;