1 /*
2  * Copyright © 2019 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 
24 #include <string.h>
25 #include <stdlib.h>
26 #include <assert.h>
27 
28 #include <vulkan/vulkan.h>
29 #include <vulkan/vk_layer.h>
30 
31 #include "git_sha1.h"
32 
33 #include "imgui.h"
34 
35 #include "overlay_params.h"
36 
37 #include "util/debug.h"
38 #include "util/hash_table.h"
39 #include "util/list.h"
40 #include "util/ralloc.h"
41 #include "util/os_time.h"
42 #include "util/os_socket.h"
43 #include "util/simple_mtx.h"
44 
45 #include "vk_enum_to_str.h"
46 #include "vk_util.h"
47 
48 /* Mapped from VkInstace/VkPhysicalDevice */
49 struct instance_data {
50    struct vk_instance_dispatch_table vtable;
51    VkInstance instance;
52 
53    struct overlay_params params;
54    bool pipeline_statistics_enabled;
55 
56    bool first_line_printed;
57 
58    int control_client;
59 
60    /* Dumping of frame stats to a file has been enabled. */
61    bool capture_enabled;
62 
63    /* Dumping of frame stats to a file has been enabled and started. */
64    bool capture_started;
65 };
66 
67 struct frame_stat {
68    uint64_t stats[OVERLAY_PARAM_ENABLED_MAX];
69 };
70 
71 /* Mapped from VkDevice */
72 struct queue_data;
73 struct device_data {
74    struct instance_data *instance;
75 
76    PFN_vkSetDeviceLoaderData set_device_loader_data;
77 
78    struct vk_device_dispatch_table vtable;
79    VkPhysicalDevice physical_device;
80    VkDevice device;
81 
82    VkPhysicalDeviceProperties properties;
83 
84    struct queue_data *graphic_queue;
85 
86    struct queue_data **queues;
87    uint32_t n_queues;
88 
89    /* For a single frame */
90    struct frame_stat frame_stats;
91 };
92 
93 /* Mapped from VkCommandBuffer */
94 struct command_buffer_data {
95    struct device_data *device;
96 
97    VkCommandBufferLevel level;
98 
99    VkCommandBuffer cmd_buffer;
100    VkQueryPool pipeline_query_pool;
101    VkQueryPool timestamp_query_pool;
102    uint32_t query_index;
103 
104    struct frame_stat stats;
105 
106    struct list_head link; /* link into queue_data::running_command_buffer */
107 };
108 
109 /* Mapped from VkQueue */
110 struct queue_data {
111    struct device_data *device;
112 
113    VkQueue queue;
114    VkQueueFlags flags;
115    uint32_t family_index;
116    uint64_t timestamp_mask;
117 
118    VkFence queries_fence;
119 
120    struct list_head running_command_buffer;
121 };
122 
123 struct overlay_draw {
124    struct list_head link;
125 
126    VkCommandBuffer command_buffer;
127 
128    VkSemaphore cross_engine_semaphore;
129 
130    VkSemaphore semaphore;
131    VkFence fence;
132 
133    VkBuffer vertex_buffer;
134    VkDeviceMemory vertex_buffer_mem;
135    VkDeviceSize vertex_buffer_size;
136 
137    VkBuffer index_buffer;
138    VkDeviceMemory index_buffer_mem;
139    VkDeviceSize index_buffer_size;
140 };
141 
142 /* Mapped from VkSwapchainKHR */
143 struct swapchain_data {
144    struct device_data *device;
145 
146    VkSwapchainKHR swapchain;
147    unsigned width, height;
148    VkFormat format;
149 
150    uint32_t n_images;
151    VkImage *images;
152    VkImageView *image_views;
153    VkFramebuffer *framebuffers;
154 
155    VkRenderPass render_pass;
156 
157    VkDescriptorPool descriptor_pool;
158    VkDescriptorSetLayout descriptor_layout;
159    VkDescriptorSet descriptor_set;
160 
161    VkSampler font_sampler;
162 
163    VkPipelineLayout pipeline_layout;
164    VkPipeline pipeline;
165 
166    VkCommandPool command_pool;
167 
168    struct list_head draws; /* List of struct overlay_draw */
169 
170    bool font_uploaded;
171    VkImage font_image;
172    VkImageView font_image_view;
173    VkDeviceMemory font_mem;
174    VkBuffer upload_font_buffer;
175    VkDeviceMemory upload_font_buffer_mem;
176 
177    /**/
178    ImGuiContext* imgui_context;
179    ImVec2 window_size;
180 
181    /**/
182    uint64_t n_frames;
183    uint64_t last_present_time;
184 
185    unsigned n_frames_since_update;
186    uint64_t last_fps_update;
187    double fps;
188 
189    enum overlay_param_enabled stat_selector;
190    double time_dividor;
191    struct frame_stat stats_min, stats_max;
192    struct frame_stat frames_stats[200];
193 
194    /* Over a single frame */
195    struct frame_stat frame_stats;
196 
197    /* Over fps_sampling_period */
198    struct frame_stat accumulated_stats;
199 };
200 
201 static const VkQueryPipelineStatisticFlags overlay_query_flags =
202    VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT |
203    VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT |
204    VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT |
205    VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_INVOCATIONS_BIT |
206    VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT |
207    VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT |
208    VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT |
209    VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT |
210    VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_CONTROL_SHADER_PATCHES_BIT |
211    VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT |
212    VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT;
213 #define OVERLAY_QUERY_COUNT (11)
214 
215 static struct hash_table_u64 *vk_object_to_data = NULL;
216 static simple_mtx_t vk_object_to_data_mutex = _SIMPLE_MTX_INITIALIZER_NP;
217 
218 thread_local ImGuiContext* __MesaImGui;
219 
ensure_vk_object_map(void)220 static inline void ensure_vk_object_map(void)
221 {
222    if (!vk_object_to_data)
223       vk_object_to_data = _mesa_hash_table_u64_create(NULL);
224 }
225 
226 #define HKEY(obj) ((uint64_t)(obj))
227 #define FIND(type, obj) ((type *)find_object_data(HKEY(obj)))
228 
find_object_data(uint64_t obj)229 static void *find_object_data(uint64_t obj)
230 {
231    simple_mtx_lock(&vk_object_to_data_mutex);
232    ensure_vk_object_map();
233    void *data = _mesa_hash_table_u64_search(vk_object_to_data, obj);
234    simple_mtx_unlock(&vk_object_to_data_mutex);
235    return data;
236 }
237 
map_object(uint64_t obj,void * data)238 static void map_object(uint64_t obj, void *data)
239 {
240    simple_mtx_lock(&vk_object_to_data_mutex);
241    ensure_vk_object_map();
242    _mesa_hash_table_u64_insert(vk_object_to_data, obj, data);
243    simple_mtx_unlock(&vk_object_to_data_mutex);
244 }
245 
unmap_object(uint64_t obj)246 static void unmap_object(uint64_t obj)
247 {
248    simple_mtx_lock(&vk_object_to_data_mutex);
249    _mesa_hash_table_u64_remove(vk_object_to_data, obj);
250    simple_mtx_unlock(&vk_object_to_data_mutex);
251 }
252 
253 /**/
254 
255 #define VK_CHECK(expr) \
256    do { \
257       VkResult __result = (expr); \
258       if (__result != VK_SUCCESS) { \
259          fprintf(stderr, "'%s' line %i failed with %s\n", \
260                  #expr, __LINE__, vk_Result_to_str(__result)); \
261       } \
262    } while (0)
263 
264 /**/
265 
get_instance_chain_info(const VkInstanceCreateInfo * pCreateInfo,VkLayerFunction func)266 static VkLayerInstanceCreateInfo *get_instance_chain_info(const VkInstanceCreateInfo *pCreateInfo,
267                                                           VkLayerFunction func)
268 {
269    vk_foreach_struct(item, pCreateInfo->pNext) {
270       if (item->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO &&
271           ((VkLayerInstanceCreateInfo *) item)->function == func)
272          return (VkLayerInstanceCreateInfo *) item;
273    }
274    unreachable("instance chain info not found");
275    return NULL;
276 }
277 
get_device_chain_info(const VkDeviceCreateInfo * pCreateInfo,VkLayerFunction func)278 static VkLayerDeviceCreateInfo *get_device_chain_info(const VkDeviceCreateInfo *pCreateInfo,
279                                                       VkLayerFunction func)
280 {
281    vk_foreach_struct(item, pCreateInfo->pNext) {
282       if (item->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO &&
283           ((VkLayerDeviceCreateInfo *) item)->function == func)
284          return (VkLayerDeviceCreateInfo *)item;
285    }
286    unreachable("device chain info not found");
287    return NULL;
288 }
289 
290 static struct VkBaseOutStructure *
clone_chain(const struct VkBaseInStructure * chain)291 clone_chain(const struct VkBaseInStructure *chain)
292 {
293    struct VkBaseOutStructure *head = NULL, *tail = NULL;
294 
295    vk_foreach_struct_const(item, chain) {
296       size_t item_size = vk_structure_type_size(item);
297       struct VkBaseOutStructure *new_item =
298          (struct VkBaseOutStructure *)malloc(item_size);;
299 
300       memcpy(new_item, item, item_size);
301 
302       if (!head)
303          head = new_item;
304       if (tail)
305          tail->pNext = new_item;
306       tail = new_item;
307    }
308 
309    return head;
310 }
311 
312 static void
free_chain(struct VkBaseOutStructure * chain)313 free_chain(struct VkBaseOutStructure *chain)
314 {
315    while (chain) {
316       void *node = chain;
317       chain = chain->pNext;
318       free(node);
319    }
320 }
321 
322 /**/
323 
new_instance_data(VkInstance instance)324 static struct instance_data *new_instance_data(VkInstance instance)
325 {
326    struct instance_data *data = rzalloc(NULL, struct instance_data);
327    data->instance = instance;
328    data->control_client = -1;
329    map_object(HKEY(data->instance), data);
330    return data;
331 }
332 
destroy_instance_data(struct instance_data * data)333 static void destroy_instance_data(struct instance_data *data)
334 {
335    if (data->params.output_file)
336       fclose(data->params.output_file);
337    if (data->params.control >= 0)
338       os_socket_close(data->params.control);
339    unmap_object(HKEY(data->instance));
340    ralloc_free(data);
341 }
342 
instance_data_map_physical_devices(struct instance_data * instance_data,bool map)343 static void instance_data_map_physical_devices(struct instance_data *instance_data,
344                                                bool map)
345 {
346    uint32_t physicalDeviceCount = 0;
347    instance_data->vtable.EnumeratePhysicalDevices(instance_data->instance,
348                                                   &physicalDeviceCount,
349                                                   NULL);
350 
351    VkPhysicalDevice *physicalDevices = (VkPhysicalDevice *) malloc(sizeof(VkPhysicalDevice) * physicalDeviceCount);
352    instance_data->vtable.EnumeratePhysicalDevices(instance_data->instance,
353                                                   &physicalDeviceCount,
354                                                   physicalDevices);
355 
356    for (uint32_t i = 0; i < physicalDeviceCount; i++) {
357       if (map)
358          map_object(HKEY(physicalDevices[i]), instance_data);
359       else
360          unmap_object(HKEY(physicalDevices[i]));
361    }
362 
363    free(physicalDevices);
364 }
365 
366 /**/
new_device_data(VkDevice device,struct instance_data * instance)367 static struct device_data *new_device_data(VkDevice device, struct instance_data *instance)
368 {
369    struct device_data *data = rzalloc(NULL, struct device_data);
370    data->instance = instance;
371    data->device = device;
372    map_object(HKEY(data->device), data);
373    return data;
374 }
375 
new_queue_data(VkQueue queue,const VkQueueFamilyProperties * family_props,uint32_t family_index,struct device_data * device_data)376 static struct queue_data *new_queue_data(VkQueue queue,
377                                          const VkQueueFamilyProperties *family_props,
378                                          uint32_t family_index,
379                                          struct device_data *device_data)
380 {
381    struct queue_data *data = rzalloc(device_data, struct queue_data);
382    data->device = device_data;
383    data->queue = queue;
384    data->flags = family_props->queueFlags;
385    data->timestamp_mask = (1ull << family_props->timestampValidBits) - 1;
386    data->family_index = family_index;
387    list_inithead(&data->running_command_buffer);
388    map_object(HKEY(data->queue), data);
389 
390    /* Fence synchronizing access to queries on that queue. */
391    VkFenceCreateInfo fence_info = {};
392    fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
393    fence_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
394    VK_CHECK(device_data->vtable.CreateFence(device_data->device,
395                                             &fence_info,
396                                             NULL,
397                                             &data->queries_fence));
398 
399    if (data->flags & VK_QUEUE_GRAPHICS_BIT)
400       device_data->graphic_queue = data;
401 
402    return data;
403 }
404 
destroy_queue(struct queue_data * data)405 static void destroy_queue(struct queue_data *data)
406 {
407    struct device_data *device_data = data->device;
408    device_data->vtable.DestroyFence(device_data->device, data->queries_fence, NULL);
409    unmap_object(HKEY(data->queue));
410    ralloc_free(data);
411 }
412 
device_map_queues(struct device_data * data,const VkDeviceCreateInfo * pCreateInfo)413 static void device_map_queues(struct device_data *data,
414                               const VkDeviceCreateInfo *pCreateInfo)
415 {
416    for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++)
417       data->n_queues += pCreateInfo->pQueueCreateInfos[i].queueCount;
418    data->queues = ralloc_array(data, struct queue_data *, data->n_queues);
419 
420    struct instance_data *instance_data = data->instance;
421    uint32_t n_family_props;
422    instance_data->vtable.GetPhysicalDeviceQueueFamilyProperties(data->physical_device,
423                                                                 &n_family_props,
424                                                                 NULL);
425    VkQueueFamilyProperties *family_props =
426       (VkQueueFamilyProperties *)malloc(sizeof(VkQueueFamilyProperties) * n_family_props);
427    instance_data->vtable.GetPhysicalDeviceQueueFamilyProperties(data->physical_device,
428                                                                 &n_family_props,
429                                                                 family_props);
430 
431    uint32_t queue_index = 0;
432    for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
433       for (uint32_t j = 0; j < pCreateInfo->pQueueCreateInfos[i].queueCount; j++) {
434          VkQueue queue;
435          data->vtable.GetDeviceQueue(data->device,
436                                      pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex,
437                                      j, &queue);
438 
439          VK_CHECK(data->set_device_loader_data(data->device, queue));
440 
441          data->queues[queue_index++] =
442             new_queue_data(queue, &family_props[pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex],
443                            pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex, data);
444       }
445    }
446 
447    free(family_props);
448 }
449 
device_unmap_queues(struct device_data * data)450 static void device_unmap_queues(struct device_data *data)
451 {
452    for (uint32_t i = 0; i < data->n_queues; i++)
453       destroy_queue(data->queues[i]);
454 }
455 
destroy_device_data(struct device_data * data)456 static void destroy_device_data(struct device_data *data)
457 {
458    unmap_object(HKEY(data->device));
459    ralloc_free(data);
460 }
461 
462 /**/
new_command_buffer_data(VkCommandBuffer cmd_buffer,VkCommandBufferLevel level,VkQueryPool pipeline_query_pool,VkQueryPool timestamp_query_pool,uint32_t query_index,struct device_data * device_data)463 static struct command_buffer_data *new_command_buffer_data(VkCommandBuffer cmd_buffer,
464                                                            VkCommandBufferLevel level,
465                                                            VkQueryPool pipeline_query_pool,
466                                                            VkQueryPool timestamp_query_pool,
467                                                            uint32_t query_index,
468                                                            struct device_data *device_data)
469 {
470    struct command_buffer_data *data = rzalloc(NULL, struct command_buffer_data);
471    data->device = device_data;
472    data->cmd_buffer = cmd_buffer;
473    data->level = level;
474    data->pipeline_query_pool = pipeline_query_pool;
475    data->timestamp_query_pool = timestamp_query_pool;
476    data->query_index = query_index;
477    list_inithead(&data->link);
478    map_object(HKEY(data->cmd_buffer), data);
479    return data;
480 }
481 
destroy_command_buffer_data(struct command_buffer_data * data)482 static void destroy_command_buffer_data(struct command_buffer_data *data)
483 {
484    unmap_object(HKEY(data->cmd_buffer));
485    list_delinit(&data->link);
486    ralloc_free(data);
487 }
488 
489 /**/
new_swapchain_data(VkSwapchainKHR swapchain,struct device_data * device_data)490 static struct swapchain_data *new_swapchain_data(VkSwapchainKHR swapchain,
491                                                  struct device_data *device_data)
492 {
493    struct instance_data *instance_data = device_data->instance;
494    struct swapchain_data *data = rzalloc(NULL, struct swapchain_data);
495    data->device = device_data;
496    data->swapchain = swapchain;
497    data->window_size = ImVec2(instance_data->params.width, instance_data->params.height);
498    list_inithead(&data->draws);
499    map_object(HKEY(data->swapchain), data);
500    return data;
501 }
502 
destroy_swapchain_data(struct swapchain_data * data)503 static void destroy_swapchain_data(struct swapchain_data *data)
504 {
505    unmap_object(HKEY(data->swapchain));
506    ralloc_free(data);
507 }
508 
get_overlay_draw(struct swapchain_data * data)509 struct overlay_draw *get_overlay_draw(struct swapchain_data *data)
510 {
511    struct device_data *device_data = data->device;
512    struct overlay_draw *draw = list_is_empty(&data->draws) ?
513       NULL : list_first_entry(&data->draws, struct overlay_draw, link);
514 
515    VkSemaphoreCreateInfo sem_info = {};
516    sem_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
517 
518    if (draw && device_data->vtable.GetFenceStatus(device_data->device, draw->fence) == VK_SUCCESS) {
519       list_del(&draw->link);
520       VK_CHECK(device_data->vtable.ResetFences(device_data->device,
521                                                1, &draw->fence));
522       list_addtail(&draw->link, &data->draws);
523       return draw;
524    }
525 
526    draw = rzalloc(data, struct overlay_draw);
527 
528    VkCommandBufferAllocateInfo cmd_buffer_info = {};
529    cmd_buffer_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
530    cmd_buffer_info.commandPool = data->command_pool;
531    cmd_buffer_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
532    cmd_buffer_info.commandBufferCount = 1;
533    VK_CHECK(device_data->vtable.AllocateCommandBuffers(device_data->device,
534                                                        &cmd_buffer_info,
535                                                        &draw->command_buffer));
536    VK_CHECK(device_data->set_device_loader_data(device_data->device,
537                                                 draw->command_buffer));
538 
539 
540    VkFenceCreateInfo fence_info = {};
541    fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
542    VK_CHECK(device_data->vtable.CreateFence(device_data->device,
543                                             &fence_info,
544                                             NULL,
545                                             &draw->fence));
546 
547    VK_CHECK(device_data->vtable.CreateSemaphore(device_data->device, &sem_info,
548                                                 NULL, &draw->semaphore));
549    VK_CHECK(device_data->vtable.CreateSemaphore(device_data->device, &sem_info,
550                                                 NULL, &draw->cross_engine_semaphore));
551 
552    list_addtail(&draw->link, &data->draws);
553 
554    return draw;
555 }
556 
param_unit(enum overlay_param_enabled param)557 static const char *param_unit(enum overlay_param_enabled param)
558 {
559    switch (param) {
560    case OVERLAY_PARAM_ENABLED_frame_timing:
561    case OVERLAY_PARAM_ENABLED_acquire_timing:
562    case OVERLAY_PARAM_ENABLED_present_timing:
563       return "(us)";
564    case OVERLAY_PARAM_ENABLED_gpu_timing:
565       return "(ns)";
566    default:
567       return "";
568    }
569 }
570 
parse_command(struct instance_data * instance_data,const char * cmd,unsigned cmdlen,const char * param,unsigned paramlen)571 static void parse_command(struct instance_data *instance_data,
572                           const char *cmd, unsigned cmdlen,
573                           const char *param, unsigned paramlen)
574 {
575    if (!strncmp(cmd, "capture", cmdlen)) {
576       int value = atoi(param);
577       bool enabled = value > 0;
578 
579       if (enabled) {
580          instance_data->capture_enabled = true;
581       } else {
582          instance_data->capture_enabled = false;
583          instance_data->capture_started = false;
584       }
585    }
586 }
587 
588 #define BUFSIZE 4096
589 
590 /**
591  * This function will process commands through the control file.
592  *
593  * A command starts with a colon, followed by the command, and followed by an
594  * option '=' and a parameter.  It has to end with a semi-colon. A full command
595  * + parameter looks like:
596  *
597  *    :cmd=param;
598  */
process_char(struct instance_data * instance_data,char c)599 static void process_char(struct instance_data *instance_data, char c)
600 {
601    static char cmd[BUFSIZE];
602    static char param[BUFSIZE];
603 
604    static unsigned cmdpos = 0;
605    static unsigned parampos = 0;
606    static bool reading_cmd = false;
607    static bool reading_param = false;
608 
609    switch (c) {
610    case ':':
611       cmdpos = 0;
612       parampos = 0;
613       reading_cmd = true;
614       reading_param = false;
615       break;
616    case ';':
617       if (!reading_cmd)
618          break;
619       cmd[cmdpos++] = '\0';
620       param[parampos++] = '\0';
621       parse_command(instance_data, cmd, cmdpos, param, parampos);
622       reading_cmd = false;
623       reading_param = false;
624       break;
625    case '=':
626       if (!reading_cmd)
627          break;
628       reading_param = true;
629       break;
630    default:
631       if (!reading_cmd)
632          break;
633 
634       if (reading_param) {
635          /* overflow means an invalid parameter */
636          if (parampos >= BUFSIZE - 1) {
637             reading_cmd = false;
638             reading_param = false;
639             break;
640          }
641 
642          param[parampos++] = c;
643       } else {
644          /* overflow means an invalid command */
645          if (cmdpos >= BUFSIZE - 1) {
646             reading_cmd = false;
647             break;
648          }
649 
650          cmd[cmdpos++] = c;
651       }
652    }
653 }
654 
control_send(struct instance_data * instance_data,const char * cmd,unsigned cmdlen,const char * param,unsigned paramlen)655 static void control_send(struct instance_data *instance_data,
656                          const char *cmd, unsigned cmdlen,
657                          const char *param, unsigned paramlen)
658 {
659    unsigned msglen = 0;
660    char buffer[BUFSIZE];
661 
662    assert(cmdlen + paramlen + 3 < BUFSIZE);
663 
664    buffer[msglen++] = ':';
665 
666    memcpy(&buffer[msglen], cmd, cmdlen);
667    msglen += cmdlen;
668 
669    if (paramlen > 0) {
670       buffer[msglen++] = '=';
671       memcpy(&buffer[msglen], param, paramlen);
672       msglen += paramlen;
673       buffer[msglen++] = ';';
674    }
675 
676    os_socket_send(instance_data->control_client, buffer, msglen, 0);
677 }
678 
control_send_connection_string(struct device_data * device_data)679 static void control_send_connection_string(struct device_data *device_data)
680 {
681    struct instance_data *instance_data = device_data->instance;
682 
683    const char *controlVersionCmd = "MesaOverlayControlVersion";
684    const char *controlVersionString = "1";
685 
686    control_send(instance_data, controlVersionCmd, strlen(controlVersionCmd),
687                 controlVersionString, strlen(controlVersionString));
688 
689    const char *deviceCmd = "DeviceName";
690    const char *deviceName = device_data->properties.deviceName;
691 
692    control_send(instance_data, deviceCmd, strlen(deviceCmd),
693                 deviceName, strlen(deviceName));
694 
695    const char *mesaVersionCmd = "MesaVersion";
696    const char *mesaVersionString = "Mesa " PACKAGE_VERSION MESA_GIT_SHA1;
697 
698    control_send(instance_data, mesaVersionCmd, strlen(mesaVersionCmd),
699                 mesaVersionString, strlen(mesaVersionString));
700 }
701 
control_client_check(struct device_data * device_data)702 static void control_client_check(struct device_data *device_data)
703 {
704    struct instance_data *instance_data = device_data->instance;
705 
706    /* Already connected, just return. */
707    if (instance_data->control_client >= 0)
708       return;
709 
710    int socket = os_socket_accept(instance_data->params.control);
711    if (socket == -1) {
712       if (errno != EAGAIN && errno != EWOULDBLOCK && errno != ECONNABORTED)
713          fprintf(stderr, "ERROR on socket: %s\n", strerror(errno));
714       return;
715    }
716 
717    if (socket >= 0) {
718       os_socket_block(socket, false);
719       instance_data->control_client = socket;
720       control_send_connection_string(device_data);
721    }
722 }
723 
control_client_disconnected(struct instance_data * instance_data)724 static void control_client_disconnected(struct instance_data *instance_data)
725 {
726    os_socket_close(instance_data->control_client);
727    instance_data->control_client = -1;
728 }
729 
process_control_socket(struct instance_data * instance_data)730 static void process_control_socket(struct instance_data *instance_data)
731 {
732    const int client = instance_data->control_client;
733    if (client >= 0) {
734       char buf[BUFSIZE];
735 
736       while (true) {
737          ssize_t n = os_socket_recv(client, buf, BUFSIZE, 0);
738 
739          if (n == -1) {
740             if (errno == EAGAIN || errno == EWOULDBLOCK) {
741                /* nothing to read, try again later */
742                break;
743             }
744 
745             if (errno != ECONNRESET)
746                fprintf(stderr, "ERROR on connection: %s\n", strerror(errno));
747 
748             control_client_disconnected(instance_data);
749          } else if (n == 0) {
750             /* recv() returns 0 when the client disconnects */
751             control_client_disconnected(instance_data);
752          }
753 
754          for (ssize_t i = 0; i < n; i++) {
755             process_char(instance_data, buf[i]);
756          }
757 
758          /* If we try to read BUFSIZE and receive BUFSIZE bytes from the
759           * socket, there's a good chance that there's still more data to be
760           * read, so we will try again. Otherwise, simply be done for this
761           * iteration and try again on the next frame.
762           */
763          if (n < BUFSIZE)
764             break;
765       }
766    }
767 }
768 
snapshot_swapchain_frame(struct swapchain_data * data)769 static void snapshot_swapchain_frame(struct swapchain_data *data)
770 {
771    struct device_data *device_data = data->device;
772    struct instance_data *instance_data = device_data->instance;
773    uint32_t f_idx = data->n_frames % ARRAY_SIZE(data->frames_stats);
774    uint64_t now = os_time_get(); /* us */
775 
776    if (instance_data->params.control >= 0) {
777       control_client_check(device_data);
778       process_control_socket(instance_data);
779    }
780 
781    if (data->last_present_time) {
782       data->frame_stats.stats[OVERLAY_PARAM_ENABLED_frame_timing] =
783          now - data->last_present_time;
784    }
785 
786    memset(&data->frames_stats[f_idx], 0, sizeof(data->frames_stats[f_idx]));
787    for (int s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++) {
788       data->frames_stats[f_idx].stats[s] += device_data->frame_stats.stats[s] + data->frame_stats.stats[s];
789       data->accumulated_stats.stats[s] += device_data->frame_stats.stats[s] + data->frame_stats.stats[s];
790    }
791 
792    /* If capture has been enabled but it hasn't started yet, it means we are on
793     * the first snapshot after it has been enabled. At this point we want to
794     * use the stats captured so far to update the display, but we don't want
795     * this data to cause noise to the stats that we want to capture from now
796     * on.
797     *
798     * capture_begin == true will trigger an update of the fps on display, and a
799     * flush of the data, but no stats will be written to the output file. This
800     * way, we will have only stats from after the capture has been enabled
801     * written to the output_file.
802     */
803    const bool capture_begin =
804       instance_data->capture_enabled && !instance_data->capture_started;
805 
806    if (data->last_fps_update) {
807       double elapsed = (double)(now - data->last_fps_update); /* us */
808       if (capture_begin ||
809           elapsed >= instance_data->params.fps_sampling_period) {
810          data->fps = 1000000.0f * data->n_frames_since_update / elapsed;
811          if (instance_data->capture_started) {
812             if (!instance_data->first_line_printed) {
813                bool first_column = true;
814 
815                instance_data->first_line_printed = true;
816 
817 #define OVERLAY_PARAM_BOOL(name) \
818                if (instance_data->params.enabled[OVERLAY_PARAM_ENABLED_##name]) { \
819                   fprintf(instance_data->params.output_file, \
820                           "%s%s%s", first_column ? "" : ", ", #name, \
821                           param_unit(OVERLAY_PARAM_ENABLED_##name)); \
822                   first_column = false; \
823                }
824 #define OVERLAY_PARAM_CUSTOM(name)
825                OVERLAY_PARAMS
826 #undef OVERLAY_PARAM_BOOL
827 #undef OVERLAY_PARAM_CUSTOM
828                fprintf(instance_data->params.output_file, "\n");
829             }
830 
831             for (int s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++) {
832                if (!instance_data->params.enabled[s])
833                   continue;
834                if (s == OVERLAY_PARAM_ENABLED_fps) {
835                   fprintf(instance_data->params.output_file,
836                           "%s%.2f", s == 0 ? "" : ", ", data->fps);
837                } else {
838                   fprintf(instance_data->params.output_file,
839                           "%s%" PRIu64, s == 0 ? "" : ", ",
840                           data->accumulated_stats.stats[s]);
841                }
842             }
843             fprintf(instance_data->params.output_file, "\n");
844             fflush(instance_data->params.output_file);
845          }
846 
847          memset(&data->accumulated_stats, 0, sizeof(data->accumulated_stats));
848          data->n_frames_since_update = 0;
849          data->last_fps_update = now;
850 
851          if (capture_begin)
852             instance_data->capture_started = true;
853       }
854    } else {
855       data->last_fps_update = now;
856    }
857 
858    memset(&device_data->frame_stats, 0, sizeof(device_data->frame_stats));
859    memset(&data->frame_stats, 0, sizeof(device_data->frame_stats));
860 
861    data->last_present_time = now;
862    data->n_frames++;
863    data->n_frames_since_update++;
864 }
865 
get_time_stat(void * _data,int _idx)866 static float get_time_stat(void *_data, int _idx)
867 {
868    struct swapchain_data *data = (struct swapchain_data *) _data;
869    if ((ARRAY_SIZE(data->frames_stats) - _idx) > data->n_frames)
870       return 0.0f;
871    int idx = ARRAY_SIZE(data->frames_stats) +
872       data->n_frames < ARRAY_SIZE(data->frames_stats) ?
873       _idx - data->n_frames :
874       _idx + data->n_frames;
875    idx %= ARRAY_SIZE(data->frames_stats);
876    /* Time stats are in us. */
877    return data->frames_stats[idx].stats[data->stat_selector] / data->time_dividor;
878 }
879 
get_stat(void * _data,int _idx)880 static float get_stat(void *_data, int _idx)
881 {
882    struct swapchain_data *data = (struct swapchain_data *) _data;
883    if ((ARRAY_SIZE(data->frames_stats) - _idx) > data->n_frames)
884       return 0.0f;
885    int idx = ARRAY_SIZE(data->frames_stats) +
886       data->n_frames < ARRAY_SIZE(data->frames_stats) ?
887       _idx - data->n_frames :
888       _idx + data->n_frames;
889    idx %= ARRAY_SIZE(data->frames_stats);
890    return data->frames_stats[idx].stats[data->stat_selector];
891 }
892 
position_layer(struct swapchain_data * data)893 static void position_layer(struct swapchain_data *data)
894 
895 {
896    struct device_data *device_data = data->device;
897    struct instance_data *instance_data = device_data->instance;
898    const float margin = 10.0f;
899 
900    ImGui::SetNextWindowBgAlpha(0.5);
901    ImGui::SetNextWindowSize(data->window_size, ImGuiCond_Always);
902    switch (instance_data->params.position) {
903    case LAYER_POSITION_TOP_LEFT:
904       ImGui::SetNextWindowPos(ImVec2(margin, margin), ImGuiCond_Always);
905       break;
906    case LAYER_POSITION_TOP_RIGHT:
907       ImGui::SetNextWindowPos(ImVec2(data->width - data->window_size.x - margin, margin),
908                               ImGuiCond_Always);
909       break;
910    case LAYER_POSITION_BOTTOM_LEFT:
911       ImGui::SetNextWindowPos(ImVec2(margin, data->height - data->window_size.y - margin),
912                               ImGuiCond_Always);
913       break;
914    case LAYER_POSITION_BOTTOM_RIGHT:
915       ImGui::SetNextWindowPos(ImVec2(data->width - data->window_size.x - margin,
916                                      data->height - data->window_size.y - margin),
917                               ImGuiCond_Always);
918       break;
919    }
920 }
921 
compute_swapchain_display(struct swapchain_data * data)922 static void compute_swapchain_display(struct swapchain_data *data)
923 {
924    struct device_data *device_data = data->device;
925    struct instance_data *instance_data = device_data->instance;
926 
927    ImGui::SetCurrentContext(data->imgui_context);
928    ImGui::NewFrame();
929    position_layer(data);
930    ImGui::Begin("Mesa overlay");
931    ImGui::Text("Device: %s", device_data->properties.deviceName);
932 
933    const char *format_name = vk_Format_to_str(data->format);
934    format_name = format_name ? (format_name + strlen("VK_FORMAT_")) : "unknown";
935    ImGui::Text("Swapchain format: %s", format_name);
936    ImGui::Text("Frames: %" PRIu64, data->n_frames);
937    if (instance_data->params.enabled[OVERLAY_PARAM_ENABLED_fps])
938       ImGui::Text("FPS: %.2f" , data->fps);
939 
940    /* Recompute min/max */
941    for (uint32_t s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++) {
942       data->stats_min.stats[s] = UINT64_MAX;
943       data->stats_max.stats[s] = 0;
944    }
945    for (uint32_t f = 0; f < MIN2(data->n_frames, ARRAY_SIZE(data->frames_stats)); f++) {
946       for (uint32_t s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++) {
947          data->stats_min.stats[s] = MIN2(data->frames_stats[f].stats[s],
948                                          data->stats_min.stats[s]);
949          data->stats_max.stats[s] = MAX2(data->frames_stats[f].stats[s],
950                                          data->stats_max.stats[s]);
951       }
952    }
953    for (uint32_t s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++) {
954       assert(data->stats_min.stats[s] != UINT64_MAX);
955    }
956 
957    for (uint32_t s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++) {
958       if (!instance_data->params.enabled[s] ||
959           s == OVERLAY_PARAM_ENABLED_fps ||
960           s == OVERLAY_PARAM_ENABLED_frame)
961          continue;
962 
963       char hash[40];
964       snprintf(hash, sizeof(hash), "##%s", overlay_param_names[s]);
965       data->stat_selector = (enum overlay_param_enabled) s;
966       data->time_dividor = 1000.0f;
967       if (s == OVERLAY_PARAM_ENABLED_gpu_timing)
968          data->time_dividor = 1000000.0f;
969 
970       if (s == OVERLAY_PARAM_ENABLED_frame_timing ||
971           s == OVERLAY_PARAM_ENABLED_acquire_timing ||
972           s == OVERLAY_PARAM_ENABLED_present_timing ||
973           s == OVERLAY_PARAM_ENABLED_gpu_timing) {
974          double min_time = data->stats_min.stats[s] / data->time_dividor;
975          double max_time = data->stats_max.stats[s] / data->time_dividor;
976          ImGui::PlotHistogram(hash, get_time_stat, data,
977                               ARRAY_SIZE(data->frames_stats), 0,
978                               NULL, min_time, max_time,
979                               ImVec2(ImGui::GetContentRegionAvailWidth(), 30));
980          ImGui::Text("%s: %.3fms [%.3f, %.3f]", overlay_param_names[s],
981                      get_time_stat(data, ARRAY_SIZE(data->frames_stats) - 1),
982                      min_time, max_time);
983       } else {
984          ImGui::PlotHistogram(hash, get_stat, data,
985                               ARRAY_SIZE(data->frames_stats), 0,
986                               NULL,
987                               data->stats_min.stats[s],
988                               data->stats_max.stats[s],
989                               ImVec2(ImGui::GetContentRegionAvailWidth(), 30));
990          ImGui::Text("%s: %.0f [%" PRIu64 ", %" PRIu64 "]", overlay_param_names[s],
991                      get_stat(data, ARRAY_SIZE(data->frames_stats) - 1),
992                      data->stats_min.stats[s], data->stats_max.stats[s]);
993       }
994    }
995    data->window_size = ImVec2(data->window_size.x, ImGui::GetCursorPosY() + 10.0f);
996    ImGui::End();
997    ImGui::EndFrame();
998    ImGui::Render();
999 }
1000 
vk_memory_type(struct device_data * data,VkMemoryPropertyFlags properties,uint32_t type_bits)1001 static uint32_t vk_memory_type(struct device_data *data,
1002                                VkMemoryPropertyFlags properties,
1003                                uint32_t type_bits)
1004 {
1005     VkPhysicalDeviceMemoryProperties prop;
1006     data->instance->vtable.GetPhysicalDeviceMemoryProperties(data->physical_device, &prop);
1007     for (uint32_t i = 0; i < prop.memoryTypeCount; i++)
1008         if ((prop.memoryTypes[i].propertyFlags & properties) == properties && type_bits & (1<<i))
1009             return i;
1010     return 0xFFFFFFFF; // Unable to find memoryType
1011 }
1012 
ensure_swapchain_fonts(struct swapchain_data * data,VkCommandBuffer command_buffer)1013 static void ensure_swapchain_fonts(struct swapchain_data *data,
1014                                    VkCommandBuffer command_buffer)
1015 {
1016    if (data->font_uploaded)
1017       return;
1018 
1019    data->font_uploaded = true;
1020 
1021    struct device_data *device_data = data->device;
1022    ImGuiIO& io = ImGui::GetIO();
1023    unsigned char* pixels;
1024    int width, height;
1025    io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
1026    size_t upload_size = width * height * 4 * sizeof(char);
1027 
1028    /* Upload buffer */
1029    VkBufferCreateInfo buffer_info = {};
1030    buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
1031    buffer_info.size = upload_size;
1032    buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
1033    buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1034    VK_CHECK(device_data->vtable.CreateBuffer(device_data->device, &buffer_info,
1035                                              NULL, &data->upload_font_buffer));
1036    VkMemoryRequirements upload_buffer_req;
1037    device_data->vtable.GetBufferMemoryRequirements(device_data->device,
1038                                                    data->upload_font_buffer,
1039                                                    &upload_buffer_req);
1040    VkMemoryAllocateInfo upload_alloc_info = {};
1041    upload_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1042    upload_alloc_info.allocationSize = upload_buffer_req.size;
1043    upload_alloc_info.memoryTypeIndex = vk_memory_type(device_data,
1044                                                       VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
1045                                                       upload_buffer_req.memoryTypeBits);
1046    VK_CHECK(device_data->vtable.AllocateMemory(device_data->device,
1047                                                &upload_alloc_info,
1048                                                NULL,
1049                                                &data->upload_font_buffer_mem));
1050    VK_CHECK(device_data->vtable.BindBufferMemory(device_data->device,
1051                                                  data->upload_font_buffer,
1052                                                  data->upload_font_buffer_mem, 0));
1053 
1054    /* Upload to Buffer */
1055    char* map = NULL;
1056    VK_CHECK(device_data->vtable.MapMemory(device_data->device,
1057                                           data->upload_font_buffer_mem,
1058                                           0, upload_size, 0, (void**)(&map)));
1059    memcpy(map, pixels, upload_size);
1060    VkMappedMemoryRange range[1] = {};
1061    range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1062    range[0].memory = data->upload_font_buffer_mem;
1063    range[0].size = upload_size;
1064    VK_CHECK(device_data->vtable.FlushMappedMemoryRanges(device_data->device, 1, range));
1065    device_data->vtable.UnmapMemory(device_data->device,
1066                                    data->upload_font_buffer_mem);
1067 
1068    /* Copy buffer to image */
1069    VkImageMemoryBarrier copy_barrier[1] = {};
1070    copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1071    copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
1072    copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1073    copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1074    copy_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1075    copy_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1076    copy_barrier[0].image = data->font_image;
1077    copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1078    copy_barrier[0].subresourceRange.levelCount = 1;
1079    copy_barrier[0].subresourceRange.layerCount = 1;
1080    device_data->vtable.CmdPipelineBarrier(command_buffer,
1081                                           VK_PIPELINE_STAGE_HOST_BIT,
1082                                           VK_PIPELINE_STAGE_TRANSFER_BIT,
1083                                           0, 0, NULL, 0, NULL,
1084                                           1, copy_barrier);
1085 
1086    VkBufferImageCopy region = {};
1087    region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1088    region.imageSubresource.layerCount = 1;
1089    region.imageExtent.width = width;
1090    region.imageExtent.height = height;
1091    region.imageExtent.depth = 1;
1092    device_data->vtable.CmdCopyBufferToImage(command_buffer,
1093                                             data->upload_font_buffer,
1094                                             data->font_image,
1095                                             VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1096                                             1, &region);
1097 
1098    VkImageMemoryBarrier use_barrier[1] = {};
1099    use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1100    use_barrier[0].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
1101    use_barrier[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
1102    use_barrier[0].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1103    use_barrier[0].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1104    use_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1105    use_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1106    use_barrier[0].image = data->font_image;
1107    use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1108    use_barrier[0].subresourceRange.levelCount = 1;
1109    use_barrier[0].subresourceRange.layerCount = 1;
1110    device_data->vtable.CmdPipelineBarrier(command_buffer,
1111                                           VK_PIPELINE_STAGE_TRANSFER_BIT,
1112                                           VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
1113                                           0,
1114                                           0, NULL,
1115                                           0, NULL,
1116                                           1, use_barrier);
1117 
1118    /* Store our identifier */
1119    io.Fonts->TexID = (ImTextureID)(intptr_t)data->font_image;
1120 }
1121 
CreateOrResizeBuffer(struct device_data * data,VkBuffer * buffer,VkDeviceMemory * buffer_memory,VkDeviceSize * buffer_size,size_t new_size,VkBufferUsageFlagBits usage)1122 static void CreateOrResizeBuffer(struct device_data *data,
1123                                  VkBuffer *buffer,
1124                                  VkDeviceMemory *buffer_memory,
1125                                  VkDeviceSize *buffer_size,
1126                                  size_t new_size, VkBufferUsageFlagBits usage)
1127 {
1128     if (*buffer != VK_NULL_HANDLE)
1129         data->vtable.DestroyBuffer(data->device, *buffer, NULL);
1130     if (*buffer_memory)
1131         data->vtable.FreeMemory(data->device, *buffer_memory, NULL);
1132 
1133     VkBufferCreateInfo buffer_info = {};
1134     buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
1135     buffer_info.size = new_size;
1136     buffer_info.usage = usage;
1137     buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1138     VK_CHECK(data->vtable.CreateBuffer(data->device, &buffer_info, NULL, buffer));
1139 
1140     VkMemoryRequirements req;
1141     data->vtable.GetBufferMemoryRequirements(data->device, *buffer, &req);
1142     VkMemoryAllocateInfo alloc_info = {};
1143     alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1144     alloc_info.allocationSize = req.size;
1145     alloc_info.memoryTypeIndex =
1146        vk_memory_type(data, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits);
1147     VK_CHECK(data->vtable.AllocateMemory(data->device, &alloc_info, NULL, buffer_memory));
1148 
1149     VK_CHECK(data->vtable.BindBufferMemory(data->device, *buffer, *buffer_memory, 0));
1150     *buffer_size = new_size;
1151 }
1152 
render_swapchain_display(struct swapchain_data * data,struct queue_data * present_queue,const VkSemaphore * wait_semaphores,unsigned n_wait_semaphores,unsigned image_index)1153 static struct overlay_draw *render_swapchain_display(struct swapchain_data *data,
1154                                                      struct queue_data *present_queue,
1155                                                      const VkSemaphore *wait_semaphores,
1156                                                      unsigned n_wait_semaphores,
1157                                                      unsigned image_index)
1158 {
1159    ImDrawData* draw_data = ImGui::GetDrawData();
1160    if (draw_data->TotalVtxCount == 0)
1161       return NULL;
1162 
1163    struct device_data *device_data = data->device;
1164    struct overlay_draw *draw = get_overlay_draw(data);
1165 
1166    device_data->vtable.ResetCommandBuffer(draw->command_buffer, 0);
1167 
1168    VkRenderPassBeginInfo render_pass_info = {};
1169    render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
1170    render_pass_info.renderPass = data->render_pass;
1171    render_pass_info.framebuffer = data->framebuffers[image_index];
1172    render_pass_info.renderArea.extent.width = data->width;
1173    render_pass_info.renderArea.extent.height = data->height;
1174 
1175    VkCommandBufferBeginInfo buffer_begin_info = {};
1176    buffer_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1177 
1178    device_data->vtable.BeginCommandBuffer(draw->command_buffer, &buffer_begin_info);
1179 
1180    ensure_swapchain_fonts(data, draw->command_buffer);
1181 
1182    /* Bounce the image to display back to color attachment layout for
1183     * rendering on top of it.
1184     */
1185    VkImageMemoryBarrier imb;
1186    imb.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1187    imb.pNext = nullptr;
1188    imb.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
1189    imb.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
1190    imb.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
1191    imb.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1192    imb.image = data->images[image_index];
1193    imb.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1194    imb.subresourceRange.baseMipLevel = 0;
1195    imb.subresourceRange.levelCount = 1;
1196    imb.subresourceRange.baseArrayLayer = 0;
1197    imb.subresourceRange.layerCount = 1;
1198    imb.srcQueueFamilyIndex = present_queue->family_index;
1199    imb.dstQueueFamilyIndex = device_data->graphic_queue->family_index;
1200    device_data->vtable.CmdPipelineBarrier(draw->command_buffer,
1201                                           VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
1202                                           VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
1203                                           0,          /* dependency flags */
1204                                           0, nullptr, /* memory barriers */
1205                                           0, nullptr, /* buffer memory barriers */
1206                                           1, &imb);   /* image memory barriers */
1207 
1208    device_data->vtable.CmdBeginRenderPass(draw->command_buffer, &render_pass_info,
1209                                           VK_SUBPASS_CONTENTS_INLINE);
1210 
1211    /* Create/Resize vertex & index buffers */
1212    size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert);
1213    size_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx);
1214    if (draw->vertex_buffer_size < vertex_size) {
1215       CreateOrResizeBuffer(device_data,
1216                            &draw->vertex_buffer,
1217                            &draw->vertex_buffer_mem,
1218                            &draw->vertex_buffer_size,
1219                            vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
1220    }
1221    if (draw->index_buffer_size < index_size) {
1222       CreateOrResizeBuffer(device_data,
1223                            &draw->index_buffer,
1224                            &draw->index_buffer_mem,
1225                            &draw->index_buffer_size,
1226                            index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
1227    }
1228 
1229     /* Upload vertex & index data */
1230     ImDrawVert* vtx_dst = NULL;
1231     ImDrawIdx* idx_dst = NULL;
1232     VK_CHECK(device_data->vtable.MapMemory(device_data->device, draw->vertex_buffer_mem,
1233                                            0, vertex_size, 0, (void**)(&vtx_dst)));
1234     VK_CHECK(device_data->vtable.MapMemory(device_data->device, draw->index_buffer_mem,
1235                                            0, index_size, 0, (void**)(&idx_dst)));
1236     for (int n = 0; n < draw_data->CmdListsCount; n++)
1237         {
1238            const ImDrawList* cmd_list = draw_data->CmdLists[n];
1239            memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
1240            memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
1241            vtx_dst += cmd_list->VtxBuffer.Size;
1242            idx_dst += cmd_list->IdxBuffer.Size;
1243         }
1244     VkMappedMemoryRange range[2] = {};
1245     range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1246     range[0].memory = draw->vertex_buffer_mem;
1247     range[0].size = VK_WHOLE_SIZE;
1248     range[1].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1249     range[1].memory = draw->index_buffer_mem;
1250     range[1].size = VK_WHOLE_SIZE;
1251     VK_CHECK(device_data->vtable.FlushMappedMemoryRanges(device_data->device, 2, range));
1252     device_data->vtable.UnmapMemory(device_data->device, draw->vertex_buffer_mem);
1253     device_data->vtable.UnmapMemory(device_data->device, draw->index_buffer_mem);
1254 
1255     /* Bind pipeline and descriptor sets */
1256     device_data->vtable.CmdBindPipeline(draw->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, data->pipeline);
1257     VkDescriptorSet desc_set[1] = { data->descriptor_set };
1258     device_data->vtable.CmdBindDescriptorSets(draw->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
1259                                               data->pipeline_layout, 0, 1, desc_set, 0, NULL);
1260 
1261     /* Bind vertex & index buffers */
1262     VkBuffer vertex_buffers[1] = { draw->vertex_buffer };
1263     VkDeviceSize vertex_offset[1] = { 0 };
1264     device_data->vtable.CmdBindVertexBuffers(draw->command_buffer, 0, 1, vertex_buffers, vertex_offset);
1265     device_data->vtable.CmdBindIndexBuffer(draw->command_buffer, draw->index_buffer, 0, VK_INDEX_TYPE_UINT16);
1266 
1267     /* Setup viewport */
1268     VkViewport viewport;
1269     viewport.x = 0;
1270     viewport.y = 0;
1271     viewport.width = draw_data->DisplaySize.x;
1272     viewport.height = draw_data->DisplaySize.y;
1273     viewport.minDepth = 0.0f;
1274     viewport.maxDepth = 1.0f;
1275     device_data->vtable.CmdSetViewport(draw->command_buffer, 0, 1, &viewport);
1276 
1277 
1278     /* Setup scale and translation through push constants :
1279      *
1280      * Our visible imgui space lies from draw_data->DisplayPos (top left) to
1281      * draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin
1282      * is typically (0,0) for single viewport apps.
1283      */
1284     float scale[2];
1285     scale[0] = 2.0f / draw_data->DisplaySize.x;
1286     scale[1] = 2.0f / draw_data->DisplaySize.y;
1287     float translate[2];
1288     translate[0] = -1.0f - draw_data->DisplayPos.x * scale[0];
1289     translate[1] = -1.0f - draw_data->DisplayPos.y * scale[1];
1290     device_data->vtable.CmdPushConstants(draw->command_buffer, data->pipeline_layout,
1291                                          VK_SHADER_STAGE_VERTEX_BIT,
1292                                          sizeof(float) * 0, sizeof(float) * 2, scale);
1293     device_data->vtable.CmdPushConstants(draw->command_buffer, data->pipeline_layout,
1294                                          VK_SHADER_STAGE_VERTEX_BIT,
1295                                          sizeof(float) * 2, sizeof(float) * 2, translate);
1296 
1297     // Render the command lists:
1298     int vtx_offset = 0;
1299     int idx_offset = 0;
1300     ImVec2 display_pos = draw_data->DisplayPos;
1301     for (int n = 0; n < draw_data->CmdListsCount; n++)
1302     {
1303         const ImDrawList* cmd_list = draw_data->CmdLists[n];
1304         for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
1305         {
1306             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
1307             // Apply scissor/clipping rectangle
1308             // FIXME: We could clamp width/height based on clamped min/max values.
1309             VkRect2D scissor;
1310             scissor.offset.x = (int32_t)(pcmd->ClipRect.x - display_pos.x) > 0 ? (int32_t)(pcmd->ClipRect.x - display_pos.x) : 0;
1311             scissor.offset.y = (int32_t)(pcmd->ClipRect.y - display_pos.y) > 0 ? (int32_t)(pcmd->ClipRect.y - display_pos.y) : 0;
1312             scissor.extent.width = (uint32_t)(pcmd->ClipRect.z - pcmd->ClipRect.x);
1313             scissor.extent.height = (uint32_t)(pcmd->ClipRect.w - pcmd->ClipRect.y + 1); // FIXME: Why +1 here?
1314             device_data->vtable.CmdSetScissor(draw->command_buffer, 0, 1, &scissor);
1315 
1316             // Draw
1317             device_data->vtable.CmdDrawIndexed(draw->command_buffer, pcmd->ElemCount, 1, idx_offset, vtx_offset, 0);
1318 
1319             idx_offset += pcmd->ElemCount;
1320         }
1321         vtx_offset += cmd_list->VtxBuffer.Size;
1322     }
1323 
1324    device_data->vtable.CmdEndRenderPass(draw->command_buffer);
1325 
1326    if (device_data->graphic_queue->family_index != present_queue->family_index)
1327    {
1328       /* Transfer the image back to the present queue family
1329        * image layout was already changed to present by the render pass
1330        */
1331       imb.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1332       imb.pNext = nullptr;
1333       imb.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
1334       imb.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
1335       imb.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
1336       imb.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
1337       imb.image = data->images[image_index];
1338       imb.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1339       imb.subresourceRange.baseMipLevel = 0;
1340       imb.subresourceRange.levelCount = 1;
1341       imb.subresourceRange.baseArrayLayer = 0;
1342       imb.subresourceRange.layerCount = 1;
1343       imb.srcQueueFamilyIndex = device_data->graphic_queue->family_index;
1344       imb.dstQueueFamilyIndex = present_queue->family_index;
1345       device_data->vtable.CmdPipelineBarrier(draw->command_buffer,
1346                                              VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
1347                                              VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
1348                                              0,          /* dependency flags */
1349                                              0, nullptr, /* memory barriers */
1350                                              0, nullptr, /* buffer memory barriers */
1351                                              1, &imb);   /* image memory barriers */
1352    }
1353 
1354    device_data->vtable.EndCommandBuffer(draw->command_buffer);
1355 
1356    /* When presenting on a different queue than where we're drawing the
1357     * overlay *AND* when the application does not provide a semaphore to
1358     * vkQueuePresent, insert our own cross engine synchronization
1359     * semaphore.
1360     */
1361    if (n_wait_semaphores == 0 && device_data->graphic_queue->queue != present_queue->queue) {
1362       VkPipelineStageFlags stages_wait = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
1363       VkSubmitInfo submit_info = {};
1364       submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1365       submit_info.commandBufferCount = 0;
1366       submit_info.pWaitDstStageMask = &stages_wait;
1367       submit_info.waitSemaphoreCount = 0;
1368       submit_info.signalSemaphoreCount = 1;
1369       submit_info.pSignalSemaphores = &draw->cross_engine_semaphore;
1370 
1371       device_data->vtable.QueueSubmit(present_queue->queue, 1, &submit_info, VK_NULL_HANDLE);
1372 
1373       submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1374       submit_info.commandBufferCount = 1;
1375       submit_info.pWaitDstStageMask = &stages_wait;
1376       submit_info.pCommandBuffers = &draw->command_buffer;
1377       submit_info.waitSemaphoreCount = 1;
1378       submit_info.pWaitSemaphores = &draw->cross_engine_semaphore;
1379       submit_info.signalSemaphoreCount = 1;
1380       submit_info.pSignalSemaphores = &draw->semaphore;
1381 
1382       device_data->vtable.QueueSubmit(device_data->graphic_queue->queue, 1, &submit_info, draw->fence);
1383    } else {
1384       VkPipelineStageFlags *stages_wait = (VkPipelineStageFlags*) malloc(sizeof(VkPipelineStageFlags) * n_wait_semaphores);
1385       for (unsigned i = 0; i < n_wait_semaphores; i++)
1386       {
1387          // wait in the fragment stage until the swapchain image is ready
1388          stages_wait[i] = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
1389       }
1390 
1391       VkSubmitInfo submit_info = {};
1392       submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1393       submit_info.commandBufferCount = 1;
1394       submit_info.pCommandBuffers = &draw->command_buffer;
1395       submit_info.pWaitDstStageMask = stages_wait;
1396       submit_info.waitSemaphoreCount = n_wait_semaphores;
1397       submit_info.pWaitSemaphores = wait_semaphores;
1398       submit_info.signalSemaphoreCount = 1;
1399       submit_info.pSignalSemaphores = &draw->semaphore;
1400 
1401       device_data->vtable.QueueSubmit(device_data->graphic_queue->queue, 1, &submit_info, draw->fence);
1402 
1403       free(stages_wait);
1404    }
1405 
1406    return draw;
1407 }
1408 
1409 static const uint32_t overlay_vert_spv[] = {
1410 #include "overlay.vert.spv.h"
1411 };
1412 static const uint32_t overlay_frag_spv[] = {
1413 #include "overlay.frag.spv.h"
1414 };
1415 
setup_swapchain_data_pipeline(struct swapchain_data * data)1416 static void setup_swapchain_data_pipeline(struct swapchain_data *data)
1417 {
1418    struct device_data *device_data = data->device;
1419    VkShaderModule vert_module, frag_module;
1420 
1421    /* Create shader modules */
1422    VkShaderModuleCreateInfo vert_info = {};
1423    vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
1424    vert_info.codeSize = sizeof(overlay_vert_spv);
1425    vert_info.pCode = overlay_vert_spv;
1426    VK_CHECK(device_data->vtable.CreateShaderModule(device_data->device,
1427                                                    &vert_info, NULL, &vert_module));
1428    VkShaderModuleCreateInfo frag_info = {};
1429    frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
1430    frag_info.codeSize = sizeof(overlay_frag_spv);
1431    frag_info.pCode = (uint32_t*)overlay_frag_spv;
1432    VK_CHECK(device_data->vtable.CreateShaderModule(device_data->device,
1433                                                    &frag_info, NULL, &frag_module));
1434 
1435    /* Font sampler */
1436    VkSamplerCreateInfo sampler_info = {};
1437    sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
1438    sampler_info.magFilter = VK_FILTER_LINEAR;
1439    sampler_info.minFilter = VK_FILTER_LINEAR;
1440    sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
1441    sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1442    sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1443    sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1444    sampler_info.minLod = -1000;
1445    sampler_info.maxLod = 1000;
1446    sampler_info.maxAnisotropy = 1.0f;
1447    VK_CHECK(device_data->vtable.CreateSampler(device_data->device, &sampler_info,
1448                                               NULL, &data->font_sampler));
1449 
1450    /* Descriptor pool */
1451    VkDescriptorPoolSize sampler_pool_size = {};
1452    sampler_pool_size.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1453    sampler_pool_size.descriptorCount = 1;
1454    VkDescriptorPoolCreateInfo desc_pool_info = {};
1455    desc_pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
1456    desc_pool_info.maxSets = 1;
1457    desc_pool_info.poolSizeCount = 1;
1458    desc_pool_info.pPoolSizes = &sampler_pool_size;
1459    VK_CHECK(device_data->vtable.CreateDescriptorPool(device_data->device,
1460                                                      &desc_pool_info,
1461                                                      NULL, &data->descriptor_pool));
1462 
1463    /* Descriptor layout */
1464    VkSampler sampler[1] = { data->font_sampler };
1465    VkDescriptorSetLayoutBinding binding[1] = {};
1466    binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1467    binding[0].descriptorCount = 1;
1468    binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
1469    binding[0].pImmutableSamplers = sampler;
1470    VkDescriptorSetLayoutCreateInfo set_layout_info = {};
1471    set_layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
1472    set_layout_info.bindingCount = 1;
1473    set_layout_info.pBindings = binding;
1474    VK_CHECK(device_data->vtable.CreateDescriptorSetLayout(device_data->device,
1475                                                           &set_layout_info,
1476                                                           NULL, &data->descriptor_layout));
1477 
1478    /* Descriptor set */
1479    VkDescriptorSetAllocateInfo alloc_info = {};
1480    alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
1481    alloc_info.descriptorPool = data->descriptor_pool;
1482    alloc_info.descriptorSetCount = 1;
1483    alloc_info.pSetLayouts = &data->descriptor_layout;
1484    VK_CHECK(device_data->vtable.AllocateDescriptorSets(device_data->device,
1485                                                        &alloc_info,
1486                                                        &data->descriptor_set));
1487 
1488    /* Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full
1489     * 3d projection matrix
1490     */
1491    VkPushConstantRange push_constants[1] = {};
1492    push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
1493    push_constants[0].offset = sizeof(float) * 0;
1494    push_constants[0].size = sizeof(float) * 4;
1495    VkPipelineLayoutCreateInfo layout_info = {};
1496    layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
1497    layout_info.setLayoutCount = 1;
1498    layout_info.pSetLayouts = &data->descriptor_layout;
1499    layout_info.pushConstantRangeCount = 1;
1500    layout_info.pPushConstantRanges = push_constants;
1501    VK_CHECK(device_data->vtable.CreatePipelineLayout(device_data->device,
1502                                                      &layout_info,
1503                                                      NULL, &data->pipeline_layout));
1504 
1505    VkPipelineShaderStageCreateInfo stage[2] = {};
1506    stage[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
1507    stage[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
1508    stage[0].module = vert_module;
1509    stage[0].pName = "main";
1510    stage[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
1511    stage[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
1512    stage[1].module = frag_module;
1513    stage[1].pName = "main";
1514 
1515    VkVertexInputBindingDescription binding_desc[1] = {};
1516    binding_desc[0].stride = sizeof(ImDrawVert);
1517    binding_desc[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
1518 
1519    VkVertexInputAttributeDescription attribute_desc[3] = {};
1520    attribute_desc[0].location = 0;
1521    attribute_desc[0].binding = binding_desc[0].binding;
1522    attribute_desc[0].format = VK_FORMAT_R32G32_SFLOAT;
1523    attribute_desc[0].offset = IM_OFFSETOF(ImDrawVert, pos);
1524    attribute_desc[1].location = 1;
1525    attribute_desc[1].binding = binding_desc[0].binding;
1526    attribute_desc[1].format = VK_FORMAT_R32G32_SFLOAT;
1527    attribute_desc[1].offset = IM_OFFSETOF(ImDrawVert, uv);
1528    attribute_desc[2].location = 2;
1529    attribute_desc[2].binding = binding_desc[0].binding;
1530    attribute_desc[2].format = VK_FORMAT_R8G8B8A8_UNORM;
1531    attribute_desc[2].offset = IM_OFFSETOF(ImDrawVert, col);
1532 
1533    VkPipelineVertexInputStateCreateInfo vertex_info = {};
1534    vertex_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
1535    vertex_info.vertexBindingDescriptionCount = 1;
1536    vertex_info.pVertexBindingDescriptions = binding_desc;
1537    vertex_info.vertexAttributeDescriptionCount = 3;
1538    vertex_info.pVertexAttributeDescriptions = attribute_desc;
1539 
1540    VkPipelineInputAssemblyStateCreateInfo ia_info = {};
1541    ia_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
1542    ia_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
1543 
1544    VkPipelineViewportStateCreateInfo viewport_info = {};
1545    viewport_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
1546    viewport_info.viewportCount = 1;
1547    viewport_info.scissorCount = 1;
1548 
1549    VkPipelineRasterizationStateCreateInfo raster_info = {};
1550    raster_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
1551    raster_info.polygonMode = VK_POLYGON_MODE_FILL;
1552    raster_info.cullMode = VK_CULL_MODE_NONE;
1553    raster_info.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
1554    raster_info.lineWidth = 1.0f;
1555 
1556    VkPipelineMultisampleStateCreateInfo ms_info = {};
1557    ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
1558    ms_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
1559 
1560    VkPipelineColorBlendAttachmentState color_attachment[1] = {};
1561    color_attachment[0].blendEnable = VK_TRUE;
1562    color_attachment[0].srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
1563    color_attachment[0].dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
1564    color_attachment[0].colorBlendOp = VK_BLEND_OP_ADD;
1565    color_attachment[0].srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
1566    color_attachment[0].dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
1567    color_attachment[0].alphaBlendOp = VK_BLEND_OP_ADD;
1568    color_attachment[0].colorWriteMask = VK_COLOR_COMPONENT_R_BIT |
1569       VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
1570 
1571    VkPipelineDepthStencilStateCreateInfo depth_info = {};
1572    depth_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
1573 
1574    VkPipelineColorBlendStateCreateInfo blend_info = {};
1575    blend_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
1576    blend_info.attachmentCount = 1;
1577    blend_info.pAttachments = color_attachment;
1578 
1579    VkDynamicState dynamic_states[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
1580    VkPipelineDynamicStateCreateInfo dynamic_state = {};
1581    dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
1582    dynamic_state.dynamicStateCount = (uint32_t)IM_ARRAYSIZE(dynamic_states);
1583    dynamic_state.pDynamicStates = dynamic_states;
1584 
1585    VkGraphicsPipelineCreateInfo info = {};
1586    info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
1587    info.flags = 0;
1588    info.stageCount = 2;
1589    info.pStages = stage;
1590    info.pVertexInputState = &vertex_info;
1591    info.pInputAssemblyState = &ia_info;
1592    info.pViewportState = &viewport_info;
1593    info.pRasterizationState = &raster_info;
1594    info.pMultisampleState = &ms_info;
1595    info.pDepthStencilState = &depth_info;
1596    info.pColorBlendState = &blend_info;
1597    info.pDynamicState = &dynamic_state;
1598    info.layout = data->pipeline_layout;
1599    info.renderPass = data->render_pass;
1600    VK_CHECK(
1601       device_data->vtable.CreateGraphicsPipelines(device_data->device, VK_NULL_HANDLE,
1602                                                   1, &info,
1603                                                   NULL, &data->pipeline));
1604 
1605    device_data->vtable.DestroyShaderModule(device_data->device, vert_module, NULL);
1606    device_data->vtable.DestroyShaderModule(device_data->device, frag_module, NULL);
1607 
1608    ImGuiIO& io = ImGui::GetIO();
1609    unsigned char* pixels;
1610    int width, height;
1611    io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
1612 
1613    /* Font image */
1614    VkImageCreateInfo image_info = {};
1615    image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
1616    image_info.imageType = VK_IMAGE_TYPE_2D;
1617    image_info.format = VK_FORMAT_R8G8B8A8_UNORM;
1618    image_info.extent.width = width;
1619    image_info.extent.height = height;
1620    image_info.extent.depth = 1;
1621    image_info.mipLevels = 1;
1622    image_info.arrayLayers = 1;
1623    image_info.samples = VK_SAMPLE_COUNT_1_BIT;
1624    image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
1625    image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
1626    image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1627    image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1628    VK_CHECK(device_data->vtable.CreateImage(device_data->device, &image_info,
1629                                             NULL, &data->font_image));
1630    VkMemoryRequirements font_image_req;
1631    device_data->vtable.GetImageMemoryRequirements(device_data->device,
1632                                                   data->font_image, &font_image_req);
1633    VkMemoryAllocateInfo image_alloc_info = {};
1634    image_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1635    image_alloc_info.allocationSize = font_image_req.size;
1636    image_alloc_info.memoryTypeIndex = vk_memory_type(device_data,
1637                                                      VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1638                                                      font_image_req.memoryTypeBits);
1639    VK_CHECK(device_data->vtable.AllocateMemory(device_data->device, &image_alloc_info,
1640                                                NULL, &data->font_mem));
1641    VK_CHECK(device_data->vtable.BindImageMemory(device_data->device,
1642                                                 data->font_image,
1643                                                 data->font_mem, 0));
1644 
1645    /* Font image view */
1646    VkImageViewCreateInfo view_info = {};
1647    view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1648    view_info.image = data->font_image;
1649    view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
1650    view_info.format = VK_FORMAT_R8G8B8A8_UNORM;
1651    view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1652    view_info.subresourceRange.levelCount = 1;
1653    view_info.subresourceRange.layerCount = 1;
1654    VK_CHECK(device_data->vtable.CreateImageView(device_data->device, &view_info,
1655                                                 NULL, &data->font_image_view));
1656 
1657    /* Descriptor set */
1658    VkDescriptorImageInfo desc_image[1] = {};
1659    desc_image[0].sampler = data->font_sampler;
1660    desc_image[0].imageView = data->font_image_view;
1661    desc_image[0].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1662    VkWriteDescriptorSet write_desc[1] = {};
1663    write_desc[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1664    write_desc[0].dstSet = data->descriptor_set;
1665    write_desc[0].descriptorCount = 1;
1666    write_desc[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1667    write_desc[0].pImageInfo = desc_image;
1668    device_data->vtable.UpdateDescriptorSets(device_data->device, 1, write_desc, 0, NULL);
1669 }
1670 
setup_swapchain_data(struct swapchain_data * data,const VkSwapchainCreateInfoKHR * pCreateInfo)1671 static void setup_swapchain_data(struct swapchain_data *data,
1672                                  const VkSwapchainCreateInfoKHR *pCreateInfo)
1673 {
1674    data->width = pCreateInfo->imageExtent.width;
1675    data->height = pCreateInfo->imageExtent.height;
1676    data->format = pCreateInfo->imageFormat;
1677 
1678    data->imgui_context = ImGui::CreateContext();
1679    ImGui::SetCurrentContext(data->imgui_context);
1680 
1681    ImGui::GetIO().IniFilename = NULL;
1682    ImGui::GetIO().DisplaySize = ImVec2((float)data->width, (float)data->height);
1683 
1684    struct device_data *device_data = data->device;
1685 
1686    /* Render pass */
1687    VkAttachmentDescription attachment_desc = {};
1688    attachment_desc.format = pCreateInfo->imageFormat;
1689    attachment_desc.samples = VK_SAMPLE_COUNT_1_BIT;
1690    attachment_desc.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
1691    attachment_desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
1692    attachment_desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
1693    attachment_desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
1694    attachment_desc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1695    attachment_desc.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
1696    VkAttachmentReference color_attachment = {};
1697    color_attachment.attachment = 0;
1698    color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1699    VkSubpassDescription subpass = {};
1700    subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
1701    subpass.colorAttachmentCount = 1;
1702    subpass.pColorAttachments = &color_attachment;
1703    VkSubpassDependency dependency = {};
1704    dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
1705    dependency.dstSubpass = 0;
1706    dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1707    dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1708    dependency.srcAccessMask = 0;
1709    dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
1710    VkRenderPassCreateInfo render_pass_info = {};
1711    render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
1712    render_pass_info.attachmentCount = 1;
1713    render_pass_info.pAttachments = &attachment_desc;
1714    render_pass_info.subpassCount = 1;
1715    render_pass_info.pSubpasses = &subpass;
1716    render_pass_info.dependencyCount = 1;
1717    render_pass_info.pDependencies = &dependency;
1718    VK_CHECK(device_data->vtable.CreateRenderPass(device_data->device,
1719                                                  &render_pass_info,
1720                                                  NULL, &data->render_pass));
1721 
1722    setup_swapchain_data_pipeline(data);
1723 
1724    VK_CHECK(device_data->vtable.GetSwapchainImagesKHR(device_data->device,
1725                                                       data->swapchain,
1726                                                       &data->n_images,
1727                                                       NULL));
1728 
1729    data->images = ralloc_array(data, VkImage, data->n_images);
1730    data->image_views = ralloc_array(data, VkImageView, data->n_images);
1731    data->framebuffers = ralloc_array(data, VkFramebuffer, data->n_images);
1732 
1733    VK_CHECK(device_data->vtable.GetSwapchainImagesKHR(device_data->device,
1734                                                       data->swapchain,
1735                                                       &data->n_images,
1736                                                       data->images));
1737 
1738    /* Image views */
1739    VkImageViewCreateInfo view_info = {};
1740    view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1741    view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
1742    view_info.format = pCreateInfo->imageFormat;
1743    view_info.components.r = VK_COMPONENT_SWIZZLE_R;
1744    view_info.components.g = VK_COMPONENT_SWIZZLE_G;
1745    view_info.components.b = VK_COMPONENT_SWIZZLE_B;
1746    view_info.components.a = VK_COMPONENT_SWIZZLE_A;
1747    view_info.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
1748    for (uint32_t i = 0; i < data->n_images; i++) {
1749       view_info.image = data->images[i];
1750       VK_CHECK(device_data->vtable.CreateImageView(device_data->device,
1751                                                    &view_info, NULL,
1752                                                    &data->image_views[i]));
1753    }
1754 
1755    /* Framebuffers */
1756    VkImageView attachment[1];
1757    VkFramebufferCreateInfo fb_info = {};
1758    fb_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
1759    fb_info.renderPass = data->render_pass;
1760    fb_info.attachmentCount = 1;
1761    fb_info.pAttachments = attachment;
1762    fb_info.width = data->width;
1763    fb_info.height = data->height;
1764    fb_info.layers = 1;
1765    for (uint32_t i = 0; i < data->n_images; i++) {
1766       attachment[0] = data->image_views[i];
1767       VK_CHECK(device_data->vtable.CreateFramebuffer(device_data->device, &fb_info,
1768                                                      NULL, &data->framebuffers[i]));
1769    }
1770 
1771    /* Command buffer pool */
1772    VkCommandPoolCreateInfo cmd_buffer_pool_info = {};
1773    cmd_buffer_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1774    cmd_buffer_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
1775    cmd_buffer_pool_info.queueFamilyIndex = device_data->graphic_queue->family_index;
1776    VK_CHECK(device_data->vtable.CreateCommandPool(device_data->device,
1777                                                   &cmd_buffer_pool_info,
1778                                                   NULL, &data->command_pool));
1779 }
1780 
shutdown_swapchain_data(struct swapchain_data * data)1781 static void shutdown_swapchain_data(struct swapchain_data *data)
1782 {
1783    struct device_data *device_data = data->device;
1784 
1785    list_for_each_entry_safe(struct overlay_draw, draw, &data->draws, link) {
1786       device_data->vtable.DestroySemaphore(device_data->device, draw->cross_engine_semaphore, NULL);
1787       device_data->vtable.DestroySemaphore(device_data->device, draw->semaphore, NULL);
1788       device_data->vtable.DestroyFence(device_data->device, draw->fence, NULL);
1789       device_data->vtable.DestroyBuffer(device_data->device, draw->vertex_buffer, NULL);
1790       device_data->vtable.DestroyBuffer(device_data->device, draw->index_buffer, NULL);
1791       device_data->vtable.FreeMemory(device_data->device, draw->vertex_buffer_mem, NULL);
1792       device_data->vtable.FreeMemory(device_data->device, draw->index_buffer_mem, NULL);
1793    }
1794 
1795    for (uint32_t i = 0; i < data->n_images; i++) {
1796       device_data->vtable.DestroyImageView(device_data->device, data->image_views[i], NULL);
1797       device_data->vtable.DestroyFramebuffer(device_data->device, data->framebuffers[i], NULL);
1798    }
1799 
1800    device_data->vtable.DestroyRenderPass(device_data->device, data->render_pass, NULL);
1801 
1802    device_data->vtable.DestroyCommandPool(device_data->device, data->command_pool, NULL);
1803 
1804    device_data->vtable.DestroyPipeline(device_data->device, data->pipeline, NULL);
1805    device_data->vtable.DestroyPipelineLayout(device_data->device, data->pipeline_layout, NULL);
1806 
1807    device_data->vtable.DestroyDescriptorPool(device_data->device,
1808                                              data->descriptor_pool, NULL);
1809    device_data->vtable.DestroyDescriptorSetLayout(device_data->device,
1810                                                   data->descriptor_layout, NULL);
1811 
1812    device_data->vtable.DestroySampler(device_data->device, data->font_sampler, NULL);
1813    device_data->vtable.DestroyImageView(device_data->device, data->font_image_view, NULL);
1814    device_data->vtable.DestroyImage(device_data->device, data->font_image, NULL);
1815    device_data->vtable.FreeMemory(device_data->device, data->font_mem, NULL);
1816 
1817    device_data->vtable.DestroyBuffer(device_data->device, data->upload_font_buffer, NULL);
1818    device_data->vtable.FreeMemory(device_data->device, data->upload_font_buffer_mem, NULL);
1819 
1820    ImGui::DestroyContext(data->imgui_context);
1821 }
1822 
before_present(struct swapchain_data * swapchain_data,struct queue_data * present_queue,const VkSemaphore * wait_semaphores,unsigned n_wait_semaphores,unsigned imageIndex)1823 static struct overlay_draw *before_present(struct swapchain_data *swapchain_data,
1824                                            struct queue_data *present_queue,
1825                                            const VkSemaphore *wait_semaphores,
1826                                            unsigned n_wait_semaphores,
1827                                            unsigned imageIndex)
1828 {
1829    struct instance_data *instance_data = swapchain_data->device->instance;
1830    struct overlay_draw *draw = NULL;
1831 
1832    snapshot_swapchain_frame(swapchain_data);
1833 
1834    if (!instance_data->params.no_display && swapchain_data->n_frames > 0) {
1835       compute_swapchain_display(swapchain_data);
1836       draw = render_swapchain_display(swapchain_data, present_queue,
1837                                       wait_semaphores, n_wait_semaphores,
1838                                       imageIndex);
1839    }
1840 
1841    return draw;
1842 }
1843 
overlay_CreateSwapchainKHR(VkDevice device,const VkSwapchainCreateInfoKHR * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkSwapchainKHR * pSwapchain)1844 static VkResult overlay_CreateSwapchainKHR(
1845     VkDevice                                    device,
1846     const VkSwapchainCreateInfoKHR*             pCreateInfo,
1847     const VkAllocationCallbacks*                pAllocator,
1848     VkSwapchainKHR*                             pSwapchain)
1849 {
1850    struct device_data *device_data = FIND(struct device_data, device);
1851    VkResult result = device_data->vtable.CreateSwapchainKHR(device, pCreateInfo, pAllocator, pSwapchain);
1852    if (result != VK_SUCCESS) return result;
1853 
1854    struct swapchain_data *swapchain_data = new_swapchain_data(*pSwapchain, device_data);
1855    setup_swapchain_data(swapchain_data, pCreateInfo);
1856    return result;
1857 }
1858 
overlay_DestroySwapchainKHR(VkDevice device,VkSwapchainKHR swapchain,const VkAllocationCallbacks * pAllocator)1859 static void overlay_DestroySwapchainKHR(
1860     VkDevice                                    device,
1861     VkSwapchainKHR                              swapchain,
1862     const VkAllocationCallbacks*                pAllocator)
1863 {
1864    if (swapchain == VK_NULL_HANDLE) {
1865       struct device_data *device_data = FIND(struct device_data, device);
1866       device_data->vtable.DestroySwapchainKHR(device, swapchain, pAllocator);
1867       return;
1868    }
1869 
1870    struct swapchain_data *swapchain_data =
1871       FIND(struct swapchain_data, swapchain);
1872 
1873    shutdown_swapchain_data(swapchain_data);
1874    swapchain_data->device->vtable.DestroySwapchainKHR(device, swapchain, pAllocator);
1875    destroy_swapchain_data(swapchain_data);
1876 }
1877 
overlay_QueuePresentKHR(VkQueue queue,const VkPresentInfoKHR * pPresentInfo)1878 static VkResult overlay_QueuePresentKHR(
1879     VkQueue                                     queue,
1880     const VkPresentInfoKHR*                     pPresentInfo)
1881 {
1882    struct queue_data *queue_data = FIND(struct queue_data, queue);
1883    struct device_data *device_data = queue_data->device;
1884    struct instance_data *instance_data = device_data->instance;
1885    uint32_t query_results[OVERLAY_QUERY_COUNT];
1886 
1887    device_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_frame]++;
1888 
1889    if (list_length(&queue_data->running_command_buffer) > 0) {
1890       /* Before getting the query results, make sure the operations have
1891        * completed.
1892        */
1893       VK_CHECK(device_data->vtable.ResetFences(device_data->device,
1894                                                1, &queue_data->queries_fence));
1895       VK_CHECK(device_data->vtable.QueueSubmit(queue, 0, NULL, queue_data->queries_fence));
1896       VK_CHECK(device_data->vtable.WaitForFences(device_data->device,
1897                                                  1, &queue_data->queries_fence,
1898                                                  VK_FALSE, UINT64_MAX));
1899 
1900       /* Now get the results. */
1901       list_for_each_entry_safe(struct command_buffer_data, cmd_buffer_data,
1902                                &queue_data->running_command_buffer, link) {
1903          list_delinit(&cmd_buffer_data->link);
1904 
1905          if (cmd_buffer_data->pipeline_query_pool) {
1906             memset(query_results, 0, sizeof(query_results));
1907             VK_CHECK(device_data->vtable.GetQueryPoolResults(device_data->device,
1908                                                              cmd_buffer_data->pipeline_query_pool,
1909                                                              cmd_buffer_data->query_index, 1,
1910                                                              sizeof(uint32_t) * OVERLAY_QUERY_COUNT,
1911                                                              query_results, 0, VK_QUERY_RESULT_WAIT_BIT));
1912 
1913             for (uint32_t i = OVERLAY_PARAM_ENABLED_vertices;
1914                  i <= OVERLAY_PARAM_ENABLED_compute_invocations; i++) {
1915                device_data->frame_stats.stats[i] += query_results[i - OVERLAY_PARAM_ENABLED_vertices];
1916             }
1917          }
1918          if (cmd_buffer_data->timestamp_query_pool) {
1919             uint64_t gpu_timestamps[2] = { 0 };
1920             VK_CHECK(device_data->vtable.GetQueryPoolResults(device_data->device,
1921                                                              cmd_buffer_data->timestamp_query_pool,
1922                                                              cmd_buffer_data->query_index * 2, 2,
1923                                                              2 * sizeof(uint64_t), gpu_timestamps, sizeof(uint64_t),
1924                                                              VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT));
1925 
1926             gpu_timestamps[0] &= queue_data->timestamp_mask;
1927             gpu_timestamps[1] &= queue_data->timestamp_mask;
1928             device_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_gpu_timing] +=
1929                (gpu_timestamps[1] - gpu_timestamps[0]) *
1930                device_data->properties.limits.timestampPeriod;
1931          }
1932       }
1933    }
1934 
1935    /* Otherwise we need to add our overlay drawing semaphore to the list of
1936     * semaphores to wait on. If we don't do that the presented picture might
1937     * be have incomplete overlay drawings.
1938     */
1939    VkResult result = VK_SUCCESS;
1940    if (instance_data->params.no_display) {
1941       for (uint32_t i = 0; i < pPresentInfo->swapchainCount; i++) {
1942          VkSwapchainKHR swapchain = pPresentInfo->pSwapchains[i];
1943          struct swapchain_data *swapchain_data =
1944             FIND(struct swapchain_data, swapchain);
1945 
1946          uint32_t image_index = pPresentInfo->pImageIndices[i];
1947 
1948          before_present(swapchain_data,
1949                         queue_data,
1950                         pPresentInfo->pWaitSemaphores,
1951                         pPresentInfo->waitSemaphoreCount,
1952                         image_index);
1953 
1954          VkPresentInfoKHR present_info = *pPresentInfo;
1955          present_info.swapchainCount = 1;
1956          present_info.pSwapchains = &swapchain;
1957          present_info.pImageIndices = &image_index;
1958 
1959          uint64_t ts0 = os_time_get();
1960          result = queue_data->device->vtable.QueuePresentKHR(queue, &present_info);
1961          uint64_t ts1 = os_time_get();
1962          swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_present_timing] += ts1 - ts0;
1963       }
1964    } else {
1965       for (uint32_t i = 0; i < pPresentInfo->swapchainCount; i++) {
1966          VkSwapchainKHR swapchain = pPresentInfo->pSwapchains[i];
1967          struct swapchain_data *swapchain_data =
1968             FIND(struct swapchain_data, swapchain);
1969 
1970          uint32_t image_index = pPresentInfo->pImageIndices[i];
1971 
1972          VkPresentInfoKHR present_info = *pPresentInfo;
1973          present_info.swapchainCount = 1;
1974          present_info.pSwapchains = &swapchain;
1975          present_info.pImageIndices = &image_index;
1976 
1977          struct overlay_draw *draw = before_present(swapchain_data,
1978                                                     queue_data,
1979                                                     pPresentInfo->pWaitSemaphores,
1980                                                     pPresentInfo->waitSemaphoreCount,
1981                                                     image_index);
1982 
1983          /* Because the submission of the overlay draw waits on the semaphores
1984           * handed for present, we don't need to have this present operation
1985           * wait on them as well, we can just wait on the overlay submission
1986           * semaphore.
1987           */
1988          present_info.pWaitSemaphores = &draw->semaphore;
1989          present_info.waitSemaphoreCount = 1;
1990 
1991          uint64_t ts0 = os_time_get();
1992          VkResult chain_result = queue_data->device->vtable.QueuePresentKHR(queue, &present_info);
1993          uint64_t ts1 = os_time_get();
1994          swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_present_timing] += ts1 - ts0;
1995          if (pPresentInfo->pResults)
1996             pPresentInfo->pResults[i] = chain_result;
1997          if (chain_result != VK_SUCCESS && result == VK_SUCCESS)
1998             result = chain_result;
1999       }
2000    }
2001    return result;
2002 }
2003 
overlay_AcquireNextImageKHR(VkDevice device,VkSwapchainKHR swapchain,uint64_t timeout,VkSemaphore semaphore,VkFence fence,uint32_t * pImageIndex)2004 static VkResult overlay_AcquireNextImageKHR(
2005     VkDevice                                    device,
2006     VkSwapchainKHR                              swapchain,
2007     uint64_t                                    timeout,
2008     VkSemaphore                                 semaphore,
2009     VkFence                                     fence,
2010     uint32_t*                                   pImageIndex)
2011 {
2012    struct swapchain_data *swapchain_data =
2013       FIND(struct swapchain_data, swapchain);
2014    struct device_data *device_data = swapchain_data->device;
2015 
2016    uint64_t ts0 = os_time_get();
2017    VkResult result = device_data->vtable.AcquireNextImageKHR(device, swapchain, timeout,
2018                                                              semaphore, fence, pImageIndex);
2019    uint64_t ts1 = os_time_get();
2020 
2021    swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire_timing] += ts1 - ts0;
2022    swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire]++;
2023 
2024    return result;
2025 }
2026 
overlay_AcquireNextImage2KHR(VkDevice device,const VkAcquireNextImageInfoKHR * pAcquireInfo,uint32_t * pImageIndex)2027 static VkResult overlay_AcquireNextImage2KHR(
2028     VkDevice                                    device,
2029     const VkAcquireNextImageInfoKHR*            pAcquireInfo,
2030     uint32_t*                                   pImageIndex)
2031 {
2032    struct swapchain_data *swapchain_data =
2033       FIND(struct swapchain_data, pAcquireInfo->swapchain);
2034    struct device_data *device_data = swapchain_data->device;
2035 
2036    uint64_t ts0 = os_time_get();
2037    VkResult result = device_data->vtable.AcquireNextImage2KHR(device, pAcquireInfo, pImageIndex);
2038    uint64_t ts1 = os_time_get();
2039 
2040    swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire_timing] += ts1 - ts0;
2041    swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire]++;
2042 
2043    return result;
2044 }
2045 
overlay_CmdDraw(VkCommandBuffer commandBuffer,uint32_t vertexCount,uint32_t instanceCount,uint32_t firstVertex,uint32_t firstInstance)2046 static void overlay_CmdDraw(
2047     VkCommandBuffer                             commandBuffer,
2048     uint32_t                                    vertexCount,
2049     uint32_t                                    instanceCount,
2050     uint32_t                                    firstVertex,
2051     uint32_t                                    firstInstance)
2052 {
2053    struct command_buffer_data *cmd_buffer_data =
2054       FIND(struct command_buffer_data, commandBuffer);
2055    cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw]++;
2056    struct device_data *device_data = cmd_buffer_data->device;
2057    device_data->vtable.CmdDraw(commandBuffer, vertexCount, instanceCount,
2058                                firstVertex, firstInstance);
2059 }
2060 
overlay_CmdDrawIndexed(VkCommandBuffer commandBuffer,uint32_t indexCount,uint32_t instanceCount,uint32_t firstIndex,int32_t vertexOffset,uint32_t firstInstance)2061 static void overlay_CmdDrawIndexed(
2062     VkCommandBuffer                             commandBuffer,
2063     uint32_t                                    indexCount,
2064     uint32_t                                    instanceCount,
2065     uint32_t                                    firstIndex,
2066     int32_t                                     vertexOffset,
2067     uint32_t                                    firstInstance)
2068 {
2069    struct command_buffer_data *cmd_buffer_data =
2070       FIND(struct command_buffer_data, commandBuffer);
2071    cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indexed]++;
2072    struct device_data *device_data = cmd_buffer_data->device;
2073    device_data->vtable.CmdDrawIndexed(commandBuffer, indexCount, instanceCount,
2074                                       firstIndex, vertexOffset, firstInstance);
2075 }
2076 
overlay_CmdDrawIndirect(VkCommandBuffer commandBuffer,VkBuffer buffer,VkDeviceSize offset,uint32_t drawCount,uint32_t stride)2077 static void overlay_CmdDrawIndirect(
2078     VkCommandBuffer                             commandBuffer,
2079     VkBuffer                                    buffer,
2080     VkDeviceSize                                offset,
2081     uint32_t                                    drawCount,
2082     uint32_t                                    stride)
2083 {
2084    struct command_buffer_data *cmd_buffer_data =
2085       FIND(struct command_buffer_data, commandBuffer);
2086    cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indirect]++;
2087    struct device_data *device_data = cmd_buffer_data->device;
2088    device_data->vtable.CmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
2089 }
2090 
overlay_CmdDrawIndexedIndirect(VkCommandBuffer commandBuffer,VkBuffer buffer,VkDeviceSize offset,uint32_t drawCount,uint32_t stride)2091 static void overlay_CmdDrawIndexedIndirect(
2092     VkCommandBuffer                             commandBuffer,
2093     VkBuffer                                    buffer,
2094     VkDeviceSize                                offset,
2095     uint32_t                                    drawCount,
2096     uint32_t                                    stride)
2097 {
2098    struct command_buffer_data *cmd_buffer_data =
2099       FIND(struct command_buffer_data, commandBuffer);
2100    cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indexed_indirect]++;
2101    struct device_data *device_data = cmd_buffer_data->device;
2102    device_data->vtable.CmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
2103 }
2104 
overlay_CmdDrawIndirectCount(VkCommandBuffer commandBuffer,VkBuffer buffer,VkDeviceSize offset,VkBuffer countBuffer,VkDeviceSize countBufferOffset,uint32_t maxDrawCount,uint32_t stride)2105 static void overlay_CmdDrawIndirectCount(
2106     VkCommandBuffer                             commandBuffer,
2107     VkBuffer                                    buffer,
2108     VkDeviceSize                                offset,
2109     VkBuffer                                    countBuffer,
2110     VkDeviceSize                                countBufferOffset,
2111     uint32_t                                    maxDrawCount,
2112     uint32_t                                    stride)
2113 {
2114    struct command_buffer_data *cmd_buffer_data =
2115       FIND(struct command_buffer_data, commandBuffer);
2116    cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indirect_count]++;
2117    struct device_data *device_data = cmd_buffer_data->device;
2118    device_data->vtable.CmdDrawIndirectCount(commandBuffer, buffer, offset,
2119                                             countBuffer, countBufferOffset,
2120                                             maxDrawCount, stride);
2121 }
2122 
overlay_CmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer,VkBuffer buffer,VkDeviceSize offset,VkBuffer countBuffer,VkDeviceSize countBufferOffset,uint32_t maxDrawCount,uint32_t stride)2123 static void overlay_CmdDrawIndexedIndirectCount(
2124     VkCommandBuffer                             commandBuffer,
2125     VkBuffer                                    buffer,
2126     VkDeviceSize                                offset,
2127     VkBuffer                                    countBuffer,
2128     VkDeviceSize                                countBufferOffset,
2129     uint32_t                                    maxDrawCount,
2130     uint32_t                                    stride)
2131 {
2132    struct command_buffer_data *cmd_buffer_data =
2133       FIND(struct command_buffer_data, commandBuffer);
2134    cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indexed_indirect_count]++;
2135    struct device_data *device_data = cmd_buffer_data->device;
2136    device_data->vtable.CmdDrawIndexedIndirectCount(commandBuffer, buffer, offset,
2137                                                    countBuffer, countBufferOffset,
2138                                                    maxDrawCount, stride);
2139 }
2140 
overlay_CmdDispatch(VkCommandBuffer commandBuffer,uint32_t groupCountX,uint32_t groupCountY,uint32_t groupCountZ)2141 static void overlay_CmdDispatch(
2142     VkCommandBuffer                             commandBuffer,
2143     uint32_t                                    groupCountX,
2144     uint32_t                                    groupCountY,
2145     uint32_t                                    groupCountZ)
2146 {
2147    struct command_buffer_data *cmd_buffer_data =
2148       FIND(struct command_buffer_data, commandBuffer);
2149    cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_dispatch]++;
2150    struct device_data *device_data = cmd_buffer_data->device;
2151    device_data->vtable.CmdDispatch(commandBuffer, groupCountX, groupCountY, groupCountZ);
2152 }
2153 
overlay_CmdDispatchIndirect(VkCommandBuffer commandBuffer,VkBuffer buffer,VkDeviceSize offset)2154 static void overlay_CmdDispatchIndirect(
2155     VkCommandBuffer                             commandBuffer,
2156     VkBuffer                                    buffer,
2157     VkDeviceSize                                offset)
2158 {
2159    struct command_buffer_data *cmd_buffer_data =
2160       FIND(struct command_buffer_data, commandBuffer);
2161    cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_dispatch_indirect]++;
2162    struct device_data *device_data = cmd_buffer_data->device;
2163    device_data->vtable.CmdDispatchIndirect(commandBuffer, buffer, offset);
2164 }
2165 
overlay_CmdBindPipeline(VkCommandBuffer commandBuffer,VkPipelineBindPoint pipelineBindPoint,VkPipeline pipeline)2166 static void overlay_CmdBindPipeline(
2167     VkCommandBuffer                             commandBuffer,
2168     VkPipelineBindPoint                         pipelineBindPoint,
2169     VkPipeline                                  pipeline)
2170 {
2171    struct command_buffer_data *cmd_buffer_data =
2172       FIND(struct command_buffer_data, commandBuffer);
2173    switch (pipelineBindPoint) {
2174    case VK_PIPELINE_BIND_POINT_GRAPHICS: cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_pipeline_graphics]++; break;
2175    case VK_PIPELINE_BIND_POINT_COMPUTE: cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_pipeline_compute]++; break;
2176    case VK_PIPELINE_BIND_POINT_RAY_TRACING_NV: cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_pipeline_raytracing]++; break;
2177    default: break;
2178    }
2179    struct device_data *device_data = cmd_buffer_data->device;
2180    device_data->vtable.CmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
2181 }
2182 
overlay_BeginCommandBuffer(VkCommandBuffer commandBuffer,const VkCommandBufferBeginInfo * pBeginInfo)2183 static VkResult overlay_BeginCommandBuffer(
2184     VkCommandBuffer                             commandBuffer,
2185     const VkCommandBufferBeginInfo*             pBeginInfo)
2186 {
2187    struct command_buffer_data *cmd_buffer_data =
2188       FIND(struct command_buffer_data, commandBuffer);
2189    struct device_data *device_data = cmd_buffer_data->device;
2190 
2191    memset(&cmd_buffer_data->stats, 0, sizeof(cmd_buffer_data->stats));
2192 
2193    /* We don't record any query in secondary command buffers, just make sure
2194     * we have the right inheritance.
2195     */
2196    if (cmd_buffer_data->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2197       VkCommandBufferBeginInfo *begin_info = (VkCommandBufferBeginInfo *)
2198          clone_chain((const struct VkBaseInStructure *)pBeginInfo);
2199       VkCommandBufferInheritanceInfo *parent_inhe_info = (VkCommandBufferInheritanceInfo *)
2200          vk_find_struct(begin_info, COMMAND_BUFFER_INHERITANCE_INFO);
2201       VkCommandBufferInheritanceInfo inhe_info = {
2202          VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO,
2203          NULL,
2204          VK_NULL_HANDLE,
2205          0,
2206          VK_NULL_HANDLE,
2207          VK_FALSE,
2208          0,
2209          overlay_query_flags,
2210       };
2211 
2212       if (parent_inhe_info)
2213          parent_inhe_info->pipelineStatistics = overlay_query_flags;
2214       else {
2215          inhe_info.pNext = begin_info->pNext;
2216          begin_info->pNext = &inhe_info;
2217       }
2218 
2219       VkResult result = device_data->vtable.BeginCommandBuffer(commandBuffer, pBeginInfo);
2220 
2221       if (!parent_inhe_info)
2222          begin_info->pNext = inhe_info.pNext;
2223 
2224       free_chain((struct VkBaseOutStructure *)begin_info);
2225 
2226       return result;
2227    }
2228 
2229    /* Otherwise record a begin query as first command. */
2230    VkResult result = device_data->vtable.BeginCommandBuffer(commandBuffer, pBeginInfo);
2231 
2232    if (result == VK_SUCCESS) {
2233       if (cmd_buffer_data->pipeline_query_pool) {
2234          device_data->vtable.CmdResetQueryPool(commandBuffer,
2235                                                cmd_buffer_data->pipeline_query_pool,
2236                                                cmd_buffer_data->query_index, 1);
2237       }
2238       if (cmd_buffer_data->timestamp_query_pool) {
2239          device_data->vtable.CmdResetQueryPool(commandBuffer,
2240                                                cmd_buffer_data->timestamp_query_pool,
2241                                                cmd_buffer_data->query_index * 2, 2);
2242       }
2243       if (cmd_buffer_data->pipeline_query_pool) {
2244          device_data->vtable.CmdBeginQuery(commandBuffer,
2245                                            cmd_buffer_data->pipeline_query_pool,
2246                                            cmd_buffer_data->query_index, 0);
2247       }
2248       if (cmd_buffer_data->timestamp_query_pool) {
2249          device_data->vtable.CmdWriteTimestamp(commandBuffer,
2250                                                VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
2251                                                cmd_buffer_data->timestamp_query_pool,
2252                                                cmd_buffer_data->query_index * 2);
2253       }
2254    }
2255 
2256    return result;
2257 }
2258 
overlay_EndCommandBuffer(VkCommandBuffer commandBuffer)2259 static VkResult overlay_EndCommandBuffer(
2260     VkCommandBuffer                             commandBuffer)
2261 {
2262    struct command_buffer_data *cmd_buffer_data =
2263       FIND(struct command_buffer_data, commandBuffer);
2264    struct device_data *device_data = cmd_buffer_data->device;
2265 
2266    if (cmd_buffer_data->timestamp_query_pool) {
2267       device_data->vtable.CmdWriteTimestamp(commandBuffer,
2268                                             VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
2269                                             cmd_buffer_data->timestamp_query_pool,
2270                                             cmd_buffer_data->query_index * 2 + 1);
2271    }
2272    if (cmd_buffer_data->pipeline_query_pool) {
2273       device_data->vtable.CmdEndQuery(commandBuffer,
2274                                       cmd_buffer_data->pipeline_query_pool,
2275                                       cmd_buffer_data->query_index);
2276    }
2277 
2278    return device_data->vtable.EndCommandBuffer(commandBuffer);
2279 }
2280 
overlay_ResetCommandBuffer(VkCommandBuffer commandBuffer,VkCommandBufferResetFlags flags)2281 static VkResult overlay_ResetCommandBuffer(
2282     VkCommandBuffer                             commandBuffer,
2283     VkCommandBufferResetFlags                   flags)
2284 {
2285    struct command_buffer_data *cmd_buffer_data =
2286       FIND(struct command_buffer_data, commandBuffer);
2287    struct device_data *device_data = cmd_buffer_data->device;
2288 
2289    memset(&cmd_buffer_data->stats, 0, sizeof(cmd_buffer_data->stats));
2290 
2291    return device_data->vtable.ResetCommandBuffer(commandBuffer, flags);
2292 }
2293 
overlay_CmdExecuteCommands(VkCommandBuffer commandBuffer,uint32_t commandBufferCount,const VkCommandBuffer * pCommandBuffers)2294 static void overlay_CmdExecuteCommands(
2295     VkCommandBuffer                             commandBuffer,
2296     uint32_t                                    commandBufferCount,
2297     const VkCommandBuffer*                      pCommandBuffers)
2298 {
2299    struct command_buffer_data *cmd_buffer_data =
2300       FIND(struct command_buffer_data, commandBuffer);
2301    struct device_data *device_data = cmd_buffer_data->device;
2302 
2303    /* Add the stats of the executed command buffers to the primary one. */
2304    for (uint32_t c = 0; c < commandBufferCount; c++) {
2305       struct command_buffer_data *sec_cmd_buffer_data =
2306          FIND(struct command_buffer_data, pCommandBuffers[c]);
2307 
2308       for (uint32_t s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++)
2309          cmd_buffer_data->stats.stats[s] += sec_cmd_buffer_data->stats.stats[s];
2310    }
2311 
2312    device_data->vtable.CmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2313 }
2314 
overlay_AllocateCommandBuffers(VkDevice device,const VkCommandBufferAllocateInfo * pAllocateInfo,VkCommandBuffer * pCommandBuffers)2315 static VkResult overlay_AllocateCommandBuffers(
2316    VkDevice                           device,
2317    const VkCommandBufferAllocateInfo* pAllocateInfo,
2318    VkCommandBuffer*                   pCommandBuffers)
2319 {
2320    struct device_data *device_data = FIND(struct device_data, device);
2321    VkResult result =
2322       device_data->vtable.AllocateCommandBuffers(device, pAllocateInfo, pCommandBuffers);
2323    if (result != VK_SUCCESS)
2324       return result;
2325 
2326    VkQueryPool pipeline_query_pool = VK_NULL_HANDLE;
2327    VkQueryPool timestamp_query_pool = VK_NULL_HANDLE;
2328    if (device_data->instance->pipeline_statistics_enabled &&
2329        pAllocateInfo->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY) {
2330       VkQueryPoolCreateInfo pool_info = {
2331          VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,
2332          NULL,
2333          0,
2334          VK_QUERY_TYPE_PIPELINE_STATISTICS,
2335          pAllocateInfo->commandBufferCount,
2336          overlay_query_flags,
2337       };
2338       VK_CHECK(device_data->vtable.CreateQueryPool(device_data->device, &pool_info,
2339                                                    NULL, &pipeline_query_pool));
2340    }
2341    if (device_data->instance->params.enabled[OVERLAY_PARAM_ENABLED_gpu_timing]) {
2342       VkQueryPoolCreateInfo pool_info = {
2343          VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,
2344          NULL,
2345          0,
2346          VK_QUERY_TYPE_TIMESTAMP,
2347          pAllocateInfo->commandBufferCount * 2,
2348          0,
2349       };
2350       VK_CHECK(device_data->vtable.CreateQueryPool(device_data->device, &pool_info,
2351                                                    NULL, &timestamp_query_pool));
2352    }
2353 
2354    for (uint32_t i = 0; i < pAllocateInfo->commandBufferCount; i++) {
2355       new_command_buffer_data(pCommandBuffers[i], pAllocateInfo->level,
2356                               pipeline_query_pool, timestamp_query_pool,
2357                               i, device_data);
2358    }
2359 
2360    if (pipeline_query_pool)
2361       map_object(HKEY(pipeline_query_pool), (void *)(uintptr_t) pAllocateInfo->commandBufferCount);
2362    if (timestamp_query_pool)
2363       map_object(HKEY(timestamp_query_pool), (void *)(uintptr_t) pAllocateInfo->commandBufferCount);
2364 
2365    return result;
2366 }
2367 
overlay_FreeCommandBuffers(VkDevice device,VkCommandPool commandPool,uint32_t commandBufferCount,const VkCommandBuffer * pCommandBuffers)2368 static void overlay_FreeCommandBuffers(
2369    VkDevice               device,
2370    VkCommandPool          commandPool,
2371    uint32_t               commandBufferCount,
2372    const VkCommandBuffer* pCommandBuffers)
2373 {
2374    struct device_data *device_data = FIND(struct device_data, device);
2375    for (uint32_t i = 0; i < commandBufferCount; i++) {
2376       struct command_buffer_data *cmd_buffer_data =
2377          FIND(struct command_buffer_data, pCommandBuffers[i]);
2378 
2379       /* It is legal to free a NULL command buffer*/
2380       if (!cmd_buffer_data)
2381          continue;
2382 
2383       uint64_t count = (uintptr_t)find_object_data(HKEY(cmd_buffer_data->pipeline_query_pool));
2384       if (count == 1) {
2385          unmap_object(HKEY(cmd_buffer_data->pipeline_query_pool));
2386          device_data->vtable.DestroyQueryPool(device_data->device,
2387                                               cmd_buffer_data->pipeline_query_pool, NULL);
2388       } else if (count != 0) {
2389          map_object(HKEY(cmd_buffer_data->pipeline_query_pool), (void *)(uintptr_t)(count - 1));
2390       }
2391       count = (uintptr_t)find_object_data(HKEY(cmd_buffer_data->timestamp_query_pool));
2392       if (count == 1) {
2393          unmap_object(HKEY(cmd_buffer_data->timestamp_query_pool));
2394          device_data->vtable.DestroyQueryPool(device_data->device,
2395                                               cmd_buffer_data->timestamp_query_pool, NULL);
2396       } else if (count != 0) {
2397          map_object(HKEY(cmd_buffer_data->timestamp_query_pool), (void *)(uintptr_t)(count - 1));
2398       }
2399       destroy_command_buffer_data(cmd_buffer_data);
2400    }
2401 
2402    device_data->vtable.FreeCommandBuffers(device, commandPool,
2403                                           commandBufferCount, pCommandBuffers);
2404 }
2405 
overlay_QueueSubmit(VkQueue queue,uint32_t submitCount,const VkSubmitInfo * pSubmits,VkFence fence)2406 static VkResult overlay_QueueSubmit(
2407     VkQueue                                     queue,
2408     uint32_t                                    submitCount,
2409     const VkSubmitInfo*                         pSubmits,
2410     VkFence                                     fence)
2411 {
2412    struct queue_data *queue_data = FIND(struct queue_data, queue);
2413    struct device_data *device_data = queue_data->device;
2414 
2415    device_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_submit]++;
2416 
2417    for (uint32_t s = 0; s < submitCount; s++) {
2418       for (uint32_t c = 0; c < pSubmits[s].commandBufferCount; c++) {
2419          struct command_buffer_data *cmd_buffer_data =
2420             FIND(struct command_buffer_data, pSubmits[s].pCommandBuffers[c]);
2421 
2422          /* Merge the submitted command buffer stats into the device. */
2423          for (uint32_t st = 0; st < OVERLAY_PARAM_ENABLED_MAX; st++)
2424             device_data->frame_stats.stats[st] += cmd_buffer_data->stats.stats[st];
2425 
2426          /* Attach the command buffer to the queue so we remember to read its
2427           * pipeline statistics & timestamps at QueuePresent().
2428           */
2429          if (!cmd_buffer_data->pipeline_query_pool &&
2430              !cmd_buffer_data->timestamp_query_pool)
2431             continue;
2432 
2433          if (list_is_empty(&cmd_buffer_data->link)) {
2434             list_addtail(&cmd_buffer_data->link,
2435                          &queue_data->running_command_buffer);
2436          } else {
2437             fprintf(stderr, "Command buffer submitted multiple times before present.\n"
2438                     "This could lead to invalid data.\n");
2439          }
2440       }
2441    }
2442 
2443    return device_data->vtable.QueueSubmit(queue, submitCount, pSubmits, fence);
2444 }
2445 
overlay_CreateDevice(VkPhysicalDevice physicalDevice,const VkDeviceCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkDevice * pDevice)2446 static VkResult overlay_CreateDevice(
2447     VkPhysicalDevice                            physicalDevice,
2448     const VkDeviceCreateInfo*                   pCreateInfo,
2449     const VkAllocationCallbacks*                pAllocator,
2450     VkDevice*                                   pDevice)
2451 {
2452    struct instance_data *instance_data =
2453       FIND(struct instance_data, physicalDevice);
2454    VkLayerDeviceCreateInfo *chain_info =
2455       get_device_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
2456 
2457    assert(chain_info->u.pLayerInfo);
2458    PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
2459    PFN_vkGetDeviceProcAddr fpGetDeviceProcAddr = chain_info->u.pLayerInfo->pfnNextGetDeviceProcAddr;
2460    PFN_vkCreateDevice fpCreateDevice = (PFN_vkCreateDevice)fpGetInstanceProcAddr(NULL, "vkCreateDevice");
2461    if (fpCreateDevice == NULL) {
2462       return VK_ERROR_INITIALIZATION_FAILED;
2463    }
2464 
2465    // Advance the link info for the next element on the chain
2466    chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
2467 
2468    VkPhysicalDeviceFeatures device_features = {};
2469    VkPhysicalDeviceFeatures *device_features_ptr = NULL;
2470 
2471    VkDeviceCreateInfo *device_info = (VkDeviceCreateInfo *)
2472       clone_chain((const struct VkBaseInStructure *)pCreateInfo);
2473 
2474    VkPhysicalDeviceFeatures2 *device_features2 = (VkPhysicalDeviceFeatures2 *)
2475       vk_find_struct(device_info, PHYSICAL_DEVICE_FEATURES_2);
2476    if (device_features2) {
2477       /* Can't use device_info->pEnabledFeatures when VkPhysicalDeviceFeatures2 is present */
2478       device_features_ptr = &device_features2->features;
2479    } else {
2480       if (device_info->pEnabledFeatures)
2481          device_features = *(device_info->pEnabledFeatures);
2482       device_features_ptr = &device_features;
2483       device_info->pEnabledFeatures = &device_features;
2484    }
2485 
2486    if (instance_data->pipeline_statistics_enabled) {
2487       device_features_ptr->inheritedQueries = true;
2488       device_features_ptr->pipelineStatisticsQuery = true;
2489    }
2490 
2491 
2492    VkResult result = fpCreateDevice(physicalDevice, device_info, pAllocator, pDevice);
2493    free_chain((struct VkBaseOutStructure *)device_info);
2494    if (result != VK_SUCCESS) return result;
2495 
2496    struct device_data *device_data = new_device_data(*pDevice, instance_data);
2497    device_data->physical_device = physicalDevice;
2498    vk_load_device_commands(*pDevice, fpGetDeviceProcAddr, &device_data->vtable);
2499 
2500    instance_data->vtable.GetPhysicalDeviceProperties(device_data->physical_device,
2501                                                      &device_data->properties);
2502 
2503    VkLayerDeviceCreateInfo *load_data_info =
2504       get_device_chain_info(pCreateInfo, VK_LOADER_DATA_CALLBACK);
2505    device_data->set_device_loader_data = load_data_info->u.pfnSetDeviceLoaderData;
2506 
2507    device_map_queues(device_data, pCreateInfo);
2508 
2509    return result;
2510 }
2511 
overlay_DestroyDevice(VkDevice device,const VkAllocationCallbacks * pAllocator)2512 static void overlay_DestroyDevice(
2513     VkDevice                                    device,
2514     const VkAllocationCallbacks*                pAllocator)
2515 {
2516    struct device_data *device_data = FIND(struct device_data, device);
2517    device_unmap_queues(device_data);
2518    device_data->vtable.DestroyDevice(device, pAllocator);
2519    destroy_device_data(device_data);
2520 }
2521 
overlay_CreateInstance(const VkInstanceCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkInstance * pInstance)2522 static VkResult overlay_CreateInstance(
2523     const VkInstanceCreateInfo*                 pCreateInfo,
2524     const VkAllocationCallbacks*                pAllocator,
2525     VkInstance*                                 pInstance)
2526 {
2527    VkLayerInstanceCreateInfo *chain_info =
2528       get_instance_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
2529 
2530    assert(chain_info->u.pLayerInfo);
2531    PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr =
2532       chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
2533    PFN_vkCreateInstance fpCreateInstance =
2534       (PFN_vkCreateInstance)fpGetInstanceProcAddr(NULL, "vkCreateInstance");
2535    if (fpCreateInstance == NULL) {
2536       return VK_ERROR_INITIALIZATION_FAILED;
2537    }
2538 
2539    // Advance the link info for the next element on the chain
2540    chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
2541 
2542    VkResult result = fpCreateInstance(pCreateInfo, pAllocator, pInstance);
2543    if (result != VK_SUCCESS) return result;
2544 
2545    struct instance_data *instance_data = new_instance_data(*pInstance);
2546    vk_load_instance_commands(instance_data->instance,
2547                              fpGetInstanceProcAddr,
2548                              &instance_data->vtable);
2549    instance_data_map_physical_devices(instance_data, true);
2550 
2551    parse_overlay_env(&instance_data->params, getenv("VK_LAYER_MESA_OVERLAY_CONFIG"));
2552 
2553    /* If there's no control file, and an output_file was specified, start
2554     * capturing fps data right away.
2555     */
2556    instance_data->capture_enabled =
2557       instance_data->params.output_file && instance_data->params.control < 0;
2558    instance_data->capture_started = instance_data->capture_enabled;
2559 
2560    for (int i = OVERLAY_PARAM_ENABLED_vertices;
2561         i <= OVERLAY_PARAM_ENABLED_compute_invocations; i++) {
2562       if (instance_data->params.enabled[i]) {
2563          instance_data->pipeline_statistics_enabled = true;
2564          break;
2565       }
2566    }
2567 
2568    return result;
2569 }
2570 
overlay_DestroyInstance(VkInstance instance,const VkAllocationCallbacks * pAllocator)2571 static void overlay_DestroyInstance(
2572     VkInstance                                  instance,
2573     const VkAllocationCallbacks*                pAllocator)
2574 {
2575    struct instance_data *instance_data = FIND(struct instance_data, instance);
2576    instance_data_map_physical_devices(instance_data, false);
2577    instance_data->vtable.DestroyInstance(instance, pAllocator);
2578    destroy_instance_data(instance_data);
2579 }
2580 
2581 static const struct {
2582    const char *name;
2583    void *ptr;
2584 } name_to_funcptr_map[] = {
2585    { "vkGetInstanceProcAddr", (void *) vkGetInstanceProcAddr },
2586    { "vkGetDeviceProcAddr", (void *) vkGetDeviceProcAddr },
2587 #define ADD_HOOK(fn) { "vk" # fn, (void *) overlay_ ## fn }
2588 #define ADD_ALIAS_HOOK(alias, fn) { "vk" # alias, (void *) overlay_ ## fn }
2589    ADD_HOOK(AllocateCommandBuffers),
2590    ADD_HOOK(FreeCommandBuffers),
2591    ADD_HOOK(ResetCommandBuffer),
2592    ADD_HOOK(BeginCommandBuffer),
2593    ADD_HOOK(EndCommandBuffer),
2594    ADD_HOOK(CmdExecuteCommands),
2595 
2596    ADD_HOOK(CmdDraw),
2597    ADD_HOOK(CmdDrawIndexed),
2598    ADD_HOOK(CmdDrawIndirect),
2599    ADD_HOOK(CmdDrawIndexedIndirect),
2600    ADD_HOOK(CmdDispatch),
2601    ADD_HOOK(CmdDispatchIndirect),
2602    ADD_HOOK(CmdDrawIndirectCount),
2603    ADD_ALIAS_HOOK(CmdDrawIndirectCountKHR, CmdDrawIndirectCount),
2604    ADD_HOOK(CmdDrawIndexedIndirectCount),
2605    ADD_ALIAS_HOOK(CmdDrawIndexedIndirectCountKHR, CmdDrawIndexedIndirectCount),
2606 
2607    ADD_HOOK(CmdBindPipeline),
2608 
2609    ADD_HOOK(CreateSwapchainKHR),
2610    ADD_HOOK(QueuePresentKHR),
2611    ADD_HOOK(DestroySwapchainKHR),
2612    ADD_HOOK(AcquireNextImageKHR),
2613    ADD_HOOK(AcquireNextImage2KHR),
2614 
2615    ADD_HOOK(QueueSubmit),
2616 
2617    ADD_HOOK(CreateDevice),
2618    ADD_HOOK(DestroyDevice),
2619 
2620    ADD_HOOK(CreateInstance),
2621    ADD_HOOK(DestroyInstance),
2622 #undef ADD_HOOK
2623 };
2624 
find_ptr(const char * name)2625 static void *find_ptr(const char *name)
2626 {
2627    for (uint32_t i = 0; i < ARRAY_SIZE(name_to_funcptr_map); i++) {
2628       if (strcmp(name, name_to_funcptr_map[i].name) == 0)
2629          return name_to_funcptr_map[i].ptr;
2630    }
2631 
2632    return NULL;
2633 }
2634 
vkGetDeviceProcAddr(VkDevice dev,const char * funcName)2635 VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice dev,
2636                                                                              const char *funcName)
2637 {
2638    void *ptr = find_ptr(funcName);
2639    if (ptr) return reinterpret_cast<PFN_vkVoidFunction>(ptr);
2640 
2641    if (dev == NULL) return NULL;
2642 
2643    struct device_data *device_data = FIND(struct device_data, dev);
2644    if (device_data->vtable.GetDeviceProcAddr == NULL) return NULL;
2645    return device_data->vtable.GetDeviceProcAddr(dev, funcName);
2646 }
2647 
vkGetInstanceProcAddr(VkInstance instance,const char * funcName)2648 VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance,
2649                                                                                const char *funcName)
2650 {
2651    void *ptr = find_ptr(funcName);
2652    if (ptr) return reinterpret_cast<PFN_vkVoidFunction>(ptr);
2653 
2654    if (instance == NULL) return NULL;
2655 
2656    struct instance_data *instance_data = FIND(struct instance_data, instance);
2657    if (instance_data->vtable.GetInstanceProcAddr == NULL) return NULL;
2658    return instance_data->vtable.GetInstanceProcAddr(instance, funcName);
2659 }
2660