-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
3324 lines (2945 loc) · 135 KB
/
Copy pathmain.cpp
File metadata and controls
3324 lines (2945 loc) · 135 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
#include "data_types.h"
#include "helper_utilities.h"
#define STB_IMAGE_IMPLEMENTATION
#include "includeLibs/stb_image.h"
#define TINYOBJLOADER_IMPLEMENTATION
#include "includeLibs/tiny_obj_loader.h"
#include <algorithm>
#include <array>
#include <bits/stdint-uintn.h>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
// #include <format> only available in C++20 with gcc>11
#include <fstream>
#include <ios>
#include <iostream>
#include <limits>
#include <map>
#include <optional>
#include <set>
#include <stdexcept>
#include <unordered_map>
#include <vector>
#include <vulkan/vk_platform.h>
#include <vulkan/vulkan_core.h>
#include "imgui/imgui.h"
#include "imgui/imgui_impl_glfw.h"
#include "imgui/imgui_impl_vulkan.h"
#include <GLFW/glfw3native.h>
#ifdef WIN32
#include <vulkan/vulkan_win32.h>
#define VK_USE_PLATFORM_WIN32_KHR /// Platform windows support ...
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h>
#endif
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <glm/fwd.hpp>
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp> // linear algebra types
#include <glm/gtc/matrix_transform.hpp>
static void
check_vk_result(VkResult err)
{
if (err == 0)
{
return;
}
fprintf(stderr, "[vulkan] Error: VkResult = %d\n", err);
if (err < 0)
{
abort();
}
}
static float rotatingTime = 0.0f;
static std::chrono::time_point<std::chrono::high_resolution_clock> startTime
= std::chrono::high_resolution_clock::now();
static std::chrono::time_point<std::chrono::high_resolution_clock> stoppedTime;
static bool stopped = false;
class TriangleApp {
public:
void run()
{
initWindow();
initVulkan();
// initImGui();
mainLoop();
cleanup();
}
private:
bool checkValidationLayerSupport()
{
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
// check if all defined validationlayers exists in the
// availableLayersVector
for (const char *layerName : validationLayers)
{
bool layerFound = false;
for (const auto &layerProperties : availableLayers)
{
if (strcmp(layerName, layerProperties.layerName) == 0)
{
layerFound = true;
break;
}
}
if (not layerFound)
{
return false;
}
}
return true;
}
/* Vulkan does not have the concept of a default framebuffer, it requires an
* infrastructure that will own the buffers we will render to, before
* visualizing them on the screen. This is known as the swap chain and must
* be explicitly created in vulkan. Not all graphic cards are capable of
* presenting images directly to a screen. Image prsentation is heavily tied
* into the window system & the surfaces associated with windows , its not
* part of Vulkan. We have to enable VK_KHR_swapchain device extension
*
*
* */
bool checkDeviceExtensionSupport(VkPhysicalDevice device)
{
// check if all required extensions are available
uint32_t extensionCount;
vkEnumerateDeviceExtensionProperties(
device, nullptr, &extensionCount, nullptr);
std::vector<VkExtensionProperties> availableExtensions(extensionCount);
vkEnumerateDeviceExtensionProperties(
device, nullptr, &extensionCount, availableExtensions.data());
std::set<std::string> requiredExtensions(deviceExtensions.begin(),
deviceExtensions.end());
for (const auto &extension : availableExtensions)
{
requiredExtensions.erase(extension.extensionName);
}
return requiredExtensions.empty();
}
void initWindow()
{
glfwInit();
glfwWindowHint(GLFW_CLIENT_API,
GLFW_NO_API); /// do not a OpenGL context
glfwWindowHint(GLFW_RESIZABLE,
GLFW_FALSE); // FIXME: resizing window lead to crashes,
// so I disabled it for now using a bigger
// resolution instead
window = glfwCreateWindow(
WINDOW_WIDTH,
WINDOW_HEIGHT,
"Earth 3D",
nullptr,
nullptr); /// optionally specify a monitor to open the window on,
/// last parameter relevant to OpenGL
glfwSetWindowUserPointer(window, this); /// store an arbitrary
glfwSetFramebufferSizeCallback(window, framebufferResizeCallback);
}
// static function bc GLFW does not know how to properly call a member
// function with the right this pointer to our instance
static void
framebufferResizeCallback(GLFWwindow *window, int width, int height)
{
auto app
= reinterpret_cast<TriangleApp *>(glfwGetWindowUserPointer(window));
app->framebufferResized = true;
}
void initVulkan()
{
createInstance();
setupDebugMessenger();
setupWindowSurface();
pickPhysicalDevice();
createLogicalDevice();
createSwapChain();
createImageViews();
createRenderPass();
createDescriptorSetLayout();
createGraphicsPipeline();
createCommandPool();
createDepthRessources();
createFrameBuffers();
createTextureImage();
createTextureImageView();
createTextureSampler();
loadModels();
createVertexBuffer();
createIndexBuffer();
createUniformBuffers();
createDescriptorPool();
createDescriptorSets();
createCommandBuffers();
createSyncObjects();
}
VkCommandBuffer BeginSingleTimeCommands(VkDevice device,
VkCommandPool commandPool)
{
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
return commandBuffer;
}
void EndSingleTimeCommands(VkDevice device,
VkCommandPool commandPool,
VkQueue graphicsQueue,
VkCommandBuffer commandBuffer)
{
vkEndCommandBuffer(commandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
// === ImGui ===
glm::vec3 eyeVec{1.8f, 1.8f, 1.8f};
glm::vec3 centerVec{1.5f, 1.5f, 1.5f};
glm::vec3 upVec{0.f, 0.f, 1.f};
glm::vec3 initialRotationAxis{1.0f, 0.0f, 0.0f};
float m_initialRotationDegrees{90.0f};
glm::vec3 rotationAxis{0.0f, 1.0f, 0.0f};
float lastRotationSpeed{7.5f};
float m_rotationSpeed{7.5f};
bool isRotating{true};
float m_fieldOfView{45.0f};
float m_zNear{0.1f};
float m_zFar{10.0f};
void setEyeVector(float x, float y, float z)
{
eyeVec[0] = x;
eyeVec[1] = y;
eyeVec[2] = z;
}
void setCenterVector(float x, float y, float z)
{
centerVec[0] = x;
centerVec[1] = y;
centerVec[2] = z;
}
void setUpVector(float x, float y, float z)
{
upVec[0] = x;
upVec[1] = y;
upVec[2] = z;
}
void toggleRotation()
{
if (isRotating)
{
isRotating = false;
lastRotationSpeed = m_rotationSpeed;
m_rotationSpeed = 1.0f;
} else
{
isRotating = true;
m_rotationSpeed = lastRotationSpeed;
}
}
void setRotationAxis(bool axisPressed[3])
{
rotationAxis = {axisPressed[0], axisPressed[1], axisPressed[2]};
}
void setInitialRotation(float initRotationDegrees)
{
m_initialRotationDegrees = initRotationDegrees;
}
void setInitialRotationSpeed(float speed) { m_rotationSpeed = speed; }
void setFielOfView(float fieldOfView) { m_fieldOfView = fieldOfView; }
void setZNear(float zNear) { m_zNear = zNear; }
void setZFar(float zFar) { m_zFar = zFar; }
bool show_demo_window = false;
bool show_another_window = false;
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
VkResult err;
void drawImGui(
std::chrono::time_point<std::chrono::high_resolution_clock> startTime)
{
ImGui_ImplVulkan_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
if (show_demo_window)
{
ImGui::ShowDemoWindow(); // Show demo window! :)
} // 3. Show another simple window.
{
ImGuiIO &io = ImGui::GetIO();
static float f = 0.0f;
static int counter = 0;
ImGui::Begin("SolarSystem 3DV - Preferences");
{
if (ImGui::CollapsingHeader("Model - View - Projection"))
{
if (ImGui::TreeNode("Model - (rotation)"))
{
static bool isRotating = true;
static float initialRotationDegrees = {90.0f};
static float initialRotationSpeed = {7.5f};
ImGui::Text("Initial rotation");
if (ImGui::Checkbox("rotate", &isRotating))
{
toggleRotation();
}
ImGui::SameLine();
static bool axisPressed[3] = {false, true, false};
if (ImGui::Checkbox("x", &axisPressed[0]))
{
setRotationAxis(axisPressed);
}
ImGui::SameLine();
if (ImGui::Checkbox("y", &axisPressed[1]))
{
setRotationAxis(axisPressed);
}
ImGui::SameLine();
if (ImGui::Checkbox("z", &axisPressed[2]))
{
setRotationAxis(axisPressed);
}
ImGui::SetNextItemWidth(80.0f);
if (ImGui::SliderFloat("Degrees",
&initialRotationDegrees,
0.0f,
360.0f))
{
setInitialRotation(initialRotationDegrees);
}
ImGui::SameLine();
ImGui::SetNextItemWidth(80.0f);
if (ImGui::SliderFloat(
"Speed", &initialRotationSpeed, 0.0f, 100.0f))
{
setInitialRotationSpeed(initialRotationSpeed);
}
ImGui::TreePop();
}
if (ImGui::TreeNode("View - (lookAt)"))
{
static float eyeVector[4] = {1.8f, 1.8f, 1.8f, 0.44f};
static float centerVector[4]
= {1.5f, 1.5f, 1.5f, 0.44f};
static bool upVector[3] = {false, false, true};
if (ImGui::SliderFloat3(
"eye (x,y,z)", eyeVector, 0.1f, 4.0f))
{
setEyeVector(
eyeVector[0], eyeVector[1], eyeVector[2]);
}
if (ImGui::SliderFloat3(
"center (x,y,z)", centerVector, 0.1f, 4.0f))
{
setCenterVector(centerVector[0],
centerVector[1],
centerVector[2]);
}
ImGui::Text("upvector: ");
ImGui::SameLine();
if (ImGui::Checkbox("x", &upVector[0]))
{
upVector[0] = true;
upVector[1] = false;
upVector[2] = false;
setUpVector(1.0f, 0.0f, 0.0f);
}
ImGui::SameLine();
if (ImGui::Checkbox("y", &upVector[1]))
{
upVector[0] = false;
upVector[1] = true;
upVector[2] = false;
setUpVector(0.0f, 1.0f, 0.0f);
}
ImGui::SameLine();
if (ImGui::Checkbox("z", &upVector[2]))
{
upVector[0] = false;
upVector[1] = false;
upVector[2] = true;
setUpVector(0.0f, 0.0f, 1.0f);
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Projection - (perspective)"))
{
static float foV{45.0f};
static float zNear{0.1f};
static float zFar{10.0f};
if (ImGui::SliderFloat(
"Fiel of view ", &foV, 0.1f, 360.0f))
{
setFielOfView(foV);
}
if (ImGui::SliderFloat("zNear", &zNear, 0.1f, zFar))
{
setZNear(zNear);
}
if (ImGui::SliderFloat("zFar", &zFar, 10.0f, 35.0f))
{
setZFar(zFar);
}
ImGui::TreePop();
}
}
ImGui::Checkbox("Demo Window",
&show_demo_window); // Edit bools storing our
// window open/close state
ImGui::Spacing();
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)",
1000.0f / io.Framerate,
io.Framerate);
ImGui::Text("StartTime rotating earth: %s ",
time_point_to_string(startTime).c_str());
}
ImGui::End();
}
// last line
ImGui::Render();
}
void initImGui()
{
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO &io = ImGui::GetIO();
io.ConfigFlags
|= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.ConfigFlags
|= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// io.ConfigFlags
// |= ImGuiConfigFlags_DockingEnable; // IF using Docking Branch
// Setup Dear ImGui style
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForVulkan(
window, true); // Second param install_callback=true will install
// GLFW callbacks and chain to existing ones.
ImGui_ImplVulkan_InitInfo init_info = {};
init_info.Instance = instance;
init_info.PhysicalDevice = physicalDevice;
init_info.Device = device;
init_info.QueueFamily = graphicsQueueFamily;
init_info.Queue = graphicsQueue;
init_info.PipelineCache = VK_NULL_HANDLE;
init_info.DescriptorPool = descriptorPool;
init_info.RenderPass = renderPass;
init_info.Subpass = 0;
init_info.MinImageCount = 2;
init_info.ImageCount = MAX_FRAMES_IN_FLIGHT;
init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT;
init_info.Allocator = nullptr;
init_info.CheckVkResultFn = check_vk_result;
ImGui_ImplVulkan_Init(&init_info);
// FIXME: probably the same command buffer like for the normal
// renderstuff this section is probably not needable
VkCommandBuffer command_buffer = BeginSingleTimeCommands(
device, commandPool); // Helper function to begin command buffer
ImGui_ImplVulkan_CreateFontsTexture(); // command_buffer);
EndSingleTimeCommands(
device,
commandPool,
graphicsQueue,
command_buffer); // Helper function to end command buffer
// ImGui_ImplVulkan_DestroyFontUploadObjects();
ImGui_ImplVulkan_DestroyFontsTexture();
}
void destroyImGui()
{
ImGui_ImplVulkan_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
void mainLoop()
{
initImGui();
while (not glfwWindowShouldClose(window))
{
glfwPollEvents();
drawFrame();
}
// as all operations are async in drawFrame() & when exiting the
// mainLoop, drawing amy still be going on, cleaning things up while
// drawing is a bad idea
err = vkDeviceWaitIdle(device);
check_vk_result(err);
destroyImGui();
}
/**
* Rendering a frame in Vulkan consists of a common set of steps
* - Wait for the previous frame to finish
* - Acquire an image from the swap chain
* - Record a command buffer which draws the scene onto that image
* - Submit the recorded command buffer
* - Present the swap chain image
* */
void drawFrame()
{
// static auto startTime = std::chrono::high_resolution_clock::now();
drawImGui(startTime);
// synchronization of execution on the GPU is explicit
// the order of operations is up to us
// many Vulkan API calls are asychronous
// these calls will return before the operations are actually finished
// & the order of execution is also undefined
// each of the operations depends on the previous one finishing
// using a semaphore to add order between queue operations
// semaphore are used to order work inside the same & different queues
// there two kinds of semaphores in Vulkan: binary & timeline, we use
// binary here its either unsignaled or signaled we use it as signal
// semaphore in one queue operation & as a wait operation in another
// queue operation, for ordering execution on the CPU we use a fence as
// a similar mechanism
// -> if the host needs to know when the GPU has finished something we
// use a fence
// -> semaphores are used to specify the execution of order of
// operations on the GPU
// -> fences are used to keep the CPU&GPU in sync with each other. We
// want to use semaphores for swapchain operations (they happen on the
// GPU) for waiting on the previous frame to finish we want to use
// fences, we need the host to wait (CPU)
vkWaitForFences(device,
1,
&inFlightFences[currentFrame],
VK_TRUE,
UINT64_MAX); /// disabled with UINT64_MAX the timeout
uint32_t imageIndex;
VkResult result
= vkAcquireNextImageKHR(device,
swapChain,
UINT64_MAX,
imageAvailableSemaphores[currentFrame],
VK_NULL_HANDLE,
&imageIndex);
if (result == VK_ERROR_OUT_OF_DATE_KHR)
{ /// The swap chain has become incompatible
/// with the surface and can no longer be
/// used for rendering. Usually happens
/// after a window resize.
recreateSwapChain();
return;
} else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR)
{ /// VK_SUBOPTIMAL_KHR: The swap chain
/// can still be used to successfully
/// present to the surface, but the
/// surface properties are no longer
/// matched exactly.
throw std::runtime_error("failed to aquire swap chain image!");
}
if (isRotating)
{
if (stopped)
{
// If we were previously stopped, calculate the accumulated time
auto resumeTime = std::chrono::high_resolution_clock::now();
auto accumulatedDuration = resumeTime - stoppedTime;
rotatingTime
+= std::chrono::duration<float>(accumulatedDuration)
.count();
stopped = false;
}
// Update the current time and calculate the new time
auto currentTime = std::chrono::high_resolution_clock::now();
rotatingTime
= std::chrono::duration<float>(currentTime - startTime).count();
} else
{
if (!stopped)
{
// Record the time when rotation is stopped
stoppedTime = std::chrono::high_resolution_clock::now();
stopped = true;
}
}
glm::mat4 finalModelMatrix = rotateModel(initialRotationAxis,
m_initialRotationDegrees,
rotationAxis,
m_rotationSpeed,
rotatingTime);
updateUniformBuffer(currentFrame, finalModelMatrix);
// only reset the fence if we are submitting work
vkResetFences(device, 1, &inFlightFences[currentFrame]);
// with the imageIndex spec. the swapchain image we can now record the
// command buffer
//
vkResetCommandBuffer(commandBuffers[currentFrame], 0);
recordCommandBuffer(commandBuffers[currentFrame], imageIndex);
// queue submission of the command buffer
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkSemaphore waitSemaphores[] = {imageAvailableSemaphores[currentFrame]};
VkPipelineStageFlags waitStages[]
= {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT};
// for details see Tutorial: submitting the command buffer
// which semaphore to wait on before the execution begins & in which
// stages the pipeline to wait
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = waitSemaphores;
submitInfo.pWaitDstStageMask = waitStages;
// which command buffer to submit for execution
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffers[currentFrame];
// which semaphores to signal once the command buffer(s) have finished
// execution
VkSemaphore signalSemaphores[]
= {renderFinishedSemaphores[currentFrame]};
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphores;
if (vkQueueSubmit(
graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame])
!= VK_SUCCESS)
{
throw std::runtime_error("failed to submit draw command buffer");
}
// last step to draw is submitting the result back to the swap chain to
// show it on the screen
VkPresentInfoKHR presentInfo{};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = signalSemaphores;
VkSwapchainKHR swapChains[] = {swapChain};
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
presentInfo.pResults = nullptr; // optional
// OMG: after >1400 lines of code we see a triangle. Congratulation :D
result = vkQueuePresentKHR(presentQueue, &presentInfo);
// returns the same values as vkAquireNextImageKHR, also recreate
// swapChain if its suboptimal, bc we want the best possible result
if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR
|| framebufferResized)
{
framebufferResized = false;
recreateSwapChain();
} else if (result != VK_SUCCESS)
{
throw std::runtime_error("failed to present swap chain image!");
}
// advance to next frame here (before ImGui integration)
currentFrame
= (currentFrame + 1)
% MAX_FRAMES_IN_FLIGHT; /// By using the modulo (%) operator,
/// we ensure that the frame index
/// loops around after every
/// MAX_FRAMES_IN_FLIGHT enqueued
/// frames.
// rotateModel(Axis::Y, 90.f, currentFrame);
}
glm::mat4 rotateModel(const glm::vec3 &initialRotationAxis,
float initialRotationAngle,
const glm::vec3 &timeRotationAxis,
float rotationSpeed,
float time)
{
// identity matrix
glm::mat4 model = glm::mat4(1.0f);
model = glm::rotate(model, initialRotationAngle, initialRotationAxis);
// if time > 1 & using a rotation angle of
// * time * glm::radians(degrees) accomplishes the purpose of rotation
// * DEGREES degrees per second.
// time-based rotationangle
float angle;
static float lastAngle;
static float
lastTime; // FIXME: how to pause the timer and when
// resuming continue from there, there are some overwrites
// or st. rotationpause / continue does not work correctly
angle = time * glm::radians(rotationSpeed);
if (isRotating)
{
lastAngle = angle;
} else
{
angle = lastAngle;
}
/**
* The glm::rotate function takes an existing transformation, rotation
* angle and rotation axis as parameters. The glm::mat4(1.0f)
* constructor returns an identity matrix. Using a rotation angle of
* time * glm::radians(degrees) accomplishes the purpose of rotation
* DEGREES degrees per second.
* */
model = glm::rotate(model, angle, timeRotationAxis);
return model;
}
/**
* Generate a new transformation every frame to make the geometry spin
* around. Using a UBO this way is not the most efficient way to pass
* frequently changing values to the shader. A more efficient way to pass a
* small buffer of data to shaders are push constants. Upcoming !
* */
void updateUniformBuffer(uint32_t currentImage, glm::mat4 modelMatrix)
{
UniformBufferObject ubo{};
ubo.model = modelMatrix;
/**
* view transformation: look at the geometry from above at a 45 degree
* angle. The glm::lookAt function takes the eye position, center
* position and up axis as parameters.
* */
ubo.view = glm::lookAt(eyeVec, centerVec, upVec);
/**
* Perspective projection with a 45 degree vertical field-of-view. The
* other parameters are the aspect ratio, near and far view planes. It
* is important to use the current swap chain extent to calculate the
* aspect ratio to take into account the new width and height of the
* window after a resize.
* */
ubo.proj = glm::perspective(glm::radians(m_fieldOfView),
swapChainExtent.width
/ (float)swapChainExtent.height,
m_zNear,
m_zFar);
// GLM was originally designed for OpenGL, where the Y coordinate of the
// clip coordinates is inverted. The easiest way to compensate for that
// is to flip the sign on the scaling factor of the Y axis in the
// projection matrix. If you don’t do this, then the image will be
// rendered upside down
ubo.proj[1][1] *= -1;
memcpy(uniformBuffersMapped[currentImage], &ubo, sizeof(ubo));
}
void cleanup()
{
cleanUpSwapChain();
vkDestroySampler(device, textureSampler, nullptr);
vkDestroyImageView(device, textureImageView, nullptr);
vkDestroyImage(device, textureImage, nullptr);
vkFreeMemory(device, textureImageMemory, nullptr);
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
{
vkDestroyBuffer(device, uniformBuffers[i], nullptr);
vkFreeMemory(device, uniformBuffersMemory[i], nullptr);
}
vkDestroyDescriptorPool(
device, descriptorPool, nullptr); // also cleans up DescriptorSets
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
vkDestroyBuffer(device, indexBuffer, nullptr);
vkFreeMemory(device, indexBufferMemory, nullptr);
vkDestroyBuffer(device, vertexBuffer, nullptr);
vkFreeMemory(device, vertexBufferMemory, nullptr);
vkDestroyPipeline(device, graphicsPipeline, nullptr);
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
vkDestroyRenderPass(device, renderPass, nullptr);
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
{
vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
vkDestroyFence(device, inFlightFences[i], nullptr);
}
vkDestroyCommandPool(device, commandPool, nullptr);
// destroy the instance right before the window
vkDestroyDevice(device, nullptr);
// must be destroyed before the instance -> to validate all code after
// this we can use a separate debug utils messenger
if (enableValidationLayers)
{
DestroyDebugUtilsMessengerEXT(instance, debugMesseger, nullptr);
}
vkDestroySurfaceKHR(instance,
surface,
nullptr); /// surface need to be destroyed before
/// the instance destruction !
vkDestroyInstance(instance, nullptr);
glfwDestroyWindow(window);
std::cout << "Cleanup!" << std::endl;
glfwTerminate();
}
void cleanUpSwapChain()
{
for (auto framebuffer : swapChainFramebuffers)
{
vkDestroyFramebuffer(device, framebuffer, nullptr);
}
for (auto imageView : swapChainImageViews)
{
vkDestroyImageView(device, imageView, nullptr);
}
vkDestroySwapchainKHR(device, swapChain, nullptr);
}
/**
* There is no global state in Vulkan and all per-application state is
* stored in a VkInstance object. Creating a VkInstance object initializes
* the Vulkan library and allows the application to pass information about
* itself to the implementation.
* */
void createInstance()
{
// 0. check for validationLayers (debugging)
if (enableValidationLayers && not checkValidationLayerSupport())
{
throw std::runtime_error(
"validation layers requested, but not available!");
}
// 1. set information about application
VkApplicationInfo appInfo{};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Earth 3D";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "No Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;
// 2. another nonoptional struct to fill for the instance
VkInstanceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
auto extensions = getRequiredExtensions();
createInfo.enabledExtensionCount = static_cast<uint32_t>(
extensions.size()); // standard: glfwExtensionCount;
createInfo.ppEnabledExtensionNames
= extensions.data(); // stadnard: glfwExtension;
VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo{};
// global validation layer determination, only available in debug build
if (enableValidationLayers)
{
createInfo.enabledLayerCount
= static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
populateDebugMessengerCreateInfo(debugCreateInfo);
debugCreateInfo.pNext
= (VkDebugUtilsMessengerCreateInfoEXT *)&debugCreateInfo;
} else
{
createInfo.enabledLayerCount = 0;
createInfo.pNext = nullptr;
}
// could check for extension support (see instance page bottom)
// ...
//
// 3. finally create the instance and check result
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS)
{
throw std::runtime_error("failed to create instance");
}
}
// for setting up a callback to handle messages and details for the
// validation layer
std::vector<const char *> getRequiredExtensions()
{
uint32_t glfwExtensionCount = 0;
const char **glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
std::vector<const char *> extensions(
glfwExtensions, glfwExtensions + glfwExtensionCount);
if (enableValidationLayers)
{
extensions.push_back(
VK_EXT_DEBUG_UTILS_EXTENSION_NAME); // to avoid typos we use the
// macro
}
return extensions;
}
// debug callback, VKAPI_ATTR / VKAPI_CALL ensure the right signature for
// Vulkan
static VKAPI_ATTR VkBool32 VKAPI_CALL
debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT
messageSeverity, /// Diag, Info, prop. Bug, Invalid
VkDebugUtilsMessageTypeFlagsEXT
messageType, /// unrelated to spec or perf.,
/// spec-violation, non-optimal Vulkan-use
const VkDebugUtilsMessengerCallbackDataEXT
*pCallbackData, /// details of the message
void *pUserData) /// pass own userdata
{
std::cerr << "validation layer: " << pCallbackData->pMessage
<< std::endl;
return VK_FALSE; /// if true the call is aborted with
/// VK_ERROR_VALIDATION_FAILED_EXT
}
// window need to be setup right after the instance creation, it can
// influence the physical device selection window surfaces are optional
// component of vulkan (e.g. one need off-screen rendering)
void setupWindowSurface()
{
#ifdef WIN32
// Windows specific code:
VkWin32SurfaceCreateInfoKHR createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
createInfo.hwnd = glfwGetWin32Window(window);
createInfo.hinstance = GetModuleHandle(nullptr);
if (vkCreateWin32SurfaceKHR(instance, &createInfo, nullptr, &surface)