forked from crosire/reshade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runtime_vk.cpp
2488 lines (2104 loc) · 100 KB
/
runtime_vk.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2014 Patrick Mours. All rights reserved.
* License: https://github.com/crosire/reshade#license
*/
#include "dll_log.hpp"
#include "dll_resources.hpp"
#include "runtime_vk.hpp"
#include "runtime_config.hpp"
#include "runtime_objects.hpp"
#include "format_utils.hpp"
#include <imgui.h>
#include <imgui_internal.h>
#define check_result(call) \
if ((call) != VK_SUCCESS) \
return
namespace reshade::vulkan
{
struct vulkan_tex_data
{
VkImage image = VK_NULL_HANDLE;
VkImageView view[4] = {};
VmaAllocation image_mem = VK_NULL_HANDLE;
VkFormat formats[2] = {};
#if RESHADE_GUI
VkDescriptorSet descriptor_set = VK_NULL_HANDLE;
#endif
};
struct vulkan_pass_data
{
VkPipeline pipeline = VK_NULL_HANDLE;
VkClearValue clear_values[8] = {};
VkRenderPassBeginInfo begin_info = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO };
};
struct vulkan_effect_data
{
VkQueryPool query_pool = VK_NULL_HANDLE;
VkDescriptorSet set[2] = {};
VkPipelineLayout pipeline_layout = VK_NULL_HANDLE;
VkDescriptorSetLayout set_layout = VK_NULL_HANDLE;
VkBuffer ubo = VK_NULL_HANDLE;
VmaAllocation ubo_mem = VK_NULL_HANDLE;
std::vector<VkDescriptorImageInfo> image_bindings;
uint32_t depth_image_binding = std::numeric_limits<uint32_t>::max();
};
struct vulkan_technique_data
{
uint32_t query_base_index = 0;
std::vector<vulkan_pass_data> passes;
};
const uint32_t MAX_IMAGE_DESCRIPTOR_SETS = 128; // TODO: Check if these limits are enough
const uint32_t MAX_EFFECT_DESCRIPTOR_SETS = 50 * 2;
void transition_layout(const VkLayerDispatchTable &vk, VkCommandBuffer cmd_list, VkImage image, VkImageLayout old_layout, VkImageLayout new_layout,
VkImageSubresourceRange subresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, VK_REMAINING_MIP_LEVELS, 0, VK_REMAINING_ARRAY_LAYERS })
{
const auto layout_to_access = [](VkImageLayout layout) -> VkAccessFlags {
switch (layout)
{
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
return VK_ACCESS_TRANSFER_READ_BIT;
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
return VK_ACCESS_TRANSFER_WRITE_BIT;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
return VK_ACCESS_SHADER_READ_BIT;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
return VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL:
return VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
return VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
}
return 0;
};
const auto layout_to_stage = [](VkImageLayout layout) -> VkPipelineStageFlags {
switch (layout)
{
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
return VK_PIPELINE_STAGE_TRANSFER_BIT;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
return VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL:
return VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR: // Can use color attachment output here, since the semaphores wait on that stage
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
return VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
}
return VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
};
VkImageMemoryBarrier transition { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER };
transition.srcAccessMask = layout_to_access(old_layout);
transition.dstAccessMask = layout_to_access(new_layout);
transition.oldLayout = old_layout;
transition.newLayout = new_layout;
transition.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
transition.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
transition.image = image;
transition.subresourceRange = subresource;
vk.CmdPipelineBarrier(cmd_list, layout_to_stage(old_layout), layout_to_stage(new_layout), 0, 0, nullptr, 0, nullptr, 1, &transition);
}
}
reshade::vulkan::runtime_vk::runtime_vk(VkDevice device, VkPhysicalDevice physical_device, uint32_t queue_family_index, const VkLayerInstanceDispatchTable &instance_table, const VkLayerDispatchTable &device_table) :
_device(device), _queue_family_index(queue_family_index), vk(device_table)
{
instance_table.GetPhysicalDeviceProperties(physical_device, &_device_props);
instance_table.GetPhysicalDeviceMemoryProperties(physical_device, &_memory_props);
_renderer_id = 0x20000 |
VK_VERSION_MAJOR(_device_props.apiVersion) << 12 |
VK_VERSION_MINOR(_device_props.apiVersion) << 8;
_vendor_id = _device_props.vendorID;
_device_id = _device_props.deviceID;
const VkFormat possible_stencil_formats[] = {
VK_FORMAT_S8_UINT,
VK_FORMAT_D16_UNORM_S8_UINT,
VK_FORMAT_D24_UNORM_S8_UINT,
VK_FORMAT_D32_SFLOAT_S8_UINT
};
// Find a supported stencil format
for (const VkFormat format : possible_stencil_formats)
{
VkFormatProperties format_props = {};
instance_table.GetPhysicalDeviceFormatProperties(physical_device, format, &format_props);
if ((format_props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) != 0)
{
_effect_stencil_format = format;
break;
}
}
// Get the main graphics queue for command submission
// There has to be at least one queue, or else this runtime would not have been created with this queue family index
// So it should be safe to just get the first one
vk.GetDeviceQueue(_device, _queue_family_index, 0, &_queue);
assert(_queue != VK_NULL_HANDLE);
{ VmaVulkanFunctions functions;
functions.vkGetPhysicalDeviceProperties = instance_table.GetPhysicalDeviceProperties;
functions.vkGetPhysicalDeviceMemoryProperties = instance_table.GetPhysicalDeviceMemoryProperties;
functions.vkAllocateMemory = device_table.AllocateMemory;
functions.vkFreeMemory = device_table.FreeMemory;
functions.vkMapMemory = device_table.MapMemory;
functions.vkUnmapMemory = device_table.UnmapMemory;
functions.vkFlushMappedMemoryRanges = device_table.FlushMappedMemoryRanges;
functions.vkInvalidateMappedMemoryRanges = device_table.InvalidateMappedMemoryRanges;
functions.vkBindBufferMemory = device_table.BindBufferMemory;
functions.vkBindImageMemory = device_table.BindImageMemory;
functions.vkGetBufferMemoryRequirements = device_table.GetBufferMemoryRequirements;
functions.vkGetImageMemoryRequirements = device_table.GetImageMemoryRequirements;
functions.vkCreateBuffer = device_table.CreateBuffer;
functions.vkDestroyBuffer = device_table.DestroyBuffer;
functions.vkCreateImage = device_table.CreateImage;
functions.vkDestroyImage = device_table.DestroyImage;
functions.vkCmdCopyBuffer = device_table.CmdCopyBuffer;
functions.vkGetBufferMemoryRequirements2KHR = device_table.GetBufferMemoryRequirements2;
functions.vkGetImageMemoryRequirements2KHR = device_table.GetImageMemoryRequirements2;
functions.vkBindBufferMemory2KHR = device_table.BindBufferMemory2;
functions.vkBindImageMemory2KHR = device_table.BindImageMemory2;
functions.vkGetPhysicalDeviceMemoryProperties2KHR = instance_table.GetPhysicalDeviceMemoryProperties2;
VmaAllocatorCreateInfo create_info = {};
// The runtime runs in a single thread, so no synchronization necessary
create_info.flags = VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT;
create_info.physicalDevice = physical_device;
create_info.device = _device;
create_info.preferredLargeHeapBlockSize = 1920 * 1080 * 4 * 16; // Allocate blocks of memory that can comfortably contain 16 Full HD images
create_info.pVulkanFunctions = &functions;
create_info.vulkanApiVersion = VK_API_VERSION_1_1; // Vulkan 1.1 is guaranteed by code in vulkan_hooks.cpp
vmaCreateAllocator(&create_info, &_alloc);
}
#if RESHADE_GUI
subscribe_to_ui("Vulkan", [this]() {
// Add some information about the device and driver to the UI
ImGui::Text("Vulkan %u.%u.%u", VK_VERSION_MAJOR(_device_props.apiVersion), VK_VERSION_MINOR(_device_props.apiVersion), VK_VERSION_PATCH(_device_props.apiVersion));
ImGui::Text("%s Driver %u.%u",
_device_props.deviceName,
VK_VERSION_MAJOR(_device_props.driverVersion),
// NVIDIA has a custom driver version scheme, so extract the proper minor version from it
_device_props.vendorID == 0x10DE ? (_device_props.driverVersion >> 14) & 0xFF : VK_VERSION_MINOR(_device_props.driverVersion));
#if RESHADE_DEPTH
ImGui::Spacing();
assert(_buffer_detection != nullptr);
draw_depth_debug_menu(*_buffer_detection);
#endif
});
#endif
#if RESHADE_DEPTH
subscribe_to_load_config([this](const ini_file &config) {
config.get("VULKAN_BUFFER_DETECTION", "UseAspectRatioHeuristics", _use_aspect_ratio_heuristics);
});
subscribe_to_save_config([this](ini_file &config) {
config.set("VULKAN_BUFFER_DETECTION", "UseAspectRatioHeuristics", _use_aspect_ratio_heuristics);
});
#endif
}
reshade::vulkan::runtime_vk::~runtime_vk()
{
vmaDestroyAllocator(_alloc);
}
bool reshade::vulkan::runtime_vk::on_init(VkSwapchainKHR swapchain, const VkSwapchainCreateInfoKHR &desc, HWND hwnd)
{
RECT window_rect = {};
GetClientRect(hwnd, &window_rect);
_width = desc.imageExtent.width;
_height = desc.imageExtent.height;
_window_width = window_rect.right - window_rect.left;
_window_height = window_rect.bottom - window_rect.top;
_color_bit_depth = desc.imageFormat >= VK_FORMAT_A2R10G10B10_UNORM_PACK32 && desc.imageFormat <= VK_FORMAT_A2B10G10R10_SINT_PACK32 ? 10 : 8;
_backbuffer_format = desc.imageFormat;
if (_queue == VK_NULL_HANDLE)
return false;
// Create back buffer shader image
assert(_backbuffer_format != VK_FORMAT_UNDEFINED);
_backbuffer_image = create_image(
_width, _height, 1, _backbuffer_format,
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VMA_MEMORY_USAGE_GPU_ONLY,
VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT);
if (_backbuffer_image == VK_NULL_HANDLE)
return false;
_backbuffer_image_view[0] = create_image_view(_backbuffer_image, make_format_normal(_backbuffer_format), 1, VK_IMAGE_ASPECT_COLOR_BIT);
if (_backbuffer_image_view[0] == VK_NULL_HANDLE)
return false;
_backbuffer_image_view[1] = create_image_view(_backbuffer_image, make_format_srgb(_backbuffer_format), 1, VK_IMAGE_ASPECT_COLOR_BIT);
if (_backbuffer_image_view[1] == VK_NULL_HANDLE)
return false;
#ifndef NDEBUG
if (vk.DebugMarkerSetObjectNameEXT != nullptr)
{
VkDebugMarkerObjectNameInfoEXT name_info { VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT };
name_info.object = (uint64_t)_backbuffer_image;
name_info.objectType = VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT;
name_info.pObjectName = "ReShade back buffer";
vk.DebugMarkerSetObjectNameEXT(_device, &name_info);
}
#endif
// Create effect depth-stencil resource
assert(_effect_stencil_format != VK_FORMAT_UNDEFINED);
_effect_stencil = create_image(
_width, _height, 1, _effect_stencil_format,
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY);
if (_effect_stencil == VK_NULL_HANDLE)
return false;
_effect_stencil_view = create_image_view(_effect_stencil, _effect_stencil_format, 1, VK_IMAGE_ASPECT_STENCIL_BIT);
if (_effect_stencil_view == VK_NULL_HANDLE)
return false;
#ifndef NDEBUG
if (vk.DebugMarkerSetObjectNameEXT != nullptr)
{
VkDebugMarkerObjectNameInfoEXT name_info{ VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT };
name_info.object = (uint64_t)_effect_stencil;
name_info.objectType = VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT;
name_info.pObjectName = "ReShade stencil buffer";
vk.DebugMarkerSetObjectNameEXT(_device, &name_info);
}
#endif
// Create default render pass
for (uint32_t k = 0; k < 2; ++k)
{
VkAttachmentReference attachment_refs[2] = {};
attachment_refs[0].attachment = 0;
attachment_refs[0].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
attachment_refs[1].attachment = 1;
attachment_refs[1].layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentDescription attachment_descs[2] = {};
attachment_descs[0].format = k == 0 ? make_format_normal(_backbuffer_format) : make_format_srgb(_backbuffer_format);
attachment_descs[0].samples = VK_SAMPLE_COUNT_1_BIT;
attachment_descs[0].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
attachment_descs[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment_descs[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment_descs[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachment_descs[0].initialLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
attachment_descs[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
attachment_descs[1].format = _effect_stencil_format;
attachment_descs[1].samples = VK_SAMPLE_COUNT_1_BIT;
attachment_descs[1].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment_descs[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachment_descs[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
attachment_descs[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment_descs[1].initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
attachment_descs[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkSubpassDependency subdep = {};
subdep.srcSubpass = VK_SUBPASS_EXTERNAL;
subdep.dstSubpass = 0;
subdep.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
subdep.dstStageMask = VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT;
subdep.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
subdep.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
VkSubpassDescription subpass = {};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &attachment_refs[0];
subpass.pDepthStencilAttachment = &attachment_refs[1];
VkRenderPassCreateInfo create_info { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO };
create_info.attachmentCount = 2;
create_info.pAttachments = attachment_descs;
create_info.subpassCount = 1;
create_info.pSubpasses = &subpass;
create_info.dependencyCount = 1;
create_info.pDependencies = &subdep;
check_result(vk.CreateRenderPass(_device, &create_info, nullptr, &_default_render_pass[k])) false;
}
// Get back buffer images
uint32_t num_images = 0;
check_result(vk.GetSwapchainImagesKHR(_device, swapchain, &num_images, nullptr)) false;
_swapchain_images.resize(num_images);
check_result(vk.GetSwapchainImagesKHR(_device, swapchain, &num_images, _swapchain_images.data())) false;
assert(desc.imageUsage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT);
_render_area = desc.imageExtent;
_swapchain_views.resize(num_images * 2);
_swapchain_frames.resize(num_images * 2);
for (uint32_t i = 0, k = 0; i < num_images; ++i, k += 2)
{
_swapchain_views[k + 1] = create_image_view(_swapchain_images[i], make_format_srgb(desc.imageFormat), 1, VK_IMAGE_ASPECT_COLOR_BIT);
_swapchain_views[k + 0] = create_image_view(_swapchain_images[i], make_format_normal(desc.imageFormat), 1, VK_IMAGE_ASPECT_COLOR_BIT);
const VkImageView attachment_views[2] = { _swapchain_views[k + 0], _effect_stencil_view };
const VkImageView attachment_views_srgb[2] = { _swapchain_views[k + 1], _effect_stencil_view };
{ VkFramebufferCreateInfo create_info { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO };
create_info.renderPass = _default_render_pass[0];
create_info.attachmentCount = 2;
create_info.pAttachments = attachment_views;
create_info.width = desc.imageExtent.width;
create_info.height = desc.imageExtent.height;
create_info.layers = 1;
check_result(vk.CreateFramebuffer(_device, &create_info, nullptr, &_swapchain_frames[k + 0])) false;
create_info.renderPass = _default_render_pass[1];
create_info.pAttachments = attachment_views_srgb;
check_result(vk.CreateFramebuffer(_device, &create_info, nullptr, &_swapchain_frames[k + 1])) false;
}
}
// Reset index since a few commands are recorded during initialization below
_cmd_index = 0;
VkCommandBuffer cmd_buffers[NUM_COMMAND_FRAMES];
{ VkCommandPoolCreateInfo create_info { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO };
create_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
create_info.queueFamilyIndex = _queue_family_index;
check_result(vk.CreateCommandPool(_device, &create_info, nullptr, &_cmd_pool)) false;
}
{ VkCommandBufferAllocateInfo alloc_info { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };
alloc_info.commandPool = _cmd_pool;
alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
alloc_info.commandBufferCount = NUM_COMMAND_FRAMES;
check_result(vk.AllocateCommandBuffers(_device, &alloc_info, cmd_buffers)) VK_NULL_HANDLE;
}
for (uint32_t i = 0; i < NUM_COMMAND_FRAMES; ++i)
{
_cmd_buffers[i].first = cmd_buffers[i];
_cmd_buffers[i].second = false; // Command buffers are in initial state
// The validation layers expect the loader to have set the dispatch pointer, but this does not happen when calling down the layer chain from here, so fix it
*reinterpret_cast<void **>(cmd_buffers[i]) = *reinterpret_cast<void **>(_device);
VkFenceCreateInfo create_info { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
create_info.flags = VK_FENCE_CREATE_SIGNALED_BIT; // Create signaled so first status check in 'on_present' succeeds
check_result(vk.CreateFence(_device, &create_info, nullptr, &_cmd_fences[i])) false;
VkSemaphoreCreateInfo sem_create_info { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
for (uint32_t k = 0; k < 2; ++k)
{
check_result(vk.CreateSemaphore(_device, &sem_create_info, nullptr, &_cmd_semaphores[i + k * NUM_COMMAND_FRAMES])) false;
}
}
// Create special fence for synchronous execution (see 'execute_command_buffer'), which is not signaled by default
{ VkFenceCreateInfo create_info { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
check_result(vk.CreateFence(_device, &create_info, nullptr, &_cmd_fences[NUM_COMMAND_FRAMES])) false;
}
// Allocate a single descriptor pool for all effects
{ VkDescriptorPoolSize pool_sizes[] = {
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, MAX_EFFECT_DESCRIPTOR_SETS }, // Only need one global UBO per set
{ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, MAX_EFFECT_DESCRIPTOR_SETS * MAX_IMAGE_DESCRIPTOR_SETS }
};
VkDescriptorPoolCreateInfo create_info { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
// No VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT set, so that all descriptors can be reset in one go via vkResetDescriptorPool
create_info.maxSets = MAX_EFFECT_DESCRIPTOR_SETS;
create_info.poolSizeCount = static_cast<uint32_t>(std::size(pool_sizes));
create_info.pPoolSizes = pool_sizes;
check_result(vk.CreateDescriptorPool(_device, &create_info, nullptr, &_effect_descriptor_pool)) false;
}
{ VkDescriptorSetLayoutBinding bindings = { 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL_GRAPHICS };
VkDescriptorSetLayoutCreateInfo create_info { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
create_info.bindingCount = 1;
create_info.pBindings = &bindings;
check_result(vk.CreateDescriptorSetLayout(_device, &create_info, nullptr, &_effect_descriptor_layout)) false;
}
// Create an empty image, which is used when no depth buffer was detected (since you cannot bind nothing to a descriptor in Vulkan)
// Use VK_FORMAT_R16_SFLOAT format, since it is mandatory according to the spec (see https://www.khronos.org/registry/vulkan/specs/1.1/html/vkspec.html#features-required-format-support)
_empty_depth_image = create_image(1, 1, 1, VK_FORMAT_R16_SFLOAT, VK_IMAGE_USAGE_SAMPLED_BIT, VMA_MEMORY_USAGE_GPU_ONLY);
if (_empty_depth_image == VK_NULL_HANDLE)
return false;
_empty_depth_image_view = create_image_view(_empty_depth_image, VK_FORMAT_R16_SFLOAT, 1, VK_IMAGE_ASPECT_COLOR_BIT);
if (_empty_depth_image_view == VK_NULL_HANDLE)
return false;
// Transition image layouts to the ones required below
if (begin_command_buffer())
{
transition_layout(vk, _cmd_buffers[_cmd_index].first, _effect_stencil, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, { aspect_flags_from_format(_effect_stencil_format), 0, 1, 0, 1 });
transition_layout(vk, _cmd_buffers[_cmd_index].first, _empty_depth_image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
execute_command_buffer();
}
#if RESHADE_GUI
if (!init_imgui_resources())
return false;
#endif
return runtime::on_init(hwnd);
}
void reshade::vulkan::runtime_vk::on_reset()
{
runtime::on_reset();
// Make sure none of the resources below are currently in use
wait_for_command_buffers();
for (VkImageView view : _swapchain_views)
vk.DestroyImageView(_device, view, nullptr);
_swapchain_views.clear();
for (VkFramebuffer frame : _swapchain_frames)
vk.DestroyFramebuffer(_device, frame, nullptr);
_swapchain_frames.clear();
_swapchain_images.clear();
for (VkFence &fence : _cmd_fences)
vk.DestroyFence(_device, fence, nullptr),
fence = VK_NULL_HANDLE;
for (VkSemaphore &semaphore : _cmd_semaphores)
vk.DestroySemaphore(_device, semaphore, nullptr),
semaphore = VK_NULL_HANDLE;
assert(_wait_stages.empty());
assert(_wait_semaphores.empty());
VkCommandBuffer cmd_buffers[NUM_COMMAND_FRAMES] = {};
for (uint32_t i = 0; i < NUM_COMMAND_FRAMES; ++i)
std::swap(cmd_buffers[i], _cmd_buffers[i].first);
if (_cmd_pool != VK_NULL_HANDLE)
{
vk.FreeCommandBuffers(_device, _cmd_pool, NUM_COMMAND_FRAMES, cmd_buffers);
vk.DestroyCommandPool(_device, _cmd_pool, nullptr);
_cmd_pool = VK_NULL_HANDLE;
}
vk.DestroyImage(_device, _backbuffer_image, nullptr);
_backbuffer_image = VK_NULL_HANDLE;
vk.DestroyImageView(_device, _backbuffer_image_view[0], nullptr);
_backbuffer_image_view[0] = VK_NULL_HANDLE;
vk.DestroyImageView(_device, _backbuffer_image_view[1], nullptr);
_backbuffer_image_view[1] = VK_NULL_HANDLE;
vk.DestroyRenderPass(_device, _default_render_pass[0], nullptr);
_default_render_pass[0] = VK_NULL_HANDLE;
vk.DestroyRenderPass(_device, _default_render_pass[1], nullptr);
_default_render_pass[1] = VK_NULL_HANDLE;
vk.DestroyImage(_device, _empty_depth_image, nullptr);
_empty_depth_image = VK_NULL_HANDLE;
vk.DestroyImageView(_device, _empty_depth_image_view, nullptr);
_empty_depth_image_view = VK_NULL_HANDLE;
vk.DestroyImage(_device, _effect_stencil, nullptr);
_effect_stencil = VK_NULL_HANDLE;
vk.DestroyImageView(_device, _effect_stencil_view, nullptr);
_effect_stencil_view = VK_NULL_HANDLE;
vk.DestroyDescriptorPool(_device, _effect_descriptor_pool, nullptr);
_effect_descriptor_pool = VK_NULL_HANDLE;
vk.DestroyDescriptorSetLayout(_device, _effect_descriptor_layout, nullptr);
_effect_descriptor_layout = VK_NULL_HANDLE;
#if RESHADE_GUI
for (unsigned int i = 0; i < NUM_IMGUI_BUFFERS; ++i)
{
vmaDestroyBuffer(_alloc, _imgui.indices[i], _imgui.indices_mem[i]);
vmaDestroyBuffer(_alloc, _imgui.vertices[i], _imgui.vertices_mem[i]);
_imgui.indices[i] = VK_NULL_HANDLE;
_imgui.vertices[i] = VK_NULL_HANDLE;
_imgui.indices_mem[i] = VK_NULL_HANDLE;
_imgui.vertices_mem[i] = VK_NULL_HANDLE;
_imgui.num_indices[i] = 0;
_imgui.num_vertices[i] = 0;
}
vk.DestroyPipeline(_device, _imgui.pipeline, nullptr);
_imgui.pipeline = VK_NULL_HANDLE;
vk.DestroyPipelineLayout(_device, _imgui.pipeline_layout, nullptr);
_imgui.pipeline_layout = VK_NULL_HANDLE;
vk.DestroyDescriptorPool(_device, _imgui.descriptor_pool, nullptr);
_imgui.descriptor_pool = VK_NULL_HANDLE;
vk.DestroyDescriptorSetLayout(_device, _imgui.descriptor_layout, nullptr);
_imgui.descriptor_layout = VK_NULL_HANDLE;
vk.DestroySampler(_device, _imgui.sampler, nullptr);
_imgui.sampler = VK_NULL_HANDLE;
#endif
#if RESHADE_DEPTH
_has_depth_texture = false;
_depth_image = VK_NULL_HANDLE;
_depth_image_override = VK_NULL_HANDLE;
vk.DestroyImageView(_device, _depth_image_view, nullptr);
_depth_image_view = VK_NULL_HANDLE;
#endif
// Free all unmanaged device memory allocated via the 'create_image' and 'create_buffer' functions
vmaFreeMemoryPages(_alloc, _allocations.size(), _allocations.data());
_allocations.clear();
}
void reshade::vulkan::runtime_vk::on_present(VkQueue queue, uint32_t swapchain_image_index, const std::vector<VkSemaphore> &wait, VkSemaphore &signal)
{
if (!_is_initialized)
return;
assert(_buffer_detection != nullptr);
_vertices = _buffer_detection->total_vertices();
_drawcalls = _buffer_detection->total_drawcalls();
_cmd_index = _framecount % NUM_COMMAND_FRAMES;
_swap_index = swapchain_image_index;
_wait_stages.resize(wait.size(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT);
_wait_semaphores.assign(wait.begin(), wait.end());
// Make sure the command buffer has finished executing before reusing it this frame
const VkFence fence = _cmd_fences[_cmd_index];
if (vk.GetFenceStatus(_device, fence) == VK_INCOMPLETE)
{
vk.WaitForFences(_device, 1, &fence, VK_TRUE, UINT64_MAX);
}
#if RESHADE_DEPTH
update_depth_image_bindings(_has_high_network_activity ? buffer_detection::depthstencil_info {} :
_buffer_detection->find_best_depth_texture(_use_aspect_ratio_heuristics ? VkExtent2D { _width, _height } : VkExtent2D { 0, 0 }, _depth_image_override));
#endif
update_and_render_effects();
runtime::on_present();
// Submit all asynchronous commands in one batch to the current queue
if (auto &cmd_info = _cmd_buffers[_cmd_index];
cmd_info.second)
{
check_result(vk.EndCommandBuffer(cmd_info.first));
signal = _cmd_semaphores[_cmd_index];
VkSubmitInfo submit_info { VK_STRUCTURE_TYPE_SUBMIT_INFO };
// If the application is presenting with a different queue than rendering, synchronize these two queues first
// This ensures that it has finished rendering before ReShade applies its own rendering
if (queue != _queue)
{
// Signal a semaphore from the queue the application is presenting with
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = &_cmd_semaphores[NUM_COMMAND_FRAMES + _cmd_index];
vk.QueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
// Wait on that semaphore in the ReShade submit
_wait_stages.push_back(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
_wait_semaphores.push_back(submit_info.pSignalSemaphores[0]);
}
submit_info.waitSemaphoreCount = static_cast<uint32_t>(_wait_semaphores.size());
submit_info.pWaitSemaphores = _wait_semaphores.data();
submit_info.pWaitDstStageMask = _wait_stages.data();
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &cmd_info.first;
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = &signal;
// Only reset fence before an actual submit which can signal it again
vk.ResetFences(_device, 1, &fence);
// Always submit to the graphics queue
if (vk.QueueSubmit(_queue, 1, &submit_info, fence) != VK_SUCCESS)
// Semaphore is not signaled if queue submission fails
signal = VK_NULL_HANDLE;
// Command buffer is now in invalid state and ready for a reset
cmd_info.second = false;
}
_wait_stages.clear();
_wait_semaphores.clear();
}
bool reshade::vulkan::runtime_vk::capture_screenshot(uint8_t *buffer) const
{
const size_t data_pitch = _width * 4;
vk_handle<VK_OBJECT_TYPE_BUFFER> intermediate(_device, vk);
VmaAllocation intermediate_mem = VK_NULL_HANDLE;
{ VkBufferCreateInfo create_info { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
create_info.size = data_pitch * _height;
create_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo alloc_info = {};
alloc_info.usage = VMA_MEMORY_USAGE_GPU_TO_CPU;
check_result(vmaCreateBuffer(_alloc, &create_info, &alloc_info, &intermediate, &intermediate_mem, nullptr)) false;
}
// Copy image into download buffer
uint8_t *mapped_data = nullptr;
if (begin_command_buffer())
{
const VkCommandBuffer cmd_list = _cmd_buffers[_cmd_index].first;
transition_layout(vk, cmd_list, _swapchain_images[_swap_index], VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
{
VkBufferImageCopy copy;
copy.bufferOffset = 0;
copy.bufferRowLength = _width;
copy.bufferImageHeight = _height;
copy.imageOffset = { 0, 0, 0 };
copy.imageExtent = { _width, _height, 1 };
copy.imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 };
vk.CmdCopyImageToBuffer(cmd_list, _swapchain_images[_swap_index], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, intermediate, 1, ©);
}
transition_layout(vk, cmd_list, _swapchain_images[_swap_index], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
// Execute and wait for completion
execute_command_buffer();
// Copy data from intermediate image into output buffer
if (vmaMapMemory(_alloc, intermediate_mem, reinterpret_cast<void **>(&mapped_data)) != VK_SUCCESS)
mapped_data = nullptr;
}
if (mapped_data != nullptr)
{
for (uint32_t y = 0; y < _height; y++, buffer += data_pitch, mapped_data += data_pitch)
{
if (_color_bit_depth == 10)
{
for (uint32_t x = 0; x < data_pitch; x += 4)
{
const uint32_t rgba = *reinterpret_cast<const uint32_t *>(mapped_data + x);
// Divide by 4 to get 10-bit range (0-1023) into 8-bit range (0-255)
buffer[x + 0] = ((rgba & 0x3FF) / 4) & 0xFF;
buffer[x + 1] = (((rgba & 0xFFC00) >> 10) / 4) & 0xFF;
buffer[x + 2] = (((rgba & 0x3FF00000) >> 20) / 4) & 0xFF;
buffer[x + 3] = 0xFF;
if (_backbuffer_format >= VK_FORMAT_A2B10G10R10_UNORM_PACK32 && _backbuffer_format <= VK_FORMAT_A2B10G10R10_SINT_PACK32)
std::swap(buffer[x + 0], buffer[x + 2]);
}
}
else
{
std::memcpy(buffer, mapped_data, data_pitch);
for (uint32_t x = 0; x < data_pitch; x += 4)
{
buffer[x + 3] = 0xFF; // Clear alpha channel
if (_backbuffer_format >= VK_FORMAT_B8G8R8A8_UNORM && _backbuffer_format <= VK_FORMAT_B8G8R8A8_SRGB)
std::swap(buffer[x + 0], buffer[x + 2]); // Format is BGRA, but output should be RGBA, so flip channels
}
}
}
vmaUnmapMemory(_alloc, intermediate_mem);
}
vmaFreeMemory(_alloc, intermediate_mem);
return mapped_data != nullptr;
}
bool reshade::vulkan::runtime_vk::init_effect(size_t index)
{
effect &effect = _effects[index];
// Load shader module
std::unordered_map<std::string, VkShaderModule> entry_points;
std::vector<vk_handle<VK_OBJECT_TYPE_SHADER_MODULE>> shader_modules;
{ VkResult res = VK_SUCCESS;
// The AMD driver has a really hard time with SPIR-V modules that have multiple entry points.
// Trying to create a graphics pipeline using a shader module created from such a SPIR-V module tends to just fail with a generic VK_ERROR_OUT_OF_HOST_MEMORY.
// This is a pretty unpleasant driver bug, but until fixed, create a separate shader module for every entry point and rewrite the SPIR-V module for each to removes all but a single entry point (and associated functions/variables).
bool has_driver_bug = (_device_props.vendorID == 0x1002); // AMD
if (!has_driver_bug)
{
VkShaderModuleCreateInfo create_info { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO };
create_info.codeSize = effect.module.spirv.size() * sizeof(uint32_t);
create_info.pCode = effect.module.spirv.data();
res = vk.CreateShaderModule(_device, &create_info, nullptr, &shader_modules.emplace_back(_device, vk));
}
for (size_t i = 0; i < effect.module.entry_points.size() && res == VK_SUCCESS; ++i)
{
const reshadefx::entry_point &entry_point = effect.module.entry_points[i];
if (has_driver_bug)
{
uint32_t current_function = 0, current_function_offset = 0;
std::vector<uint32_t> spirv = effect.module.spirv;
std::vector<uint32_t> functions_to_remove, variables_to_remove;
for (uint32_t inst = 5 /* Skip SPIR-V header information */; inst < spirv.size();)
{
const uint32_t op = spirv[inst] & 0xFFFF;
const uint32_t len = (spirv[inst] >> 16) & 0xFFFF;
assert(len != 0);
switch (op)
{
case 15: // OpEntryPoint
// Look for any non-matching entry points
if (entry_point.name != reinterpret_cast<const char *>(&spirv[inst + 3]))
{
functions_to_remove.push_back(spirv[inst + 2]);
// Get interface variables
for (size_t k = inst + 3 + ((strlen(reinterpret_cast<const char *>(&spirv[inst + 3])) + 4) / 4); k < inst + len; ++k)
variables_to_remove.push_back(spirv[k]);
// Remove this entry point from the module
spirv.erase(spirv.begin() + inst, spirv.begin() + inst + len);
continue;
}
break;
case 16: // OpExecutionMode
if (std::find(functions_to_remove.begin(), functions_to_remove.end(), spirv[inst + 1]) != functions_to_remove.end())
{
spirv.erase(spirv.begin() + inst, spirv.begin() + inst + len);
continue;
}
break;
case 59: // OpVariable
// Remove all declarations of the interface variables for non-matching entry points
if (std::find(variables_to_remove.begin(), variables_to_remove.end(), spirv[inst + 2]) != variables_to_remove.end())
{
spirv.erase(spirv.begin() + inst, spirv.begin() + inst + len);
continue;
}
break;
case 71: // OpDecorate
// Remove all decorations targeting any of the interface variables for non-matching entry points
if (std::find(variables_to_remove.begin(), variables_to_remove.end(), spirv[inst + 1]) != variables_to_remove.end())
{
spirv.erase(spirv.begin() + inst, spirv.begin() + inst + len);
continue;
}
break;
case 54: // OpFunction
current_function = spirv[inst + 2];
current_function_offset = inst;
break;
case 56: // OpFunctionEnd
// Remove all function definitions for non-matching entry points
if (std::find(functions_to_remove.begin(), functions_to_remove.end(), current_function) != functions_to_remove.end())
{
spirv.erase(spirv.begin() + current_function_offset, spirv.begin() + inst + len);
inst = current_function_offset;
continue;
}
break;
}
inst += len;
}
VkShaderModuleCreateInfo create_info { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO };
create_info.codeSize = spirv.size() * sizeof(uint32_t);
create_info.pCode = spirv.data();
res = vk.CreateShaderModule(_device, &create_info, nullptr, &shader_modules.emplace_back(_device, vk));
}
entry_points[entry_point.name] = shader_modules.back();
}
if (res != VK_SUCCESS)
{
LOG(ERROR) << "Failed to create shader module. "
"Vulkan error code is " << res << '.';
return false;
}
}
if (_effect_data.size() <= index)
_effect_data.resize(index + 1);
vulkan_effect_data &effect_data = _effect_data[index];
// Create query pool for time measurements
{ VkQueryPoolCreateInfo create_info { VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO };
create_info.queryType = VK_QUERY_TYPE_TIMESTAMP;
create_info.queryCount = static_cast<uint32_t>(effect.module.techniques.size() * 2 * NUM_COMMAND_FRAMES);
check_result(vk.CreateQueryPool(_device, &create_info, nullptr, &effect_data.query_pool)) false;
}
// Initialize pipeline layout
{ std::vector<VkDescriptorSetLayoutBinding> bindings;
bindings.reserve(effect.module.num_sampler_bindings);
for (uint32_t i = 0; i < effect.module.num_sampler_bindings; ++i)
bindings.push_back({ i, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL_GRAPHICS });
VkDescriptorSetLayoutCreateInfo create_info { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
create_info.bindingCount = uint32_t(bindings.size());
create_info.pBindings = bindings.data();
check_result(vk.CreateDescriptorSetLayout(_device, &create_info, nullptr, &effect_data.set_layout)) false;
}
const VkDescriptorSetLayout set_layouts[2] = { _effect_descriptor_layout, effect_data.set_layout };
{ VkPipelineLayoutCreateInfo create_info { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
create_info.setLayoutCount = 2; // [0] = Global UBO, [1] = Samplers
create_info.pSetLayouts = set_layouts;
check_result(vk.CreatePipelineLayout(_device, &create_info, nullptr, &effect_data.pipeline_layout)) false;
}
// Create global uniform buffer object
if (!effect.uniform_data_storage.empty())
{
effect_data.ubo = create_buffer(
effect.uniform_data_storage.size(),
VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU,
0, 0, &effect_data.ubo_mem);
if (effect_data.ubo == VK_NULL_HANDLE)
return false;
}
// Initialize image and sampler bindings
std::vector<VkDescriptorImageInfo> image_bindings(effect.module.num_sampler_bindings);
for (const reshadefx::sampler_info &info : effect.module.samplers)
{
VkDescriptorImageInfo &image_binding = image_bindings[info.binding];
image_binding.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
const auto existing_texture = std::find_if(_textures.begin(), _textures.end(),
[&texture_name = info.texture_name](const auto &item) {
return item.unique_name == texture_name && item.impl != nullptr;
});
assert(existing_texture != _textures.end());
switch (existing_texture->impl_reference)
{
case texture_reference::back_buffer:
image_binding.imageView = _backbuffer_image_view[info.srgb];
break;
case texture_reference::depth_buffer:
// Set to a default view to avoid crash because of this being null
image_binding.imageView = _empty_depth_image_view;
#if RESHADE_DEPTH
if (_depth_image_view != VK_NULL_HANDLE)
image_binding.imageView = _depth_image_view;
#endif
// Keep track of the depth buffer texture descriptor to simplify updating it
effect_data.depth_image_binding = info.binding;
break;
default:
image_binding.imageView =
static_cast<vulkan_tex_data *>(existing_texture->impl)->view[info.srgb];
break;
}
// Unset bindings are not allowed, so fail initialization for the entire effect in that case
if (image_binding.imageView == VK_NULL_HANDLE)
return false;
VkSamplerCreateInfo create_info { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO };
create_info.addressModeU = static_cast<VkSamplerAddressMode>(static_cast<uint32_t>(info.address_u) - 1);
create_info.addressModeV = static_cast<VkSamplerAddressMode>(static_cast<uint32_t>(info.address_v) - 1);
create_info.addressModeW = static_cast<VkSamplerAddressMode>(static_cast<uint32_t>(info.address_w) - 1);
create_info.mipLodBias = info.lod_bias;
create_info.anisotropyEnable = VK_FALSE;
create_info.maxAnisotropy = 1.0f;
create_info.compareEnable = VK_FALSE;
create_info.compareOp = VK_COMPARE_OP_ALWAYS;
create_info.minLod = info.min_lod;
create_info.maxLod = info.max_lod;
switch (info.filter)
{
case reshadefx::texture_filter::min_mag_mip_point:
create_info.magFilter = VK_FILTER_NEAREST;
create_info.minFilter = VK_FILTER_NEAREST;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
break;
case reshadefx::texture_filter::min_mag_point_mip_linear:
create_info.magFilter = VK_FILTER_NEAREST;
create_info.minFilter = VK_FILTER_NEAREST;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
break;
case reshadefx::texture_filter::min_point_mag_linear_mip_point:
create_info.magFilter = VK_FILTER_LINEAR;
create_info.minFilter = VK_FILTER_NEAREST;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
break;
case reshadefx::texture_filter::min_point_mag_mip_linear:
create_info.magFilter = VK_FILTER_LINEAR;
create_info.minFilter = VK_FILTER_NEAREST;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
break;
case reshadefx::texture_filter::min_linear_mag_mip_point:
create_info.magFilter = VK_FILTER_NEAREST;
create_info.minFilter = VK_FILTER_LINEAR;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
break;
case reshadefx::texture_filter::min_linear_mag_point_mip_linear:
create_info.magFilter = VK_FILTER_NEAREST;
create_info.minFilter = VK_FILTER_LINEAR;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
break;
case reshadefx::texture_filter::min_mag_linear_mip_point:
create_info.magFilter = VK_FILTER_LINEAR;
create_info.minFilter = VK_FILTER_LINEAR;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
break;
case reshadefx::texture_filter::min_mag_mip_linear:
create_info.magFilter = VK_FILTER_LINEAR;
create_info.minFilter = VK_FILTER_LINEAR;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
break;
}
// Generate hash for sampler description
size_t desc_hash = 2166136261;
for (size_t i = 0; i < sizeof(create_info); ++i)
desc_hash = (desc_hash * 16777619) ^ reinterpret_cast<const uint8_t *>(&create_info)[i];
auto it = _effect_sampler_states.find(desc_hash);
if (it == _effect_sampler_states.end())
{
VkSampler sampler = VK_NULL_HANDLE;
check_result(vk.CreateSampler(_device, &create_info, nullptr, &sampler)) false;
it = _effect_sampler_states.emplace(desc_hash, sampler).first;