forked from flightlessmango/MangoHud
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvulkan.cpp
More file actions
2204 lines (1886 loc) · 87.7 KB
/
vulkan.cpp
File metadata and controls
2204 lines (1886 loc) · 87.7 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
/*
* Copyright © 2019 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifdef _WIN32
#include <windows.h>
#endif
#include <algorithm>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <thread>
#include <chrono>
#include <unordered_map>
#include <mutex>
#include <vector>
#include <list>
#include <array>
#include <iomanip>
#include <sstream>
#include <inttypes.h>
#include <spdlog/spdlog.h>
#include <imgui.h>
#include "mesa/util/macros.h" // defines "restrict" for vk_util.h
#include "mesa/util/os_socket.h"
#include <vulkan/vulkan.h>
#include <vulkan/vk_layer.h>
#include <vulkan/vk_util.h>
#include "vk_enum_to_str.h"
#include "vk_dispatch_table.h"
#include "overlay.h"
#include "notify.h"
#include "blacklist.h"
#include "pci_ids.h"
#if defined(HAVE_WAYLAND)
#include "wayland_hook.h"
#endif
#include "real_dlsym.h"
#include "file_utils.h"
#ifdef __linux__
#include <dlfcn.h>
#include "implot.h"
#endif
#include "imgui_utils.h"
#include "fps_limiter.h"
using namespace std;
float offset_x, offset_y, hudSpacing;
int hudFirstRow, hudSecondRow;
VkPhysicalDeviceDriverProperties driverProps = {};
#if !defined(_WIN32)
namespace MangoHud { namespace GL {
extern swapchain_stats sw_stats;
}}
#endif
/* Mapped from VkInstace/VkPhysicalDevice */
struct instance_data {
struct vk_instance_dispatch_table vtable;
struct vk_physical_device_dispatch_table pd_vtable;
VkInstance instance;
struct overlay_params params;
uint32_t api_version;
string engineName, engineVersion;
enum EngineTypes engine;
notify_thread notifier;
int control_client;
uint32_t applicationVersion;
};
/* Mapped from VkDevice */
struct queue_data;
struct device_data {
struct instance_data *instance;
PFN_vkSetDeviceLoaderData set_device_loader_data;
struct vk_device_dispatch_table vtable;
VkPhysicalDevice physical_device;
VkDevice device;
VkPhysicalDeviceProperties properties;
struct queue_data *graphic_queue;
std::vector<struct queue_data *> queues;
};
/* Mapped from VkCommandBuffer */
struct command_buffer_data {
struct device_data *device;
VkCommandBufferLevel level;
VkCommandBuffer cmd_buffer;
struct queue_data *queue_data;
};
/* Mapped from VkQueue */
struct queue_data {
struct device_data *device;
VkQueue queue;
VkQueueFlags flags;
uint32_t family_index;
};
struct overlay_draw {
VkCommandBuffer command_buffer;
VkSemaphore cross_engine_semaphore;
VkSemaphore semaphore;
VkFence fence;
VkBuffer vertex_buffer;
VkDeviceMemory vertex_buffer_mem;
VkDeviceSize vertex_buffer_size;
VkBuffer index_buffer;
VkDeviceMemory index_buffer_mem;
VkDeviceSize index_buffer_size;
};
/* Mapped from VkSwapchainKHR */
struct swapchain_data {
struct device_data *device;
VkSwapchainKHR swapchain;
unsigned width, height;
VkFormat format;
std::vector<VkImage> images;
std::vector<VkImageView> image_views;
std::vector<VkFramebuffer> framebuffers;
VkRenderPass render_pass;
VkDescriptorPool descriptor_pool;
VkDescriptorSetLayout descriptor_layout;
VkDescriptorSet descriptor_set;
VkSampler font_sampler;
VkPipelineLayout pipeline_layout;
VkPipeline pipeline;
VkCommandPool command_pool;
std::vector<overlay_draw *> draws; /* vector of struct overlay_draw */
bool font_uploaded;
VkImage font_image;
VkImageView font_image_view;
VkDeviceMemory font_mem;
VkBuffer upload_font_buffer;
VkDeviceMemory upload_font_buffer_mem;
struct imgui_contexts imgui_contexts;
ImFontAtlas* font_atlas;
ImVec2 window_size;
struct swapchain_stats sw_stats;
};
// single global lock, for simplicity
std::mutex global_lock;
typedef std::lock_guard<std::mutex> scoped_lock;
std::unordered_map<uint64_t, void *> vk_object_to_data;
thread_local ImGuiContext* __MesaImGui;
#define HKEY(obj) ((uint64_t)(obj))
#define FIND(type, obj) (reinterpret_cast<type *>(find_object_data(HKEY(obj))))
static void *find_object_data(uint64_t obj)
{
::scoped_lock lk(global_lock);
return vk_object_to_data[obj];
}
static void map_object(uint64_t obj, void *data)
{
::scoped_lock lk(global_lock);
vk_object_to_data[obj] = data;
}
static void unmap_object(uint64_t obj)
{
::scoped_lock lk(global_lock);
vk_object_to_data.erase(obj);
}
/**/
#define VK_CHECK(expr) \
do { \
VkResult __result = (expr); \
if (__result != VK_SUCCESS) { \
SPDLOG_ERROR("'{}' line {} failed with {}", \
#expr, __LINE__, vk_Result_to_str(__result)); \
} \
} while (0)
/**/
static void shutdown_swapchain_font(struct swapchain_data*);
static VkLayerInstanceCreateInfo *get_instance_chain_info(const VkInstanceCreateInfo *pCreateInfo,
VkLayerFunction func)
{
vk_foreach_struct(item, pCreateInfo->pNext) {
if (item->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO &&
((VkLayerInstanceCreateInfo *) item)->function == func)
return (VkLayerInstanceCreateInfo *) item;
}
UNREACHABLE("instance chain info not found");
return NULL;
}
static VkLayerDeviceCreateInfo *get_device_chain_info(const VkDeviceCreateInfo *pCreateInfo,
VkLayerFunction func)
{
vk_foreach_struct(item, pCreateInfo->pNext) {
if (item->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO &&
((VkLayerDeviceCreateInfo *) item)->function == func)
return (VkLayerDeviceCreateInfo *)item;
}
UNREACHABLE("device chain info not found");
return NULL;
}
/**/
static struct instance_data *new_instance_data(VkInstance instance)
{
struct instance_data *data = new instance_data();
data->instance = instance;
data->params = {};
data->params.control = -1;
data->control_client = -1;
map_object(HKEY(data->instance), data);
return data;
}
static void destroy_instance_data(struct instance_data *data)
{
if (data->params.control >= 0)
os_socket_close(data->params.control);
unmap_object(HKEY(data->instance));
delete data;
}
static void instance_data_map_physical_devices(struct instance_data *instance_data,
bool map)
{
uint32_t physicalDeviceCount = 0;
instance_data->vtable.EnumeratePhysicalDevices(instance_data->instance,
&physicalDeviceCount,
NULL);
std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
instance_data->vtable.EnumeratePhysicalDevices(instance_data->instance,
&physicalDeviceCount,
physicalDevices.data());
for (uint32_t i = 0; i < physicalDeviceCount; i++) {
if (map)
map_object(HKEY(physicalDevices[i]), instance_data);
else
unmap_object(HKEY(physicalDevices[i]));
}
}
/**/
static struct device_data *new_device_data(VkDevice device, struct instance_data *instance)
{
struct device_data *data = new device_data();
data->instance = instance;
data->device = device;
map_object(HKEY(data->device), data);
return data;
}
static struct queue_data *new_queue_data(VkQueue queue,
const VkQueueFamilyProperties *family_props,
uint32_t family_index,
struct device_data *device_data)
{
struct queue_data *data = new queue_data();
data->device = device_data;
data->queue = queue;
data->flags = family_props->queueFlags;
data->family_index = family_index;
map_object(HKEY(data->queue), data);
if (data->flags & VK_QUEUE_GRAPHICS_BIT)
device_data->graphic_queue = data;
return data;
}
static void destroy_queue(struct queue_data *data)
{
unmap_object(HKEY(data->queue));
delete data;
}
static void device_map_queues(struct device_data *data,
const VkDeviceCreateInfo *pCreateInfo)
{
uint32_t n_queues = 0;
for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++)
n_queues += pCreateInfo->pQueueCreateInfos[i].queueCount;
data->queues.resize(n_queues);
struct instance_data *instance_data = data->instance;
uint32_t n_family_props;
instance_data->pd_vtable.GetPhysicalDeviceQueueFamilyProperties(data->physical_device,
&n_family_props,
NULL);
std::vector<VkQueueFamilyProperties> family_props(n_family_props);
instance_data->pd_vtable.GetPhysicalDeviceQueueFamilyProperties(data->physical_device,
&n_family_props,
family_props.data());
uint32_t queue_index = 0;
for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
for (uint32_t j = 0; j < pCreateInfo->pQueueCreateInfos[i].queueCount; j++) {
VkQueue queue;
data->vtable.GetDeviceQueue(data->device,
pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex,
j, &queue);
VK_CHECK(data->set_device_loader_data(data->device, queue));
data->queues[queue_index++] =
new_queue_data(queue, &family_props[pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex],
pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex, data);
}
}
}
static void device_unmap_queues(struct device_data *data)
{
for (auto q : data->queues)
destroy_queue(q);
}
static void destroy_device_data(struct device_data *data)
{
unmap_object(HKEY(data->device));
delete data;
}
/**/
static struct command_buffer_data *new_command_buffer_data(VkCommandBuffer cmd_buffer,
VkCommandBufferLevel level,
struct device_data *device_data)
{
struct command_buffer_data *data = new command_buffer_data();
data->device = device_data;
data->cmd_buffer = cmd_buffer;
data->level = level;
map_object(HKEY(data->cmd_buffer), data);
return data;
}
static void destroy_command_buffer_data(struct command_buffer_data *data)
{
unmap_object(HKEY(data->cmd_buffer));
delete data;
}
/**/
static struct swapchain_data *new_swapchain_data(VkSwapchainKHR swapchain,
struct device_data *device_data)
{
struct instance_data *instance_data = device_data->instance;
struct swapchain_data *data = new swapchain_data();
data->device = device_data;
data->swapchain = swapchain;
data->window_size = ImVec2(instance_data->params.width, instance_data->params.height);
data->font_atlas = IM_NEW(ImFontAtlas);
map_object(HKEY(data->swapchain), data);
return data;
}
static void destroy_swapchain_data(struct swapchain_data *data)
{
unmap_object(HKEY(data->swapchain));
delete data;
}
static struct overlay_draw *get_overlay_draw(struct swapchain_data *data, unsigned image_idx)
{
struct device_data *device_data = data->device;
const size_t images_count = data->images.size();
if (data->draws.size() < images_count) {
data->draws.resize(images_count, nullptr);
}
struct overlay_draw *draw = data->draws[image_idx];
VkSemaphoreCreateInfo sem_info = {};
sem_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
if (draw) {
VK_CHECK(device_data->vtable.WaitForFences(device_data->device, 1,
&draw->fence, VK_TRUE, ~0ull));
VK_CHECK(device_data->vtable.ResetFences(device_data->device,
1, &draw->fence));
return draw;
}
draw = new overlay_draw();
VkCommandBufferAllocateInfo cmd_buffer_info = {};
cmd_buffer_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
cmd_buffer_info.commandPool = data->command_pool;
cmd_buffer_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
cmd_buffer_info.commandBufferCount = 1;
VK_CHECK(device_data->vtable.AllocateCommandBuffers(device_data->device,
&cmd_buffer_info,
&draw->command_buffer));
VK_CHECK(device_data->set_device_loader_data(device_data->device,
draw->command_buffer));
VkFenceCreateInfo fence_info = {};
fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
VK_CHECK(device_data->vtable.CreateFence(device_data->device,
&fence_info,
NULL,
&draw->fence));
VK_CHECK(device_data->vtable.CreateSemaphore(device_data->device, &sem_info,
NULL, &draw->semaphore));
VK_CHECK(device_data->vtable.CreateSemaphore(device_data->device, &sem_info,
NULL, &draw->cross_engine_semaphore));
data->draws[image_idx] = draw;
return draw;
}
static void snapshot_swapchain_frame(struct swapchain_data *data)
{
struct device_data *device_data = data->device;
struct instance_data *instance_data = device_data->instance;
update_hud_info(data->sw_stats, instance_data->params, device_data->properties.vendorID);
check_keybinds(instance_data->params);
#ifdef __linux__
if (instance_data->params.control >= 0) {
control_client_check(instance_data->params.control, instance_data->control_client, gpu.c_str());
process_control_socket(instance_data->control_client, instance_data->params);
}
#endif
}
static void compute_swapchain_display(struct swapchain_data *data)
{
struct device_data *device_data = data->device;
struct instance_data *instance_data = device_data->instance;
if (get_params()->no_display)
return;
auto saved_imgui_context = get_current_imgui_contexts();
make_imgui_contexts_current(data->imgui_contexts);
if (HUDElements.colors.update)
HUDElements.convert_colors(instance_data->params);
ImGui::NewFrame();
{
::scoped_lock lk(instance_data->notifier.mutex);
overlay_new_frame(instance_data->params);
position_layer(data->sw_stats, instance_data->params, data->window_size);
render_imgui(data->sw_stats, instance_data->params, data->window_size, true);
overlay_end_frame();
}
ImGui::EndFrame();
ImGui::Render();
make_imgui_contexts_current(saved_imgui_context);
}
static uint32_t vk_memory_type(struct device_data *data,
VkMemoryPropertyFlags properties,
uint32_t type_bits)
{
VkPhysicalDeviceMemoryProperties prop;
data->instance->pd_vtable.GetPhysicalDeviceMemoryProperties(data->physical_device, &prop);
for (uint32_t i = 0; i < prop.memoryTypeCount; i++)
if ((prop.memoryTypes[i].propertyFlags & properties) == properties && type_bits & (1<<i))
return i;
return 0xFFFFFFFF; // Unable to find memoryType
}
static void update_image_descriptor(struct swapchain_data *data, VkImageView image_view, VkDescriptorSet set)
{
struct device_data *device_data = data->device;
/* Descriptor set */
VkDescriptorImageInfo desc_image[1] = {};
desc_image[0].sampler = data->font_sampler;
desc_image[0].imageView = image_view;
desc_image[0].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
VkWriteDescriptorSet write_desc[1] = {};
write_desc[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write_desc[0].dstSet = set;
write_desc[0].descriptorCount = 1;
write_desc[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
write_desc[0].pImageInfo = desc_image;
device_data->vtable.UpdateDescriptorSets(device_data->device, 1, write_desc, 0, NULL);
}
static void upload_image_data(struct device_data *device_data,
VkCommandBuffer command_buffer,
void *pixels,
VkDeviceSize upload_size,
uint32_t width,
uint32_t height,
VkBuffer& upload_buffer,
VkDeviceMemory& upload_buffer_mem,
VkImage image)
{
/* Upload buffer */
VkBufferCreateInfo buffer_info = {};
buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_info.size = upload_size;
buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VK_CHECK(device_data->vtable.CreateBuffer(device_data->device, &buffer_info,
NULL, &upload_buffer));
VkMemoryRequirements upload_buffer_req;
device_data->vtable.GetBufferMemoryRequirements(device_data->device,
upload_buffer,
&upload_buffer_req);
VkMemoryAllocateInfo upload_alloc_info = {};
upload_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
upload_alloc_info.allocationSize = upload_buffer_req.size;
upload_alloc_info.memoryTypeIndex = vk_memory_type(device_data,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
upload_buffer_req.memoryTypeBits);
VK_CHECK(device_data->vtable.AllocateMemory(device_data->device,
&upload_alloc_info,
NULL,
&upload_buffer_mem));
VK_CHECK(device_data->vtable.BindBufferMemory(device_data->device,
upload_buffer,
upload_buffer_mem, 0));
/* Upload to Buffer */
char* map = NULL;
VK_CHECK(device_data->vtable.MapMemory(device_data->device,
upload_buffer_mem,
0, upload_size, 0, (void**)(&map)));
memcpy(map, pixels, upload_size);
VkMappedMemoryRange range[1] = {};
range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
range[0].memory = upload_buffer_mem;
range[0].size = upload_size;
VK_CHECK(device_data->vtable.FlushMappedMemoryRanges(device_data->device, 1, range));
device_data->vtable.UnmapMemory(device_data->device,
upload_buffer_mem);
/* Copy buffer to image */
VkImageMemoryBarrier copy_barrier[1] = {};
copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
copy_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
copy_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
copy_barrier[0].image = image;
copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copy_barrier[0].subresourceRange.levelCount = 1;
copy_barrier[0].subresourceRange.layerCount = 1;
device_data->vtable.CmdPipelineBarrier(command_buffer,
VK_PIPELINE_STAGE_HOST_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 0, NULL,
1, copy_barrier);
VkBufferImageCopy region = {};
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.layerCount = 1;
region.imageExtent.width = width;
region.imageExtent.height = height;
region.imageExtent.depth = 1;
device_data->vtable.CmdCopyBufferToImage(command_buffer,
upload_buffer,
image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1, ®ion);
VkImageMemoryBarrier use_barrier[1] = {};
use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
use_barrier[0].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
use_barrier[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
use_barrier[0].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
use_barrier[0].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
use_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
use_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
use_barrier[0].image = image;
use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
use_barrier[0].subresourceRange.levelCount = 1;
use_barrier[0].subresourceRange.layerCount = 1;
device_data->vtable.CmdPipelineBarrier(command_buffer,
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
0,
0, NULL,
0, NULL,
1, use_barrier);
}
static void create_image(struct swapchain_data *data,
VkDescriptorSet descriptor_set,
uint32_t width,
uint32_t height,
VkFormat format,
VkImage& image,
VkDeviceMemory& image_mem,
VkImageView& image_view)
{
struct device_data *device_data = data->device;
VkImageCreateInfo image_info = {};
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.format = format;
image_info.extent.width = width;
image_info.extent.height = height;
image_info.extent.depth = 1;
image_info.mipLevels = 1;
image_info.arrayLayers = 1;
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
VK_CHECK(device_data->vtable.CreateImage(device_data->device, &image_info,
NULL, &image));
VkMemoryRequirements font_image_req;
device_data->vtable.GetImageMemoryRequirements(device_data->device,
image, &font_image_req);
VkMemoryAllocateInfo image_alloc_info = {};
image_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
image_alloc_info.allocationSize = font_image_req.size;
image_alloc_info.memoryTypeIndex = vk_memory_type(device_data,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
font_image_req.memoryTypeBits);
VK_CHECK(device_data->vtable.AllocateMemory(device_data->device, &image_alloc_info,
NULL, &image_mem));
VK_CHECK(device_data->vtable.BindImageMemory(device_data->device,
image,
image_mem, 0));
/* Font image view */
VkImageViewCreateInfo view_info = {};
view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
view_info.image = image;
view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
view_info.format = format;
view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
view_info.subresourceRange.levelCount = 1;
view_info.subresourceRange.layerCount = 1;
VK_CHECK(device_data->vtable.CreateImageView(device_data->device, &view_info,
NULL, &image_view));
update_image_descriptor(data, image_view, descriptor_set);
}
static VkDescriptorSet create_image_with_desc(struct swapchain_data *data,
uint32_t width,
uint32_t height,
VkFormat format,
VkImage& image,
VkDeviceMemory& image_mem,
VkImageView& image_view)
{
struct device_data *device_data = data->device;
VkDescriptorSet descriptor_set {};
VkDescriptorSetAllocateInfo alloc_info {};
alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
alloc_info.descriptorPool = data->descriptor_pool;
alloc_info.descriptorSetCount = 1;
alloc_info.pSetLayouts = &data->descriptor_layout;
VK_CHECK(device_data->vtable.AllocateDescriptorSets(device_data->device,
&alloc_info,
&descriptor_set));
create_image(data, descriptor_set, width, height, format, image, image_mem, image_view);
return descriptor_set;
}
static void check_fonts(struct swapchain_data* data)
{
struct device_data *device_data = data->device;
struct instance_data *instance_data = device_data->instance;
auto& params = instance_data->params;
if (params.font_params_hash != data->sw_stats.font_params_hash)
{
SPDLOG_DEBUG("Recreating font image");
VkDescriptorSet desc_set = (VkDescriptorSet)data->font_atlas->TexID;
create_fonts(data->font_atlas, instance_data->params, data->sw_stats.font_small, data->sw_stats.font_text, data->sw_stats.font_secondary);
unsigned char* pixels;
int width, height;
data->font_atlas->GetTexDataAsAlpha8(&pixels, &width, &height);
// wait for rendering to complete, if any
device_data->vtable.DeviceWaitIdle(device_data->device);
shutdown_swapchain_font(data);
if (desc_set)
create_image(data, desc_set, width, height, VK_FORMAT_R8_UNORM, data->font_image, data->font_mem, data->font_image_view);
else
desc_set = create_image_with_desc(data, width, height, VK_FORMAT_R8_UNORM, data->font_image, data->font_mem, data->font_image_view);
data->font_atlas->SetTexID((ImTextureID)desc_set);
data->font_uploaded = false;
data->sw_stats.font_params_hash = params.font_params_hash;
SPDLOG_DEBUG("Default font tex size: {}x{}px", width, height);
}
}
static void ensure_swapchain_fonts(struct swapchain_data *data,
VkCommandBuffer command_buffer)
{
struct device_data *device_data = data->device;
check_fonts(data);
if (data->font_uploaded)
return;
data->font_uploaded = true;
unsigned char* pixels;
int width, height;
data->font_atlas->GetTexDataAsAlpha8(&pixels, &width, &height);
size_t upload_size = width * height * 1 * sizeof(char);
upload_image_data(device_data, command_buffer, pixels, upload_size, width, height, data->upload_font_buffer, data->upload_font_buffer_mem, data->font_image);
}
static void CreateOrResizeBuffer(struct device_data *data,
VkBuffer *buffer,
VkDeviceMemory *buffer_memory,
VkDeviceSize *buffer_size,
size_t new_size, VkBufferUsageFlagBits usage)
{
if (*buffer != VK_NULL_HANDLE)
data->vtable.DestroyBuffer(data->device, *buffer, NULL);
if (*buffer_memory)
data->vtable.FreeMemory(data->device, *buffer_memory, NULL);
if (data->properties.limits.nonCoherentAtomSize > 0)
{
VkDeviceSize atom_size = data->properties.limits.nonCoherentAtomSize - 1;
new_size = (new_size + atom_size) & ~atom_size;
}
VkBufferCreateInfo buffer_info = {};
buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_info.size = new_size;
buffer_info.usage = usage;
buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VK_CHECK(data->vtable.CreateBuffer(data->device, &buffer_info, NULL, buffer));
VkMemoryRequirements req;
data->vtable.GetBufferMemoryRequirements(data->device, *buffer, &req);
VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = req.size;
alloc_info.memoryTypeIndex =
vk_memory_type(data, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits);
VK_CHECK(data->vtable.AllocateMemory(data->device, &alloc_info, NULL, buffer_memory));
VK_CHECK(data->vtable.BindBufferMemory(data->device, *buffer, *buffer_memory, 0));
*buffer_size = new_size;
}
static struct overlay_draw *render_swapchain_display(struct swapchain_data *data,
struct queue_data *present_queue,
const VkSemaphore *wait_semaphores,
unsigned n_wait_semaphores,
unsigned image_index)
{
auto saved_imgui_context = get_current_imgui_contexts();
make_imgui_contexts_current(data->imgui_contexts);
ImDrawData* draw_data = ImGui::GetDrawData();
struct device_data *device_data = data->device;
if (!draw_data || draw_data->TotalVtxCount == 0 || get_params()->no_display)
{
make_imgui_contexts_current(saved_imgui_context);
return nullptr;
}
struct overlay_draw *draw = get_overlay_draw(data, image_index);
device_data->vtable.ResetCommandBuffer(draw->command_buffer, 0);
VkRenderPassBeginInfo render_pass_info = {};
render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
render_pass_info.renderPass = data->render_pass;
render_pass_info.framebuffer = data->framebuffers[image_index];
render_pass_info.renderArea.extent.width = data->width;
render_pass_info.renderArea.extent.height = data->height;
VkCommandBufferBeginInfo buffer_begin_info = {};
buffer_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
device_data->vtable.BeginCommandBuffer(draw->command_buffer, &buffer_begin_info);
ensure_swapchain_fonts(data, draw->command_buffer);
/* Bounce the image to display back to color attachment layout for
* rendering on top of it.
*/
VkImageMemoryBarrier imb;
imb.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
imb.pNext = nullptr;
imb.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
imb.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
imb.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
imb.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
imb.image = data->images[image_index];
imb.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
imb.subresourceRange.baseMipLevel = 0;
imb.subresourceRange.levelCount = 1;
imb.subresourceRange.baseArrayLayer = 0;
imb.subresourceRange.layerCount = 1;
imb.srcQueueFamilyIndex = present_queue->family_index;
imb.dstQueueFamilyIndex = device_data->graphic_queue->family_index;
device_data->vtable.CmdPipelineBarrier(draw->command_buffer,
VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
0, /* dependency flags */
0, nullptr, /* memory barriers */
0, nullptr, /* buffer memory barriers */
1, &imb); /* image memory barriers */
device_data->vtable.CmdBeginRenderPass(draw->command_buffer, &render_pass_info,
VK_SUBPASS_CONTENTS_INLINE);
/* Create/Resize vertex & index buffers */
size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert);
size_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx);
if (draw->vertex_buffer_size < vertex_size) {
CreateOrResizeBuffer(device_data,
&draw->vertex_buffer,
&draw->vertex_buffer_mem,
&draw->vertex_buffer_size,
vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
}
if (draw->index_buffer_size < index_size) {
CreateOrResizeBuffer(device_data,
&draw->index_buffer,
&draw->index_buffer_mem,
&draw->index_buffer_size,
index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
}
/* Upload vertex & index data */
ImDrawVert* vtx_dst = NULL;
ImDrawIdx* idx_dst = NULL;
VK_CHECK(device_data->vtable.MapMemory(device_data->device, draw->vertex_buffer_mem,
0, draw->vertex_buffer_size, 0, (void**)(&vtx_dst)));
VK_CHECK(device_data->vtable.MapMemory(device_data->device, draw->index_buffer_mem,
0, draw->index_buffer_size, 0, (void**)(&idx_dst)));
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
vtx_dst += cmd_list->VtxBuffer.Size;
idx_dst += cmd_list->IdxBuffer.Size;
}
VkMappedMemoryRange range[2] = {};
range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
range[0].memory = draw->vertex_buffer_mem;
range[0].size = VK_WHOLE_SIZE;
range[1].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
range[1].memory = draw->index_buffer_mem;
range[1].size = VK_WHOLE_SIZE;
VK_CHECK(device_data->vtable.FlushMappedMemoryRanges(device_data->device, 2, range));
device_data->vtable.UnmapMemory(device_data->device, draw->vertex_buffer_mem);
device_data->vtable.UnmapMemory(device_data->device, draw->index_buffer_mem);
/* Bind pipeline and descriptor sets */
device_data->vtable.CmdBindPipeline(draw->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, data->pipeline);
#if 1 // disable if using >1 font textures
VkDescriptorSet desc_set[1] = {
//data->descriptor_set
reinterpret_cast<VkDescriptorSet>(data->font_atlas->TexID)
};
device_data->vtable.CmdBindDescriptorSets(draw->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
data->pipeline_layout, 0, 1, desc_set, 0, NULL);
#endif
/* Bind vertex & index buffers */
VkBuffer vertex_buffers[1] = { draw->vertex_buffer };
VkDeviceSize vertex_offset[1] = { 0 };
device_data->vtable.CmdBindVertexBuffers(draw->command_buffer, 0, 1, vertex_buffers, vertex_offset);
device_data->vtable.CmdBindIndexBuffer(draw->command_buffer, draw->index_buffer, 0, VK_INDEX_TYPE_UINT16);
/* Setup viewport */
VkViewport viewport;
viewport.x = 0;
viewport.y = 0;
viewport.width = draw_data->DisplaySize.x;
viewport.height = draw_data->DisplaySize.y;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
device_data->vtable.CmdSetViewport(draw->command_buffer, 0, 1, &viewport);
/* Setup scale and translation through push constants :
*
* Our visible imgui space lies from draw_data->DisplayPos (top left) to
* draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin
* is typically (0,0) for single viewport apps.
*/
float scale[2];
scale[0] = 2.0f / draw_data->DisplaySize.x;
scale[1] = 2.0f / draw_data->DisplaySize.y;
float translate[2];
translate[0] = -1.0f - draw_data->DisplayPos.x * scale[0];
translate[1] = -1.0f - draw_data->DisplayPos.y * scale[1];
device_data->vtable.CmdPushConstants(draw->command_buffer, data->pipeline_layout,
VK_SHADER_STAGE_VERTEX_BIT,
sizeof(float) * 0, sizeof(float) * 2, scale);
device_data->vtable.CmdPushConstants(draw->command_buffer, data->pipeline_layout,
VK_SHADER_STAGE_VERTEX_BIT,
sizeof(float) * 2, sizeof(float) * 2, translate);
// Render the command lists:
int vtx_offset = 0;
int idx_offset = 0;
ImVec2 display_pos = draw_data->DisplayPos;
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
// Apply scissor/clipping rectangle
// FIXME: We could clamp width/height based on clamped min/max values.
VkRect2D scissor;
scissor.offset.x = (int32_t)(pcmd->ClipRect.x - display_pos.x) > 0 ? (int32_t)(pcmd->ClipRect.x - display_pos.x) : 0;
scissor.offset.y = (int32_t)(pcmd->ClipRect.y - display_pos.y) > 0 ? (int32_t)(pcmd->ClipRect.y - display_pos.y) : 0;
scissor.extent.width = (uint32_t)(pcmd->ClipRect.z - pcmd->ClipRect.x);
scissor.extent.height = (uint32_t)(pcmd->ClipRect.w - pcmd->ClipRect.y + 1); // FIXME: Why +1 here?
device_data->vtable.CmdSetScissor(draw->command_buffer, 0, 1, &scissor);
#if 0 //enable if using >1 font textures or use texture array
VkDescriptorSet desc_set[1] = { (VkDescriptorSet)pcmd->TextureId };
device_data->vtable.CmdBindDescriptorSets(draw->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
data->pipeline_layout, 0, 1, desc_set, 0, NULL);
#endif
// Draw
device_data->vtable.CmdDrawIndexed(draw->command_buffer, pcmd->ElemCount, 1, idx_offset, vtx_offset, 0);
idx_offset += pcmd->ElemCount;
}
vtx_offset += cmd_list->VtxBuffer.Size;
}
device_data->vtable.CmdEndRenderPass(draw->command_buffer);
if (device_data->graphic_queue->family_index != present_queue->family_index)