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