-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy path36_multiple_objects.cpp
More file actions
1744 lines (1514 loc) · 63.2 KB
/
36_multiple_objects.cpp
File metadata and controls
1744 lines (1514 loc) · 63.2 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 <algorithm>
#include <array>
#include <assert.h>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <limits>
#include <memory>
#include <optional>
#include <stdexcept>
#include <vector>
#if defined(__INTELLISENSE__) || !defined(USE_CPP20_MODULES)
# include <vulkan/vulkan_raii.hpp>
#else
import vulkan_hpp;
#endif
#if defined(__ANDROID__)
# include <vulkan/vulkan_android.h>
# include <vulkan/vulkan_core.h>
#endif
#include <vulkan/vulkan_profiles.hpp>
#if defined(__ANDROID__)
# define PLATFORM_ANDROID 1
#else
# define PLATFORM_DESKTOP 1
#endif
// Include tinygltf instead of tinyobjloader
// TINYGLTF_IMPLEMENTATION is already defined in the command line
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <tiny_gltf.h>
// Include KTX library for texture loading
#include <ktx.h>
#if PLATFORM_ANDROID
# include <android/asset_manager.h>
# include <android/asset_manager_jni.h>
# include <android/log.h>
# include <game-activity/native_app_glue/android_native_app_glue.h>
// Declare and implement app_dummy function from native_app_glue
extern "C" void app_dummy()
{
// This is a dummy function that does nothing
// It's used to prevent the linker from stripping out the native_app_glue code
}
// Define AAssetManager type for Android
typedef AAssetManager AssetManagerType;
# define LOGI(...) ((void) __android_log_print(ANDROID_LOG_INFO, "VulkanTutorial", __VA_ARGS__))
# define LOGW(...) ((void) __android_log_print(ANDROID_LOG_WARN, "VulkanTutorial", __VA_ARGS__))
# define LOGE(...) ((void) __android_log_print(ANDROID_LOG_ERROR, "VulkanTutorial", __VA_ARGS__))
#else
// Define AAssetManager type for non-Android platforms
typedef void AssetManagerType;
// Desktop-specific includes
# define GLFW_INCLUDE_VULKAN
# include <GLFW/glfw3.h>
// Define logging macros for Desktop
# define LOGI(...) \
printf(__VA_ARGS__); \
printf("\n")
# define LOGW(...) \
printf(__VA_ARGS__); \
printf("\n")
# define LOGE(...) \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n")
#endif
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#define GLM_ENABLE_EXPERIMENTAL
#define GLM_FORCE_CXX11
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/hash.hpp>
constexpr uint32_t WIDTH = 800;
constexpr uint32_t HEIGHT = 600;
// Update paths to use glTF model and KTX2 texture
const std::string MODEL_PATH = "models/viking_room.glb";
const std::string TEXTURE_PATH = "textures/viking_room.ktx2";
constexpr int MAX_FRAMES_IN_FLIGHT = 2;
// Define the number of objects to render
constexpr int MAX_OBJECTS = 3;
// Define VpProfileProperties structure for Android only
#if PLATFORM_ANDROID
# ifndef VP_PROFILE_PROPERTIES_DEFINED
# define VP_PROFILE_PROPERTIES_DEFINED
struct VpProfileProperties
{
char name[256];
uint32_t specVersion;
};
# endif
#endif
// Define Vulkan Profile constants
#ifndef VP_KHR_ROADMAP_2022_NAME
# define VP_KHR_ROADMAP_2022_NAME "VP_KHR_roadmap_2022"
#endif
#ifndef VP_KHR_ROADMAP_2022_SPEC_VERSION
# define VP_KHR_ROADMAP_2022_SPEC_VERSION 1
#endif
struct AppInfo
{
bool profileSupported = false;
VpProfileProperties profile;
};
#if PLATFORM_ANDROID
void android_main(android_app *app);
struct AndroidAppState
{
ANativeWindow *nativeWindow = nullptr;
bool initialized = false;
android_app *app = nullptr;
};
#endif
#ifdef NDEBUG
constexpr bool enableValidationLayers = false;
#else
constexpr bool enableValidationLayers = true;
#endif
struct Vertex
{
glm::vec3 pos;
glm::vec3 color;
glm::vec2 texCoord;
static vk::VertexInputBindingDescription getBindingDescription()
{
return {0, sizeof(Vertex), vk::VertexInputRate::eVertex};
}
static std::array<vk::VertexInputAttributeDescription, 3> getAttributeDescriptions()
{
return {
vk::VertexInputAttributeDescription(0, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, pos)),
vk::VertexInputAttributeDescription(1, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, color)),
vk::VertexInputAttributeDescription(2, 0, vk::Format::eR32G32Sfloat, offsetof(Vertex, texCoord))};
}
bool operator==(const Vertex &other) const
{
return pos == other.pos && color == other.color && texCoord == other.texCoord;
}
};
template <>
struct std::hash<Vertex>
{
size_t operator()(Vertex const &vertex) const noexcept
{
return ((hash<glm::vec3>()(vertex.pos) ^ (hash<glm::vec3>()(vertex.color) << 1)) >> 1) ^ (hash<glm::vec2>()(vertex.texCoord) << 1);
}
};
// Define a structure to hold per-object data
struct GameObject
{
// Transform properties
glm::vec3 position = {0.0f, 0.0f, 0.0f};
glm::vec3 rotation = {0.0f, 0.0f, 0.0f};
glm::vec3 scale = {1.0f, 1.0f, 1.0f};
// Uniform buffer for this object (one per frame in flight)
std::vector<vk::raii::Buffer> uniformBuffers;
std::vector<vk::raii::DeviceMemory> uniformBuffersMemory;
std::vector<void *> uniformBuffersMapped;
// Descriptor sets for this object (one per frame in flight)
std::vector<vk::raii::DescriptorSet> descriptorSets;
// Calculate model matrix based on position, rotation, and scale
glm::mat4 getModelMatrix() const
{
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, position);
model = glm::rotate(model, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
model = glm::rotate(model, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
model = glm::rotate(model, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
model = glm::scale(model, scale);
return model;
}
};
struct UniformBufferObject
{
alignas(16) glm::mat4 model;
alignas(16) glm::mat4 view;
alignas(16) glm::mat4 proj;
};
class VulkanApplication
{
public:
#if PLATFORM_ANDROID
void cleanupAndroid()
{
// Clean up resources in each GameObject
for (auto &gameObject : gameObjects)
{
// Unmap memory
for (size_t i = 0; i < gameObject.uniformBuffersMemory.size(); i++)
{
if (gameObject.uniformBuffersMapped[i] != nullptr)
{
gameObject.uniformBuffersMemory[i].unmapMemory();
}
}
// Clear vectors to release resources
gameObject.uniformBuffers.clear();
gameObject.uniformBuffersMemory.clear();
gameObject.uniformBuffersMapped.clear();
gameObject.descriptorSets.clear();
}
}
void run(android_app *app)
{
androidAppState.nativeWindow = app->window;
androidAppState.app = app;
app->userData = &androidAppState;
app->onAppCmd = handleAppCommand;
// Note: onInputEvent is no longer a member of android_app in the current NDK version
// Input events are now handled differently
int events;
android_poll_source *source;
while (app->destroyRequested == 0)
{
while (ALooper_pollOnce(androidAppState.initialized ? 0 : -1, nullptr, &events, (void **) &source) >= 0)
{
if (source != nullptr)
{
source->process(app, source);
}
}
if (androidAppState.initialized && androidAppState.nativeWindow != nullptr)
{
drawFrame();
}
}
if (androidAppState.initialized)
{
device.waitIdle();
cleanupAndroid();
}
}
#else
void run()
{
initWindow();
initVulkan();
mainLoop();
cleanup();
}
#endif
private:
#if PLATFORM_ANDROID
AndroidAppState androidAppState;
static void handleAppCommand(android_app *app, int32_t cmd)
{
auto *appState = static_cast<AndroidAppState *>(app->userData);
switch (cmd)
{
case APP_CMD_INIT_WINDOW:
if (app->window != nullptr)
{
appState->nativeWindow = app->window;
// We can't cast AndroidAppState to VulkanApplication directly
// Instead, we need to access the VulkanApplication instance through a global variable
// or another mechanism. For now, we'll just set the initialized flag.
appState->initialized = true;
}
break;
case APP_CMD_TERM_WINDOW:
appState->nativeWindow = nullptr;
break;
default:
break;
}
}
static int32_t handleInputEvent(android_app *app, AInputEvent *event)
{
if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION)
{
float x = AMotionEvent_getX(event, 0);
float y = AMotionEvent_getY(event, 0);
LOGI("Touch at: %f, %f", x, y);
return 1;
}
return 0;
}
#else
GLFWwindow *window = nullptr;
#endif
AppInfo appInfo = {};
vk::raii::Context context;
vk::raii::Instance instance = nullptr;
vk::raii::DebugUtilsMessengerEXT debugMessenger = nullptr;
vk::raii::SurfaceKHR surface = nullptr;
vk::raii::PhysicalDevice physicalDevice = nullptr;
vk::raii::Device device = nullptr;
uint32_t queueIndex = ~0;
vk::raii::Queue queue = nullptr;
vk::raii::SwapchainKHR swapChain = nullptr;
std::vector<vk::Image> swapChainImages;
vk::SurfaceFormatKHR swapChainSurfaceFormat;
vk::Extent2D swapChainExtent;
std::vector<vk::raii::ImageView> swapChainImageViews;
vk::raii::DescriptorSetLayout descriptorSetLayout = nullptr;
vk::raii::PipelineLayout pipelineLayout = nullptr;
vk::raii::Pipeline graphicsPipeline = nullptr;
vk::raii::Image depthImage = nullptr;
vk::raii::DeviceMemory depthImageMemory = nullptr;
vk::raii::ImageView depthImageView = nullptr;
vk::raii::Image textureImage = nullptr;
vk::raii::DeviceMemory textureImageMemory = nullptr;
vk::raii::ImageView textureImageView = nullptr;
vk::raii::Sampler textureSampler = nullptr;
vk::Format textureImageFormat = vk::Format::eUndefined;
std::vector<Vertex> vertices;
std::vector<uint32_t> indices;
vk::raii::Buffer vertexBuffer = nullptr;
vk::raii::DeviceMemory vertexBufferMemory = nullptr;
vk::raii::Buffer indexBuffer = nullptr;
vk::raii::DeviceMemory indexBufferMemory = nullptr;
// Array of game objects to render
std::array<GameObject, MAX_OBJECTS> gameObjects;
vk::raii::DescriptorPool descriptorPool = nullptr;
vk::raii::CommandPool commandPool = nullptr;
std::vector<vk::raii::CommandBuffer> commandBuffers;
std::vector<vk::raii::Semaphore> presentCompleteSemaphores;
std::vector<vk::raii::Semaphore> renderFinishedSemaphores;
std::vector<vk::raii::Fence> inFlightFences;
uint32_t frameIndex = 0;
bool framebufferResized = false;
std::vector<const char *> requiredDeviceExtension = {
vk::KHRSwapchainExtensionName,
vk::KHRCreateRenderpass2ExtensionName};
#if PLATFORM_DESKTOP
void initWindow()
{
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
window = glfwCreateWindow(WIDTH, HEIGHT, "Vulkan", nullptr, nullptr);
glfwSetWindowUserPointer(window, this);
glfwSetFramebufferSizeCallback(window, framebufferResizeCallback);
}
static void framebufferResizeCallback(GLFWwindow *window, int width, int height)
{
auto app = static_cast<VulkanApplication *>(glfwGetWindowUserPointer(window));
app->framebufferResized = true;
}
#endif
public:
void initVulkan()
{
createInstance();
setupDebugMessenger();
createSurface();
pickPhysicalDevice();
createLogicalDevice();
createSwapChain();
createImageViews();
createDescriptorSetLayout();
createGraphicsPipeline();
createCommandPool();
createDepthResources();
createTextureImage();
createTextureImageView();
createTextureSampler();
loadModel();
createVertexBuffer();
createIndexBuffer();
setupGameObjects();
createUniformBuffers();
createDescriptorPool();
createDescriptorSets();
createCommandBuffers();
createSyncObjects();
}
private:
#if PLATFORM_DESKTOP
void mainLoop()
{
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
drawFrame();
}
device.waitIdle();
}
#endif
void cleanupSwapChain()
{
swapChainImageViews.clear();
swapChain = nullptr;
}
#if PLATFORM_DESKTOP
void cleanup()
{
// Clean up resources in each GameObject
for (auto &gameObject : gameObjects)
{
// Unmap memory
for (size_t i = 0; i < gameObject.uniformBuffersMemory.size(); i++)
{
if (gameObject.uniformBuffersMapped[i] != nullptr)
{
gameObject.uniformBuffersMemory[i].unmapMemory();
}
}
// Clear vectors to release resources
gameObject.uniformBuffers.clear();
gameObject.uniformBuffersMemory.clear();
gameObject.uniformBuffersMapped.clear();
gameObject.descriptorSets.clear();
}
// Clean up GLFW resources
glfwDestroyWindow(window);
glfwTerminate();
}
#endif
void recreateSwapChain()
{
#if PLATFORM_DESKTOP
int width = 0, height = 0;
glfwGetFramebufferSize(window, &width, &height);
while (width == 0 || height == 0)
{
glfwGetFramebufferSize(window, &width, &height);
glfwWaitEvents();
}
#endif
device.waitIdle();
cleanupSwapChain();
createSwapChain();
createImageViews();
createDepthResources();
}
void createInstance()
{
constexpr vk::ApplicationInfo appInfo{
.pApplicationName = "Hello Triangle",
.applicationVersion = VK_MAKE_VERSION(1, 0, 0),
.pEngineName = "No Engine",
.engineVersion = VK_MAKE_VERSION(1, 0, 0),
.apiVersion = VK_API_VERSION_1_3};
auto extensions = getRequiredInstanceExtensions();
vk::InstanceCreateInfo createInfo{
.pApplicationInfo = &appInfo,
.enabledExtensionCount = static_cast<uint32_t>(extensions.size()),
.ppEnabledExtensionNames = extensions.data()};
instance = vk::raii::Instance(context, createInfo);
LOGI("Vulkan instance created");
}
void setupDebugMessenger()
{
// Debug messenger setup is disabled for now to avoid compatibility issues
// This is a simplified approach to get the code compiling
if (!enableValidationLayers)
return;
LOGI("Debug messenger setup skipped for compatibility");
}
void createSurface()
{
#if PLATFORM_DESKTOP
VkSurfaceKHR _surface;
if (glfwCreateWindowSurface(*instance, window, nullptr, &_surface) != VK_SUCCESS)
{
throw std::runtime_error("failed to create window surface!");
}
surface = vk::raii::SurfaceKHR(instance, _surface);
#else
VkSurfaceKHR _surface;
VkAndroidSurfaceCreateInfoKHR createInfo{
.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR,
.window = androidAppState.nativeWindow};
if (vkCreateAndroidSurfaceKHR(*instance, &createInfo, nullptr, &_surface) != VK_SUCCESS)
{
throw std::runtime_error("failed to create Android surface!");
}
surface = vk::raii::SurfaceKHR(instance, _surface);
#endif
}
bool isDeviceSuitable(vk::raii::PhysicalDevice const &physicalDevice)
{
// Check if the physicalDevice supports the Vulkan 1.3 API version
bool supportsVulkan1_3 = physicalDevice.getProperties().apiVersion >= VK_API_VERSION_1_3;
// Check if any of the queue families support graphics operations
auto queueFamilies = physicalDevice.getQueueFamilyProperties();
bool supportsGraphics = std::ranges::any_of(queueFamilies, [](auto const &qfp) { return !!(qfp.queueFlags & vk::QueueFlagBits::eGraphics); });
// Check if all required physicalDevice extensions are available
auto availableDeviceExtensions = physicalDevice.enumerateDeviceExtensionProperties();
bool supportsAllRequiredExtensions =
std::ranges::all_of(requiredDeviceExtension,
[&availableDeviceExtensions](auto const &requiredDeviceExtension) {
return std::ranges::any_of(availableDeviceExtensions,
[requiredDeviceExtension](auto const &availableDeviceExtension) { return strcmp(availableDeviceExtension.extensionName, requiredDeviceExtension) == 0; });
});
// Check if the physicalDevice supports the required features
auto features =
physicalDevice
.template getFeatures2<vk::PhysicalDeviceFeatures2, vk::PhysicalDeviceVulkan13Features, vk::PhysicalDeviceExtendedDynamicStateFeaturesEXT>();
bool supportsRequiredFeatures = features.template get<vk::PhysicalDeviceVulkan13Features>().dynamicRendering &&
features.template get<vk::PhysicalDeviceExtendedDynamicStateFeaturesEXT>().extendedDynamicState;
// Return true if the physicalDevice meets all the criteria
return supportsVulkan1_3 && supportsGraphics && supportsAllRequiredExtensions && supportsRequiredFeatures;
}
void pickPhysicalDevice()
{
std::vector<vk::raii::PhysicalDevice> physicalDevices = instance.enumeratePhysicalDevices();
auto const devIter = std::ranges::find_if(physicalDevices, [&](auto const &physicalDevice) { return isDeviceSuitable(physicalDevice); });
if (devIter == physicalDevices.end())
{
throw std::runtime_error("failed to find a suitable GPU!");
}
physicalDevice = *devIter;
// Check for Vulkan profile support
VpProfileProperties profileProperties;
#if PLATFORM_ANDROID
strcpy(profileProperties.name, VP_KHR_ROADMAP_2022_NAME);
#else
strcpy(profileProperties.profileName, VP_KHR_ROADMAP_2022_NAME);
#endif
profileProperties.specVersion = VP_KHR_ROADMAP_2022_SPEC_VERSION;
VkBool32 supported = VK_FALSE;
bool result = false;
#if PLATFORM_ANDROID
// Create a vp::ProfileDesc from our VpProfileProperties
vp::ProfileDesc profileDesc = {profileProperties.name, profileProperties.specVersion};
// Use vp::GetProfileSupport for Android
result = vp::GetProfileSupport(*physicalDevice, // Pass the physical device directly
&profileDesc, // Pass the profile description
&supported // Output parameter for support status
);
#else
// Use vpGetPhysicalDeviceProfileSupport for Desktop
VkResult vk_result = vpGetPhysicalDeviceProfileSupport(*instance, *physicalDevice, &profileProperties, &supported);
result = vk_result == static_cast<int>(vk::Result::eSuccess);
#endif
const char *name = nullptr;
#ifdef PLATFORM_ANDROID
name = profileProperties.name;
#else
name = profileProperties.profileName;
#endif
if (result && supported == VK_TRUE)
{
appInfo.profileSupported = true;
appInfo.profile = profileProperties;
LOGI("Device supports Vulkan profile: %s", name);
}
else
{
LOGI("Device does not support Vulkan profile: %s", name);
}
}
void createLogicalDevice()
{
std::vector<vk::QueueFamilyProperties> queueFamilyProperties = physicalDevice.getQueueFamilyProperties();
// get the first index into queueFamilyProperties which supports both graphics and present
for (uint32_t qfpIndex = 0; qfpIndex < queueFamilyProperties.size(); qfpIndex++)
{
if ((queueFamilyProperties[qfpIndex].queueFlags & vk::QueueFlagBits::eGraphics) &&
physicalDevice.getSurfaceSupportKHR(qfpIndex, *surface))
{
// found a queue family that supports both graphics and present
queueIndex = qfpIndex;
break;
}
}
if (queueIndex == ~0)
{
throw std::runtime_error("Could not find a queue for graphics and present -> terminating");
}
// query for Vulkan 1.3 features
auto features = physicalDevice.getFeatures2();
vk::PhysicalDeviceVulkan13Features vulkan13Features;
vk::PhysicalDeviceExtendedDynamicStateFeaturesEXT extendedDynamicStateFeatures;
vulkan13Features.dynamicRendering = vk::True;
vulkan13Features.synchronization2 = vk::True;
extendedDynamicStateFeatures.extendedDynamicState = vk::True;
vulkan13Features.pNext = &extendedDynamicStateFeatures;
features.pNext = &vulkan13Features;
// create a Device
float queuePriority = 0.5f;
vk::DeviceQueueCreateInfo deviceQueueCreateInfo{.queueFamilyIndex = queueIndex, .queueCount = 1, .pQueuePriorities = &queuePriority};
vk::DeviceCreateInfo deviceCreateInfo{
.pNext = &features,
.queueCreateInfoCount = 1,
.pQueueCreateInfos = &deviceQueueCreateInfo,
.enabledExtensionCount = static_cast<uint32_t>(requiredDeviceExtension.size()),
.ppEnabledExtensionNames = requiredDeviceExtension.data()};
// Create the device with the appropriate features
device = vk::raii::Device(physicalDevice, deviceCreateInfo);
queue = vk::raii::Queue(device, queueIndex, 0);
}
void createSwapChain()
{
vk::SurfaceCapabilitiesKHR surfaceCapabilities = physicalDevice.getSurfaceCapabilitiesKHR(*surface);
swapChainExtent = chooseSwapExtent(surfaceCapabilities);
uint32_t minImageCount = chooseSwapMinImageCount(surfaceCapabilities);
std::vector<vk::SurfaceFormatKHR> availableFormats = physicalDevice.getSurfaceFormatsKHR(*surface);
swapChainSurfaceFormat = chooseSwapSurfaceFormat(availableFormats);
std::vector<vk::PresentModeKHR> availablePresentModes = physicalDevice.getSurfacePresentModesKHR(*surface);
vk::PresentModeKHR presentMode = chooseSwapPresentMode(availablePresentModes);
vk::SwapchainCreateInfoKHR swapChainCreateInfo{.surface = *surface,
.minImageCount = minImageCount,
.imageFormat = swapChainSurfaceFormat.format,
.imageColorSpace = swapChainSurfaceFormat.colorSpace,
.imageExtent = swapChainExtent,
.imageArrayLayers = 1,
.imageUsage = vk::ImageUsageFlagBits::eColorAttachment,
.imageSharingMode = vk::SharingMode::eExclusive,
.preTransform = surfaceCapabilities.currentTransform,
.compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque,
.presentMode = presentMode,
.clipped = true};
swapChain = vk::raii::SwapchainKHR(device, swapChainCreateInfo);
swapChainImages = swapChain.getImages();
}
void createImageViews()
{
assert(swapChainImageViews.empty());
vk::ImageViewCreateInfo imageViewCreateInfo{.viewType = vk::ImageViewType::e2D,
.format = swapChainSurfaceFormat.format,
.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}};
for (auto &image : swapChainImages)
{
imageViewCreateInfo.image = image;
swapChainImageViews.emplace_back(device, imageViewCreateInfo);
}
}
void createDescriptorSetLayout()
{
std::array bindings = {
vk::DescriptorSetLayoutBinding(0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex, nullptr),
vk::DescriptorSetLayoutBinding(1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment, nullptr)};
vk::DescriptorSetLayoutCreateInfo layoutInfo{.bindingCount = static_cast<uint32_t>(bindings.size()), .pBindings = bindings.data()};
descriptorSetLayout = vk::raii::DescriptorSetLayout(device, layoutInfo);
}
void createGraphicsPipeline()
{
vk::raii::ShaderModule shaderModule = createShaderModule(this->readFile("shaders/slang.spv"));
vk::PipelineShaderStageCreateInfo vertShaderStageInfo{.stage = vk::ShaderStageFlagBits::eVertex, .module = *shaderModule, .pName = "vertMain"};
vk::PipelineShaderStageCreateInfo fragShaderStageInfo{.stage = vk::ShaderStageFlagBits::eFragment, .module = *shaderModule, .pName = "fragMain"};
vk::PipelineShaderStageCreateInfo shaderStages[] = {vertShaderStageInfo, fragShaderStageInfo};
auto bindingDescription = Vertex::getBindingDescription();
auto attributeDescriptions = Vertex::getAttributeDescriptions();
vk::PipelineVertexInputStateCreateInfo vertexInputInfo{
.vertexBindingDescriptionCount = 1,
.pVertexBindingDescriptions = &bindingDescription,
.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size()),
.pVertexAttributeDescriptions = attributeDescriptions.data()};
vk::PipelineInputAssemblyStateCreateInfo inputAssembly{
.topology = vk::PrimitiveTopology::eTriangleList,
.primitiveRestartEnable = vk::False};
vk::PipelineViewportStateCreateInfo viewportState{
.viewportCount = 1,
.scissorCount = 1};
vk::PipelineRasterizationStateCreateInfo rasterizer{
.depthClampEnable = vk::False,
.rasterizerDiscardEnable = vk::False,
.polygonMode = vk::PolygonMode::eFill,
.cullMode = vk::CullModeFlagBits::eBack,
.frontFace = vk::FrontFace::eCounterClockwise,
.depthBiasEnable = vk::False,
.lineWidth = 1.0f};
vk::PipelineMultisampleStateCreateInfo multisampling{
.rasterizationSamples = vk::SampleCountFlagBits::e1,
.sampleShadingEnable = vk::False};
vk::PipelineDepthStencilStateCreateInfo depthStencil{
.depthTestEnable = vk::True,
.depthWriteEnable = vk::True,
.depthCompareOp = vk::CompareOp::eLess,
.depthBoundsTestEnable = vk::False,
.stencilTestEnable = vk::False};
vk::PipelineColorBlendAttachmentState colorBlendAttachment{
.blendEnable = vk::False,
.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA};
vk::PipelineColorBlendStateCreateInfo colorBlending{
.logicOpEnable = vk::False,
.logicOp = vk::LogicOp::eCopy,
.attachmentCount = 1,
.pAttachments = &colorBlendAttachment};
std::vector dynamicStates = {
vk::DynamicState::eViewport,
vk::DynamicState::eScissor};
vk::PipelineDynamicStateCreateInfo dynamicState{.dynamicStateCount = static_cast<uint32_t>(dynamicStates.size()), .pDynamicStates = dynamicStates.data()};
vk::PipelineLayoutCreateInfo pipelineLayoutInfo{.setLayoutCount = 1, .pSetLayouts = &*descriptorSetLayout, .pushConstantRangeCount = 0};
pipelineLayout = vk::raii::PipelineLayout(device, pipelineLayoutInfo);
vk::Format depthFormat = findDepthFormat();
vk::StructureChain<vk::GraphicsPipelineCreateInfo, vk::PipelineRenderingCreateInfo> pipelineCreateInfoChain = {
{.stageCount = 2,
.pStages = shaderStages,
.pVertexInputState = &vertexInputInfo,
.pInputAssemblyState = &inputAssembly,
.pViewportState = &viewportState,
.pRasterizationState = &rasterizer,
.pMultisampleState = &multisampling,
.pDepthStencilState = &depthStencil,
.pColorBlendState = &colorBlending,
.pDynamicState = &dynamicState,
.layout = *pipelineLayout,
.renderPass = nullptr},
{.colorAttachmentCount = 1, .pColorAttachmentFormats = &swapChainSurfaceFormat.format, .depthAttachmentFormat = depthFormat}};
graphicsPipeline = vk::raii::Pipeline(device, nullptr, pipelineCreateInfoChain.get<vk::GraphicsPipelineCreateInfo>());
}
void createCommandPool()
{
vk::CommandPoolCreateInfo poolInfo{
.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
.queueFamilyIndex = queueIndex};
commandPool = vk::raii::CommandPool(device, poolInfo);
}
void createDepthResources()
{
vk::Format depthFormat = findDepthFormat();
createImage(swapChainExtent.width, swapChainExtent.height, depthFormat, vk::ImageTiling::eOptimal, vk::ImageUsageFlagBits::eDepthStencilAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, depthImage, depthImageMemory);
depthImageView = createImageView(depthImage, depthFormat, vk::ImageAspectFlagBits::eDepth);
}
vk::Format findSupportedFormat(const std::vector<vk::Format> &candidates, vk::ImageTiling tiling, vk::FormatFeatureFlags features) const
{
for (const auto format : candidates)
{
vk::FormatProperties props = physicalDevice.getFormatProperties(format);
if (tiling == vk::ImageTiling::eLinear && (props.linearTilingFeatures & features) == features)
{
return format;
}
if (tiling == vk::ImageTiling::eOptimal && (props.optimalTilingFeatures & features) == features)
{
return format;
}
}
throw std::runtime_error("failed to find supported format!");
}
[[nodiscard]] vk::Format findDepthFormat() const
{
return findSupportedFormat(
{vk::Format::eD32Sfloat, vk::Format::eD32SfloatS8Uint, vk::Format::eD24UnormS8Uint},
vk::ImageTiling::eOptimal,
vk::FormatFeatureFlagBits::eDepthStencilAttachment);
}
static bool hasStencilComponent(vk::Format format)
{
return format == vk::Format::eD32SfloatS8Uint || format == vk::Format::eD24UnormS8Uint;
}
void createTextureImage()
{
// Load KTX2 texture instead of using stb_image
ktxTexture *kTexture;
KTX_error_code result = ktxTexture_CreateFromNamedFile(
TEXTURE_PATH.c_str(),
KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT,
&kTexture);
if (result != KTX_SUCCESS)
{
throw std::runtime_error("failed to load ktx texture image!");
}
// Get texture dimensions and data
uint32_t texWidth = kTexture->baseWidth;
uint32_t texHeight = kTexture->baseHeight;
ktx_size_t imageSize = ktxTexture_GetImageSize(kTexture, 0);
ktx_uint8_t *ktxTextureData = ktxTexture_GetData(kTexture);
vk::raii::Buffer stagingBuffer({});
vk::raii::DeviceMemory stagingBufferMemory({});
createBuffer(imageSize, vk::BufferUsageFlagBits::eTransferSrc, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, stagingBuffer, stagingBufferMemory);
void *data = stagingBufferMemory.mapMemory(0, imageSize);
memcpy(data, ktxTextureData, imageSize);
stagingBufferMemory.unmapMemory();
// Determine the Vulkan format from KTX format
vk::Format textureFormat;
// Check if the KTX texture has a format
if (kTexture->classId == ktxTexture2_c)
{
// For KTX2 files, we can get the format directly
auto *ktx2 = reinterpret_cast<ktxTexture2 *>(kTexture);
textureFormat = static_cast<vk::Format>(ktx2->vkFormat);
if (textureFormat == vk::Format::eUndefined)
{
// If the format is undefined, fall back to a reasonable default
textureFormat = vk::Format::eR8G8B8A8Unorm;
}
}
else
{
// For KTX1 files or if we can't determine the format, use a reasonable default
textureFormat = vk::Format::eR8G8B8A8Unorm;
}
textureImageFormat = textureFormat;
createImage(texWidth, texHeight, textureFormat, vk::ImageTiling::eOptimal,
vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
vk::MemoryPropertyFlagBits::eDeviceLocal, textureImage, textureImageMemory);
transitionImageLayout(textureImage, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal);
copyBufferToImage(stagingBuffer, textureImage, texWidth, texHeight);
transitionImageLayout(textureImage, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal);
ktxTexture_Destroy(kTexture);
}
void createTextureImageView()
{
textureImageView = createImageView(textureImage, textureImageFormat, vk::ImageAspectFlagBits::eColor);
}
void createTextureSampler()
{
vk::PhysicalDeviceProperties properties = physicalDevice.getProperties();
vk::SamplerCreateInfo samplerInfo{
.magFilter = vk::Filter::eLinear,
.minFilter = vk::Filter::eLinear,
.mipmapMode = vk::SamplerMipmapMode::eLinear,
.addressModeU = vk::SamplerAddressMode::eRepeat,
.addressModeV = vk::SamplerAddressMode::eRepeat,
.addressModeW = vk::SamplerAddressMode::eRepeat,
.mipLodBias = 0.0f,
.anisotropyEnable = vk::True,
.maxAnisotropy = properties.limits.maxSamplerAnisotropy,
.compareEnable = vk::False,
.compareOp = vk::CompareOp::eAlways};
textureSampler = vk::raii::Sampler(device, samplerInfo);
}
vk::raii::ImageView createImageView(vk::raii::Image &image, vk::Format format, vk::ImageAspectFlags aspectFlags)
{
vk::ImageViewCreateInfo viewInfo{
.image = *image,
.viewType = vk::ImageViewType::e2D,
.format = format,
.subresourceRange = {aspectFlags, 0, 1, 0, 1}};
return vk::raii::ImageView(device, viewInfo);
}
void createImage(uint32_t width, uint32_t height, vk::Format format, vk::ImageTiling tiling, vk::ImageUsageFlags usage, vk::MemoryPropertyFlags properties, vk::raii::Image &image, vk::raii::DeviceMemory &imageMemory)
{
vk::ImageCreateInfo imageInfo{
.imageType = vk::ImageType::e2D,
.format = format,
.extent = {width, height, 1},
.mipLevels = 1,
.arrayLayers = 1,
.samples = vk::SampleCountFlagBits::e1,
.tiling = tiling,
.usage = usage,
.sharingMode = vk::SharingMode::eExclusive,
.initialLayout = vk::ImageLayout::eUndefined};
image = vk::raii::Image(device, imageInfo);
vk::MemoryRequirements memRequirements = image.getMemoryRequirements();
vk::MemoryAllocateInfo allocInfo{
.allocationSize = memRequirements.size,
.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties)};
imageMemory = vk::raii::DeviceMemory(device, allocInfo);
image.bindMemory(*imageMemory, 0);
}
void transitionImageLayout(const vk::raii::Image &image, vk::ImageLayout oldLayout, vk::ImageLayout newLayout)
{
auto commandBuffer = beginSingleTimeCommands();
vk::ImageMemoryBarrier barrier{
.oldLayout = oldLayout,
.newLayout = newLayout,
.image = *image,
.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}};
vk::PipelineStageFlags sourceStage;
vk::PipelineStageFlags destinationStage;
if (oldLayout == vk::ImageLayout::eUndefined && newLayout == vk::ImageLayout::eTransferDstOptimal)
{
barrier.srcAccessMask = {};
barrier.dstAccessMask = vk::AccessFlagBits::eTransferWrite;
sourceStage = vk::PipelineStageFlagBits::eTopOfPipe;
destinationStage = vk::PipelineStageFlagBits::eTransfer;
}
else if (oldLayout == vk::ImageLayout::eTransferDstOptimal && newLayout == vk::ImageLayout::eShaderReadOnlyOptimal)
{
barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
sourceStage = vk::PipelineStageFlagBits::eTransfer;
destinationStage = vk::PipelineStageFlagBits::eFragmentShader;
}
else
{