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