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