vulkan/overlay: fix includes
[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_dispatch_table_helper.h>
30 #include <vulkan/vk_layer.h>
31 #include <vulkan/vk_layer_data.h>
32 #include <vulkan/vk_layer_extension_utils.h>
33 #include <vulkan/vk_loader_platform.h>
34 #include "vk_layer_table.h"
35
36 #include "imgui.h"
37
38 #include "util/debug.h"
39 #include "util/hash_table.h"
40 #include "util/ralloc.h"
41 #include "util/os_time.h"
42 #include "util/simple_mtx.h"
43
44 #include "vk_enum_to_str.h"
45
46 enum layer_position {
47 LAYER_POSITION_TOP_LEFT,
48 LAYER_POSITION_TOP_RIGHT,
49 LAYER_POSITION_BOTTOM_LEFT,
50 LAYER_POSITION_BOTTOM_RIGHT,
51 };
52
53 static enum layer_position
54 parse_layer_position(const char *str)
55 {
56 if (!str || !strcmp(str, "top-left"))
57 return LAYER_POSITION_TOP_LEFT;
58 if (!strcmp(str, "top-right"))
59 return LAYER_POSITION_TOP_RIGHT;
60 if (!strcmp(str, "bottom-left"))
61 return LAYER_POSITION_BOTTOM_LEFT;
62 if (!strcmp(str, "bottom-right"))
63 return LAYER_POSITION_BOTTOM_RIGHT;
64 return LAYER_POSITION_TOP_LEFT;
65 }
66
67 /* Mapped from VkInstace/VkPhysicalDevice */
68 struct instance_data {
69 VkLayerInstanceDispatchTable vtable;
70 VkInstance instance;
71
72 enum layer_position position;
73 uint64_t enabled_stats;
74 };
75
76 enum frame_stat_type {
77 FRAME_STAT_SUBMIT,
78 FRAME_STAT_DRAW,
79 FRAME_STAT_DRAW_INDEXED,
80 FRAME_STAT_DRAW_INDIRECT,
81 FRAME_STAT_DRAW_INDEXED_INDIRECT,
82 FRAME_STAT_DRAW_INDIRECT_COUNT,
83 FRAME_STAT_DRAW_INDEXED_INDIRECT_COUNT,
84 FRAME_STAT_DISPATCH,
85 FRAME_STAT_DISPATCH_INDIRECT,
86 FRAME_STAT_PIPELINE_GRAPHICS,
87 FRAME_STAT_PIPELINE_COMPUTE,
88 FRAME_STAT_PIPELINE_RAYTRACING,
89
90 FRAME_STAT_COUNT,
91
92 FRAME_STAT_ACQUIRE_TIMING = FRAME_STAT_COUNT,
93 FRAME_STAT_HELP,
94 };
95
96 #define FRAME_STAT_ENABLED(id) (1ULL << (FRAME_STAT_ ## id))
97
98 static struct debug_control enable_flags[] = {
99 { "submit", FRAME_STAT_ENABLED(SUBMIT) },
100 { "draw", FRAME_STAT_ENABLED(DRAW) },
101 { "draw-indexed", FRAME_STAT_ENABLED(DRAW_INDEXED) },
102 { "draw-indirect", FRAME_STAT_ENABLED(DRAW_INDIRECT) },
103 { "draw-indexed-indirect", FRAME_STAT_ENABLED(DRAW_INDEXED_INDIRECT) },
104 { "draw-indirect-count", FRAME_STAT_ENABLED(DRAW_INDIRECT_COUNT) },
105 { "draw-indexed-indirect-count", FRAME_STAT_ENABLED(DRAW_INDEXED_INDIRECT_COUNT) },
106 { "dispatch", FRAME_STAT_ENABLED(DISPATCH) },
107 { "dispatch-indirect", FRAME_STAT_ENABLED(DISPATCH_INDIRECT) },
108 { "pipeline-graphics", FRAME_STAT_ENABLED(PIPELINE_GRAPHICS) },
109 { "pipeline-compute", FRAME_STAT_ENABLED(PIPELINE_COMPUTE) },
110 { "pipeline-raytracing", FRAME_STAT_ENABLED(PIPELINE_RAYTRACING) },
111 { "acquire-timing", FRAME_STAT_ENABLED(ACQUIRE_TIMING) },
112 { "help", FRAME_STAT_ENABLED(HELP) },
113 { NULL, 0 },
114 };
115
116 struct frame_stat {
117 uint32_t stats[FRAME_STAT_COUNT];
118 };
119
120 /* Mapped from VkDevice/VkCommandBuffer */
121 struct queue_data;
122 struct device_data {
123 struct instance_data *instance;
124
125 VkLayerDispatchTable vtable;
126 VkPhysicalDevice physical_device;
127 VkDevice device;
128
129 VkPhysicalDeviceProperties properties;
130
131 struct queue_data *graphic_queue;
132
133 struct queue_data **queues;
134 uint32_t n_queues;
135
136 struct frame_stat stats;
137 };
138
139 /* Mapped from VkQueue */
140 struct queue_data {
141 struct device_data *device;
142
143 VkQueue queue;
144 VkQueueFlags flags;
145 uint32_t family_index;
146 };
147
148 /* Mapped from VkSwapchainKHR */
149 struct swapchain_data {
150 struct device_data *device;
151
152 VkSwapchainKHR swapchain;
153 unsigned width, height;
154 VkFormat format;
155
156 uint32_t n_images;
157 VkImage *images;
158 VkImageView *image_views;
159 VkFramebuffer *framebuffers;
160
161 VkRenderPass render_pass;
162
163 VkDescriptorPool descriptor_pool;
164 VkDescriptorSetLayout descriptor_layout;
165 VkDescriptorSet descriptor_set;
166
167 VkSampler font_sampler;
168
169 VkPipelineLayout pipeline_layout;
170 VkPipeline pipeline;
171
172 VkCommandPool command_pool;
173
174 struct {
175 VkCommandBuffer command_buffer;
176
177 VkBuffer vertex_buffer;
178 VkDeviceMemory vertex_buffer_mem;
179 VkDeviceSize vertex_buffer_size;
180
181 VkBuffer index_buffer;
182 VkDeviceMemory index_buffer_mem;
183 VkDeviceSize index_buffer_size;
184 } frame_data[2];
185
186 bool font_uploaded;
187 VkImage font_image;
188 VkImageView font_image_view;
189 VkDeviceMemory font_mem;
190 VkBuffer upload_font_buffer;
191 VkDeviceMemory upload_font_buffer_mem;
192
193 VkFence fence;
194 VkSemaphore submission_semaphore;
195
196 /**/
197 ImGuiContext* imgui_context;
198 ImVec2 window_size;
199
200 /**/
201 uint64_t n_frames;
202 uint64_t last_present_time;
203
204 unsigned n_frames_since_update;
205 uint64_t last_fps_update;
206 double fps;
207
208 double frame_times[200];
209
210 double acquire_times[200];
211 uint64_t n_acquire;
212
213 enum frame_stat_type stat_selector;
214 struct frame_stat stats_min, stats_max;
215 struct frame_stat stats[200];
216 };
217
218 static struct hash_table *vk_object_to_data = NULL;
219 static simple_mtx_t vk_object_to_data_mutex = _SIMPLE_MTX_INITIALIZER_NP;
220
221 thread_local ImGuiContext* __MesaImGui;
222
223 static inline void ensure_vk_object_map(void)
224 {
225 if (!vk_object_to_data) {
226 vk_object_to_data = _mesa_hash_table_create(NULL,
227 _mesa_hash_pointer,
228 _mesa_key_pointer_equal);
229 }
230 }
231
232 #define FIND_SWAPCHAIN_DATA(obj) ((struct swapchain_data *)find_object_data((void *) obj))
233 #define FIND_DEVICE_DATA(obj) ((struct device_data *)find_object_data((void *) obj))
234 #define FIND_QUEUE_DATA(obj) ((struct queue_data *)find_object_data((void *) obj))
235 #define FIND_PHYSICAL_DEVICE_DATA(obj) ((struct instance_data *)find_object_data((void *) obj))
236 #define FIND_INSTANCE_DATA(obj) ((struct instance_data *)find_object_data((void *) obj))
237 static void *find_object_data(void *obj)
238 {
239 simple_mtx_lock(&vk_object_to_data_mutex);
240 ensure_vk_object_map();
241 struct hash_entry *entry = _mesa_hash_table_search(vk_object_to_data, obj);
242 void *data = entry ? entry->data : NULL;
243 simple_mtx_unlock(&vk_object_to_data_mutex);
244 return data;
245 }
246
247 static void map_object(void *obj, void *data)
248 {
249 simple_mtx_lock(&vk_object_to_data_mutex);
250 ensure_vk_object_map();
251 _mesa_hash_table_insert(vk_object_to_data, obj, data);
252 simple_mtx_unlock(&vk_object_to_data_mutex);
253 }
254
255 static void unmap_object(void *obj)
256 {
257 simple_mtx_lock(&vk_object_to_data_mutex);
258 struct hash_entry *entry = _mesa_hash_table_search(vk_object_to_data, obj);
259 _mesa_hash_table_remove(vk_object_to_data, entry);
260 simple_mtx_unlock(&vk_object_to_data_mutex);
261 }
262
263 /**/
264 static struct instance_data *new_instance_data(VkInstance instance)
265 {
266 struct instance_data *data = rzalloc(NULL, struct instance_data);
267 data->instance = instance;
268 map_object(data->instance, data);
269 return data;
270 }
271
272 static void destroy_instance_data(struct instance_data *data)
273 {
274 unmap_object(data->instance);
275 ralloc_free(data);
276 }
277
278 static void instance_data_map_physical_devices(struct instance_data *instance_data,
279 bool map)
280 {
281 uint32_t physicalDeviceCount = 0;
282 instance_data->vtable.EnumeratePhysicalDevices(instance_data->instance,
283 &physicalDeviceCount,
284 NULL);
285
286 VkPhysicalDevice *physicalDevices = (VkPhysicalDevice *) malloc(sizeof(VkPhysicalDevice) * physicalDeviceCount);
287 instance_data->vtable.EnumeratePhysicalDevices(instance_data->instance,
288 &physicalDeviceCount,
289 physicalDevices);
290
291 for (uint32_t i = 0; i < physicalDeviceCount; i++) {
292 if (map)
293 map_object(physicalDevices[i], instance_data);
294 else
295 unmap_object(physicalDevices[i]);
296 }
297
298 free(physicalDevices);
299 }
300
301 /**/
302 static struct device_data *new_device_data(VkDevice device, struct instance_data *instance)
303 {
304 struct device_data *data = rzalloc(NULL, struct device_data);
305 data->instance = instance;
306 data->device = device;
307 map_object(data->device, data);
308 return data;
309 }
310
311 static struct queue_data *new_queue_data(VkQueue queue,
312 const VkQueueFamilyProperties *family_props,
313 uint32_t family_index,
314 struct device_data *device_data)
315 {
316 struct queue_data *data = rzalloc(device_data, struct queue_data);
317 data->device = device_data;
318 data->queue = queue;
319 data->flags = family_props->queueFlags;
320 data->family_index = family_index;
321 map_object(data->queue, data);
322
323 if (data->flags & VK_QUEUE_GRAPHICS_BIT)
324 device_data->graphic_queue = data;
325
326 return data;
327 }
328
329 static void device_map_queues(struct device_data *data,
330 const VkDeviceCreateInfo *pCreateInfo)
331 {
332 for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++)
333 data->n_queues += pCreateInfo->pQueueCreateInfos[i].queueCount;
334 data->queues = ralloc_array(data, struct queue_data *, data->n_queues);
335
336 struct instance_data *instance_data = data->instance;
337 uint32_t n_family_props;
338 instance_data->vtable.GetPhysicalDeviceQueueFamilyProperties(data->physical_device,
339 &n_family_props,
340 NULL);
341 VkQueueFamilyProperties *family_props =
342 (VkQueueFamilyProperties *)malloc(sizeof(VkQueueFamilyProperties) * n_family_props);
343 instance_data->vtable.GetPhysicalDeviceQueueFamilyProperties(data->physical_device,
344 &n_family_props,
345 family_props);
346
347 uint32_t queue_index = 0;
348 for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
349 for (uint32_t j = 0; j < pCreateInfo->pQueueCreateInfos[i].queueCount; j++) {
350 VkQueue queue;
351 data->vtable.GetDeviceQueue(data->device,
352 pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex,
353 j, &queue);
354 data->queues[queue_index++] =
355 new_queue_data(queue, &family_props[pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex],
356 pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex, data);
357 }
358 }
359
360 free(family_props);
361 }
362
363 static void device_unmap_queues(struct device_data *data)
364 {
365 for (uint32_t i = 0; i < data->n_queues; i++)
366 unmap_object(data->queues[i]->queue);
367 }
368
369 static void destroy_device_data(struct device_data *data)
370 {
371 unmap_object(data->device);
372 ralloc_free(data);
373 }
374
375 static void check_vk_result(VkResult err)
376 {
377 if (err != VK_SUCCESS)
378 printf("ERROR!\n");
379 }
380
381 /**/
382 static struct swapchain_data *new_swapchain_data(VkSwapchainKHR swapchain,
383 struct device_data *device_data)
384 {
385 struct swapchain_data *data = rzalloc(NULL, struct swapchain_data);
386 data->device = device_data;
387 data->swapchain = swapchain;
388 data->window_size = ImVec2(300, 300);
389 map_object((void *) data->swapchain, data);
390 return data;
391 }
392
393 static void destroy_swapchain_data(struct swapchain_data *data)
394 {
395 unmap_object((void *) data->swapchain);
396 ralloc_free(data);
397 }
398
399 static void snapshot_swapchain_frame(struct swapchain_data *data)
400 {
401 uint64_t now = os_time_get();
402
403 if (data->last_present_time) {
404 data->frame_times[(data->n_frames - 1) % ARRAY_SIZE(data->frame_times)] =
405 ((double)now - (double)data->last_present_time) / 1000.0;
406 }
407
408 if (data->last_fps_update) {
409 double elapsed = (double)(now - data->last_fps_update);
410 if (elapsed >= 500000.0) {
411 data->fps = ((uint64_t)data->n_frames_since_update * 1000000 / elapsed);
412 data->n_frames_since_update = 0;
413 data->last_fps_update = now;
414 }
415 } else {
416 data->last_fps_update = now;
417 }
418
419 struct device_data *device_data = data->device;
420 data->stats[data->n_frames % ARRAY_SIZE(data->frame_times)] = device_data->stats;
421 memset(&device_data->stats, 0, sizeof(device_data->stats));
422
423 data->last_present_time = now;
424 data->n_frames++;
425 data->n_frames_since_update++;
426 }
427
428 static float get_frame_timing(void *_data, int _idx)
429 {
430 struct swapchain_data *data = (struct swapchain_data *) _data;
431 if ((ARRAY_SIZE(data->frame_times) - _idx) > (data->n_frames - 2))
432 return 0.0f;
433 int idx = ARRAY_SIZE(data->frame_times) +
434 (data->n_frames - 2) < ARRAY_SIZE(data->frame_times) ?
435 _idx - (data->n_frames - 2) :
436 _idx + (data->n_frames - 2);
437 idx %= ARRAY_SIZE(data->frame_times);
438 return data->frame_times[idx];
439 }
440
441 static float get_acquire_timing(void *_data, int _idx)
442 {
443 struct swapchain_data *data = (struct swapchain_data *) _data;
444 if ((ARRAY_SIZE(data->acquire_times) - _idx) > data->n_acquire)
445 return 0.0f;
446 int idx = ARRAY_SIZE(data->acquire_times) +
447 data->n_acquire < ARRAY_SIZE(data->acquire_times) ?
448 _idx - data->n_acquire :
449 _idx + data->n_acquire;
450 idx %= ARRAY_SIZE(data->acquire_times);
451 return data->acquire_times[idx];
452 }
453
454 static float get_stat(void *_data, int _idx)
455 {
456 struct swapchain_data *data = (struct swapchain_data *) _data;
457 if ((ARRAY_SIZE(data->stats) - _idx) > data->n_frames)
458 return 0.0f;
459 int idx = ARRAY_SIZE(data->stats) +
460 data->n_frames < ARRAY_SIZE(data->stats) ?
461 _idx - data->n_frames :
462 _idx + data->n_frames;
463 idx %= ARRAY_SIZE(data->stats);
464 return data->stats[idx].stats[data->stat_selector];
465 }
466
467 static void position_layer(struct swapchain_data *data)
468
469 {
470 struct device_data *device_data = data->device;
471 struct instance_data *instance_data = device_data->instance;
472
473 ImGui::SetNextWindowBgAlpha(0.5);
474 ImGui::SetNextWindowSize(data->window_size, ImGuiCond_Always);
475 switch (instance_data->position) {
476 case LAYER_POSITION_TOP_LEFT:
477 ImGui::SetNextWindowPos(ImVec2(0, 0), ImGuiCond_Always);
478 break;
479 case LAYER_POSITION_TOP_RIGHT:
480 ImGui::SetNextWindowPos(ImVec2(data->width - data->window_size.x, 0),
481 ImGuiCond_Always);
482 break;
483 case LAYER_POSITION_BOTTOM_LEFT:
484 ImGui::SetNextWindowPos(ImVec2(0, data->height - data->window_size.y),
485 ImGuiCond_Always);
486 break;
487 case LAYER_POSITION_BOTTOM_RIGHT:
488 ImGui::SetNextWindowPos(ImVec2(data->width - data->window_size.x,
489 data->height - data->window_size.y),
490 ImGuiCond_Always);
491 break;
492 }
493 }
494
495 static void compute_swapchain_display(struct swapchain_data *data)
496 {
497 struct device_data *device_data = data->device;
498 struct instance_data *instance_data = device_data->instance;
499
500 ImGui::SetCurrentContext(data->imgui_context);
501 ImGui::NewFrame();
502 position_layer(data);
503 ImGui::Begin("Mesa overlay");
504 ImGui::Text("Device: %s", device_data->properties.deviceName);
505
506 const char *format_name = vk_Format_to_str(data->format);
507 format_name = format_name ? (format_name + strlen("VK_FORMAT_")) : "unknown";
508 ImGui::Text("Swapchain format: %s", format_name);
509 ImGui::Text("Frames: %" PRIu64, data->n_frames);
510 ImGui::Text("FPS: %.2f" , data->fps);
511
512 {
513 double min_time = FLT_MAX, max_time = 0.0f;
514 for (uint32_t i = 0; i < MIN2(data->n_frames - 2, ARRAY_SIZE(data->frame_times)); i++) {
515 min_time = MIN2(min_time, data->frame_times[i]);
516 max_time = MAX2(max_time, data->frame_times[i]);
517 }
518 ImGui::PlotHistogram("##Frame timings", get_frame_timing, data,
519 ARRAY_SIZE(data->frame_times), 0,
520 NULL, min_time, max_time,
521 ImVec2(ImGui::GetContentRegionAvailWidth(), 30));
522 ImGui::Text("Frame timing: %.3fms [%.3f, %.3f]",
523 get_frame_timing(data, ARRAY_SIZE(data->frame_times) - 1),
524 min_time, max_time);
525 }
526
527 if (instance_data->enabled_stats & FRAME_STAT_ENABLED(ACQUIRE_TIMING)) {
528 double min_time = FLT_MAX, max_time = 0.0f;
529 for (uint32_t i = 0; i < MIN2(data->n_acquire - 2, ARRAY_SIZE(data->acquire_times)); i++) {
530 min_time = MIN2(min_time, data->acquire_times[i]);
531 max_time = MAX2(max_time, data->acquire_times[i]);
532 }
533 ImGui::PlotHistogram("##Acquire timings", get_acquire_timing, data,
534 ARRAY_SIZE(data->acquire_times), 0,
535 NULL, min_time, max_time,
536 ImVec2(ImGui::GetContentRegionAvailWidth(), 30));
537 ImGui::Text("Acquire timing: %.3fms [%.3f, %.3f]",
538 get_acquire_timing(data, ARRAY_SIZE(data->acquire_times) - 1),
539 min_time, max_time);
540
541 for (uint32_t i = 0; i < ARRAY_SIZE(data->stats_min.stats); i++) {
542 data->stats_min.stats[i] = UINT32_MAX;
543 data->stats_max.stats[i] = 0;
544 }
545 for (uint32_t i = 0; i < MIN2(data->n_frames - 1, ARRAY_SIZE(data->stats)); i++) {
546 for (uint32_t j = 0; j < ARRAY_SIZE(data->stats[0].stats); j++) {
547 data->stats_min.stats[j] = MIN2(data->stats[i].stats[j],
548 data->stats_min.stats[j]);
549 data->stats_max.stats[j] = MAX2(data->stats[i].stats[j],
550 data->stats_max.stats[j]);
551 }
552 }
553 }
554
555 for (uint32_t i = 0; i < ARRAY_SIZE(device_data->stats.stats); i++) {
556 if (!(instance_data->enabled_stats & (1ULL << i)))
557 continue;
558
559 char hash[40];
560 snprintf(hash, sizeof(hash), "##%s", enable_flags[i].string);
561 data->stat_selector = (enum frame_stat_type) i;
562
563 ImGui::PlotHistogram(hash, get_stat, data,
564 ARRAY_SIZE(data->stats), 0,
565 NULL,
566 data->stats_min.stats[i],
567 data->stats_max.stats[i],
568 ImVec2(ImGui::GetContentRegionAvailWidth(), 30));
569 ImGui::Text("%s: %.0f [%u, %u]", enable_flags[i].string,
570 get_stat(data, ARRAY_SIZE(data->stats) - 1),
571 data->stats_min.stats[i], data->stats_max.stats[i]);
572 }
573 data->window_size = ImVec2(data->window_size.x, ImGui::GetCursorPosY() + 10.0f);
574 ImGui::End();
575 ImGui::EndFrame();
576 ImGui::Render();
577 }
578
579 static uint32_t vk_memory_type(struct device_data *data,
580 VkMemoryPropertyFlags properties,
581 uint32_t type_bits)
582 {
583 VkPhysicalDeviceMemoryProperties prop;
584 data->instance->vtable.GetPhysicalDeviceMemoryProperties(data->physical_device, &prop);
585 for (uint32_t i = 0; i < prop.memoryTypeCount; i++)
586 if ((prop.memoryTypes[i].propertyFlags & properties) == properties && type_bits & (1<<i))
587 return i;
588 return 0xFFFFFFFF; // Unable to find memoryType
589 }
590
591 static void ensure_swapchain_fonts(struct swapchain_data *data,
592 VkCommandBuffer command_buffer)
593 {
594 if (data->font_uploaded)
595 return;
596
597 data->font_uploaded = true;
598
599 struct device_data *device_data = data->device;
600 VkResult err;
601 ImGuiIO& io = ImGui::GetIO();
602 unsigned char* pixels;
603 int width, height;
604 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
605 size_t upload_size = width * height * 4 * sizeof(char);
606
607 /* Upload buffer */
608 VkBufferCreateInfo buffer_info = {};
609 buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
610 buffer_info.size = upload_size;
611 buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
612 buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
613 err = device_data->vtable.CreateBuffer(device_data->device, &buffer_info,
614 NULL, &data->upload_font_buffer);
615 check_vk_result(err);
616 VkMemoryRequirements upload_buffer_req;
617 device_data->vtable.GetBufferMemoryRequirements(device_data->device,
618 data->upload_font_buffer,
619 &upload_buffer_req);
620 VkMemoryAllocateInfo upload_alloc_info = {};
621 upload_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
622 upload_alloc_info.allocationSize = upload_buffer_req.size;
623 upload_alloc_info.memoryTypeIndex = vk_memory_type(device_data,
624 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
625 upload_buffer_req.memoryTypeBits);
626 err = device_data->vtable.AllocateMemory(device_data->device,
627 &upload_alloc_info,
628 NULL,
629 &data->upload_font_buffer_mem);
630 check_vk_result(err);
631 err = device_data->vtable.BindBufferMemory(device_data->device,
632 data->upload_font_buffer,
633 data->upload_font_buffer_mem, 0);
634 check_vk_result(err);
635
636 /* Upload to Buffer */
637 char* map = NULL;
638 err = device_data->vtable.MapMemory(device_data->device,
639 data->upload_font_buffer_mem,
640 0, upload_size, 0, (void**)(&map));
641 check_vk_result(err);
642 memcpy(map, pixels, upload_size);
643 VkMappedMemoryRange range[1] = {};
644 range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
645 range[0].memory = data->upload_font_buffer_mem;
646 range[0].size = upload_size;
647 err = device_data->vtable.FlushMappedMemoryRanges(device_data->device, 1, range);
648 check_vk_result(err);
649 device_data->vtable.UnmapMemory(device_data->device,
650 data->upload_font_buffer_mem);
651
652 /* Copy buffer to image */
653 VkImageMemoryBarrier copy_barrier[1] = {};
654 copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
655 copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
656 copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
657 copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
658 copy_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
659 copy_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
660 copy_barrier[0].image = data->font_image;
661 copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
662 copy_barrier[0].subresourceRange.levelCount = 1;
663 copy_barrier[0].subresourceRange.layerCount = 1;
664 device_data->vtable.CmdPipelineBarrier(command_buffer,
665 VK_PIPELINE_STAGE_HOST_BIT,
666 VK_PIPELINE_STAGE_TRANSFER_BIT,
667 0, 0, NULL, 0, NULL,
668 1, copy_barrier);
669
670 VkBufferImageCopy region = {};
671 region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
672 region.imageSubresource.layerCount = 1;
673 region.imageExtent.width = width;
674 region.imageExtent.height = height;
675 region.imageExtent.depth = 1;
676 device_data->vtable.CmdCopyBufferToImage(command_buffer,
677 data->upload_font_buffer,
678 data->font_image,
679 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
680 1, &region);
681
682 VkImageMemoryBarrier use_barrier[1] = {};
683 use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
684 use_barrier[0].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
685 use_barrier[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
686 use_barrier[0].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
687 use_barrier[0].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
688 use_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
689 use_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
690 use_barrier[0].image = data->font_image;
691 use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
692 use_barrier[0].subresourceRange.levelCount = 1;
693 use_barrier[0].subresourceRange.layerCount = 1;
694 device_data->vtable.CmdPipelineBarrier(command_buffer,
695 VK_PIPELINE_STAGE_TRANSFER_BIT,
696 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
697 0,
698 0, NULL,
699 0, NULL,
700 1, use_barrier);
701
702 /* Store our identifier */
703 io.Fonts->TexID = (ImTextureID)(intptr_t)data->font_image;
704 }
705
706 static void CreateOrResizeBuffer(struct device_data *data,
707 VkBuffer *buffer,
708 VkDeviceMemory *buffer_memory,
709 VkDeviceSize *buffer_size,
710 size_t new_size, VkBufferUsageFlagBits usage)
711 {
712 VkResult err;
713 if (*buffer != VK_NULL_HANDLE)
714 data->vtable.DestroyBuffer(data->device, *buffer, NULL);
715 if (*buffer_memory)
716 data->vtable.FreeMemory(data->device, *buffer_memory, NULL);
717
718 VkBufferCreateInfo buffer_info = {};
719 buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
720 buffer_info.size = new_size;
721 buffer_info.usage = usage;
722 buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
723 err = data->vtable.CreateBuffer(data->device, &buffer_info, NULL, buffer);
724 check_vk_result(err);
725
726 VkMemoryRequirements req;
727 data->vtable.GetBufferMemoryRequirements(data->device, *buffer, &req);
728 VkMemoryAllocateInfo alloc_info = {};
729 alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
730 alloc_info.allocationSize = req.size;
731 alloc_info.memoryTypeIndex =
732 vk_memory_type(data, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits);
733 err = data->vtable.AllocateMemory(data->device, &alloc_info, NULL, buffer_memory);
734 check_vk_result(err);
735
736 err = data->vtable.BindBufferMemory(data->device, *buffer, *buffer_memory, 0);
737 check_vk_result(err);
738 *buffer_size = new_size;
739 }
740
741 static void render_swapchain_display(struct swapchain_data *data, unsigned image_index)
742 {
743 ImDrawData* draw_data = ImGui::GetDrawData();
744 if (draw_data->TotalVtxCount == 0)
745 return;
746
747 struct device_data *device_data = data->device;
748 uint32_t idx = data->n_frames % ARRAY_SIZE(data->frame_data);
749 VkCommandBuffer command_buffer = data->frame_data[idx].command_buffer;
750 VkResult err;
751
752 device_data->vtable.ResetCommandBuffer(command_buffer, 0);
753
754 VkRenderPassBeginInfo render_pass_info = {};
755 render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
756 render_pass_info.renderPass = data->render_pass;
757 render_pass_info.framebuffer = data->framebuffers[image_index];
758 render_pass_info.renderArea.extent.width = data->width;
759 render_pass_info.renderArea.extent.height = data->height;
760
761 VkCommandBufferBeginInfo buffer_begin_info = {};
762 buffer_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
763
764 device_data->vtable.BeginCommandBuffer(command_buffer, &buffer_begin_info);
765
766 ensure_swapchain_fonts(data, command_buffer);
767
768 /* Bounce the image to display back to color attachment layout for
769 * rendering on top of it.
770 */
771 VkImageMemoryBarrier imb;
772 imb.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
773 imb.pNext = nullptr;
774 imb.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
775 imb.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
776 imb.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
777 imb.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
778 imb.image = data->images[image_index];
779 imb.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
780 imb.subresourceRange.baseMipLevel = 0;
781 imb.subresourceRange.levelCount = 1;
782 imb.subresourceRange.baseArrayLayer = 0;
783 imb.subresourceRange.layerCount = 1;
784 imb.srcQueueFamilyIndex = device_data->graphic_queue->family_index;
785 imb.dstQueueFamilyIndex = device_data->graphic_queue->family_index;
786 device_data->vtable.CmdPipelineBarrier(command_buffer,
787 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
788 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
789 0, /* dependency flags */
790 0, nullptr, /* memory barriers */
791 0, nullptr, /* buffer memory barriers */
792 1, &imb); /* image memory barriers */
793
794 device_data->vtable.CmdBeginRenderPass(command_buffer, &render_pass_info,
795 VK_SUBPASS_CONTENTS_INLINE);
796
797 /* Create/Resize vertex & index buffers */
798 size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert);
799 size_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx);
800 if (data->frame_data[idx].vertex_buffer_size < vertex_size) {
801 CreateOrResizeBuffer(device_data,
802 &data->frame_data[idx].vertex_buffer,
803 &data->frame_data[idx].vertex_buffer_mem,
804 &data->frame_data[idx].vertex_buffer_size,
805 vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
806 }
807 if (data->frame_data[idx].index_buffer_size < index_size) {
808 CreateOrResizeBuffer(device_data,
809 &data->frame_data[idx].index_buffer,
810 &data->frame_data[idx].index_buffer_mem,
811 &data->frame_data[idx].index_buffer_size,
812 index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
813 }
814
815 /* Upload vertex & index data */
816 VkBuffer vertex_buffer = data->frame_data[idx].vertex_buffer;
817 VkDeviceMemory vertex_mem = data->frame_data[idx].vertex_buffer_mem;
818 VkBuffer index_buffer = data->frame_data[idx].index_buffer;
819 VkDeviceMemory index_mem = data->frame_data[idx].index_buffer_mem;
820 ImDrawVert* vtx_dst = NULL;
821 ImDrawIdx* idx_dst = NULL;
822 err = device_data->vtable.MapMemory(device_data->device, vertex_mem,
823 0, vertex_size, 0, (void**)(&vtx_dst));
824 check_vk_result(err);
825 err = device_data->vtable.MapMemory(device_data->device, index_mem,
826 0, index_size, 0, (void**)(&idx_dst));
827 check_vk_result(err);
828 for (int n = 0; n < draw_data->CmdListsCount; n++)
829 {
830 const ImDrawList* cmd_list = draw_data->CmdLists[n];
831 memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
832 memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
833 vtx_dst += cmd_list->VtxBuffer.Size;
834 idx_dst += cmd_list->IdxBuffer.Size;
835 }
836 VkMappedMemoryRange range[2] = {};
837 range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
838 range[0].memory = vertex_mem;
839 range[0].size = VK_WHOLE_SIZE;
840 range[1].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
841 range[1].memory = index_mem;
842 range[1].size = VK_WHOLE_SIZE;
843 err = device_data->vtable.FlushMappedMemoryRanges(device_data->device, 2, range);
844 check_vk_result(err);
845 device_data->vtable.UnmapMemory(device_data->device, vertex_mem);
846 device_data->vtable.UnmapMemory(device_data->device, index_mem);
847
848 /* Bind pipeline and descriptor sets */
849 device_data->vtable.CmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, data->pipeline);
850 VkDescriptorSet desc_set[1] = { data->descriptor_set };
851 device_data->vtable.CmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
852 data->pipeline_layout, 0, 1, desc_set, 0, NULL);
853
854 /* Bind vertex & index buffers */
855 VkBuffer vertex_buffers[1] = { vertex_buffer };
856 VkDeviceSize vertex_offset[1] = { 0 };
857 device_data->vtable.CmdBindVertexBuffers(command_buffer, 0, 1, vertex_buffers, vertex_offset);
858 device_data->vtable.CmdBindIndexBuffer(command_buffer, index_buffer, 0, VK_INDEX_TYPE_UINT16);
859
860 /* Setup viewport */
861 VkViewport viewport;
862 viewport.x = 0;
863 viewport.y = 0;
864 viewport.width = draw_data->DisplaySize.x;
865 viewport.height = draw_data->DisplaySize.y;
866 viewport.minDepth = 0.0f;
867 viewport.maxDepth = 1.0f;
868 device_data->vtable.CmdSetViewport(command_buffer, 0, 1, &viewport);
869
870
871 /* Setup scale and translation through push constants :
872 *
873 * Our visible imgui space lies from draw_data->DisplayPos (top left) to
874 * draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin
875 * is typically (0,0) for single viewport apps.
876 */
877 float scale[2];
878 scale[0] = 2.0f / draw_data->DisplaySize.x;
879 scale[1] = 2.0f / draw_data->DisplaySize.y;
880 float translate[2];
881 translate[0] = -1.0f - draw_data->DisplayPos.x * scale[0];
882 translate[1] = -1.0f - draw_data->DisplayPos.y * scale[1];
883 device_data->vtable.CmdPushConstants(command_buffer, data->pipeline_layout,
884 VK_SHADER_STAGE_VERTEX_BIT,
885 sizeof(float) * 0, sizeof(float) * 2, scale);
886 device_data->vtable.CmdPushConstants(command_buffer, data->pipeline_layout,
887 VK_SHADER_STAGE_VERTEX_BIT,
888 sizeof(float) * 2, sizeof(float) * 2, translate);
889
890 // Render the command lists:
891 int vtx_offset = 0;
892 int idx_offset = 0;
893 ImVec2 display_pos = draw_data->DisplayPos;
894 for (int n = 0; n < draw_data->CmdListsCount; n++)
895 {
896 const ImDrawList* cmd_list = draw_data->CmdLists[n];
897 for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
898 {
899 const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
900 // Apply scissor/clipping rectangle
901 // FIXME: We could clamp width/height based on clamped min/max values.
902 VkRect2D scissor;
903 scissor.offset.x = (int32_t)(pcmd->ClipRect.x - display_pos.x) > 0 ? (int32_t)(pcmd->ClipRect.x - display_pos.x) : 0;
904 scissor.offset.y = (int32_t)(pcmd->ClipRect.y - display_pos.y) > 0 ? (int32_t)(pcmd->ClipRect.y - display_pos.y) : 0;
905 scissor.extent.width = (uint32_t)(pcmd->ClipRect.z - pcmd->ClipRect.x);
906 scissor.extent.height = (uint32_t)(pcmd->ClipRect.w - pcmd->ClipRect.y + 1); // FIXME: Why +1 here?
907 device_data->vtable.CmdSetScissor(command_buffer, 0, 1, &scissor);
908
909 // Draw
910 device_data->vtable.CmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, idx_offset, vtx_offset, 0);
911
912 idx_offset += pcmd->ElemCount;
913 }
914 vtx_offset += cmd_list->VtxBuffer.Size;
915 }
916
917 device_data->vtable.CmdEndRenderPass(command_buffer);
918 device_data->vtable.EndCommandBuffer(command_buffer);
919
920 if (data->submission_semaphore) {
921 device_data->vtable.DestroySemaphore(device_data->device,
922 data->submission_semaphore,
923 NULL);
924 }
925 /* Submission semaphore */
926 VkSemaphoreCreateInfo semaphore_info = {};
927 semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
928 err = device_data->vtable.CreateSemaphore(device_data->device, &semaphore_info,
929 NULL, &data->submission_semaphore);
930 check_vk_result(err);
931
932 VkSubmitInfo submit_info = {};
933 submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
934 submit_info.commandBufferCount = 1;
935 submit_info.pCommandBuffers = &command_buffer;
936 submit_info.signalSemaphoreCount = 1;
937 submit_info.pSignalSemaphores = &data->submission_semaphore;
938
939 device_data->vtable.WaitForFences(device_data->device, 1, &data->fence, VK_TRUE, UINT64_MAX);
940 device_data->vtable.ResetFences(device_data->device, 1, &data->fence);
941 device_data->vtable.QueueSubmit(device_data->graphic_queue->queue, 1, &submit_info, data->fence);
942 }
943
944 static const uint32_t overlay_vert_spv[] = {
945 #include "overlay.vert.spv.h"
946 };
947 static const uint32_t overlay_frag_spv[] = {
948 #include "overlay.frag.spv.h"
949 };
950
951 static void setup_swapchain_data_pipeline(struct swapchain_data *data)
952 {
953 struct device_data *device_data = data->device;
954 VkShaderModule vert_module, frag_module;
955 VkResult err;
956
957 /* Create shader modules */
958 VkShaderModuleCreateInfo vert_info = {};
959 vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
960 vert_info.codeSize = sizeof(overlay_vert_spv);
961 vert_info.pCode = overlay_vert_spv;
962 err = device_data->vtable.CreateShaderModule(device_data->device,
963 &vert_info, NULL, &vert_module);
964 check_vk_result(err);
965 VkShaderModuleCreateInfo frag_info = {};
966 frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
967 frag_info.codeSize = sizeof(overlay_frag_spv);
968 frag_info.pCode = (uint32_t*)overlay_frag_spv;
969 err = device_data->vtable.CreateShaderModule(device_data->device,
970 &frag_info, NULL, &frag_module);
971 check_vk_result(err);
972
973 /* Font sampler */
974 VkSamplerCreateInfo sampler_info = {};
975 sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
976 sampler_info.magFilter = VK_FILTER_LINEAR;
977 sampler_info.minFilter = VK_FILTER_LINEAR;
978 sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
979 sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
980 sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
981 sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
982 sampler_info.minLod = -1000;
983 sampler_info.maxLod = 1000;
984 sampler_info.maxAnisotropy = 1.0f;
985 err = device_data->vtable.CreateSampler(device_data->device, &sampler_info,
986 NULL, &data->font_sampler);
987 check_vk_result(err);
988
989 /* Descriptor pool */
990 VkDescriptorPoolSize sampler_pool_size = {};
991 sampler_pool_size.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
992 sampler_pool_size.descriptorCount = 1;
993 VkDescriptorPoolCreateInfo desc_pool_info = {};
994 desc_pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
995 desc_pool_info.maxSets = 1;
996 desc_pool_info.poolSizeCount = 1;
997 desc_pool_info.pPoolSizes = &sampler_pool_size;
998 err = device_data->vtable.CreateDescriptorPool(device_data->device,
999 &desc_pool_info,
1000 NULL, &data->descriptor_pool);
1001 check_vk_result(err);
1002
1003 /* Descriptor layout */
1004 VkSampler sampler[1] = { data->font_sampler };
1005 VkDescriptorSetLayoutBinding binding[1] = {};
1006 binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1007 binding[0].descriptorCount = 1;
1008 binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
1009 binding[0].pImmutableSamplers = sampler;
1010 VkDescriptorSetLayoutCreateInfo set_layout_info = {};
1011 set_layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
1012 set_layout_info.bindingCount = 1;
1013 set_layout_info.pBindings = binding;
1014 err = device_data->vtable.CreateDescriptorSetLayout(device_data->device,
1015 &set_layout_info,
1016 NULL, &data->descriptor_layout);
1017 check_vk_result(err);
1018
1019 /* Descriptor set */
1020 VkDescriptorSetAllocateInfo alloc_info = {};
1021 alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
1022 alloc_info.descriptorPool = data->descriptor_pool;
1023 alloc_info.descriptorSetCount = 1;
1024 alloc_info.pSetLayouts = &data->descriptor_layout;
1025 err = device_data->vtable.AllocateDescriptorSets(device_data->device,
1026 &alloc_info,
1027 &data->descriptor_set);
1028 check_vk_result(err);
1029
1030 /* Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full
1031 * 3d projection matrix
1032 */
1033 VkPushConstantRange push_constants[1] = {};
1034 push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
1035 push_constants[0].offset = sizeof(float) * 0;
1036 push_constants[0].size = sizeof(float) * 4;
1037 VkPipelineLayoutCreateInfo layout_info = {};
1038 layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
1039 layout_info.setLayoutCount = 1;
1040 layout_info.pSetLayouts = &data->descriptor_layout;
1041 layout_info.pushConstantRangeCount = 1;
1042 layout_info.pPushConstantRanges = push_constants;
1043 err = device_data->vtable.CreatePipelineLayout(device_data->device,
1044 &layout_info,
1045 NULL, &data->pipeline_layout);
1046 check_vk_result(err);
1047
1048
1049 VkPipelineShaderStageCreateInfo stage[2] = {};
1050 stage[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
1051 stage[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
1052 stage[0].module = vert_module;
1053 stage[0].pName = "main";
1054 stage[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
1055 stage[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
1056 stage[1].module = frag_module;
1057 stage[1].pName = "main";
1058
1059 VkVertexInputBindingDescription binding_desc[1] = {};
1060 binding_desc[0].stride = sizeof(ImDrawVert);
1061 binding_desc[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
1062
1063 VkVertexInputAttributeDescription attribute_desc[3] = {};
1064 attribute_desc[0].location = 0;
1065 attribute_desc[0].binding = binding_desc[0].binding;
1066 attribute_desc[0].format = VK_FORMAT_R32G32_SFLOAT;
1067 attribute_desc[0].offset = IM_OFFSETOF(ImDrawVert, pos);
1068 attribute_desc[1].location = 1;
1069 attribute_desc[1].binding = binding_desc[0].binding;
1070 attribute_desc[1].format = VK_FORMAT_R32G32_SFLOAT;
1071 attribute_desc[1].offset = IM_OFFSETOF(ImDrawVert, uv);
1072 attribute_desc[2].location = 2;
1073 attribute_desc[2].binding = binding_desc[0].binding;
1074 attribute_desc[2].format = VK_FORMAT_R8G8B8A8_UNORM;
1075 attribute_desc[2].offset = IM_OFFSETOF(ImDrawVert, col);
1076
1077 VkPipelineVertexInputStateCreateInfo vertex_info = {};
1078 vertex_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
1079 vertex_info.vertexBindingDescriptionCount = 1;
1080 vertex_info.pVertexBindingDescriptions = binding_desc;
1081 vertex_info.vertexAttributeDescriptionCount = 3;
1082 vertex_info.pVertexAttributeDescriptions = attribute_desc;
1083
1084 VkPipelineInputAssemblyStateCreateInfo ia_info = {};
1085 ia_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
1086 ia_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
1087
1088 VkPipelineViewportStateCreateInfo viewport_info = {};
1089 viewport_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
1090 viewport_info.viewportCount = 1;
1091 viewport_info.scissorCount = 1;
1092
1093 VkPipelineRasterizationStateCreateInfo raster_info = {};
1094 raster_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
1095 raster_info.polygonMode = VK_POLYGON_MODE_FILL;
1096 raster_info.cullMode = VK_CULL_MODE_NONE;
1097 raster_info.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
1098 raster_info.lineWidth = 1.0f;
1099
1100 VkPipelineMultisampleStateCreateInfo ms_info = {};
1101 ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
1102 ms_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
1103
1104 VkPipelineColorBlendAttachmentState color_attachment[1] = {};
1105 color_attachment[0].blendEnable = VK_TRUE;
1106 color_attachment[0].srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
1107 color_attachment[0].dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
1108 color_attachment[0].colorBlendOp = VK_BLEND_OP_ADD;
1109 color_attachment[0].srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
1110 color_attachment[0].dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
1111 color_attachment[0].alphaBlendOp = VK_BLEND_OP_ADD;
1112 color_attachment[0].colorWriteMask = VK_COLOR_COMPONENT_R_BIT |
1113 VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
1114
1115 VkPipelineDepthStencilStateCreateInfo depth_info = {};
1116 depth_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
1117
1118 VkPipelineColorBlendStateCreateInfo blend_info = {};
1119 blend_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
1120 blend_info.attachmentCount = 1;
1121 blend_info.pAttachments = color_attachment;
1122
1123 VkDynamicState dynamic_states[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
1124 VkPipelineDynamicStateCreateInfo dynamic_state = {};
1125 dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
1126 dynamic_state.dynamicStateCount = (uint32_t)IM_ARRAYSIZE(dynamic_states);
1127 dynamic_state.pDynamicStates = dynamic_states;
1128
1129 VkGraphicsPipelineCreateInfo info = {};
1130 info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
1131 info.flags = 0;
1132 info.stageCount = 2;
1133 info.pStages = stage;
1134 info.pVertexInputState = &vertex_info;
1135 info.pInputAssemblyState = &ia_info;
1136 info.pViewportState = &viewport_info;
1137 info.pRasterizationState = &raster_info;
1138 info.pMultisampleState = &ms_info;
1139 info.pDepthStencilState = &depth_info;
1140 info.pColorBlendState = &blend_info;
1141 info.pDynamicState = &dynamic_state;
1142 info.layout = data->pipeline_layout;
1143 info.renderPass = data->render_pass;
1144 err = device_data->vtable.CreateGraphicsPipelines(device_data->device, VK_NULL_HANDLE,
1145 1, &info,
1146 NULL, &data->pipeline);
1147 check_vk_result(err);
1148
1149 device_data->vtable.DestroyShaderModule(device_data->device, vert_module, NULL);
1150 device_data->vtable.DestroyShaderModule(device_data->device, frag_module, NULL);
1151
1152 ImGuiIO& io = ImGui::GetIO();
1153 unsigned char* pixels;
1154 int width, height;
1155 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
1156
1157 /* Font image */
1158 VkImageCreateInfo image_info = {};
1159 image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
1160 image_info.imageType = VK_IMAGE_TYPE_2D;
1161 image_info.format = VK_FORMAT_R8G8B8A8_UNORM;
1162 image_info.extent.width = width;
1163 image_info.extent.height = height;
1164 image_info.extent.depth = 1;
1165 image_info.mipLevels = 1;
1166 image_info.arrayLayers = 1;
1167 image_info.samples = VK_SAMPLE_COUNT_1_BIT;
1168 image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
1169 image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
1170 image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1171 image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1172 err = device_data->vtable.CreateImage(device_data->device, &image_info,
1173 NULL, &data->font_image);
1174 check_vk_result(err);
1175 VkMemoryRequirements font_image_req;
1176 device_data->vtable.GetImageMemoryRequirements(device_data->device,
1177 data->font_image, &font_image_req);
1178 VkMemoryAllocateInfo image_alloc_info = {};
1179 image_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1180 image_alloc_info.allocationSize = font_image_req.size;
1181 image_alloc_info.memoryTypeIndex = vk_memory_type(device_data,
1182 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1183 font_image_req.memoryTypeBits);
1184 err = device_data->vtable.AllocateMemory(device_data->device, &image_alloc_info,
1185 NULL, &data->font_mem);
1186 check_vk_result(err);
1187 err = device_data->vtable.BindImageMemory(device_data->device,
1188 data->font_image,
1189 data->font_mem, 0);
1190 check_vk_result(err);
1191
1192 /* Font image view */
1193 VkImageViewCreateInfo view_info = {};
1194 view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1195 view_info.image = data->font_image;
1196 view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
1197 view_info.format = VK_FORMAT_R8G8B8A8_UNORM;
1198 view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1199 view_info.subresourceRange.levelCount = 1;
1200 view_info.subresourceRange.layerCount = 1;
1201 err = device_data->vtable.CreateImageView(device_data->device, &view_info,
1202 NULL, &data->font_image_view);
1203 check_vk_result(err);
1204
1205 /* Descriptor set */
1206 VkDescriptorImageInfo desc_image[1] = {};
1207 desc_image[0].sampler = data->font_sampler;
1208 desc_image[0].imageView = data->font_image_view;
1209 desc_image[0].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1210 VkWriteDescriptorSet write_desc[1] = {};
1211 write_desc[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1212 write_desc[0].dstSet = data->descriptor_set;
1213 write_desc[0].descriptorCount = 1;
1214 write_desc[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1215 write_desc[0].pImageInfo = desc_image;
1216 device_data->vtable.UpdateDescriptorSets(device_data->device, 1, write_desc, 0, NULL);
1217 }
1218
1219 static void setup_swapchain_data(struct swapchain_data *data,
1220 const VkSwapchainCreateInfoKHR *pCreateInfo)
1221 {
1222 data->width = pCreateInfo->imageExtent.width;
1223 data->height = pCreateInfo->imageExtent.height;
1224 data->format = pCreateInfo->imageFormat;
1225
1226 data->imgui_context = ImGui::CreateContext();
1227 ImGui::SetCurrentContext(data->imgui_context);
1228
1229 ImGui::GetIO().IniFilename = NULL;
1230 ImGui::GetIO().DisplaySize = ImVec2((float)data->width, (float)data->height);
1231
1232 struct device_data *device_data = data->device;
1233 VkResult err;
1234
1235 /* Render pass */
1236 VkAttachmentDescription attachment_desc = {};
1237 attachment_desc.format = pCreateInfo->imageFormat;
1238 attachment_desc.samples = VK_SAMPLE_COUNT_1_BIT;
1239 attachment_desc.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
1240 attachment_desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
1241 attachment_desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
1242 attachment_desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
1243 attachment_desc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1244 attachment_desc.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
1245 VkAttachmentReference color_attachment = {};
1246 color_attachment.attachment = 0;
1247 color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1248 VkSubpassDescription subpass = {};
1249 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
1250 subpass.colorAttachmentCount = 1;
1251 subpass.pColorAttachments = &color_attachment;
1252 VkSubpassDependency dependency = {};
1253 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
1254 dependency.dstSubpass = 0;
1255 dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1256 dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1257 dependency.srcAccessMask = 0;
1258 dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
1259 VkRenderPassCreateInfo render_pass_info = {};
1260 render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
1261 render_pass_info.attachmentCount = 1;
1262 render_pass_info.pAttachments = &attachment_desc;
1263 render_pass_info.subpassCount = 1;
1264 render_pass_info.pSubpasses = &subpass;
1265 render_pass_info.dependencyCount = 1;
1266 render_pass_info.pDependencies = &dependency;
1267 err = device_data->vtable.CreateRenderPass(device_data->device,
1268 &render_pass_info,
1269 NULL, &data->render_pass);
1270 check_vk_result(err);
1271
1272 setup_swapchain_data_pipeline(data);
1273
1274 device_data->vtable.GetSwapchainImagesKHR(device_data->device,
1275 data->swapchain,
1276 &data->n_images,
1277 NULL);
1278 data->images = ralloc_array(data, VkImage, data->n_images);
1279 data->image_views = ralloc_array(data, VkImageView, data->n_images);
1280 data->framebuffers = ralloc_array(data, VkFramebuffer, data->n_images);
1281
1282 device_data->vtable.GetSwapchainImagesKHR(device_data->device,
1283 data->swapchain,
1284 &data->n_images,
1285 data->images);
1286
1287 /* Image views */
1288 VkImageViewCreateInfo view_info = {};
1289 view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1290 view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
1291 view_info.format = pCreateInfo->imageFormat;
1292 view_info.components.r = VK_COMPONENT_SWIZZLE_R;
1293 view_info.components.g = VK_COMPONENT_SWIZZLE_G;
1294 view_info.components.b = VK_COMPONENT_SWIZZLE_B;
1295 view_info.components.a = VK_COMPONENT_SWIZZLE_A;
1296 view_info.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
1297 for (uint32_t i = 0; i < data->n_images; i++) {
1298 view_info.image = data->images[i];
1299 err = device_data->vtable.CreateImageView(device_data->device, &view_info,
1300 NULL, &data->image_views[i]);
1301 check_vk_result(err);
1302 }
1303
1304 /* Framebuffers */
1305 VkImageView attachment[1];
1306 VkFramebufferCreateInfo fb_info = {};
1307 fb_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
1308 fb_info.renderPass = data->render_pass;
1309 fb_info.attachmentCount = 1;
1310 fb_info.pAttachments = attachment;
1311 fb_info.width = data->width;
1312 fb_info.height = data->height;
1313 fb_info.layers = 1;
1314 for (uint32_t i = 0; i < data->n_images; i++) {
1315 attachment[0] = data->image_views[i];
1316 err = device_data->vtable.CreateFramebuffer(device_data->device, &fb_info,
1317 NULL, &data->framebuffers[i]);
1318 check_vk_result(err);
1319 }
1320
1321 /* Command buffer */
1322 VkCommandPoolCreateInfo cmd_buffer_pool_info = {};
1323 cmd_buffer_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1324 cmd_buffer_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
1325 cmd_buffer_pool_info.queueFamilyIndex = device_data->graphic_queue->family_index;
1326 err = device_data->vtable.CreateCommandPool(device_data->device,
1327 &cmd_buffer_pool_info,
1328 NULL, &data->command_pool);
1329 check_vk_result(err);
1330
1331 VkCommandBuffer cmd_bufs[ARRAY_SIZE(data->frame_data)];
1332
1333 VkCommandBufferAllocateInfo cmd_buffer_info = {};
1334 cmd_buffer_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1335 cmd_buffer_info.commandPool = data->command_pool;
1336 cmd_buffer_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1337 cmd_buffer_info.commandBufferCount = 2;
1338 err = device_data->vtable.AllocateCommandBuffers(device_data->device,
1339 &cmd_buffer_info,
1340 cmd_bufs);
1341 check_vk_result(err);
1342
1343 for (uint32_t i = 0; i < ARRAY_SIZE(data->frame_data); i++)
1344 data->frame_data[i].command_buffer = cmd_bufs[i];
1345
1346
1347 /* Submission fence */
1348 VkFenceCreateInfo fence_info = {};
1349 fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1350 fence_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
1351 err = device_data->vtable.CreateFence(device_data->device, &fence_info,
1352 NULL, &data->fence);
1353 check_vk_result(err);
1354
1355 }
1356
1357 static void shutdown_swapchain_data(struct swapchain_data *data)
1358 {
1359 struct device_data *device_data = data->device;
1360
1361 for (uint32_t i = 0; i < data->n_images; i++) {
1362 device_data->vtable.DestroyImageView(device_data->device, data->image_views[i], NULL);
1363 device_data->vtable.DestroyFramebuffer(device_data->device, data->framebuffers[i], NULL);
1364 }
1365
1366 device_data->vtable.DestroyRenderPass(device_data->device, data->render_pass, NULL);
1367
1368 for (uint32_t i = 0; i < ARRAY_SIZE(data->frame_data); i++) {
1369 device_data->vtable.FreeCommandBuffers(device_data->device,
1370 data->command_pool,
1371 1, &data->frame_data[i].command_buffer);
1372 if (data->frame_data[i].vertex_buffer)
1373 device_data->vtable.DestroyBuffer(device_data->device, data->frame_data[i].vertex_buffer, NULL);
1374 if (data->frame_data[i].index_buffer)
1375 device_data->vtable.DestroyBuffer(device_data->device, data->frame_data[i].index_buffer, NULL);
1376 if (data->frame_data[i].vertex_buffer_mem)
1377 device_data->vtable.FreeMemory(device_data->device, data->frame_data[i].vertex_buffer_mem, NULL);
1378 if (data->frame_data[i].index_buffer_mem)
1379 device_data->vtable.FreeMemory(device_data->device, data->frame_data[i].index_buffer_mem, NULL);
1380 }
1381 device_data->vtable.DestroyCommandPool(device_data->device, data->command_pool, NULL);
1382
1383 device_data->vtable.DestroyFence(device_data->device, data->fence, NULL);
1384 if (data->submission_semaphore)
1385 device_data->vtable.DestroySemaphore(device_data->device, data->submission_semaphore, NULL);
1386
1387 device_data->vtable.DestroyPipeline(device_data->device, data->pipeline, NULL);
1388 device_data->vtable.DestroyPipelineLayout(device_data->device, data->pipeline_layout, NULL);
1389
1390 device_data->vtable.FreeDescriptorSets(device_data->device, data->descriptor_pool,
1391 1, &data->descriptor_set);
1392 device_data->vtable.DestroyDescriptorPool(device_data->device,
1393 data->descriptor_pool, NULL);
1394 device_data->vtable.DestroyDescriptorSetLayout(device_data->device,
1395 data->descriptor_layout, NULL);
1396
1397 device_data->vtable.DestroySampler(device_data->device, data->font_sampler, NULL);
1398 device_data->vtable.DestroyImageView(device_data->device, data->font_image_view, NULL);
1399 device_data->vtable.DestroyImage(device_data->device, data->font_image, NULL);
1400 device_data->vtable.FreeMemory(device_data->device, data->font_mem, NULL);
1401
1402 device_data->vtable.DestroyBuffer(device_data->device, data->upload_font_buffer, NULL);
1403 device_data->vtable.FreeMemory(device_data->device, data->upload_font_buffer_mem, NULL);
1404
1405 ImGui::DestroyContext(data->imgui_context);
1406 }
1407
1408 static void before_present(struct swapchain_data *swapchain_data,
1409 unsigned imageIndex)
1410 {
1411 snapshot_swapchain_frame(swapchain_data);
1412
1413 compute_swapchain_display(swapchain_data);
1414 render_swapchain_display(swapchain_data, imageIndex);
1415 }
1416
1417 VKAPI_ATTR VkResult VKAPI_CALL overlay_CreateSwapchainKHR(
1418 VkDevice device,
1419 const VkSwapchainCreateInfoKHR* pCreateInfo,
1420 const VkAllocationCallbacks* pAllocator,
1421 VkSwapchainKHR* pSwapchain)
1422 {
1423 struct device_data *device_data = FIND_DEVICE_DATA(device);
1424 VkResult result = device_data->vtable.CreateSwapchainKHR(device, pCreateInfo, pAllocator, pSwapchain);
1425 if (result != VK_SUCCESS) return result;
1426
1427 struct swapchain_data *swapchain_data = new_swapchain_data(*pSwapchain, device_data);
1428 setup_swapchain_data(swapchain_data, pCreateInfo);
1429 return result;
1430 }
1431
1432 VKAPI_ATTR void VKAPI_CALL overlay_DestroySwapchainKHR(
1433 VkDevice device,
1434 VkSwapchainKHR swapchain,
1435 const VkAllocationCallbacks* pAllocator)
1436 {
1437 struct swapchain_data *swapchain_data = FIND_SWAPCHAIN_DATA(swapchain);
1438
1439 shutdown_swapchain_data(swapchain_data);
1440 swapchain_data->device->vtable.DestroySwapchainKHR(device, swapchain, pAllocator);
1441 destroy_swapchain_data(swapchain_data);
1442 }
1443
1444 VKAPI_ATTR VkResult VKAPI_CALL overlay_QueuePresentKHR(
1445 VkQueue queue,
1446 const VkPresentInfoKHR* pPresentInfo)
1447 {
1448 struct queue_data *queue_data = FIND_QUEUE_DATA(queue);
1449 struct device_data *device_data = queue_data->device;
1450
1451 /* If we present on the graphic queue this layer is using to draw an
1452 * overlay, we don't need more than submitting the overlay draw prior to
1453 * present.
1454 */
1455 if (queue_data == device_data->graphic_queue) {
1456 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; i++) {
1457 struct swapchain_data *swapchain_data = FIND_SWAPCHAIN_DATA(pPresentInfo->pSwapchains[i]);
1458 before_present(swapchain_data, pPresentInfo->pImageIndices[i]);
1459 }
1460 return queue_data->device->vtable.QueuePresentKHR(queue, pPresentInfo);
1461 }
1462
1463 /* Otherwise we need to do cross queue synchronization to tie the overlay
1464 * draw into the present queue.
1465 */
1466 VkPresentInfoKHR present_info = *pPresentInfo;
1467 VkSemaphore *semaphores =
1468 (VkSemaphore *)malloc(sizeof(VkSemaphore) * (pPresentInfo->waitSemaphoreCount + pPresentInfo->swapchainCount));
1469 for (uint32_t i = 0; i < pPresentInfo->waitSemaphoreCount; i++)
1470 semaphores[i] = pPresentInfo->pWaitSemaphores[i];
1471 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; i++) {
1472 struct swapchain_data *swapchain_data = FIND_SWAPCHAIN_DATA(pPresentInfo->pSwapchains[i]);
1473 before_present(swapchain_data, pPresentInfo->pImageIndices[i]);
1474 semaphores[pPresentInfo->waitSemaphoreCount + i] = swapchain_data->submission_semaphore;
1475 }
1476 present_info.pWaitSemaphores = semaphores;
1477 present_info.waitSemaphoreCount = pPresentInfo->waitSemaphoreCount + pPresentInfo->swapchainCount;
1478 VkResult result = queue_data->device->vtable.QueuePresentKHR(queue, &present_info);
1479 free(semaphores);
1480 return result;
1481 }
1482
1483 VKAPI_ATTR VkResult VKAPI_CALL overlay_AcquireNextImageKHR(
1484 VkDevice device,
1485 VkSwapchainKHR swapchain,
1486 uint64_t timeout,
1487 VkSemaphore semaphore,
1488 VkFence fence,
1489 uint32_t* pImageIndex)
1490 {
1491 struct swapchain_data *swapchain_data = FIND_SWAPCHAIN_DATA(swapchain);
1492 struct device_data *device_data = swapchain_data->device;
1493
1494 uint64_t ts0 = os_time_get();
1495 VkResult result = device_data->vtable.AcquireNextImageKHR(device, swapchain, timeout,
1496 semaphore, fence, pImageIndex);
1497 uint64_t ts1 = os_time_get();
1498
1499 swapchain_data->acquire_times[swapchain_data->n_acquire %
1500 ARRAY_SIZE(swapchain_data->acquire_times)] =
1501 ((double)ts1 - (double)ts0) / 1000.0;
1502 swapchain_data->n_acquire++;
1503
1504 return result;
1505 }
1506
1507 VKAPI_ATTR VkResult VKAPI_CALL overlay_AcquireNextImage2KHR(
1508 VkDevice device,
1509 const VkAcquireNextImageInfoKHR* pAcquireInfo,
1510 uint32_t* pImageIndex)
1511 {
1512 struct swapchain_data *swapchain_data = FIND_SWAPCHAIN_DATA(pAcquireInfo->swapchain);
1513 struct device_data *device_data = swapchain_data->device;
1514
1515 uint64_t ts0 = os_time_get();
1516 VkResult result = device_data->vtable.AcquireNextImage2KHR(device, pAcquireInfo, pImageIndex);
1517 uint64_t ts1 = os_time_get();
1518
1519 swapchain_data->acquire_times[swapchain_data->n_acquire %
1520 ARRAY_SIZE(swapchain_data->acquire_times)] =
1521 ((double)ts1 - (double)ts0) / 1000.0;
1522 swapchain_data->n_acquire++;
1523
1524 return result;
1525 }
1526
1527 VKAPI_ATTR void VKAPI_CALL overlay_CmdDraw(
1528 VkCommandBuffer commandBuffer,
1529 uint32_t vertexCount,
1530 uint32_t instanceCount,
1531 uint32_t firstVertex,
1532 uint32_t firstInstance)
1533 {
1534 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1535 device_data->vtable.CmdDraw(commandBuffer, vertexCount, instanceCount,
1536 firstVertex, firstInstance);
1537 device_data->stats.stats[FRAME_STAT_DRAW]++;
1538 }
1539
1540 VKAPI_ATTR void VKAPI_CALL overlay_CmdDrawIndexed(
1541 VkCommandBuffer commandBuffer,
1542 uint32_t indexCount,
1543 uint32_t instanceCount,
1544 uint32_t firstIndex,
1545 int32_t vertexOffset,
1546 uint32_t firstInstance)
1547 {
1548 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1549 device_data->vtable.CmdDrawIndexed(commandBuffer, indexCount, instanceCount,
1550 firstIndex, vertexOffset, firstInstance);
1551 device_data->stats.stats[FRAME_STAT_DRAW_INDEXED]++;
1552 }
1553
1554 VKAPI_ATTR void VKAPI_CALL overlay_CmdDrawIndirect(
1555 VkCommandBuffer commandBuffer,
1556 VkBuffer buffer,
1557 VkDeviceSize offset,
1558 uint32_t drawCount,
1559 uint32_t stride)
1560 {
1561 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1562 device_data->vtable.CmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
1563 device_data->stats.stats[FRAME_STAT_DRAW_INDIRECT]++;
1564 }
1565
1566 VKAPI_ATTR void VKAPI_CALL overlay_CmdDrawIndexedIndirect(
1567 VkCommandBuffer commandBuffer,
1568 VkBuffer buffer,
1569 VkDeviceSize offset,
1570 uint32_t drawCount,
1571 uint32_t stride)
1572 {
1573 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1574 device_data->vtable.CmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
1575 device_data->stats.stats[FRAME_STAT_DRAW_INDEXED_INDIRECT]++;
1576 }
1577
1578 VKAPI_ATTR void VKAPI_CALL overlay_CmdDrawIndirectCountKHR(
1579 VkCommandBuffer commandBuffer,
1580 VkBuffer buffer,
1581 VkDeviceSize offset,
1582 VkBuffer countBuffer,
1583 VkDeviceSize countBufferOffset,
1584 uint32_t maxDrawCount,
1585 uint32_t stride)
1586 {
1587 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1588 device_data->vtable.CmdDrawIndirectCountKHR(commandBuffer, buffer, offset,
1589 countBuffer, countBufferOffset,
1590 maxDrawCount, stride);
1591 device_data->stats.stats[FRAME_STAT_DRAW_INDIRECT_COUNT]++;
1592 }
1593
1594 VKAPI_ATTR void VKAPI_CALL overlay_CmdDrawIndexedIndirectCountKHR(
1595 VkCommandBuffer commandBuffer,
1596 VkBuffer buffer,
1597 VkDeviceSize offset,
1598 VkBuffer countBuffer,
1599 VkDeviceSize countBufferOffset,
1600 uint32_t maxDrawCount,
1601 uint32_t stride)
1602 {
1603 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1604 device_data->vtable.CmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset,
1605 countBuffer, countBufferOffset,
1606 maxDrawCount, stride);
1607 device_data->stats.stats[FRAME_STAT_DRAW_INDEXED_INDIRECT_COUNT]++;
1608 }
1609
1610 VKAPI_ATTR void VKAPI_CALL overlay_CmdDispatch(
1611 VkCommandBuffer commandBuffer,
1612 uint32_t groupCountX,
1613 uint32_t groupCountY,
1614 uint32_t groupCountZ)
1615 {
1616 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1617 device_data->vtable.CmdDispatch(commandBuffer, groupCountX, groupCountY, groupCountZ);
1618 device_data->stats.stats[FRAME_STAT_DISPATCH]++;
1619 }
1620
1621 VKAPI_ATTR void VKAPI_CALL overlay_CmdDispatchIndirect(
1622 VkCommandBuffer commandBuffer,
1623 VkBuffer buffer,
1624 VkDeviceSize offset)
1625 {
1626 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1627 device_data->vtable.CmdDispatchIndirect(commandBuffer, buffer, offset);
1628 device_data->stats.stats[FRAME_STAT_DISPATCH_INDIRECT]++;
1629 }
1630
1631 VKAPI_ATTR void VKAPI_CALL overlay_CmdBindPipeline(
1632 VkCommandBuffer commandBuffer,
1633 VkPipelineBindPoint pipelineBindPoint,
1634 VkPipeline pipeline)
1635 {
1636 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1637 device_data->vtable.CmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1638 switch (pipelineBindPoint) {
1639 case VK_PIPELINE_BIND_POINT_GRAPHICS: device_data->stats.stats[FRAME_STAT_PIPELINE_GRAPHICS]++; break;
1640 case VK_PIPELINE_BIND_POINT_COMPUTE: device_data->stats.stats[FRAME_STAT_PIPELINE_COMPUTE]++; break;
1641 case VK_PIPELINE_BIND_POINT_RAY_TRACING_NV: device_data->stats.stats[FRAME_STAT_PIPELINE_RAYTRACING]++; break;
1642 default: break;
1643 }
1644 }
1645
1646 VKAPI_ATTR VkResult VKAPI_CALL overlay_AllocateCommandBuffers(VkDevice device,
1647 const VkCommandBufferAllocateInfo* pAllocateInfo,
1648 VkCommandBuffer* pCommandBuffers)
1649 {
1650 struct device_data *device_data = FIND_DEVICE_DATA(device);
1651
1652 VkResult result =
1653 device_data->vtable.AllocateCommandBuffers(device, pAllocateInfo, pCommandBuffers);
1654 if (result != VK_SUCCESS) return result;
1655
1656 for (uint32_t i = 0; i < pAllocateInfo->commandBufferCount; i++)
1657 map_object(pCommandBuffers[i], device_data);
1658
1659 return result;
1660 }
1661
1662 VKAPI_ATTR void VKAPI_CALL overlay_FreeCommandBuffers(VkDevice device,
1663 VkCommandPool commandPool,
1664 uint32_t commandBufferCount,
1665 const VkCommandBuffer* pCommandBuffers)
1666 {
1667 struct device_data *device_data = FIND_DEVICE_DATA(device);
1668
1669 for (uint32_t i = 0; i < commandBufferCount; i++)
1670 unmap_object(pCommandBuffers[i]);
1671
1672 device_data->vtable.FreeCommandBuffers(device, commandPool,
1673 commandBufferCount, pCommandBuffers);
1674 }
1675
1676 VKAPI_ATTR VkResult VKAPI_CALL overlay_QueueSubmit(
1677 VkQueue queue,
1678 uint32_t submitCount,
1679 const VkSubmitInfo* pSubmits,
1680 VkFence fence)
1681 {
1682 struct queue_data *queue_data = FIND_QUEUE_DATA(queue);
1683 struct device_data *device_data = queue_data->device;
1684
1685 device_data->stats.stats[FRAME_STAT_SUBMIT]++;
1686
1687 return device_data->vtable.QueueSubmit(queue, submitCount, pSubmits, fence);
1688 }
1689
1690 VKAPI_ATTR VkResult VKAPI_CALL overlay_CreateDevice(
1691 VkPhysicalDevice physicalDevice,
1692 const VkDeviceCreateInfo* pCreateInfo,
1693 const VkAllocationCallbacks* pAllocator,
1694 VkDevice* pDevice)
1695 {
1696 struct instance_data *instance_data = FIND_PHYSICAL_DEVICE_DATA(physicalDevice);
1697 VkLayerDeviceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
1698
1699 assert(chain_info->u.pLayerInfo);
1700 PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
1701 PFN_vkGetDeviceProcAddr fpGetDeviceProcAddr = chain_info->u.pLayerInfo->pfnNextGetDeviceProcAddr;
1702 PFN_vkCreateDevice fpCreateDevice = (PFN_vkCreateDevice)fpGetInstanceProcAddr(NULL, "vkCreateDevice");
1703 if (fpCreateDevice == NULL) {
1704 return VK_ERROR_INITIALIZATION_FAILED;
1705 }
1706
1707 // Advance the link info for the next element on the chain
1708 chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
1709
1710 VkResult result = fpCreateDevice(physicalDevice, pCreateInfo, pAllocator, pDevice);
1711 if (result != VK_SUCCESS) return result;
1712
1713 struct device_data *device_data = new_device_data(*pDevice, instance_data);
1714 device_data->physical_device = physicalDevice;
1715 layer_init_device_dispatch_table(*pDevice, &device_data->vtable, fpGetDeviceProcAddr);
1716
1717 instance_data->vtable.GetPhysicalDeviceProperties(device_data->physical_device,
1718 &device_data->properties);
1719
1720 device_map_queues(device_data, pCreateInfo);
1721
1722 return result;
1723 }
1724
1725 VKAPI_ATTR void VKAPI_CALL overlay_DestroyDevice(
1726 VkDevice device,
1727 const VkAllocationCallbacks* pAllocator)
1728 {
1729 struct device_data *device_data = FIND_DEVICE_DATA(device);
1730 device_unmap_queues(device_data);
1731 device_data->vtable.DestroyDevice(device, pAllocator);
1732 destroy_device_data(device_data);
1733 }
1734
1735 VKAPI_ATTR VkResult VKAPI_CALL overlay_CreateInstance(
1736 const VkInstanceCreateInfo* pCreateInfo,
1737 const VkAllocationCallbacks* pAllocator,
1738 VkInstance* pInstance)
1739 {
1740 VkLayerInstanceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
1741
1742 assert(chain_info->u.pLayerInfo);
1743 PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr =
1744 chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
1745 PFN_vkCreateInstance fpCreateInstance =
1746 (PFN_vkCreateInstance)fpGetInstanceProcAddr(NULL, "vkCreateInstance");
1747 if (fpCreateInstance == NULL) {
1748 return VK_ERROR_INITIALIZATION_FAILED;
1749 }
1750
1751 // Advance the link info for the next element on the chain
1752 chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
1753
1754 VkResult result = fpCreateInstance(pCreateInfo, pAllocator, pInstance);
1755 if (result != VK_SUCCESS) return result;
1756
1757 struct instance_data *instance_data = new_instance_data(*pInstance);
1758 layer_init_instance_dispatch_table(instance_data->instance,
1759 &instance_data->vtable,
1760 fpGetInstanceProcAddr);
1761 instance_data_map_physical_devices(instance_data, true);
1762
1763 const char *stats_config = getenv("VK_LAYER_MESA_OVERLAY_STATS");
1764 instance_data->enabled_stats = parse_debug_string(stats_config,
1765 enable_flags);
1766
1767 if (instance_data->enabled_stats & FRAME_STAT_ENABLED(HELP)) {
1768 fprintf(stderr, "Available stats:\n");
1769 for (uint32_t i = 0; enable_flags[i].string != NULL; i++)
1770 fprintf(stderr, "\t%s\n", enable_flags[i].string);
1771 fprintf(stderr, "Position layer using VK_LAYER_MESA_OVERLAY_POSITION=\n"
1772 "\ttop-left\n"
1773 "\ttop-right\n"
1774 "\tbottom-left\n"
1775 "\tbottom-right\n");
1776 }
1777
1778 instance_data->position =
1779 parse_layer_position(getenv("VK_LAYER_MESA_OVERLAY_POSITION"));
1780
1781 return result;
1782 }
1783
1784 VKAPI_ATTR void VKAPI_CALL overlay_DestroyInstance(
1785 VkInstance instance,
1786 const VkAllocationCallbacks* pAllocator)
1787 {
1788 struct instance_data *instance_data = FIND_INSTANCE_DATA(instance);
1789 instance_data_map_physical_devices(instance_data, false);
1790 instance_data->vtable.DestroyInstance(instance, pAllocator);
1791 destroy_instance_data(instance_data);
1792 }
1793
1794 static const struct {
1795 const char *name;
1796 void *ptr;
1797 } name_to_funcptr_map[] = {
1798 { "vkGetDeviceProcAddr", (void *) vkGetDeviceProcAddr },
1799 #define ADD_HOOK(fn) { "vk" # fn, (void *) overlay_ ## fn }
1800 ADD_HOOK(AllocateCommandBuffers),
1801
1802 ADD_HOOK(CmdDraw),
1803 ADD_HOOK(CmdDrawIndexed),
1804 ADD_HOOK(CmdDrawIndexedIndirect),
1805 ADD_HOOK(CmdDispatch),
1806 ADD_HOOK(CmdDispatchIndirect),
1807 ADD_HOOK(CmdDrawIndirectCountKHR),
1808 ADD_HOOK(CmdDrawIndexedIndirectCountKHR),
1809
1810 ADD_HOOK(CmdBindPipeline),
1811
1812 ADD_HOOK(CreateSwapchainKHR),
1813 ADD_HOOK(QueuePresentKHR),
1814 ADD_HOOK(DestroySwapchainKHR),
1815 ADD_HOOK(AcquireNextImageKHR),
1816 ADD_HOOK(AcquireNextImage2KHR),
1817
1818 ADD_HOOK(QueueSubmit),
1819 ADD_HOOK(CreateInstance),
1820 ADD_HOOK(DestroyInstance),
1821 ADD_HOOK(CreateDevice),
1822 ADD_HOOK(DestroyDevice),
1823 #undef ADD_HOOK
1824 };
1825
1826 static void *find_ptr(const char *name)
1827 {
1828 for (uint32_t i = 0; i < ARRAY_SIZE(name_to_funcptr_map); i++) {
1829 if (strcmp(name, name_to_funcptr_map[i].name) == 0)
1830 return name_to_funcptr_map[i].ptr;
1831 }
1832
1833 return NULL;
1834 }
1835
1836 VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice dev,
1837 const char *funcName)
1838 {
1839 void *ptr = find_ptr(funcName);
1840 if (ptr) return reinterpret_cast<PFN_vkVoidFunction>(ptr);
1841
1842 if (dev == NULL) return NULL;
1843
1844 struct device_data *device_data = FIND_DEVICE_DATA(dev);
1845 if (device_data->vtable.GetDeviceProcAddr == NULL) return NULL;
1846 return device_data->vtable.GetDeviceProcAddr(dev, funcName);
1847 }
1848
1849 VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance,
1850 const char *funcName)
1851 {
1852 void *ptr = find_ptr(funcName);
1853 if (ptr) return reinterpret_cast<PFN_vkVoidFunction>(ptr);
1854
1855 if (instance == NULL) return NULL;
1856
1857 struct instance_data *instance_data = FIND_INSTANCE_DATA(instance);
1858 if (instance_data->vtable.GetInstanceProcAddr == NULL) return NULL;
1859 return instance_data->vtable.GetInstanceProcAddr(instance, funcName);
1860 }