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