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