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