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