-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy path38_ray_tracing.cpp
More file actions
2010 lines (1697 loc) · 84.1 KB
/
38_ray_tracing.cpp
File metadata and controls
2010 lines (1697 loc) · 84.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <algorithm>
#include <array>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <limits>
#include <memory>
#include <stdexcept>
#include <vector>
#if defined(__INTELLISENSE__) || !defined(USE_CPP20_MODULES)
# include <vulkan/vulkan_raii.hpp>
#else
import vulkan_hpp;
#endif
#define GLFW_INCLUDE_VULKAN // REQUIRED only for GLFW CreateWindowSurface.
#include <GLFW/glfw3.h>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/hash.hpp>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#define TINYOBJLOADER_IMPLEMENTATION
#include <tiny_obj_loader.h>
#ifndef LAB_TASK_LEVEL
# define LAB_TASK_LEVEL 1
#endif
#define LAB_TASK_AS_BUILD_AND_BIND 4
#define LAB_TASK_AS_ANIMATION 6
#define LAB_TASK_AS_OPAQUE_FLAG 7
#define LAB_TASK_INSTANCE_LUT 9
#define LAB_TASK_REFLECTIONS 11
constexpr uint32_t WIDTH = 800;
constexpr uint32_t HEIGHT = 600;
const std::string MODEL_PATH = "models/plant_on_table.obj";
constexpr int MAX_FRAMES_IN_FLIGHT = 2;
const std::vector<char const *> validationLayers = {
"VK_LAYER_KHRONOS_validation"};
#ifdef NDEBUG
constexpr bool enableValidationLayers = false;
#else
constexpr bool enableValidationLayers = true;
#endif
struct Vertex
{
glm::vec3 pos;
glm::vec3 color;
glm::vec2 texCoord;
glm::vec3 normal;
static vk::VertexInputBindingDescription getBindingDescription()
{
return {0, sizeof(Vertex), vk::VertexInputRate::eVertex};
}
static std::array<vk::VertexInputAttributeDescription, 4> 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)),
vk::VertexInputAttributeDescription(3, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, normal))};
}
bool operator==(const Vertex &other) const
{
return pos == other.pos && color == other.color && texCoord == other.texCoord && normal == other.normal;
}
};
template <>
struct std::hash<Vertex>
{
size_t operator()(Vertex const &vertex) const noexcept
{
auto h = std::hash<glm::vec3>()(vertex.pos) ^ (std::hash<glm::vec3>()(vertex.color) << 1);
h = (h >> 1) ^ (std::hash<glm::vec2>()(vertex.texCoord) << 1);
h = (h >> 1) ^ (std::hash<glm::vec3>()(vertex.normal) << 1);
return h;
}
};
struct UniformBufferObject
{
alignas(16) glm::mat4 model;
alignas(16) glm::mat4 view;
alignas(16) glm::mat4 proj;
alignas(16) glm::vec3 cameraPos;
};
struct PushConstant
{
uint32_t materialIndex;
uint32_t reflective;
};
class VulkanRaytracingApplication
{
public:
void run()
{
initWindow();
initVulkan();
mainLoop();
cleanup();
}
~VulkanRaytracingApplication()
{
if (*device)
{
device.waitIdle();
}
}
private:
GLFWwindow *window = nullptr;
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;
vk::raii::Queue graphicsQueue = nullptr;
vk::raii::Queue presentQueue = nullptr;
vk::raii::SwapchainKHR swapChain = nullptr;
std::vector<vk::Image> swapChainImages;
vk::Format swapChainImageFormat = vk::Format::eUndefined;
vk::Extent2D swapChainExtent;
std::vector<vk::raii::ImageView> swapChainImageViews;
vk::raii::DescriptorSetLayout descriptorSetLayoutGlobal = nullptr;
vk::raii::DescriptorSetLayout descriptorSetLayoutMaterial = 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;
std::vector<vk::raii::Image> textureImages;
std::vector<vk::raii::DeviceMemory> textureImageMemories;
std::vector<vk::raii::ImageView> textureImageViews;
vk::raii::Sampler textureSampler = nullptr;
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;
vk::raii::Buffer uvBuffer = nullptr;
vk::raii::DeviceMemory uvBufferMemory = nullptr;
std::vector<vk::raii::Buffer> blasBuffers;
std::vector<vk::raii::DeviceMemory> blasMemories;
std::vector<vk::raii::AccelerationStructureKHR> blasHandles;
std::vector<vk::AccelerationStructureInstanceKHR> instances;
vk::raii::Buffer instanceBuffer = nullptr;
vk::raii::DeviceMemory instanceMemory = nullptr;
vk::raii::Buffer tlasBuffer = nullptr;
vk::raii::DeviceMemory tlasMemory = nullptr;
vk::raii::Buffer tlasScratchBuffer = nullptr;
vk::raii::DeviceMemory tlasScratchMemory = nullptr;
vk::raii::AccelerationStructureKHR tlas = nullptr;
struct InstanceLUT
{
uint32_t materialID;
uint32_t indexBufferOffset;
};
std::vector<InstanceLUT> instanceLUTs;
vk::raii::Buffer instanceLUTBuffer = nullptr;
vk::raii::DeviceMemory instanceLUTBufferMemory = nullptr;
UniformBufferObject ubo{};
std::vector<vk::raii::Buffer> uniformBuffers;
std::vector<vk::raii::DeviceMemory> uniformBuffersMemory;
std::vector<void *> uniformBuffersMapped;
struct SubMesh
{
uint32_t indexOffset;
uint32_t indexCount;
int materialID;
uint32_t firstVertex;
uint32_t maxVertex;
bool alphaCut;
bool reflective;
};
std::vector<SubMesh> submeshes;
std::vector<tinyobj::material_t> materials;
vk::raii::DescriptorPool descriptorPool = nullptr;
std::vector<vk::raii::DescriptorSet> globalDescriptorSets;
std::vector<vk::raii::DescriptorSet> materialDescriptorSets;
vk::raii::CommandPool commandPool = nullptr;
std::vector<vk::raii::CommandBuffer> commandBuffers;
uint32_t graphicsIndex = 0;
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::KHRSpirv14ExtensionName,
vk::KHRSynchronization2ExtensionName,
vk::KHRCreateRenderpass2ExtensionName,
vk::KHRAccelerationStructureExtensionName,
vk::KHRBufferDeviceAddressExtensionName,
vk::KHRDeferredHostOperationsExtensionName,
vk::KHRRayQueryExtensionName};
void initWindow()
{
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
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<VulkanRaytracingApplication *>(glfwGetWindowUserPointer(window));
app->framebufferResized = true;
}
void initVulkan()
{
createInstance();
setupDebugMessenger();
createSurface();
pickPhysicalDevice();
createLogicalDevice();
createSwapChain();
createImageViews();
createCommandPool();
loadModel();
createDescriptorSetLayout();
createGraphicsPipeline();
createDepthResources();
createTextureSampler();
createVertexBuffer();
createIndexBuffer();
createUVBuffer();
createAccelerationStructures();
createInstanceLUTBuffer();
createUniformBuffers();
createDescriptorPool();
createDescriptorSets();
createCommandBuffers();
createSyncObjects();
}
void mainLoop()
{
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
drawFrame();
}
device.waitIdle();
}
void cleanupSwapChain()
{
swapChainImageViews.clear();
swapChain = nullptr;
}
void cleanup() const
{
glfwDestroyWindow(window);
glfwTerminate();
}
void recreateSwapChain()
{
int width = 0, height = 0;
glfwGetFramebufferSize(window, &width, &height);
while (width == 0 || height == 0)
{
glfwGetFramebufferSize(window, &width, &height);
glfwWaitEvents();
}
device.waitIdle();
cleanupSwapChain();
createSwapChain();
createImageViews();
createDepthResources();
}
void createInstance()
{
constexpr vk::ApplicationInfo appInfo{.pApplicationName = "Vulkan Tutorial Ray Tracing",
.applicationVersion = VK_MAKE_VERSION(1, 0, 0),
.pEngineName = "No Engine",
.engineVersion = VK_MAKE_VERSION(1, 0, 0),
.apiVersion = vk::ApiVersion14};
// Get the required layers
std::vector<char const *> requiredLayers;
if (enableValidationLayers)
{
requiredLayers.assign(validationLayers.begin(), validationLayers.end());
}
// Check if the required layers are supported by the Vulkan implementation.
auto layerProperties = context.enumerateInstanceLayerProperties();
for (auto const &requiredLayer : requiredLayers)
{
if (std::ranges::none_of(layerProperties,
[requiredLayer](auto const &layerProperty) { return strcmp(layerProperty.layerName, requiredLayer) == 0; }))
{
throw std::runtime_error("Required layer not supported: " + std::string(requiredLayer));
}
}
// Get the required extensions.
auto requiredExtensions = getRequiredExtensions();
// Check if the required extensions are supported by the Vulkan implementation.
auto extensionProperties = context.enumerateInstanceExtensionProperties();
for (auto const &requiredExtension : requiredExtensions)
{
if (std::ranges::none_of(extensionProperties,
[requiredExtension](auto const &extensionProperty) { return strcmp(extensionProperty.extensionName, requiredExtension) == 0; }))
{
throw std::runtime_error("Required extension not supported: " + std::string(requiredExtension));
}
}
vk::InstanceCreateInfo createInfo{
.pApplicationInfo = &appInfo,
.enabledLayerCount = static_cast<uint32_t>(requiredLayers.size()),
.ppEnabledLayerNames = requiredLayers.data(),
.enabledExtensionCount = static_cast<uint32_t>(requiredExtensions.size()),
.ppEnabledExtensionNames = requiredExtensions.data()};
instance = vk::raii::Instance(context, createInfo);
}
void setupDebugMessenger()
{
if (!enableValidationLayers)
return;
vk::DebugUtilsMessageSeverityFlagsEXT severityFlags(vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose | vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning | vk::DebugUtilsMessageSeverityFlagBitsEXT::eError);
vk::DebugUtilsMessageTypeFlagsEXT messageTypeFlags(vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance | vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation);
vk::DebugUtilsMessengerCreateInfoEXT debugUtilsMessengerCreateInfoEXT{
.messageSeverity = severityFlags,
.messageType = messageTypeFlags,
.pfnUserCallback = &debugCallback};
debugMessenger = instance.createDebugUtilsMessengerEXT(debugUtilsMessengerCreateInfoEXT);
}
void createSurface()
{
VkSurfaceKHR _surface;
if (glfwCreateWindowSurface(*instance, window, nullptr, &_surface) != 0)
{
throw std::runtime_error("failed to create window surface!");
}
surface = vk::raii::SurfaceKHR(instance, _surface);
}
void pickPhysicalDevice()
{
std::vector<vk::raii::PhysicalDevice> devices = instance.enumeratePhysicalDevices();
const auto devIter = std::ranges::find_if(
devices,
[&](auto const &device) {
// Check if the device supports the Vulkan 1.3 API version
bool supportsVulkan1_3 = device.getProperties().apiVersion >= VK_API_VERSION_1_3;
// Check if any of the queue families support graphics operations
auto queueFamilies = device.getQueueFamilyProperties();
bool supportsGraphics =
std::ranges::any_of(queueFamilies, [](auto const &qfp) { return !!(qfp.queueFlags & vk::QueueFlagBits::eGraphics); });
// Check if all required device extensions are available
auto availableDeviceExtensions = device.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; });
});
auto features = device.template getFeatures2<vk::PhysicalDeviceFeatures2,
vk::PhysicalDeviceVulkan12Features,
vk::PhysicalDeviceVulkan13Features,
vk::PhysicalDeviceExtendedDynamicStateFeaturesEXT,
vk::PhysicalDeviceAccelerationStructureFeaturesKHR,
vk::PhysicalDeviceRayQueryFeaturesKHR>();
bool supportsRequiredFeatures = features.template get<vk::PhysicalDeviceFeatures2>().features.samplerAnisotropy &&
features.template get<vk::PhysicalDeviceVulkan13Features>().dynamicRendering &&
features.template get<vk::PhysicalDeviceExtendedDynamicStateFeaturesEXT>().extendedDynamicState &&
features.template get<vk::PhysicalDeviceVulkan12Features>().descriptorBindingSampledImageUpdateAfterBind &&
features.template get<vk::PhysicalDeviceVulkan12Features>().descriptorBindingPartiallyBound &&
features.template get<vk::PhysicalDeviceVulkan12Features>().descriptorBindingVariableDescriptorCount &&
features.template get<vk::PhysicalDeviceVulkan12Features>().runtimeDescriptorArray &&
features.template get<vk::PhysicalDeviceVulkan12Features>().shaderSampledImageArrayNonUniformIndexing &&
features.template get<vk::PhysicalDeviceVulkan12Features>().bufferDeviceAddress &&
features.template get<vk::PhysicalDeviceAccelerationStructureFeaturesKHR>().accelerationStructure &&
features.template get<vk::PhysicalDeviceRayQueryFeaturesKHR>().rayQuery;
return supportsVulkan1_3 && supportsGraphics && supportsAllRequiredExtensions && supportsRequiredFeatures;
});
if (devIter != devices.end())
{
physicalDevice = *devIter;
}
else
{
throw std::runtime_error("failed to find a suitable GPU!");
}
}
void createLogicalDevice()
{
// find the index of the first queue family that supports graphics
std::vector<vk::QueueFamilyProperties> queueFamilyProperties = physicalDevice.getQueueFamilyProperties();
// get the first index into queueFamilyProperties which supports graphics
auto graphicsQueueFamilyProperty = std::ranges::find_if(queueFamilyProperties, [](auto const &qfp) { return (qfp.queueFlags & vk::QueueFlagBits::eGraphics) != static_cast<vk::QueueFlags>(0); });
graphicsIndex = static_cast<uint32_t>(std::distance(queueFamilyProperties.begin(), graphicsQueueFamilyProperty));
// determine a queueFamilyIndex that supports present
// first check if the graphicsIndex is good enough
auto presentIndex = physicalDevice.getSurfaceSupportKHR(graphicsIndex, *surface) ? graphicsIndex : ~0;
if (presentIndex == queueFamilyProperties.size())
{
// the graphicsIndex doesn't support present -> look for another family index that supports both
// graphics and present
for (size_t i = 0; i < queueFamilyProperties.size(); i++)
{
if ((queueFamilyProperties[i].queueFlags & vk::QueueFlagBits::eGraphics) &&
physicalDevice.getSurfaceSupportKHR(static_cast<uint32_t>(i), *surface))
{
graphicsIndex = static_cast<uint32_t>(i);
presentIndex = graphicsIndex;
break;
}
}
if (presentIndex == queueFamilyProperties.size())
{
// there's nothing like a single family index that supports both graphics and present -> look for another
// family index that supports present
for (size_t i = 0; i < queueFamilyProperties.size(); i++)
{
if (physicalDevice.getSurfaceSupportKHR(static_cast<uint32_t>(i), *surface))
{
presentIndex = static_cast<uint32_t>(i);
break;
}
}
}
}
if ((graphicsIndex == queueFamilyProperties.size()) || (presentIndex == queueFamilyProperties.size()))
{
throw std::runtime_error("Could not find a queue for graphics or present -> terminating");
}
// query for Vulkan 1.3 features
vk::StructureChain<vk::PhysicalDeviceFeatures2, vk::PhysicalDeviceVulkan12Features,
vk::PhysicalDeviceVulkan13Features, vk::PhysicalDeviceExtendedDynamicStateFeaturesEXT,
vk::PhysicalDeviceAccelerationStructureFeaturesKHR, vk::PhysicalDeviceRayQueryFeaturesKHR>
featureChain = {
{.features = {.samplerAnisotropy = true}}, // vk::PhysicalDeviceFeatures2
{.shaderSampledImageArrayNonUniformIndexing = true, .descriptorBindingSampledImageUpdateAfterBind = true, .descriptorBindingPartiallyBound = true, .descriptorBindingVariableDescriptorCount = true, .runtimeDescriptorArray = true, .bufferDeviceAddress = true}, // vk::PhysicalDeviceVulkan12Features
{.synchronization2 = true, .dynamicRendering = true}, // vk::PhysicalDeviceVulkan13Features
{.extendedDynamicState = true}, // vk::PhysicalDeviceExtendedDynamicStateFeaturesEXT
{.accelerationStructure = true}, // vk::PhysicalDeviceAccelerationStructureFeaturesKHR
{.rayQuery = true} // vk::PhysicalDeviceRayQueryFeaturesKHR
};
// create a Device
float queuePriority = 0.5f;
vk::DeviceQueueCreateInfo deviceQueueCreateInfo{.queueFamilyIndex = graphicsIndex, .queueCount = 1, .pQueuePriorities = &queuePriority};
vk::DeviceCreateInfo deviceCreateInfo{.pNext = &featureChain.get<vk::PhysicalDeviceFeatures2>(),
.queueCreateInfoCount = 1,
.pQueueCreateInfos = &deviceQueueCreateInfo,
.enabledExtensionCount = static_cast<uint32_t>(requiredDeviceExtension.size()),
.ppEnabledExtensionNames = requiredDeviceExtension.data()};
device = vk::raii::Device(physicalDevice, deviceCreateInfo);
graphicsQueue = vk::raii::Queue(device, graphicsIndex, 0);
presentQueue = vk::raii::Queue(device, presentIndex, 0);
}
void createSwapChain()
{
auto surfaceCapabilities = physicalDevice.getSurfaceCapabilitiesKHR(surface);
swapChainImageFormat = chooseSwapSurfaceFormat(physicalDevice.getSurfaceFormatsKHR(surface));
swapChainExtent = chooseSwapExtent(surfaceCapabilities);
auto minImageCount = std::max(3u, surfaceCapabilities.minImageCount);
minImageCount = (surfaceCapabilities.maxImageCount > 0 && minImageCount > surfaceCapabilities.maxImageCount) ? surfaceCapabilities.maxImageCount : minImageCount;
vk::SwapchainCreateInfoKHR swapChainCreateInfo{
.surface = surface, .minImageCount = minImageCount, .imageFormat = swapChainImageFormat, .imageColorSpace = vk::ColorSpaceKHR::eSrgbNonlinear, .imageExtent = swapChainExtent, .imageArrayLayers = 1, .imageUsage = vk::ImageUsageFlagBits::eColorAttachment, .imageSharingMode = vk::SharingMode::eExclusive, .preTransform = surfaceCapabilities.currentTransform, .compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque, .presentMode = chooseSwapPresentMode(physicalDevice.getSurfacePresentModesKHR(surface)), .clipped = true};
swapChain = vk::raii::SwapchainKHR(device, swapChainCreateInfo);
swapChainImages = swapChain.getImages();
}
void createImageViews()
{
vk::ImageViewCreateInfo imageViewCreateInfo{
.viewType = vk::ImageViewType::e2D,
.format = swapChainImageFormat,
.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}};
for (auto& image : swapChainImages)
{
imageViewCreateInfo.image = image;
swapChainImageViews.emplace_back(device, imageViewCreateInfo);
}
}
void createDescriptorSetLayout()
{
// Use descriptor set 0 for global data
// TASK04: The acceleration structure uses binding 1
std::array global_bindings = {
vk::DescriptorSetLayoutBinding(0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, nullptr),
vk::DescriptorSetLayoutBinding(1, vk::DescriptorType::eAccelerationStructureKHR, 1, vk::ShaderStageFlagBits::eFragment, nullptr),
vk::DescriptorSetLayoutBinding(2, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eFragment, nullptr),
vk::DescriptorSetLayoutBinding(3, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eFragment, nullptr),
vk::DescriptorSetLayoutBinding(4, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eFragment, nullptr)};
vk::DescriptorSetLayoutCreateInfo globalLayoutInfo{.bindingCount = static_cast<uint32_t>(global_bindings.size()), .pBindings = global_bindings.data()};
descriptorSetLayoutGlobal = vk::raii::DescriptorSetLayout(device, globalLayoutInfo);
// Use descriptor set 1 for bindless material data
uint32_t textureCount = static_cast<uint32_t>(textureImageViews.size());
std::array material_bindings = {
vk::DescriptorSetLayoutBinding(0, vk::DescriptorType::eSampler, 1, vk::ShaderStageFlagBits::eFragment, nullptr),
vk::DescriptorSetLayoutBinding(1, vk::DescriptorType::eSampledImage, static_cast<uint32_t>(textureCount), vk::ShaderStageFlagBits::eFragment, nullptr)};
std::vector<vk::DescriptorBindingFlags> bindingFlags = {
vk::DescriptorBindingFlagBits::eUpdateAfterBind,
vk::DescriptorBindingFlagBits::ePartiallyBound | vk::DescriptorBindingFlagBits::eVariableDescriptorCount | vk::DescriptorBindingFlagBits::eUpdateAfterBind};
vk::DescriptorSetLayoutBindingFlagsCreateInfo flagsCreateInfo{
.bindingCount = static_cast<uint32_t>(bindingFlags.size()),
.pBindingFlags = bindingFlags.data()};
vk::DescriptorSetLayoutCreateInfo materialLayoutInfo{
.pNext = &flagsCreateInfo,
.flags = vk::DescriptorSetLayoutCreateFlagBits::eUpdateAfterBindPool,
.bindingCount = static_cast<uint32_t>(material_bindings.size()),
.pBindings = material_bindings.data(),
};
descriptorSetLayoutMaterial = vk::raii::DescriptorSetLayout(device, materialLayoutInfo);
}
void createGraphicsPipeline()
{
vk::raii::ShaderModule shaderModule = createShaderModule(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::DescriptorSetLayout setLayouts[] = {*descriptorSetLayoutGlobal, *descriptorSetLayoutMaterial};
vk::PushConstantRange pushConstantRange{
.stageFlags = vk::ShaderStageFlagBits::eFragment,
.offset = 0,
.size = sizeof(PushConstant)};
vk::PipelineLayoutCreateInfo pipelineLayoutInfo{.setLayoutCount = 2, .pSetLayouts = setLayouts, .pushConstantRangeCount = 1, .pPushConstantRanges = &pushConstantRange};
pipelineLayout = vk::raii::PipelineLayout(device, pipelineLayoutInfo);
vk::Format depthFormat = findDepthFormat();
/* TASK01: Check the setup for dynamic rendering
*
* This new struct replaces what previously was the render pass in the pipeline creation.
* Note how this structure is now linked in .pNext below, and .renderPass is not used.
*/
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 = &swapChainImageFormat, .depthAttachmentFormat = depthFormat}};
graphicsPipeline = vk::raii::Pipeline(device, nullptr, pipelineCreateInfoChain.get<vk::GraphicsPipelineCreateInfo>());
}
void createCommandPool()
{
vk::CommandPoolCreateInfo poolInfo{
.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
.queueFamilyIndex = graphicsIndex};
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;
}
std::pair<vk::raii::Image, vk::raii::DeviceMemory> createTextureImage(const std::string &path)
{
int texWidth, texHeight, texChannels;
stbi_uc *pixels = stbi_load(path.c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha);
vk::DeviceSize imageSize = texWidth * texHeight * 4;
if (!pixels)
{
throw std::runtime_error("failed to load texture image!");
}
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, pixels, imageSize);
stagingBufferMemory.unmapMemory();
stbi_image_free(pixels);
vk::raii::Image textureImage = nullptr;
vk::raii::DeviceMemory textureImageMemory = nullptr;
createImage(texWidth, texHeight, vk::Format::eR8G8B8A8Srgb, 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, static_cast<uint32_t>(texWidth), static_cast<uint32_t>(texHeight));
transitionImageLayout(textureImage, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal);
return std::make_pair(std::move(textureImage), std::move(textureImageMemory));
}
vk::raii::ImageView createTextureImageView(vk::raii::Image &textureImage)
{
return createImageView(textureImage, vk::Format::eR8G8B8A8Srgb, 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
{
throw std::invalid_argument("unsupported layout transition!");
}
commandBuffer->pipelineBarrier(sourceStage, destinationStage, {}, {}, nullptr, barrier);
endSingleTimeCommands(*commandBuffer);
}
void copyBufferToImage(const vk::raii::Buffer &buffer, vk::raii::Image &image, uint32_t width, uint32_t height)
{
std::unique_ptr<vk::raii::CommandBuffer> commandBuffer = beginSingleTimeCommands();
vk::BufferImageCopy region{
.bufferOffset = 0,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1},
.imageOffset = {0, 0, 0},
.imageExtent = {width, height, 1}};
commandBuffer->copyBufferToImage(buffer, image, vk::ImageLayout::eTransferDstOptimal, {region});
endSingleTimeCommands(*commandBuffer);
}
void loadModel()
{
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> localMaterials;
std::string warn, err;
if (!LoadObj(&attrib, &shapes, &localMaterials, &warn, &err, MODEL_PATH.c_str(), MODEL_PATH.substr(0, MODEL_PATH.find_last_of("/\\")).c_str()))
{
throw std::runtime_error(warn + err);
}
size_t materialOffset = materials.size();
size_t oldTextureCount = textureImageViews.size();
materials.insert(materials.end(), localMaterials.begin(), localMaterials.end());
std::unordered_map<Vertex, uint32_t> uniqueVertices{};
uint32_t indexOffset = 0;
for (const auto &shape : shapes)
{
std::cout << "Loading mesh: " << shape.name << ": " << shape.mesh.indices.size() / 3 << " triangles\n";
uint32_t startOffset = indexOffset;
uint32_t localMaxV = 0;
for (const auto &index : shape.mesh.indices)
{
Vertex vertex{};
vertex.pos = {
attrib.vertices[3 * index.vertex_index + 0],
attrib.vertices[3 * index.vertex_index + 1],
attrib.vertices[3 * index.vertex_index + 2]};
vertex.texCoord = {
attrib.texcoords[2 * index.texcoord_index + 0],
1.0f - attrib.texcoords[2 * index.texcoord_index + 1]};
vertex.color = {1.0f, 1.0f, 1.0f};
if (index.normal_index >= 0)
{
vertex.normal = {
attrib.normals[3 * index.normal_index + 0],
attrib.normals[3 * index.normal_index + 1],
attrib.normals[3 * index.normal_index + 2]};
}
else
{
vertex.normal = {0.0f, 0.0f, 0.0f};
}
if (!uniqueVertices.contains(vertex))
{
uniqueVertices[vertex] = static_cast<uint32_t>(vertices.size());
vertices.push_back(vertex);
}
indices.push_back(uniqueVertices[vertex]);
indexOffset++;
uint32_t vi;
auto it = uniqueVertices.find(vertex);
if (it != uniqueVertices.end())
{
vi = it->second;
}
else
{
vi = static_cast<uint32_t>(vertices.size());
uniqueVertices[vertex] = vi;
vertices.push_back(vertex);
}
localMaxV = std::max(localMaxV, vi);
}
int localMaterialID = shape.mesh.material_ids.empty() ? -1 : shape.mesh.material_ids[0];
int globalMaterialID = (localMaterialID < 0) ? -1 : static_cast<int>(materialOffset + localMaterialID);
uint32_t indexCount = indexOffset - startOffset;
// Note that this is only valid for this particular MODEL_PATH
bool alphaCut = (shape.name.find("nettle_plant") != std::string::npos);
bool reflective = (shape.name.find("table") != std::string::npos);
submeshes.push_back({.indexOffset = startOffset,
.indexCount = indexCount,
.materialID = globalMaterialID,
.firstVertex = 0u,
.maxVertex = localMaxV + 1,
.alphaCut = alphaCut,
.reflective = reflective});
}
for (size_t i = 0; i < localMaterials.size(); ++i)
{
const auto &material = localMaterials[i];
if (!material.diffuse_texname.empty())
{
std::string texturePath = MODEL_PATH.substr(0, MODEL_PATH.find_last_of("/\\")) + "/" + material.diffuse_texname;
auto [img, mem] = createTextureImage(texturePath);
textureImages.push_back(std::move(img));
textureImageMemories.push_back(std::move(mem));
textureImageViews.emplace_back(createTextureImageView(textureImages.back()));
}
else
{
std::cout << "No texture for material: " << material.name << std::endl;
}
}
}
void createVertexBuffer()
{
vk::DeviceSize bufferSize = sizeof(vertices[0]) * vertices.size();
vk::raii::Buffer stagingBuffer({});
vk::raii::DeviceMemory stagingBufferMemory({});
createBuffer(bufferSize, vk::BufferUsageFlagBits::eTransferSrc, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, stagingBuffer, stagingBufferMemory);
void *dataStaging = stagingBufferMemory.mapMemory(0, bufferSize);
memcpy(dataStaging, vertices.data(), bufferSize);
stagingBufferMemory.unmapMemory();
createBuffer(bufferSize, vk::BufferUsageFlagBits::eTransferDst | vk::BufferUsageFlagBits::eVertexBuffer | vk::BufferUsageFlagBits::eShaderDeviceAddress | vk::BufferUsageFlagBits::eAccelerationStructureBuildInputReadOnlyKHR, vk::MemoryPropertyFlagBits::eDeviceLocal, vertexBuffer, vertexBufferMemory);
copyBuffer(stagingBuffer, vertexBuffer, bufferSize);
}