2 * Copyright © 2019 Intel Corporation
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:
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
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
28 #include <vulkan/vulkan.h>
29 #include <vulkan/vk_layer.h>
35 #include "overlay_params.h"
37 #include "util/debug.h"
38 #include "util/hash_table.h"
39 #include "util/list.h"
40 #include "util/ralloc.h"
41 #include "util/os_time.h"
42 #include "util/os_socket.h"
43 #include "util/simple_mtx.h"
45 #include "vk_enum_to_str.h"
48 /* Mapped from VkInstace/VkPhysicalDevice */
49 struct instance_data
{
50 struct vk_instance_dispatch_table vtable
;
53 struct overlay_params params
;
54 bool pipeline_statistics_enabled
;
56 bool first_line_printed
;
60 /* Dumping of frame stats to a file has been enabled. */
63 /* Dumping of frame stats to a file has been enabled and started. */
68 uint64_t stats
[OVERLAY_PARAM_ENABLED_MAX
];
71 /* Mapped from VkDevice */
74 struct instance_data
*instance
;
76 PFN_vkSetDeviceLoaderData set_device_loader_data
;
78 struct vk_device_dispatch_table vtable
;
79 VkPhysicalDevice physical_device
;
82 VkPhysicalDeviceProperties properties
;
84 struct queue_data
*graphic_queue
;
86 struct queue_data
**queues
;
89 /* For a single frame */
90 struct frame_stat frame_stats
;
93 /* Mapped from VkCommandBuffer */
94 struct command_buffer_data
{
95 struct device_data
*device
;
97 VkCommandBufferLevel level
;
99 VkCommandBuffer cmd_buffer
;
100 VkQueryPool pipeline_query_pool
;
101 VkQueryPool timestamp_query_pool
;
102 uint32_t query_index
;
104 struct frame_stat stats
;
106 struct list_head link
; /* link into queue_data::running_command_buffer */
109 /* Mapped from VkQueue */
111 struct device_data
*device
;
115 uint32_t family_index
;
116 uint64_t timestamp_mask
;
118 VkFence queries_fence
;
120 struct list_head running_command_buffer
;
123 struct overlay_draw
{
124 struct list_head link
;
126 VkCommandBuffer command_buffer
;
128 VkSemaphore semaphore
;
131 VkBuffer vertex_buffer
;
132 VkDeviceMemory vertex_buffer_mem
;
133 VkDeviceSize vertex_buffer_size
;
135 VkBuffer index_buffer
;
136 VkDeviceMemory index_buffer_mem
;
137 VkDeviceSize index_buffer_size
;
140 /* Mapped from VkSwapchainKHR */
141 struct swapchain_data
{
142 struct device_data
*device
;
144 VkSwapchainKHR swapchain
;
145 unsigned width
, height
;
150 VkImageView
*image_views
;
151 VkFramebuffer
*framebuffers
;
153 VkRenderPass render_pass
;
155 VkDescriptorPool descriptor_pool
;
156 VkDescriptorSetLayout descriptor_layout
;
157 VkDescriptorSet descriptor_set
;
159 VkSampler font_sampler
;
161 VkPipelineLayout pipeline_layout
;
164 VkCommandPool command_pool
;
166 struct list_head draws
; /* List of struct overlay_draw */
170 VkImageView font_image_view
;
171 VkDeviceMemory font_mem
;
172 VkBuffer upload_font_buffer
;
173 VkDeviceMemory upload_font_buffer_mem
;
176 ImGuiContext
* imgui_context
;
181 uint64_t last_present_time
;
183 unsigned n_frames_since_update
;
184 uint64_t last_fps_update
;
187 enum overlay_param_enabled stat_selector
;
189 struct frame_stat stats_min
, stats_max
;
190 struct frame_stat frames_stats
[200];
192 /* Over a single frame */
193 struct frame_stat frame_stats
;
195 /* Over fps_sampling_period */
196 struct frame_stat accumulated_stats
;
199 static const VkQueryPipelineStatisticFlags overlay_query_flags
=
200 VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT
|
201 VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT
|
202 VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT
|
203 VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_INVOCATIONS_BIT
|
204 VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT
|
205 VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT
|
206 VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT
|
207 VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT
|
208 VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_CONTROL_SHADER_PATCHES_BIT
|
209 VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT
|
210 VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT
;
211 #define OVERLAY_QUERY_COUNT (11)
213 static struct hash_table_u64
*vk_object_to_data
= NULL
;
214 static simple_mtx_t vk_object_to_data_mutex
= _SIMPLE_MTX_INITIALIZER_NP
;
216 thread_local ImGuiContext
* __MesaImGui
;
218 static inline void ensure_vk_object_map(void)
220 if (!vk_object_to_data
)
221 vk_object_to_data
= _mesa_hash_table_u64_create(NULL
);
224 #define HKEY(obj) ((uint64_t)(obj))
225 #define FIND(type, obj) ((type *)find_object_data(HKEY(obj)))
227 static void *find_object_data(uint64_t obj
)
229 simple_mtx_lock(&vk_object_to_data_mutex
);
230 ensure_vk_object_map();
231 void *data
= _mesa_hash_table_u64_search(vk_object_to_data
, obj
);
232 simple_mtx_unlock(&vk_object_to_data_mutex
);
236 static void map_object(uint64_t obj
, void *data
)
238 simple_mtx_lock(&vk_object_to_data_mutex
);
239 ensure_vk_object_map();
240 _mesa_hash_table_u64_insert(vk_object_to_data
, obj
, data
);
241 simple_mtx_unlock(&vk_object_to_data_mutex
);
244 static void unmap_object(uint64_t obj
)
246 simple_mtx_lock(&vk_object_to_data_mutex
);
247 _mesa_hash_table_u64_remove(vk_object_to_data
, obj
);
248 simple_mtx_unlock(&vk_object_to_data_mutex
);
253 #define VK_CHECK(expr) \
255 VkResult __result = (expr); \
256 if (__result != VK_SUCCESS) { \
257 fprintf(stderr, "'%s' line %i failed with %s\n", \
258 #expr, __LINE__, vk_Result_to_str(__result)); \
264 static VkLayerInstanceCreateInfo
*get_instance_chain_info(const VkInstanceCreateInfo
*pCreateInfo
,
265 VkLayerFunction func
)
267 vk_foreach_struct(item
, pCreateInfo
->pNext
) {
268 if (item
->sType
== VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO
&&
269 ((VkLayerInstanceCreateInfo
*) item
)->function
== func
)
270 return (VkLayerInstanceCreateInfo
*) item
;
272 unreachable("instance chain info not found");
276 static VkLayerDeviceCreateInfo
*get_device_chain_info(const VkDeviceCreateInfo
*pCreateInfo
,
277 VkLayerFunction func
)
279 vk_foreach_struct(item
, pCreateInfo
->pNext
) {
280 if (item
->sType
== VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO
&&
281 ((VkLayerDeviceCreateInfo
*) item
)->function
== func
)
282 return (VkLayerDeviceCreateInfo
*)item
;
284 unreachable("device chain info not found");
288 static struct VkBaseOutStructure
*
289 clone_chain(const struct VkBaseInStructure
*chain
)
291 struct VkBaseOutStructure
*head
= NULL
, *tail
= NULL
;
293 vk_foreach_struct_const(item
, chain
) {
294 size_t item_size
= vk_structure_type_size(item
);
295 struct VkBaseOutStructure
*new_item
=
296 (struct VkBaseOutStructure
*)malloc(item_size
);;
298 memcpy(new_item
, item
, item_size
);
303 tail
->pNext
= new_item
;
311 free_chain(struct VkBaseOutStructure
*chain
)
315 chain
= chain
->pNext
;
322 static struct instance_data
*new_instance_data(VkInstance instance
)
324 struct instance_data
*data
= rzalloc(NULL
, struct instance_data
);
325 data
->instance
= instance
;
326 data
->control_client
= -1;
327 map_object(HKEY(data
->instance
), data
);
331 static void destroy_instance_data(struct instance_data
*data
)
333 if (data
->params
.output_file
)
334 fclose(data
->params
.output_file
);
335 if (data
->params
.control
>= 0)
336 os_socket_close(data
->params
.control
);
337 unmap_object(HKEY(data
->instance
));
341 static void instance_data_map_physical_devices(struct instance_data
*instance_data
,
344 uint32_t physicalDeviceCount
= 0;
345 instance_data
->vtable
.EnumeratePhysicalDevices(instance_data
->instance
,
346 &physicalDeviceCount
,
349 VkPhysicalDevice
*physicalDevices
= (VkPhysicalDevice
*) malloc(sizeof(VkPhysicalDevice
) * physicalDeviceCount
);
350 instance_data
->vtable
.EnumeratePhysicalDevices(instance_data
->instance
,
351 &physicalDeviceCount
,
354 for (uint32_t i
= 0; i
< physicalDeviceCount
; i
++) {
356 map_object(HKEY(physicalDevices
[i
]), instance_data
);
358 unmap_object(HKEY(physicalDevices
[i
]));
361 free(physicalDevices
);
365 static struct device_data
*new_device_data(VkDevice device
, struct instance_data
*instance
)
367 struct device_data
*data
= rzalloc(NULL
, struct device_data
);
368 data
->instance
= instance
;
369 data
->device
= device
;
370 map_object(HKEY(data
->device
), data
);
374 static struct queue_data
*new_queue_data(VkQueue queue
,
375 const VkQueueFamilyProperties
*family_props
,
376 uint32_t family_index
,
377 struct device_data
*device_data
)
379 struct queue_data
*data
= rzalloc(device_data
, struct queue_data
);
380 data
->device
= device_data
;
382 data
->flags
= family_props
->queueFlags
;
383 data
->timestamp_mask
= (1ull << family_props
->timestampValidBits
) - 1;
384 data
->family_index
= family_index
;
385 list_inithead(&data
->running_command_buffer
);
386 map_object(HKEY(data
->queue
), data
);
388 /* Fence synchronizing access to queries on that queue. */
389 VkFenceCreateInfo fence_info
= {};
390 fence_info
.sType
= VK_STRUCTURE_TYPE_FENCE_CREATE_INFO
;
391 fence_info
.flags
= VK_FENCE_CREATE_SIGNALED_BIT
;
392 VK_CHECK(device_data
->vtable
.CreateFence(device_data
->device
,
395 &data
->queries_fence
));
397 if (data
->flags
& VK_QUEUE_GRAPHICS_BIT
)
398 device_data
->graphic_queue
= data
;
403 static void destroy_queue(struct queue_data
*data
)
405 struct device_data
*device_data
= data
->device
;
406 device_data
->vtable
.DestroyFence(device_data
->device
, data
->queries_fence
, NULL
);
407 unmap_object(HKEY(data
->queue
));
411 static void device_map_queues(struct device_data
*data
,
412 const VkDeviceCreateInfo
*pCreateInfo
)
414 for (uint32_t i
= 0; i
< pCreateInfo
->queueCreateInfoCount
; i
++)
415 data
->n_queues
+= pCreateInfo
->pQueueCreateInfos
[i
].queueCount
;
416 data
->queues
= ralloc_array(data
, struct queue_data
*, data
->n_queues
);
418 struct instance_data
*instance_data
= data
->instance
;
419 uint32_t n_family_props
;
420 instance_data
->vtable
.GetPhysicalDeviceQueueFamilyProperties(data
->physical_device
,
423 VkQueueFamilyProperties
*family_props
=
424 (VkQueueFamilyProperties
*)malloc(sizeof(VkQueueFamilyProperties
) * n_family_props
);
425 instance_data
->vtable
.GetPhysicalDeviceQueueFamilyProperties(data
->physical_device
,
429 uint32_t queue_index
= 0;
430 for (uint32_t i
= 0; i
< pCreateInfo
->queueCreateInfoCount
; i
++) {
431 for (uint32_t j
= 0; j
< pCreateInfo
->pQueueCreateInfos
[i
].queueCount
; j
++) {
433 data
->vtable
.GetDeviceQueue(data
->device
,
434 pCreateInfo
->pQueueCreateInfos
[i
].queueFamilyIndex
,
437 VK_CHECK(data
->set_device_loader_data(data
->device
, queue
));
439 data
->queues
[queue_index
++] =
440 new_queue_data(queue
, &family_props
[pCreateInfo
->pQueueCreateInfos
[i
].queueFamilyIndex
],
441 pCreateInfo
->pQueueCreateInfos
[i
].queueFamilyIndex
, data
);
448 static void device_unmap_queues(struct device_data
*data
)
450 for (uint32_t i
= 0; i
< data
->n_queues
; i
++)
451 destroy_queue(data
->queues
[i
]);
454 static void destroy_device_data(struct device_data
*data
)
456 unmap_object(HKEY(data
->device
));
461 static struct command_buffer_data
*new_command_buffer_data(VkCommandBuffer cmd_buffer
,
462 VkCommandBufferLevel level
,
463 VkQueryPool pipeline_query_pool
,
464 VkQueryPool timestamp_query_pool
,
465 uint32_t query_index
,
466 struct device_data
*device_data
)
468 struct command_buffer_data
*data
= rzalloc(NULL
, struct command_buffer_data
);
469 data
->device
= device_data
;
470 data
->cmd_buffer
= cmd_buffer
;
472 data
->pipeline_query_pool
= pipeline_query_pool
;
473 data
->timestamp_query_pool
= timestamp_query_pool
;
474 data
->query_index
= query_index
;
475 list_inithead(&data
->link
);
476 map_object(HKEY(data
->cmd_buffer
), data
);
480 static void destroy_command_buffer_data(struct command_buffer_data
*data
)
482 unmap_object(HKEY(data
->cmd_buffer
));
483 list_delinit(&data
->link
);
488 static struct swapchain_data
*new_swapchain_data(VkSwapchainKHR swapchain
,
489 struct device_data
*device_data
)
491 struct instance_data
*instance_data
= device_data
->instance
;
492 struct swapchain_data
*data
= rzalloc(NULL
, struct swapchain_data
);
493 data
->device
= device_data
;
494 data
->swapchain
= swapchain
;
495 data
->window_size
= ImVec2(instance_data
->params
.width
, instance_data
->params
.height
);
496 list_inithead(&data
->draws
);
497 map_object(HKEY(data
->swapchain
), data
);
501 static void destroy_swapchain_data(struct swapchain_data
*data
)
503 unmap_object(HKEY(data
->swapchain
));
507 struct overlay_draw
*get_overlay_draw(struct swapchain_data
*data
)
509 struct device_data
*device_data
= data
->device
;
510 struct overlay_draw
*draw
= list_is_empty(&data
->draws
) ?
511 NULL
: list_first_entry(&data
->draws
, struct overlay_draw
, link
);
513 VkSemaphoreCreateInfo sem_info
= {};
514 sem_info
.sType
= VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO
;
516 if (draw
&& device_data
->vtable
.GetFenceStatus(device_data
->device
, draw
->fence
) == VK_SUCCESS
) {
517 list_del(&draw
->link
);
518 VK_CHECK(device_data
->vtable
.ResetFences(device_data
->device
,
520 list_addtail(&draw
->link
, &data
->draws
);
524 draw
= rzalloc(data
, struct overlay_draw
);
526 VkCommandBufferAllocateInfo cmd_buffer_info
= {};
527 cmd_buffer_info
.sType
= VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO
;
528 cmd_buffer_info
.commandPool
= data
->command_pool
;
529 cmd_buffer_info
.level
= VK_COMMAND_BUFFER_LEVEL_PRIMARY
;
530 cmd_buffer_info
.commandBufferCount
= 1;
531 VK_CHECK(device_data
->vtable
.AllocateCommandBuffers(device_data
->device
,
533 &draw
->command_buffer
));
534 VK_CHECK(device_data
->set_device_loader_data(device_data
->device
,
535 draw
->command_buffer
));
538 VkFenceCreateInfo fence_info
= {};
539 fence_info
.sType
= VK_STRUCTURE_TYPE_FENCE_CREATE_INFO
;
540 VK_CHECK(device_data
->vtable
.CreateFence(device_data
->device
,
545 VK_CHECK(device_data
->vtable
.CreateSemaphore(device_data
->device
, &sem_info
,
546 NULL
, &draw
->semaphore
));
548 list_addtail(&draw
->link
, &data
->draws
);
553 static const char *param_unit(enum overlay_param_enabled param
)
556 case OVERLAY_PARAM_ENABLED_frame_timing
:
557 case OVERLAY_PARAM_ENABLED_acquire_timing
:
558 case OVERLAY_PARAM_ENABLED_present_timing
:
560 case OVERLAY_PARAM_ENABLED_gpu_timing
:
567 static void parse_command(struct instance_data
*instance_data
,
568 const char *cmd
, unsigned cmdlen
,
569 const char *param
, unsigned paramlen
)
571 if (!strncmp(cmd
, "capture", cmdlen
)) {
572 int value
= atoi(param
);
573 bool enabled
= value
> 0;
576 instance_data
->capture_enabled
= true;
578 instance_data
->capture_enabled
= false;
579 instance_data
->capture_started
= false;
587 * This function will process commands through the control file.
589 * A command starts with a colon, followed by the command, and followed by an
590 * option '=' and a parameter. It has to end with a semi-colon. A full command
591 * + parameter looks like:
595 static void process_char(struct instance_data
*instance_data
, char c
)
597 static char cmd
[BUFSIZE
];
598 static char param
[BUFSIZE
];
600 static unsigned cmdpos
= 0;
601 static unsigned parampos
= 0;
602 static bool reading_cmd
= false;
603 static bool reading_param
= false;
610 reading_param
= false;
615 cmd
[cmdpos
++] = '\0';
616 param
[parampos
++] = '\0';
617 parse_command(instance_data
, cmd
, cmdpos
, param
, parampos
);
619 reading_param
= false;
624 reading_param
= true;
631 /* overflow means an invalid parameter */
632 if (parampos
>= BUFSIZE
- 1) {
634 reading_param
= false;
638 param
[parampos
++] = c
;
640 /* overflow means an invalid command */
641 if (cmdpos
>= BUFSIZE
- 1) {
651 static void control_send(struct instance_data
*instance_data
,
652 const char *cmd
, unsigned cmdlen
,
653 const char *param
, unsigned paramlen
)
656 char buffer
[BUFSIZE
];
658 assert(cmdlen
+ paramlen
+ 3 < BUFSIZE
);
660 buffer
[msglen
++] = ':';
662 memcpy(&buffer
[msglen
], cmd
, cmdlen
);
666 buffer
[msglen
++] = '=';
667 memcpy(&buffer
[msglen
], param
, paramlen
);
669 buffer
[msglen
++] = ';';
672 os_socket_send(instance_data
->control_client
, buffer
, msglen
, 0);
675 static void control_send_connection_string(struct device_data
*device_data
)
677 struct instance_data
*instance_data
= device_data
->instance
;
679 const char *controlVersionCmd
= "MesaOverlayControlVersion";
680 const char *controlVersionString
= "1";
682 control_send(instance_data
, controlVersionCmd
, strlen(controlVersionCmd
),
683 controlVersionString
, strlen(controlVersionString
));
685 const char *deviceCmd
= "DeviceName";
686 const char *deviceName
= device_data
->properties
.deviceName
;
688 control_send(instance_data
, deviceCmd
, strlen(deviceCmd
),
689 deviceName
, strlen(deviceName
));
691 const char *mesaVersionCmd
= "MesaVersion";
692 const char *mesaVersionString
= "Mesa " PACKAGE_VERSION MESA_GIT_SHA1
;
694 control_send(instance_data
, mesaVersionCmd
, strlen(mesaVersionCmd
),
695 mesaVersionString
, strlen(mesaVersionString
));
698 static void control_client_check(struct device_data
*device_data
)
700 struct instance_data
*instance_data
= device_data
->instance
;
702 /* Already connected, just return. */
703 if (instance_data
->control_client
>= 0)
706 int socket
= os_socket_accept(instance_data
->params
.control
);
708 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
&& errno
!= ECONNABORTED
)
709 fprintf(stderr
, "ERROR on socket: %s\n", strerror(errno
));
714 os_socket_block(socket
, false);
715 instance_data
->control_client
= socket
;
716 control_send_connection_string(device_data
);
720 static void control_client_disconnected(struct instance_data
*instance_data
)
722 os_socket_close(instance_data
->control_client
);
723 instance_data
->control_client
= -1;
726 static void process_control_socket(struct instance_data
*instance_data
)
728 const int client
= instance_data
->control_client
;
733 ssize_t n
= os_socket_recv(client
, buf
, BUFSIZE
, 0);
736 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
) {
737 /* nothing to read, try again later */
741 if (errno
!= ECONNRESET
)
742 fprintf(stderr
, "ERROR on connection: %s\n", strerror(errno
));
744 control_client_disconnected(instance_data
);
746 /* recv() returns 0 when the client disconnects */
747 control_client_disconnected(instance_data
);
750 for (ssize_t i
= 0; i
< n
; i
++) {
751 process_char(instance_data
, buf
[i
]);
754 /* If we try to read BUFSIZE and receive BUFSIZE bytes from the
755 * socket, there's a good chance that there's still more data to be
756 * read, so we will try again. Otherwise, simply be done for this
757 * iteration and try again on the next frame.
765 static void snapshot_swapchain_frame(struct swapchain_data
*data
)
767 struct device_data
*device_data
= data
->device
;
768 struct instance_data
*instance_data
= device_data
->instance
;
769 uint32_t f_idx
= data
->n_frames
% ARRAY_SIZE(data
->frames_stats
);
770 uint64_t now
= os_time_get(); /* us */
772 if (instance_data
->params
.control
>= 0) {
773 control_client_check(device_data
);
774 process_control_socket(instance_data
);
777 if (data
->last_present_time
) {
778 data
->frame_stats
.stats
[OVERLAY_PARAM_ENABLED_frame_timing
] =
779 now
- data
->last_present_time
;
782 memset(&data
->frames_stats
[f_idx
], 0, sizeof(data
->frames_stats
[f_idx
]));
783 for (int s
= 0; s
< OVERLAY_PARAM_ENABLED_MAX
; s
++) {
784 data
->frames_stats
[f_idx
].stats
[s
] += device_data
->frame_stats
.stats
[s
] + data
->frame_stats
.stats
[s
];
785 data
->accumulated_stats
.stats
[s
] += device_data
->frame_stats
.stats
[s
] + data
->frame_stats
.stats
[s
];
788 /* If capture has been enabled but it hasn't started yet, it means we are on
789 * the first snapshot after it has been enabled. At this point we want to
790 * use the stats captured so far to update the display, but we don't want
791 * this data to cause noise to the stats that we want to capture from now
794 * capture_begin == true will trigger an update of the fps on display, and a
795 * flush of the data, but no stats will be written to the output file. This
796 * way, we will have only stats from after the capture has been enabled
797 * written to the output_file.
799 const bool capture_begin
=
800 instance_data
->capture_enabled
&& !instance_data
->capture_started
;
802 if (data
->last_fps_update
) {
803 double elapsed
= (double)(now
- data
->last_fps_update
); /* us */
805 elapsed
>= instance_data
->params
.fps_sampling_period
) {
806 data
->fps
= 1000000.0f
* data
->n_frames_since_update
/ elapsed
;
807 if (instance_data
->capture_started
) {
808 if (!instance_data
->first_line_printed
) {
809 bool first_column
= true;
811 instance_data
->first_line_printed
= true;
813 #define OVERLAY_PARAM_BOOL(name) \
814 if (instance_data->params.enabled[OVERLAY_PARAM_ENABLED_##name]) { \
815 fprintf(instance_data->params.output_file, \
816 "%s%s%s", first_column ? "" : ", ", #name, \
817 param_unit(OVERLAY_PARAM_ENABLED_##name)); \
818 first_column = false; \
820 #define OVERLAY_PARAM_CUSTOM(name)
822 #undef OVERLAY_PARAM_BOOL
823 #undef OVERLAY_PARAM_CUSTOM
824 fprintf(instance_data
->params
.output_file
, "\n");
827 for (int s
= 0; s
< OVERLAY_PARAM_ENABLED_MAX
; s
++) {
828 if (!instance_data
->params
.enabled
[s
])
830 if (s
== OVERLAY_PARAM_ENABLED_fps
) {
831 fprintf(instance_data
->params
.output_file
,
832 "%s%.2f", s
== 0 ? "" : ", ", data
->fps
);
834 fprintf(instance_data
->params
.output_file
,
835 "%s%" PRIu64
, s
== 0 ? "" : ", ",
836 data
->accumulated_stats
.stats
[s
]);
839 fprintf(instance_data
->params
.output_file
, "\n");
840 fflush(instance_data
->params
.output_file
);
843 memset(&data
->accumulated_stats
, 0, sizeof(data
->accumulated_stats
));
844 data
->n_frames_since_update
= 0;
845 data
->last_fps_update
= now
;
848 instance_data
->capture_started
= true;
851 data
->last_fps_update
= now
;
854 memset(&device_data
->frame_stats
, 0, sizeof(device_data
->frame_stats
));
855 memset(&data
->frame_stats
, 0, sizeof(device_data
->frame_stats
));
857 data
->last_present_time
= now
;
859 data
->n_frames_since_update
++;
862 static float get_time_stat(void *_data
, int _idx
)
864 struct swapchain_data
*data
= (struct swapchain_data
*) _data
;
865 if ((ARRAY_SIZE(data
->frames_stats
) - _idx
) > data
->n_frames
)
867 int idx
= ARRAY_SIZE(data
->frames_stats
) +
868 data
->n_frames
< ARRAY_SIZE(data
->frames_stats
) ?
869 _idx
- data
->n_frames
:
870 _idx
+ data
->n_frames
;
871 idx
%= ARRAY_SIZE(data
->frames_stats
);
872 /* Time stats are in us. */
873 return data
->frames_stats
[idx
].stats
[data
->stat_selector
] / data
->time_dividor
;
876 static float get_stat(void *_data
, int _idx
)
878 struct swapchain_data
*data
= (struct swapchain_data
*) _data
;
879 if ((ARRAY_SIZE(data
->frames_stats
) - _idx
) > data
->n_frames
)
881 int idx
= ARRAY_SIZE(data
->frames_stats
) +
882 data
->n_frames
< ARRAY_SIZE(data
->frames_stats
) ?
883 _idx
- data
->n_frames
:
884 _idx
+ data
->n_frames
;
885 idx
%= ARRAY_SIZE(data
->frames_stats
);
886 return data
->frames_stats
[idx
].stats
[data
->stat_selector
];
889 static void position_layer(struct swapchain_data
*data
)
892 struct device_data
*device_data
= data
->device
;
893 struct instance_data
*instance_data
= device_data
->instance
;
894 const float margin
= 10.0f
;
896 ImGui::SetNextWindowBgAlpha(0.5);
897 ImGui::SetNextWindowSize(data
->window_size
, ImGuiCond_Always
);
898 switch (instance_data
->params
.position
) {
899 case LAYER_POSITION_TOP_LEFT
:
900 ImGui::SetNextWindowPos(ImVec2(margin
, margin
), ImGuiCond_Always
);
902 case LAYER_POSITION_TOP_RIGHT
:
903 ImGui::SetNextWindowPos(ImVec2(data
->width
- data
->window_size
.x
- margin
, margin
),
906 case LAYER_POSITION_BOTTOM_LEFT
:
907 ImGui::SetNextWindowPos(ImVec2(margin
, data
->height
- data
->window_size
.y
- margin
),
910 case LAYER_POSITION_BOTTOM_RIGHT
:
911 ImGui::SetNextWindowPos(ImVec2(data
->width
- data
->window_size
.x
- margin
,
912 data
->height
- data
->window_size
.y
- margin
),
918 static void compute_swapchain_display(struct swapchain_data
*data
)
920 struct device_data
*device_data
= data
->device
;
921 struct instance_data
*instance_data
= device_data
->instance
;
923 ImGui::SetCurrentContext(data
->imgui_context
);
925 position_layer(data
);
926 ImGui::Begin("Mesa overlay");
927 ImGui::Text("Device: %s", device_data
->properties
.deviceName
);
929 const char *format_name
= vk_Format_to_str(data
->format
);
930 format_name
= format_name
? (format_name
+ strlen("VK_FORMAT_")) : "unknown";
931 ImGui::Text("Swapchain format: %s", format_name
);
932 ImGui::Text("Frames: %" PRIu64
, data
->n_frames
);
933 if (instance_data
->params
.enabled
[OVERLAY_PARAM_ENABLED_fps
])
934 ImGui::Text("FPS: %.2f" , data
->fps
);
936 /* Recompute min/max */
937 for (uint32_t s
= 0; s
< OVERLAY_PARAM_ENABLED_MAX
; s
++) {
938 data
->stats_min
.stats
[s
] = UINT64_MAX
;
939 data
->stats_max
.stats
[s
] = 0;
941 for (uint32_t f
= 0; f
< MIN2(data
->n_frames
, ARRAY_SIZE(data
->frames_stats
)); f
++) {
942 for (uint32_t s
= 0; s
< OVERLAY_PARAM_ENABLED_MAX
; s
++) {
943 data
->stats_min
.stats
[s
] = MIN2(data
->frames_stats
[f
].stats
[s
],
944 data
->stats_min
.stats
[s
]);
945 data
->stats_max
.stats
[s
] = MAX2(data
->frames_stats
[f
].stats
[s
],
946 data
->stats_max
.stats
[s
]);
949 for (uint32_t s
= 0; s
< OVERLAY_PARAM_ENABLED_MAX
; s
++) {
950 assert(data
->stats_min
.stats
[s
] != UINT64_MAX
);
953 for (uint32_t s
= 0; s
< OVERLAY_PARAM_ENABLED_MAX
; s
++) {
954 if (!instance_data
->params
.enabled
[s
] ||
955 s
== OVERLAY_PARAM_ENABLED_fps
||
956 s
== OVERLAY_PARAM_ENABLED_frame
)
960 snprintf(hash
, sizeof(hash
), "##%s", overlay_param_names
[s
]);
961 data
->stat_selector
= (enum overlay_param_enabled
) s
;
962 data
->time_dividor
= 1000.0f
;
963 if (s
== OVERLAY_PARAM_ENABLED_gpu_timing
)
964 data
->time_dividor
= 1000000.0f
;
966 if (s
== OVERLAY_PARAM_ENABLED_frame_timing
||
967 s
== OVERLAY_PARAM_ENABLED_acquire_timing
||
968 s
== OVERLAY_PARAM_ENABLED_present_timing
||
969 s
== OVERLAY_PARAM_ENABLED_gpu_timing
) {
970 double min_time
= data
->stats_min
.stats
[s
] / data
->time_dividor
;
971 double max_time
= data
->stats_max
.stats
[s
] / data
->time_dividor
;
972 ImGui::PlotHistogram(hash
, get_time_stat
, data
,
973 ARRAY_SIZE(data
->frames_stats
), 0,
974 NULL
, min_time
, max_time
,
975 ImVec2(ImGui::GetContentRegionAvailWidth(), 30));
976 ImGui::Text("%s: %.3fms [%.3f, %.3f]", overlay_param_names
[s
],
977 get_time_stat(data
, ARRAY_SIZE(data
->frames_stats
) - 1),
980 ImGui::PlotHistogram(hash
, get_stat
, data
,
981 ARRAY_SIZE(data
->frames_stats
), 0,
983 data
->stats_min
.stats
[s
],
984 data
->stats_max
.stats
[s
],
985 ImVec2(ImGui::GetContentRegionAvailWidth(), 30));
986 ImGui::Text("%s: %.0f [%" PRIu64
", %" PRIu64
"]", overlay_param_names
[s
],
987 get_stat(data
, ARRAY_SIZE(data
->frames_stats
) - 1),
988 data
->stats_min
.stats
[s
], data
->stats_max
.stats
[s
]);
991 data
->window_size
= ImVec2(data
->window_size
.x
, ImGui::GetCursorPosY() + 10.0f
);
997 static uint32_t vk_memory_type(struct device_data
*data
,
998 VkMemoryPropertyFlags properties
,
1001 VkPhysicalDeviceMemoryProperties prop
;
1002 data
->instance
->vtable
.GetPhysicalDeviceMemoryProperties(data
->physical_device
, &prop
);
1003 for (uint32_t i
= 0; i
< prop
.memoryTypeCount
; i
++)
1004 if ((prop
.memoryTypes
[i
].propertyFlags
& properties
) == properties
&& type_bits
& (1<<i
))
1006 return 0xFFFFFFFF; // Unable to find memoryType
1009 static void ensure_swapchain_fonts(struct swapchain_data
*data
,
1010 VkCommandBuffer command_buffer
)
1012 if (data
->font_uploaded
)
1015 data
->font_uploaded
= true;
1017 struct device_data
*device_data
= data
->device
;
1018 ImGuiIO
& io
= ImGui::GetIO();
1019 unsigned char* pixels
;
1021 io
.Fonts
->GetTexDataAsRGBA32(&pixels
, &width
, &height
);
1022 size_t upload_size
= width
* height
* 4 * sizeof(char);
1025 VkBufferCreateInfo buffer_info
= {};
1026 buffer_info
.sType
= VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO
;
1027 buffer_info
.size
= upload_size
;
1028 buffer_info
.usage
= VK_BUFFER_USAGE_TRANSFER_SRC_BIT
;
1029 buffer_info
.sharingMode
= VK_SHARING_MODE_EXCLUSIVE
;
1030 VK_CHECK(device_data
->vtable
.CreateBuffer(device_data
->device
, &buffer_info
,
1031 NULL
, &data
->upload_font_buffer
));
1032 VkMemoryRequirements upload_buffer_req
;
1033 device_data
->vtable
.GetBufferMemoryRequirements(device_data
->device
,
1034 data
->upload_font_buffer
,
1035 &upload_buffer_req
);
1036 VkMemoryAllocateInfo upload_alloc_info
= {};
1037 upload_alloc_info
.sType
= VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO
;
1038 upload_alloc_info
.allocationSize
= upload_buffer_req
.size
;
1039 upload_alloc_info
.memoryTypeIndex
= vk_memory_type(device_data
,
1040 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT
,
1041 upload_buffer_req
.memoryTypeBits
);
1042 VK_CHECK(device_data
->vtable
.AllocateMemory(device_data
->device
,
1045 &data
->upload_font_buffer_mem
));
1046 VK_CHECK(device_data
->vtable
.BindBufferMemory(device_data
->device
,
1047 data
->upload_font_buffer
,
1048 data
->upload_font_buffer_mem
, 0));
1050 /* Upload to Buffer */
1052 VK_CHECK(device_data
->vtable
.MapMemory(device_data
->device
,
1053 data
->upload_font_buffer_mem
,
1054 0, upload_size
, 0, (void**)(&map
)));
1055 memcpy(map
, pixels
, upload_size
);
1056 VkMappedMemoryRange range
[1] = {};
1057 range
[0].sType
= VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE
;
1058 range
[0].memory
= data
->upload_font_buffer_mem
;
1059 range
[0].size
= upload_size
;
1060 VK_CHECK(device_data
->vtable
.FlushMappedMemoryRanges(device_data
->device
, 1, range
));
1061 device_data
->vtable
.UnmapMemory(device_data
->device
,
1062 data
->upload_font_buffer_mem
);
1064 /* Copy buffer to image */
1065 VkImageMemoryBarrier copy_barrier
[1] = {};
1066 copy_barrier
[0].sType
= VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER
;
1067 copy_barrier
[0].dstAccessMask
= VK_ACCESS_TRANSFER_WRITE_BIT
;
1068 copy_barrier
[0].oldLayout
= VK_IMAGE_LAYOUT_UNDEFINED
;
1069 copy_barrier
[0].newLayout
= VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
;
1070 copy_barrier
[0].srcQueueFamilyIndex
= VK_QUEUE_FAMILY_IGNORED
;
1071 copy_barrier
[0].dstQueueFamilyIndex
= VK_QUEUE_FAMILY_IGNORED
;
1072 copy_barrier
[0].image
= data
->font_image
;
1073 copy_barrier
[0].subresourceRange
.aspectMask
= VK_IMAGE_ASPECT_COLOR_BIT
;
1074 copy_barrier
[0].subresourceRange
.levelCount
= 1;
1075 copy_barrier
[0].subresourceRange
.layerCount
= 1;
1076 device_data
->vtable
.CmdPipelineBarrier(command_buffer
,
1077 VK_PIPELINE_STAGE_HOST_BIT
,
1078 VK_PIPELINE_STAGE_TRANSFER_BIT
,
1079 0, 0, NULL
, 0, NULL
,
1082 VkBufferImageCopy region
= {};
1083 region
.imageSubresource
.aspectMask
= VK_IMAGE_ASPECT_COLOR_BIT
;
1084 region
.imageSubresource
.layerCount
= 1;
1085 region
.imageExtent
.width
= width
;
1086 region
.imageExtent
.height
= height
;
1087 region
.imageExtent
.depth
= 1;
1088 device_data
->vtable
.CmdCopyBufferToImage(command_buffer
,
1089 data
->upload_font_buffer
,
1091 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
,
1094 VkImageMemoryBarrier use_barrier
[1] = {};
1095 use_barrier
[0].sType
= VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER
;
1096 use_barrier
[0].srcAccessMask
= VK_ACCESS_TRANSFER_WRITE_BIT
;
1097 use_barrier
[0].dstAccessMask
= VK_ACCESS_SHADER_READ_BIT
;
1098 use_barrier
[0].oldLayout
= VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
;
1099 use_barrier
[0].newLayout
= VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
;
1100 use_barrier
[0].srcQueueFamilyIndex
= VK_QUEUE_FAMILY_IGNORED
;
1101 use_barrier
[0].dstQueueFamilyIndex
= VK_QUEUE_FAMILY_IGNORED
;
1102 use_barrier
[0].image
= data
->font_image
;
1103 use_barrier
[0].subresourceRange
.aspectMask
= VK_IMAGE_ASPECT_COLOR_BIT
;
1104 use_barrier
[0].subresourceRange
.levelCount
= 1;
1105 use_barrier
[0].subresourceRange
.layerCount
= 1;
1106 device_data
->vtable
.CmdPipelineBarrier(command_buffer
,
1107 VK_PIPELINE_STAGE_TRANSFER_BIT
,
1108 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT
,
1114 /* Store our identifier */
1115 io
.Fonts
->TexID
= (ImTextureID
)(intptr_t)data
->font_image
;
1118 static void CreateOrResizeBuffer(struct device_data
*data
,
1120 VkDeviceMemory
*buffer_memory
,
1121 VkDeviceSize
*buffer_size
,
1122 size_t new_size
, VkBufferUsageFlagBits usage
)
1124 if (*buffer
!= VK_NULL_HANDLE
)
1125 data
->vtable
.DestroyBuffer(data
->device
, *buffer
, NULL
);
1127 data
->vtable
.FreeMemory(data
->device
, *buffer_memory
, NULL
);
1129 VkBufferCreateInfo buffer_info
= {};
1130 buffer_info
.sType
= VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO
;
1131 buffer_info
.size
= new_size
;
1132 buffer_info
.usage
= usage
;
1133 buffer_info
.sharingMode
= VK_SHARING_MODE_EXCLUSIVE
;
1134 VK_CHECK(data
->vtable
.CreateBuffer(data
->device
, &buffer_info
, NULL
, buffer
));
1136 VkMemoryRequirements req
;
1137 data
->vtable
.GetBufferMemoryRequirements(data
->device
, *buffer
, &req
);
1138 VkMemoryAllocateInfo alloc_info
= {};
1139 alloc_info
.sType
= VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO
;
1140 alloc_info
.allocationSize
= req
.size
;
1141 alloc_info
.memoryTypeIndex
=
1142 vk_memory_type(data
, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT
, req
.memoryTypeBits
);
1143 VK_CHECK(data
->vtable
.AllocateMemory(data
->device
, &alloc_info
, NULL
, buffer_memory
));
1145 VK_CHECK(data
->vtable
.BindBufferMemory(data
->device
, *buffer
, *buffer_memory
, 0));
1146 *buffer_size
= new_size
;
1149 static struct overlay_draw
*render_swapchain_display(struct swapchain_data
*data
,
1150 struct queue_data
*present_queue
,
1151 const VkSemaphore
*wait_semaphores
,
1152 unsigned n_wait_semaphores
,
1153 unsigned image_index
)
1155 ImDrawData
* draw_data
= ImGui::GetDrawData();
1156 if (draw_data
->TotalVtxCount
== 0)
1159 struct device_data
*device_data
= data
->device
;
1160 struct overlay_draw
*draw
= get_overlay_draw(data
);
1162 device_data
->vtable
.ResetCommandBuffer(draw
->command_buffer
, 0);
1164 VkRenderPassBeginInfo render_pass_info
= {};
1165 render_pass_info
.sType
= VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO
;
1166 render_pass_info
.renderPass
= data
->render_pass
;
1167 render_pass_info
.framebuffer
= data
->framebuffers
[image_index
];
1168 render_pass_info
.renderArea
.extent
.width
= data
->width
;
1169 render_pass_info
.renderArea
.extent
.height
= data
->height
;
1171 VkCommandBufferBeginInfo buffer_begin_info
= {};
1172 buffer_begin_info
.sType
= VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO
;
1174 device_data
->vtable
.BeginCommandBuffer(draw
->command_buffer
, &buffer_begin_info
);
1176 ensure_swapchain_fonts(data
, draw
->command_buffer
);
1178 /* Bounce the image to display back to color attachment layout for
1179 * rendering on top of it.
1181 VkImageMemoryBarrier imb
;
1182 imb
.sType
= VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER
;
1183 imb
.pNext
= nullptr;
1184 imb
.srcAccessMask
= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT
;
1185 imb
.dstAccessMask
= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT
;
1186 imb
.oldLayout
= VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
;
1187 imb
.newLayout
= VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
;
1188 imb
.image
= data
->images
[image_index
];
1189 imb
.subresourceRange
.aspectMask
= VK_IMAGE_ASPECT_COLOR_BIT
;
1190 imb
.subresourceRange
.baseMipLevel
= 0;
1191 imb
.subresourceRange
.levelCount
= 1;
1192 imb
.subresourceRange
.baseArrayLayer
= 0;
1193 imb
.subresourceRange
.layerCount
= 1;
1194 imb
.srcQueueFamilyIndex
= present_queue
->family_index
;
1195 imb
.dstQueueFamilyIndex
= device_data
->graphic_queue
->family_index
;
1196 device_data
->vtable
.CmdPipelineBarrier(draw
->command_buffer
,
1197 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT
,
1198 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT
,
1199 0, /* dependency flags */
1200 0, nullptr, /* memory barriers */
1201 0, nullptr, /* buffer memory barriers */
1202 1, &imb
); /* image memory barriers */
1204 device_data
->vtable
.CmdBeginRenderPass(draw
->command_buffer
, &render_pass_info
,
1205 VK_SUBPASS_CONTENTS_INLINE
);
1207 /* Create/Resize vertex & index buffers */
1208 size_t vertex_size
= draw_data
->TotalVtxCount
* sizeof(ImDrawVert
);
1209 size_t index_size
= draw_data
->TotalIdxCount
* sizeof(ImDrawIdx
);
1210 if (draw
->vertex_buffer_size
< vertex_size
) {
1211 CreateOrResizeBuffer(device_data
,
1212 &draw
->vertex_buffer
,
1213 &draw
->vertex_buffer_mem
,
1214 &draw
->vertex_buffer_size
,
1215 vertex_size
, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT
);
1217 if (draw
->index_buffer_size
< index_size
) {
1218 CreateOrResizeBuffer(device_data
,
1219 &draw
->index_buffer
,
1220 &draw
->index_buffer_mem
,
1221 &draw
->index_buffer_size
,
1222 index_size
, VK_BUFFER_USAGE_INDEX_BUFFER_BIT
);
1225 /* Upload vertex & index data */
1226 ImDrawVert
* vtx_dst
= NULL
;
1227 ImDrawIdx
* idx_dst
= NULL
;
1228 VK_CHECK(device_data
->vtable
.MapMemory(device_data
->device
, draw
->vertex_buffer_mem
,
1229 0, vertex_size
, 0, (void**)(&vtx_dst
)));
1230 VK_CHECK(device_data
->vtable
.MapMemory(device_data
->device
, draw
->index_buffer_mem
,
1231 0, index_size
, 0, (void**)(&idx_dst
)));
1232 for (int n
= 0; n
< draw_data
->CmdListsCount
; n
++)
1234 const ImDrawList
* cmd_list
= draw_data
->CmdLists
[n
];
1235 memcpy(vtx_dst
, cmd_list
->VtxBuffer
.Data
, cmd_list
->VtxBuffer
.Size
* sizeof(ImDrawVert
));
1236 memcpy(idx_dst
, cmd_list
->IdxBuffer
.Data
, cmd_list
->IdxBuffer
.Size
* sizeof(ImDrawIdx
));
1237 vtx_dst
+= cmd_list
->VtxBuffer
.Size
;
1238 idx_dst
+= cmd_list
->IdxBuffer
.Size
;
1240 VkMappedMemoryRange range
[2] = {};
1241 range
[0].sType
= VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE
;
1242 range
[0].memory
= draw
->vertex_buffer_mem
;
1243 range
[0].size
= VK_WHOLE_SIZE
;
1244 range
[1].sType
= VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE
;
1245 range
[1].memory
= draw
->index_buffer_mem
;
1246 range
[1].size
= VK_WHOLE_SIZE
;
1247 VK_CHECK(device_data
->vtable
.FlushMappedMemoryRanges(device_data
->device
, 2, range
));
1248 device_data
->vtable
.UnmapMemory(device_data
->device
, draw
->vertex_buffer_mem
);
1249 device_data
->vtable
.UnmapMemory(device_data
->device
, draw
->index_buffer_mem
);
1251 /* Bind pipeline and descriptor sets */
1252 device_data
->vtable
.CmdBindPipeline(draw
->command_buffer
, VK_PIPELINE_BIND_POINT_GRAPHICS
, data
->pipeline
);
1253 VkDescriptorSet desc_set
[1] = { data
->descriptor_set
};
1254 device_data
->vtable
.CmdBindDescriptorSets(draw
->command_buffer
, VK_PIPELINE_BIND_POINT_GRAPHICS
,
1255 data
->pipeline_layout
, 0, 1, desc_set
, 0, NULL
);
1257 /* Bind vertex & index buffers */
1258 VkBuffer vertex_buffers
[1] = { draw
->vertex_buffer
};
1259 VkDeviceSize vertex_offset
[1] = { 0 };
1260 device_data
->vtable
.CmdBindVertexBuffers(draw
->command_buffer
, 0, 1, vertex_buffers
, vertex_offset
);
1261 device_data
->vtable
.CmdBindIndexBuffer(draw
->command_buffer
, draw
->index_buffer
, 0, VK_INDEX_TYPE_UINT16
);
1263 /* Setup viewport */
1264 VkViewport viewport
;
1267 viewport
.width
= draw_data
->DisplaySize
.x
;
1268 viewport
.height
= draw_data
->DisplaySize
.y
;
1269 viewport
.minDepth
= 0.0f
;
1270 viewport
.maxDepth
= 1.0f
;
1271 device_data
->vtable
.CmdSetViewport(draw
->command_buffer
, 0, 1, &viewport
);
1274 /* Setup scale and translation through push constants :
1276 * Our visible imgui space lies from draw_data->DisplayPos (top left) to
1277 * draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin
1278 * is typically (0,0) for single viewport apps.
1281 scale
[0] = 2.0f
/ draw_data
->DisplaySize
.x
;
1282 scale
[1] = 2.0f
/ draw_data
->DisplaySize
.y
;
1284 translate
[0] = -1.0f
- draw_data
->DisplayPos
.x
* scale
[0];
1285 translate
[1] = -1.0f
- draw_data
->DisplayPos
.y
* scale
[1];
1286 device_data
->vtable
.CmdPushConstants(draw
->command_buffer
, data
->pipeline_layout
,
1287 VK_SHADER_STAGE_VERTEX_BIT
,
1288 sizeof(float) * 0, sizeof(float) * 2, scale
);
1289 device_data
->vtable
.CmdPushConstants(draw
->command_buffer
, data
->pipeline_layout
,
1290 VK_SHADER_STAGE_VERTEX_BIT
,
1291 sizeof(float) * 2, sizeof(float) * 2, translate
);
1293 // Render the command lists:
1296 ImVec2 display_pos
= draw_data
->DisplayPos
;
1297 for (int n
= 0; n
< draw_data
->CmdListsCount
; n
++)
1299 const ImDrawList
* cmd_list
= draw_data
->CmdLists
[n
];
1300 for (int cmd_i
= 0; cmd_i
< cmd_list
->CmdBuffer
.Size
; cmd_i
++)
1302 const ImDrawCmd
* pcmd
= &cmd_list
->CmdBuffer
[cmd_i
];
1303 // Apply scissor/clipping rectangle
1304 // FIXME: We could clamp width/height based on clamped min/max values.
1306 scissor
.offset
.x
= (int32_t)(pcmd
->ClipRect
.x
- display_pos
.x
) > 0 ? (int32_t)(pcmd
->ClipRect
.x
- display_pos
.x
) : 0;
1307 scissor
.offset
.y
= (int32_t)(pcmd
->ClipRect
.y
- display_pos
.y
) > 0 ? (int32_t)(pcmd
->ClipRect
.y
- display_pos
.y
) : 0;
1308 scissor
.extent
.width
= (uint32_t)(pcmd
->ClipRect
.z
- pcmd
->ClipRect
.x
);
1309 scissor
.extent
.height
= (uint32_t)(pcmd
->ClipRect
.w
- pcmd
->ClipRect
.y
+ 1); // FIXME: Why +1 here?
1310 device_data
->vtable
.CmdSetScissor(draw
->command_buffer
, 0, 1, &scissor
);
1313 device_data
->vtable
.CmdDrawIndexed(draw
->command_buffer
, pcmd
->ElemCount
, 1, idx_offset
, vtx_offset
, 0);
1315 idx_offset
+= pcmd
->ElemCount
;
1317 vtx_offset
+= cmd_list
->VtxBuffer
.Size
;
1320 device_data
->vtable
.CmdEndRenderPass(draw
->command_buffer
);
1322 /* Bounce the image to display back to present layout. */
1323 imb
.sType
= VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER
;
1324 imb
.pNext
= nullptr;
1325 imb
.srcAccessMask
= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT
;
1326 imb
.dstAccessMask
= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT
;
1327 imb
.oldLayout
= VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
;
1328 imb
.newLayout
= VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
;
1329 imb
.image
= data
->images
[image_index
];
1330 imb
.subresourceRange
.aspectMask
= VK_IMAGE_ASPECT_COLOR_BIT
;
1331 imb
.subresourceRange
.baseMipLevel
= 0;
1332 imb
.subresourceRange
.levelCount
= 1;
1333 imb
.subresourceRange
.baseArrayLayer
= 0;
1334 imb
.subresourceRange
.layerCount
= 1;
1335 imb
.srcQueueFamilyIndex
= device_data
->graphic_queue
->family_index
;
1336 imb
.dstQueueFamilyIndex
= present_queue
->family_index
;
1337 device_data
->vtable
.CmdPipelineBarrier(draw
->command_buffer
,
1338 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT
,
1339 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT
,
1340 0, /* dependency flags */
1341 0, nullptr, /* memory barriers */
1342 0, nullptr, /* buffer memory barriers */
1343 1, &imb
); /* image memory barriers */
1345 device_data
->vtable
.EndCommandBuffer(draw
->command_buffer
);
1347 VkSubmitInfo submit_info
= {};
1348 VkPipelineStageFlags stage_wait
= VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT
;
1349 submit_info
.sType
= VK_STRUCTURE_TYPE_SUBMIT_INFO
;
1350 submit_info
.commandBufferCount
= 1;
1351 submit_info
.pCommandBuffers
= &draw
->command_buffer
;
1352 submit_info
.pWaitDstStageMask
= &stage_wait
;
1353 submit_info
.waitSemaphoreCount
= n_wait_semaphores
;
1354 submit_info
.pWaitSemaphores
= wait_semaphores
;
1355 submit_info
.signalSemaphoreCount
= 1;
1356 submit_info
.pSignalSemaphores
= &draw
->semaphore
;
1358 device_data
->vtable
.QueueSubmit(device_data
->graphic_queue
->queue
, 1, &submit_info
, draw
->fence
);
1363 static const uint32_t overlay_vert_spv
[] = {
1364 #include "overlay.vert.spv.h"
1366 static const uint32_t overlay_frag_spv
[] = {
1367 #include "overlay.frag.spv.h"
1370 static void setup_swapchain_data_pipeline(struct swapchain_data
*data
)
1372 struct device_data
*device_data
= data
->device
;
1373 VkShaderModule vert_module
, frag_module
;
1375 /* Create shader modules */
1376 VkShaderModuleCreateInfo vert_info
= {};
1377 vert_info
.sType
= VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO
;
1378 vert_info
.codeSize
= sizeof(overlay_vert_spv
);
1379 vert_info
.pCode
= overlay_vert_spv
;
1380 VK_CHECK(device_data
->vtable
.CreateShaderModule(device_data
->device
,
1381 &vert_info
, NULL
, &vert_module
));
1382 VkShaderModuleCreateInfo frag_info
= {};
1383 frag_info
.sType
= VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO
;
1384 frag_info
.codeSize
= sizeof(overlay_frag_spv
);
1385 frag_info
.pCode
= (uint32_t*)overlay_frag_spv
;
1386 VK_CHECK(device_data
->vtable
.CreateShaderModule(device_data
->device
,
1387 &frag_info
, NULL
, &frag_module
));
1390 VkSamplerCreateInfo sampler_info
= {};
1391 sampler_info
.sType
= VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO
;
1392 sampler_info
.magFilter
= VK_FILTER_LINEAR
;
1393 sampler_info
.minFilter
= VK_FILTER_LINEAR
;
1394 sampler_info
.mipmapMode
= VK_SAMPLER_MIPMAP_MODE_LINEAR
;
1395 sampler_info
.addressModeU
= VK_SAMPLER_ADDRESS_MODE_REPEAT
;
1396 sampler_info
.addressModeV
= VK_SAMPLER_ADDRESS_MODE_REPEAT
;
1397 sampler_info
.addressModeW
= VK_SAMPLER_ADDRESS_MODE_REPEAT
;
1398 sampler_info
.minLod
= -1000;
1399 sampler_info
.maxLod
= 1000;
1400 sampler_info
.maxAnisotropy
= 1.0f
;
1401 VK_CHECK(device_data
->vtable
.CreateSampler(device_data
->device
, &sampler_info
,
1402 NULL
, &data
->font_sampler
));
1404 /* Descriptor pool */
1405 VkDescriptorPoolSize sampler_pool_size
= {};
1406 sampler_pool_size
.type
= VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER
;
1407 sampler_pool_size
.descriptorCount
= 1;
1408 VkDescriptorPoolCreateInfo desc_pool_info
= {};
1409 desc_pool_info
.sType
= VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO
;
1410 desc_pool_info
.maxSets
= 1;
1411 desc_pool_info
.poolSizeCount
= 1;
1412 desc_pool_info
.pPoolSizes
= &sampler_pool_size
;
1413 VK_CHECK(device_data
->vtable
.CreateDescriptorPool(device_data
->device
,
1415 NULL
, &data
->descriptor_pool
));
1417 /* Descriptor layout */
1418 VkSampler sampler
[1] = { data
->font_sampler
};
1419 VkDescriptorSetLayoutBinding binding
[1] = {};
1420 binding
[0].descriptorType
= VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER
;
1421 binding
[0].descriptorCount
= 1;
1422 binding
[0].stageFlags
= VK_SHADER_STAGE_FRAGMENT_BIT
;
1423 binding
[0].pImmutableSamplers
= sampler
;
1424 VkDescriptorSetLayoutCreateInfo set_layout_info
= {};
1425 set_layout_info
.sType
= VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO
;
1426 set_layout_info
.bindingCount
= 1;
1427 set_layout_info
.pBindings
= binding
;
1428 VK_CHECK(device_data
->vtable
.CreateDescriptorSetLayout(device_data
->device
,
1430 NULL
, &data
->descriptor_layout
));
1432 /* Descriptor set */
1433 VkDescriptorSetAllocateInfo alloc_info
= {};
1434 alloc_info
.sType
= VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO
;
1435 alloc_info
.descriptorPool
= data
->descriptor_pool
;
1436 alloc_info
.descriptorSetCount
= 1;
1437 alloc_info
.pSetLayouts
= &data
->descriptor_layout
;
1438 VK_CHECK(device_data
->vtable
.AllocateDescriptorSets(device_data
->device
,
1440 &data
->descriptor_set
));
1442 /* Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full
1443 * 3d projection matrix
1445 VkPushConstantRange push_constants
[1] = {};
1446 push_constants
[0].stageFlags
= VK_SHADER_STAGE_VERTEX_BIT
;
1447 push_constants
[0].offset
= sizeof(float) * 0;
1448 push_constants
[0].size
= sizeof(float) * 4;
1449 VkPipelineLayoutCreateInfo layout_info
= {};
1450 layout_info
.sType
= VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO
;
1451 layout_info
.setLayoutCount
= 1;
1452 layout_info
.pSetLayouts
= &data
->descriptor_layout
;
1453 layout_info
.pushConstantRangeCount
= 1;
1454 layout_info
.pPushConstantRanges
= push_constants
;
1455 VK_CHECK(device_data
->vtable
.CreatePipelineLayout(device_data
->device
,
1457 NULL
, &data
->pipeline_layout
));
1459 VkPipelineShaderStageCreateInfo stage
[2] = {};
1460 stage
[0].sType
= VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO
;
1461 stage
[0].stage
= VK_SHADER_STAGE_VERTEX_BIT
;
1462 stage
[0].module
= vert_module
;
1463 stage
[0].pName
= "main";
1464 stage
[1].sType
= VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO
;
1465 stage
[1].stage
= VK_SHADER_STAGE_FRAGMENT_BIT
;
1466 stage
[1].module
= frag_module
;
1467 stage
[1].pName
= "main";
1469 VkVertexInputBindingDescription binding_desc
[1] = {};
1470 binding_desc
[0].stride
= sizeof(ImDrawVert
);
1471 binding_desc
[0].inputRate
= VK_VERTEX_INPUT_RATE_VERTEX
;
1473 VkVertexInputAttributeDescription attribute_desc
[3] = {};
1474 attribute_desc
[0].location
= 0;
1475 attribute_desc
[0].binding
= binding_desc
[0].binding
;
1476 attribute_desc
[0].format
= VK_FORMAT_R32G32_SFLOAT
;
1477 attribute_desc
[0].offset
= IM_OFFSETOF(ImDrawVert
, pos
);
1478 attribute_desc
[1].location
= 1;
1479 attribute_desc
[1].binding
= binding_desc
[0].binding
;
1480 attribute_desc
[1].format
= VK_FORMAT_R32G32_SFLOAT
;
1481 attribute_desc
[1].offset
= IM_OFFSETOF(ImDrawVert
, uv
);
1482 attribute_desc
[2].location
= 2;
1483 attribute_desc
[2].binding
= binding_desc
[0].binding
;
1484 attribute_desc
[2].format
= VK_FORMAT_R8G8B8A8_UNORM
;
1485 attribute_desc
[2].offset
= IM_OFFSETOF(ImDrawVert
, col
);
1487 VkPipelineVertexInputStateCreateInfo vertex_info
= {};
1488 vertex_info
.sType
= VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO
;
1489 vertex_info
.vertexBindingDescriptionCount
= 1;
1490 vertex_info
.pVertexBindingDescriptions
= binding_desc
;
1491 vertex_info
.vertexAttributeDescriptionCount
= 3;
1492 vertex_info
.pVertexAttributeDescriptions
= attribute_desc
;
1494 VkPipelineInputAssemblyStateCreateInfo ia_info
= {};
1495 ia_info
.sType
= VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO
;
1496 ia_info
.topology
= VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST
;
1498 VkPipelineViewportStateCreateInfo viewport_info
= {};
1499 viewport_info
.sType
= VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO
;
1500 viewport_info
.viewportCount
= 1;
1501 viewport_info
.scissorCount
= 1;
1503 VkPipelineRasterizationStateCreateInfo raster_info
= {};
1504 raster_info
.sType
= VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO
;
1505 raster_info
.polygonMode
= VK_POLYGON_MODE_FILL
;
1506 raster_info
.cullMode
= VK_CULL_MODE_NONE
;
1507 raster_info
.frontFace
= VK_FRONT_FACE_COUNTER_CLOCKWISE
;
1508 raster_info
.lineWidth
= 1.0f
;
1510 VkPipelineMultisampleStateCreateInfo ms_info
= {};
1511 ms_info
.sType
= VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO
;
1512 ms_info
.rasterizationSamples
= VK_SAMPLE_COUNT_1_BIT
;
1514 VkPipelineColorBlendAttachmentState color_attachment
[1] = {};
1515 color_attachment
[0].blendEnable
= VK_TRUE
;
1516 color_attachment
[0].srcColorBlendFactor
= VK_BLEND_FACTOR_SRC_ALPHA
;
1517 color_attachment
[0].dstColorBlendFactor
= VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA
;
1518 color_attachment
[0].colorBlendOp
= VK_BLEND_OP_ADD
;
1519 color_attachment
[0].srcAlphaBlendFactor
= VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA
;
1520 color_attachment
[0].dstAlphaBlendFactor
= VK_BLEND_FACTOR_ZERO
;
1521 color_attachment
[0].alphaBlendOp
= VK_BLEND_OP_ADD
;
1522 color_attachment
[0].colorWriteMask
= VK_COLOR_COMPONENT_R_BIT
|
1523 VK_COLOR_COMPONENT_G_BIT
| VK_COLOR_COMPONENT_B_BIT
| VK_COLOR_COMPONENT_A_BIT
;
1525 VkPipelineDepthStencilStateCreateInfo depth_info
= {};
1526 depth_info
.sType
= VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO
;
1528 VkPipelineColorBlendStateCreateInfo blend_info
= {};
1529 blend_info
.sType
= VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO
;
1530 blend_info
.attachmentCount
= 1;
1531 blend_info
.pAttachments
= color_attachment
;
1533 VkDynamicState dynamic_states
[2] = { VK_DYNAMIC_STATE_VIEWPORT
, VK_DYNAMIC_STATE_SCISSOR
};
1534 VkPipelineDynamicStateCreateInfo dynamic_state
= {};
1535 dynamic_state
.sType
= VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO
;
1536 dynamic_state
.dynamicStateCount
= (uint32_t)IM_ARRAYSIZE(dynamic_states
);
1537 dynamic_state
.pDynamicStates
= dynamic_states
;
1539 VkGraphicsPipelineCreateInfo info
= {};
1540 info
.sType
= VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO
;
1542 info
.stageCount
= 2;
1543 info
.pStages
= stage
;
1544 info
.pVertexInputState
= &vertex_info
;
1545 info
.pInputAssemblyState
= &ia_info
;
1546 info
.pViewportState
= &viewport_info
;
1547 info
.pRasterizationState
= &raster_info
;
1548 info
.pMultisampleState
= &ms_info
;
1549 info
.pDepthStencilState
= &depth_info
;
1550 info
.pColorBlendState
= &blend_info
;
1551 info
.pDynamicState
= &dynamic_state
;
1552 info
.layout
= data
->pipeline_layout
;
1553 info
.renderPass
= data
->render_pass
;
1555 device_data
->vtable
.CreateGraphicsPipelines(device_data
->device
, VK_NULL_HANDLE
,
1557 NULL
, &data
->pipeline
));
1559 device_data
->vtable
.DestroyShaderModule(device_data
->device
, vert_module
, NULL
);
1560 device_data
->vtable
.DestroyShaderModule(device_data
->device
, frag_module
, NULL
);
1562 ImGuiIO
& io
= ImGui::GetIO();
1563 unsigned char* pixels
;
1565 io
.Fonts
->GetTexDataAsRGBA32(&pixels
, &width
, &height
);
1568 VkImageCreateInfo image_info
= {};
1569 image_info
.sType
= VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO
;
1570 image_info
.imageType
= VK_IMAGE_TYPE_2D
;
1571 image_info
.format
= VK_FORMAT_R8G8B8A8_UNORM
;
1572 image_info
.extent
.width
= width
;
1573 image_info
.extent
.height
= height
;
1574 image_info
.extent
.depth
= 1;
1575 image_info
.mipLevels
= 1;
1576 image_info
.arrayLayers
= 1;
1577 image_info
.samples
= VK_SAMPLE_COUNT_1_BIT
;
1578 image_info
.tiling
= VK_IMAGE_TILING_OPTIMAL
;
1579 image_info
.usage
= VK_IMAGE_USAGE_SAMPLED_BIT
| VK_IMAGE_USAGE_TRANSFER_DST_BIT
;
1580 image_info
.sharingMode
= VK_SHARING_MODE_EXCLUSIVE
;
1581 image_info
.initialLayout
= VK_IMAGE_LAYOUT_UNDEFINED
;
1582 VK_CHECK(device_data
->vtable
.CreateImage(device_data
->device
, &image_info
,
1583 NULL
, &data
->font_image
));
1584 VkMemoryRequirements font_image_req
;
1585 device_data
->vtable
.GetImageMemoryRequirements(device_data
->device
,
1586 data
->font_image
, &font_image_req
);
1587 VkMemoryAllocateInfo image_alloc_info
= {};
1588 image_alloc_info
.sType
= VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO
;
1589 image_alloc_info
.allocationSize
= font_image_req
.size
;
1590 image_alloc_info
.memoryTypeIndex
= vk_memory_type(device_data
,
1591 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT
,
1592 font_image_req
.memoryTypeBits
);
1593 VK_CHECK(device_data
->vtable
.AllocateMemory(device_data
->device
, &image_alloc_info
,
1594 NULL
, &data
->font_mem
));
1595 VK_CHECK(device_data
->vtable
.BindImageMemory(device_data
->device
,
1597 data
->font_mem
, 0));
1599 /* Font image view */
1600 VkImageViewCreateInfo view_info
= {};
1601 view_info
.sType
= VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO
;
1602 view_info
.image
= data
->font_image
;
1603 view_info
.viewType
= VK_IMAGE_VIEW_TYPE_2D
;
1604 view_info
.format
= VK_FORMAT_R8G8B8A8_UNORM
;
1605 view_info
.subresourceRange
.aspectMask
= VK_IMAGE_ASPECT_COLOR_BIT
;
1606 view_info
.subresourceRange
.levelCount
= 1;
1607 view_info
.subresourceRange
.layerCount
= 1;
1608 VK_CHECK(device_data
->vtable
.CreateImageView(device_data
->device
, &view_info
,
1609 NULL
, &data
->font_image_view
));
1611 /* Descriptor set */
1612 VkDescriptorImageInfo desc_image
[1] = {};
1613 desc_image
[0].sampler
= data
->font_sampler
;
1614 desc_image
[0].imageView
= data
->font_image_view
;
1615 desc_image
[0].imageLayout
= VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
;
1616 VkWriteDescriptorSet write_desc
[1] = {};
1617 write_desc
[0].sType
= VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET
;
1618 write_desc
[0].dstSet
= data
->descriptor_set
;
1619 write_desc
[0].descriptorCount
= 1;
1620 write_desc
[0].descriptorType
= VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER
;
1621 write_desc
[0].pImageInfo
= desc_image
;
1622 device_data
->vtable
.UpdateDescriptorSets(device_data
->device
, 1, write_desc
, 0, NULL
);
1625 static void setup_swapchain_data(struct swapchain_data
*data
,
1626 const VkSwapchainCreateInfoKHR
*pCreateInfo
)
1628 data
->width
= pCreateInfo
->imageExtent
.width
;
1629 data
->height
= pCreateInfo
->imageExtent
.height
;
1630 data
->format
= pCreateInfo
->imageFormat
;
1632 data
->imgui_context
= ImGui::CreateContext();
1633 ImGui::SetCurrentContext(data
->imgui_context
);
1635 ImGui::GetIO().IniFilename
= NULL
;
1636 ImGui::GetIO().DisplaySize
= ImVec2((float)data
->width
, (float)data
->height
);
1638 struct device_data
*device_data
= data
->device
;
1641 VkAttachmentDescription attachment_desc
= {};
1642 attachment_desc
.format
= pCreateInfo
->imageFormat
;
1643 attachment_desc
.samples
= VK_SAMPLE_COUNT_1_BIT
;
1644 attachment_desc
.loadOp
= VK_ATTACHMENT_LOAD_OP_LOAD
;
1645 attachment_desc
.storeOp
= VK_ATTACHMENT_STORE_OP_STORE
;
1646 attachment_desc
.stencilLoadOp
= VK_ATTACHMENT_LOAD_OP_DONT_CARE
;
1647 attachment_desc
.stencilStoreOp
= VK_ATTACHMENT_STORE_OP_DONT_CARE
;
1648 attachment_desc
.initialLayout
= VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
;
1649 attachment_desc
.finalLayout
= VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
;
1650 VkAttachmentReference color_attachment
= {};
1651 color_attachment
.attachment
= 0;
1652 color_attachment
.layout
= VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
;
1653 VkSubpassDescription subpass
= {};
1654 subpass
.pipelineBindPoint
= VK_PIPELINE_BIND_POINT_GRAPHICS
;
1655 subpass
.colorAttachmentCount
= 1;
1656 subpass
.pColorAttachments
= &color_attachment
;
1657 VkSubpassDependency dependency
= {};
1658 dependency
.srcSubpass
= VK_SUBPASS_EXTERNAL
;
1659 dependency
.dstSubpass
= 0;
1660 dependency
.srcStageMask
= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT
;
1661 dependency
.dstStageMask
= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT
;
1662 dependency
.srcAccessMask
= 0;
1663 dependency
.dstAccessMask
= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT
;
1664 VkRenderPassCreateInfo render_pass_info
= {};
1665 render_pass_info
.sType
= VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO
;
1666 render_pass_info
.attachmentCount
= 1;
1667 render_pass_info
.pAttachments
= &attachment_desc
;
1668 render_pass_info
.subpassCount
= 1;
1669 render_pass_info
.pSubpasses
= &subpass
;
1670 render_pass_info
.dependencyCount
= 1;
1671 render_pass_info
.pDependencies
= &dependency
;
1672 VK_CHECK(device_data
->vtable
.CreateRenderPass(device_data
->device
,
1674 NULL
, &data
->render_pass
));
1676 setup_swapchain_data_pipeline(data
);
1678 VK_CHECK(device_data
->vtable
.GetSwapchainImagesKHR(device_data
->device
,
1683 data
->images
= ralloc_array(data
, VkImage
, data
->n_images
);
1684 data
->image_views
= ralloc_array(data
, VkImageView
, data
->n_images
);
1685 data
->framebuffers
= ralloc_array(data
, VkFramebuffer
, data
->n_images
);
1687 VK_CHECK(device_data
->vtable
.GetSwapchainImagesKHR(device_data
->device
,
1693 VkImageViewCreateInfo view_info
= {};
1694 view_info
.sType
= VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO
;
1695 view_info
.viewType
= VK_IMAGE_VIEW_TYPE_2D
;
1696 view_info
.format
= pCreateInfo
->imageFormat
;
1697 view_info
.components
.r
= VK_COMPONENT_SWIZZLE_R
;
1698 view_info
.components
.g
= VK_COMPONENT_SWIZZLE_G
;
1699 view_info
.components
.b
= VK_COMPONENT_SWIZZLE_B
;
1700 view_info
.components
.a
= VK_COMPONENT_SWIZZLE_A
;
1701 view_info
.subresourceRange
= { VK_IMAGE_ASPECT_COLOR_BIT
, 0, 1, 0, 1 };
1702 for (uint32_t i
= 0; i
< data
->n_images
; i
++) {
1703 view_info
.image
= data
->images
[i
];
1704 VK_CHECK(device_data
->vtable
.CreateImageView(device_data
->device
,
1706 &data
->image_views
[i
]));
1710 VkImageView attachment
[1];
1711 VkFramebufferCreateInfo fb_info
= {};
1712 fb_info
.sType
= VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO
;
1713 fb_info
.renderPass
= data
->render_pass
;
1714 fb_info
.attachmentCount
= 1;
1715 fb_info
.pAttachments
= attachment
;
1716 fb_info
.width
= data
->width
;
1717 fb_info
.height
= data
->height
;
1719 for (uint32_t i
= 0; i
< data
->n_images
; i
++) {
1720 attachment
[0] = data
->image_views
[i
];
1721 VK_CHECK(device_data
->vtable
.CreateFramebuffer(device_data
->device
, &fb_info
,
1722 NULL
, &data
->framebuffers
[i
]));
1725 /* Command buffer pool */
1726 VkCommandPoolCreateInfo cmd_buffer_pool_info
= {};
1727 cmd_buffer_pool_info
.sType
= VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO
;
1728 cmd_buffer_pool_info
.flags
= VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT
;
1729 cmd_buffer_pool_info
.queueFamilyIndex
= device_data
->graphic_queue
->family_index
;
1730 VK_CHECK(device_data
->vtable
.CreateCommandPool(device_data
->device
,
1731 &cmd_buffer_pool_info
,
1732 NULL
, &data
->command_pool
));
1735 static void shutdown_swapchain_data(struct swapchain_data
*data
)
1737 struct device_data
*device_data
= data
->device
;
1739 list_for_each_entry_safe(struct overlay_draw
, draw
, &data
->draws
, link
) {
1740 device_data
->vtable
.DestroySemaphore(device_data
->device
, draw
->semaphore
, NULL
);
1741 device_data
->vtable
.DestroyFence(device_data
->device
, draw
->fence
, NULL
);
1742 device_data
->vtable
.DestroyBuffer(device_data
->device
, draw
->vertex_buffer
, NULL
);
1743 device_data
->vtable
.DestroyBuffer(device_data
->device
, draw
->index_buffer
, NULL
);
1744 device_data
->vtable
.FreeMemory(device_data
->device
, draw
->vertex_buffer_mem
, NULL
);
1745 device_data
->vtable
.FreeMemory(device_data
->device
, draw
->index_buffer_mem
, NULL
);
1748 for (uint32_t i
= 0; i
< data
->n_images
; i
++) {
1749 device_data
->vtable
.DestroyImageView(device_data
->device
, data
->image_views
[i
], NULL
);
1750 device_data
->vtable
.DestroyFramebuffer(device_data
->device
, data
->framebuffers
[i
], NULL
);
1753 device_data
->vtable
.DestroyRenderPass(device_data
->device
, data
->render_pass
, NULL
);
1755 device_data
->vtable
.DestroyCommandPool(device_data
->device
, data
->command_pool
, NULL
);
1757 device_data
->vtable
.DestroyPipeline(device_data
->device
, data
->pipeline
, NULL
);
1758 device_data
->vtable
.DestroyPipelineLayout(device_data
->device
, data
->pipeline_layout
, NULL
);
1760 device_data
->vtable
.DestroyDescriptorPool(device_data
->device
,
1761 data
->descriptor_pool
, NULL
);
1762 device_data
->vtable
.DestroyDescriptorSetLayout(device_data
->device
,
1763 data
->descriptor_layout
, NULL
);
1765 device_data
->vtable
.DestroySampler(device_data
->device
, data
->font_sampler
, NULL
);
1766 device_data
->vtable
.DestroyImageView(device_data
->device
, data
->font_image_view
, NULL
);
1767 device_data
->vtable
.DestroyImage(device_data
->device
, data
->font_image
, NULL
);
1768 device_data
->vtable
.FreeMemory(device_data
->device
, data
->font_mem
, NULL
);
1770 device_data
->vtable
.DestroyBuffer(device_data
->device
, data
->upload_font_buffer
, NULL
);
1771 device_data
->vtable
.FreeMemory(device_data
->device
, data
->upload_font_buffer_mem
, NULL
);
1773 ImGui::DestroyContext(data
->imgui_context
);
1776 static struct overlay_draw
*before_present(struct swapchain_data
*swapchain_data
,
1777 struct queue_data
*present_queue
,
1778 const VkSemaphore
*wait_semaphores
,
1779 unsigned n_wait_semaphores
,
1780 unsigned imageIndex
)
1782 struct instance_data
*instance_data
= swapchain_data
->device
->instance
;
1783 struct overlay_draw
*draw
= NULL
;
1785 snapshot_swapchain_frame(swapchain_data
);
1787 if (!instance_data
->params
.no_display
&& swapchain_data
->n_frames
> 0) {
1788 compute_swapchain_display(swapchain_data
);
1789 draw
= render_swapchain_display(swapchain_data
, present_queue
,
1790 wait_semaphores
, n_wait_semaphores
,
1797 static VkResult
overlay_CreateSwapchainKHR(
1799 const VkSwapchainCreateInfoKHR
* pCreateInfo
,
1800 const VkAllocationCallbacks
* pAllocator
,
1801 VkSwapchainKHR
* pSwapchain
)
1803 struct device_data
*device_data
= FIND(struct device_data
, device
);
1804 VkResult result
= device_data
->vtable
.CreateSwapchainKHR(device
, pCreateInfo
, pAllocator
, pSwapchain
);
1805 if (result
!= VK_SUCCESS
) return result
;
1807 struct swapchain_data
*swapchain_data
= new_swapchain_data(*pSwapchain
, device_data
);
1808 setup_swapchain_data(swapchain_data
, pCreateInfo
);
1812 static void overlay_DestroySwapchainKHR(
1814 VkSwapchainKHR swapchain
,
1815 const VkAllocationCallbacks
* pAllocator
)
1817 struct swapchain_data
*swapchain_data
=
1818 FIND(struct swapchain_data
, swapchain
);
1820 shutdown_swapchain_data(swapchain_data
);
1821 swapchain_data
->device
->vtable
.DestroySwapchainKHR(device
, swapchain
, pAllocator
);
1822 destroy_swapchain_data(swapchain_data
);
1825 static VkResult
overlay_QueuePresentKHR(
1827 const VkPresentInfoKHR
* pPresentInfo
)
1829 struct queue_data
*queue_data
= FIND(struct queue_data
, queue
);
1830 struct device_data
*device_data
= queue_data
->device
;
1831 struct instance_data
*instance_data
= device_data
->instance
;
1832 uint32_t query_results
[OVERLAY_QUERY_COUNT
];
1834 device_data
->frame_stats
.stats
[OVERLAY_PARAM_ENABLED_frame
]++;
1836 if (list_length(&queue_data
->running_command_buffer
) > 0) {
1837 /* Before getting the query results, make sure the operations have
1840 VK_CHECK(device_data
->vtable
.ResetFences(device_data
->device
,
1841 1, &queue_data
->queries_fence
));
1842 VK_CHECK(device_data
->vtable
.QueueSubmit(queue
, 0, NULL
, queue_data
->queries_fence
));
1843 VK_CHECK(device_data
->vtable
.WaitForFences(device_data
->device
,
1844 1, &queue_data
->queries_fence
,
1845 VK_FALSE
, UINT64_MAX
));
1847 /* Now get the results. */
1848 list_for_each_entry_safe(struct command_buffer_data
, cmd_buffer_data
,
1849 &queue_data
->running_command_buffer
, link
) {
1850 list_delinit(&cmd_buffer_data
->link
);
1852 if (cmd_buffer_data
->pipeline_query_pool
) {
1853 memset(query_results
, 0, sizeof(query_results
));
1854 VK_CHECK(device_data
->vtable
.GetQueryPoolResults(device_data
->device
,
1855 cmd_buffer_data
->pipeline_query_pool
,
1856 cmd_buffer_data
->query_index
, 1,
1857 sizeof(uint32_t) * OVERLAY_QUERY_COUNT
,
1858 query_results
, 0, VK_QUERY_RESULT_WAIT_BIT
));
1860 for (uint32_t i
= OVERLAY_PARAM_ENABLED_vertices
;
1861 i
<= OVERLAY_PARAM_ENABLED_compute_invocations
; i
++) {
1862 device_data
->frame_stats
.stats
[i
] += query_results
[i
- OVERLAY_PARAM_ENABLED_vertices
];
1865 if (cmd_buffer_data
->timestamp_query_pool
) {
1866 uint64_t gpu_timestamps
[2] = { 0 };
1867 VK_CHECK(device_data
->vtable
.GetQueryPoolResults(device_data
->device
,
1868 cmd_buffer_data
->timestamp_query_pool
,
1869 cmd_buffer_data
->query_index
* 2, 2,
1870 2 * sizeof(uint64_t), gpu_timestamps
, sizeof(uint64_t),
1871 VK_QUERY_RESULT_WAIT_BIT
| VK_QUERY_RESULT_64_BIT
));
1873 gpu_timestamps
[0] &= queue_data
->timestamp_mask
;
1874 gpu_timestamps
[1] &= queue_data
->timestamp_mask
;
1875 device_data
->frame_stats
.stats
[OVERLAY_PARAM_ENABLED_gpu_timing
] +=
1876 (gpu_timestamps
[1] - gpu_timestamps
[0]) *
1877 device_data
->properties
.limits
.timestampPeriod
;
1882 /* Otherwise we need to add our overlay drawing semaphore to the list of
1883 * semaphores to wait on. If we don't do that the presented picture might
1884 * be have incomplete overlay drawings.
1886 VkResult result
= VK_SUCCESS
;
1887 if (instance_data
->params
.no_display
) {
1888 for (uint32_t i
= 0; i
< pPresentInfo
->swapchainCount
; i
++) {
1889 VkSwapchainKHR swapchain
= pPresentInfo
->pSwapchains
[i
];
1890 struct swapchain_data
*swapchain_data
=
1891 FIND(struct swapchain_data
, swapchain
);
1893 before_present(swapchain_data
,
1895 pPresentInfo
->pWaitSemaphores
,
1896 pPresentInfo
->waitSemaphoreCount
,
1897 pPresentInfo
->pImageIndices
[i
]);
1899 VkPresentInfoKHR present_info
= *pPresentInfo
;
1900 present_info
.swapchainCount
= 1;
1901 present_info
.pSwapchains
= &swapchain
;
1903 uint64_t ts0
= os_time_get();
1904 result
= queue_data
->device
->vtable
.QueuePresentKHR(queue
, &present_info
);
1905 uint64_t ts1
= os_time_get();
1906 swapchain_data
->frame_stats
.stats
[OVERLAY_PARAM_ENABLED_present_timing
] += ts1
- ts0
;
1909 for (uint32_t i
= 0; i
< pPresentInfo
->swapchainCount
; i
++) {
1910 VkSwapchainKHR swapchain
= pPresentInfo
->pSwapchains
[i
];
1911 struct swapchain_data
*swapchain_data
=
1912 FIND(struct swapchain_data
, swapchain
);
1913 VkPresentInfoKHR present_info
= *pPresentInfo
;
1914 present_info
.swapchainCount
= 1;
1915 present_info
.pSwapchains
= &swapchain
;
1917 uint32_t image_index
= pPresentInfo
->pImageIndices
[i
];
1919 struct overlay_draw
*draw
= before_present(swapchain_data
,
1921 pPresentInfo
->pWaitSemaphores
,
1922 pPresentInfo
->waitSemaphoreCount
,
1925 /* Because the submission of the overlay draw waits on the semaphores
1926 * handed for present, we don't need to have this present operation
1927 * wait on them as well, we can just wait on the overlay submission
1930 present_info
.pWaitSemaphores
= &draw
->semaphore
;
1931 present_info
.waitSemaphoreCount
= 1;
1933 uint64_t ts0
= os_time_get();
1934 VkResult chain_result
= queue_data
->device
->vtable
.QueuePresentKHR(queue
, &present_info
);
1935 uint64_t ts1
= os_time_get();
1936 swapchain_data
->frame_stats
.stats
[OVERLAY_PARAM_ENABLED_present_timing
] += ts1
- ts0
;
1937 if (pPresentInfo
->pResults
)
1938 pPresentInfo
->pResults
[i
] = chain_result
;
1939 if (chain_result
!= VK_SUCCESS
&& result
== VK_SUCCESS
)
1940 result
= chain_result
;
1946 static VkResult
overlay_AcquireNextImageKHR(
1948 VkSwapchainKHR swapchain
,
1950 VkSemaphore semaphore
,
1952 uint32_t* pImageIndex
)
1954 struct swapchain_data
*swapchain_data
=
1955 FIND(struct swapchain_data
, swapchain
);
1956 struct device_data
*device_data
= swapchain_data
->device
;
1958 uint64_t ts0
= os_time_get();
1959 VkResult result
= device_data
->vtable
.AcquireNextImageKHR(device
, swapchain
, timeout
,
1960 semaphore
, fence
, pImageIndex
);
1961 uint64_t ts1
= os_time_get();
1963 swapchain_data
->frame_stats
.stats
[OVERLAY_PARAM_ENABLED_acquire_timing
] += ts1
- ts0
;
1964 swapchain_data
->frame_stats
.stats
[OVERLAY_PARAM_ENABLED_acquire
]++;
1969 static VkResult
overlay_AcquireNextImage2KHR(
1971 const VkAcquireNextImageInfoKHR
* pAcquireInfo
,
1972 uint32_t* pImageIndex
)
1974 struct swapchain_data
*swapchain_data
=
1975 FIND(struct swapchain_data
, pAcquireInfo
->swapchain
);
1976 struct device_data
*device_data
= swapchain_data
->device
;
1978 uint64_t ts0
= os_time_get();
1979 VkResult result
= device_data
->vtable
.AcquireNextImage2KHR(device
, pAcquireInfo
, pImageIndex
);
1980 uint64_t ts1
= os_time_get();
1982 swapchain_data
->frame_stats
.stats
[OVERLAY_PARAM_ENABLED_acquire_timing
] += ts1
- ts0
;
1983 swapchain_data
->frame_stats
.stats
[OVERLAY_PARAM_ENABLED_acquire
]++;
1988 static void overlay_CmdDraw(
1989 VkCommandBuffer commandBuffer
,
1990 uint32_t vertexCount
,
1991 uint32_t instanceCount
,
1992 uint32_t firstVertex
,
1993 uint32_t firstInstance
)
1995 struct command_buffer_data
*cmd_buffer_data
=
1996 FIND(struct command_buffer_data
, commandBuffer
);
1997 cmd_buffer_data
->stats
.stats
[OVERLAY_PARAM_ENABLED_draw
]++;
1998 struct device_data
*device_data
= cmd_buffer_data
->device
;
1999 device_data
->vtable
.CmdDraw(commandBuffer
, vertexCount
, instanceCount
,
2000 firstVertex
, firstInstance
);
2003 static void overlay_CmdDrawIndexed(
2004 VkCommandBuffer commandBuffer
,
2005 uint32_t indexCount
,
2006 uint32_t instanceCount
,
2007 uint32_t firstIndex
,
2008 int32_t vertexOffset
,
2009 uint32_t firstInstance
)
2011 struct command_buffer_data
*cmd_buffer_data
=
2012 FIND(struct command_buffer_data
, commandBuffer
);
2013 cmd_buffer_data
->stats
.stats
[OVERLAY_PARAM_ENABLED_draw_indexed
]++;
2014 struct device_data
*device_data
= cmd_buffer_data
->device
;
2015 device_data
->vtable
.CmdDrawIndexed(commandBuffer
, indexCount
, instanceCount
,
2016 firstIndex
, vertexOffset
, firstInstance
);
2019 static void overlay_CmdDrawIndirect(
2020 VkCommandBuffer commandBuffer
,
2022 VkDeviceSize offset
,
2026 struct command_buffer_data
*cmd_buffer_data
=
2027 FIND(struct command_buffer_data
, commandBuffer
);
2028 cmd_buffer_data
->stats
.stats
[OVERLAY_PARAM_ENABLED_draw_indirect
]++;
2029 struct device_data
*device_data
= cmd_buffer_data
->device
;
2030 device_data
->vtable
.CmdDrawIndirect(commandBuffer
, buffer
, offset
, drawCount
, stride
);
2033 static void overlay_CmdDrawIndexedIndirect(
2034 VkCommandBuffer commandBuffer
,
2036 VkDeviceSize offset
,
2040 struct command_buffer_data
*cmd_buffer_data
=
2041 FIND(struct command_buffer_data
, commandBuffer
);
2042 cmd_buffer_data
->stats
.stats
[OVERLAY_PARAM_ENABLED_draw_indexed_indirect
]++;
2043 struct device_data
*device_data
= cmd_buffer_data
->device
;
2044 device_data
->vtable
.CmdDrawIndexedIndirect(commandBuffer
, buffer
, offset
, drawCount
, stride
);
2047 static void overlay_CmdDrawIndirectCountKHR(
2048 VkCommandBuffer commandBuffer
,
2050 VkDeviceSize offset
,
2051 VkBuffer countBuffer
,
2052 VkDeviceSize countBufferOffset
,
2053 uint32_t maxDrawCount
,
2056 struct command_buffer_data
*cmd_buffer_data
=
2057 FIND(struct command_buffer_data
, commandBuffer
);
2058 cmd_buffer_data
->stats
.stats
[OVERLAY_PARAM_ENABLED_draw_indirect_count
]++;
2059 struct device_data
*device_data
= cmd_buffer_data
->device
;
2060 device_data
->vtable
.CmdDrawIndirectCountKHR(commandBuffer
, buffer
, offset
,
2061 countBuffer
, countBufferOffset
,
2062 maxDrawCount
, stride
);
2065 static void overlay_CmdDrawIndexedIndirectCountKHR(
2066 VkCommandBuffer commandBuffer
,
2068 VkDeviceSize offset
,
2069 VkBuffer countBuffer
,
2070 VkDeviceSize countBufferOffset
,
2071 uint32_t maxDrawCount
,
2074 struct command_buffer_data
*cmd_buffer_data
=
2075 FIND(struct command_buffer_data
, commandBuffer
);
2076 cmd_buffer_data
->stats
.stats
[OVERLAY_PARAM_ENABLED_draw_indexed_indirect_count
]++;
2077 struct device_data
*device_data
= cmd_buffer_data
->device
;
2078 device_data
->vtable
.CmdDrawIndexedIndirectCountKHR(commandBuffer
, buffer
, offset
,
2079 countBuffer
, countBufferOffset
,
2080 maxDrawCount
, stride
);
2083 static void overlay_CmdDispatch(
2084 VkCommandBuffer commandBuffer
,
2085 uint32_t groupCountX
,
2086 uint32_t groupCountY
,
2087 uint32_t groupCountZ
)
2089 struct command_buffer_data
*cmd_buffer_data
=
2090 FIND(struct command_buffer_data
, commandBuffer
);
2091 cmd_buffer_data
->stats
.stats
[OVERLAY_PARAM_ENABLED_dispatch
]++;
2092 struct device_data
*device_data
= cmd_buffer_data
->device
;
2093 device_data
->vtable
.CmdDispatch(commandBuffer
, groupCountX
, groupCountY
, groupCountZ
);
2096 static void overlay_CmdDispatchIndirect(
2097 VkCommandBuffer commandBuffer
,
2099 VkDeviceSize offset
)
2101 struct command_buffer_data
*cmd_buffer_data
=
2102 FIND(struct command_buffer_data
, commandBuffer
);
2103 cmd_buffer_data
->stats
.stats
[OVERLAY_PARAM_ENABLED_dispatch_indirect
]++;
2104 struct device_data
*device_data
= cmd_buffer_data
->device
;
2105 device_data
->vtable
.CmdDispatchIndirect(commandBuffer
, buffer
, offset
);
2108 static void overlay_CmdBindPipeline(
2109 VkCommandBuffer commandBuffer
,
2110 VkPipelineBindPoint pipelineBindPoint
,
2111 VkPipeline pipeline
)
2113 struct command_buffer_data
*cmd_buffer_data
=
2114 FIND(struct command_buffer_data
, commandBuffer
);
2115 switch (pipelineBindPoint
) {
2116 case VK_PIPELINE_BIND_POINT_GRAPHICS
: cmd_buffer_data
->stats
.stats
[OVERLAY_PARAM_ENABLED_pipeline_graphics
]++; break;
2117 case VK_PIPELINE_BIND_POINT_COMPUTE
: cmd_buffer_data
->stats
.stats
[OVERLAY_PARAM_ENABLED_pipeline_compute
]++; break;
2118 case VK_PIPELINE_BIND_POINT_RAY_TRACING_NV
: cmd_buffer_data
->stats
.stats
[OVERLAY_PARAM_ENABLED_pipeline_raytracing
]++; break;
2121 struct device_data
*device_data
= cmd_buffer_data
->device
;
2122 device_data
->vtable
.CmdBindPipeline(commandBuffer
, pipelineBindPoint
, pipeline
);
2125 static VkResult
overlay_BeginCommandBuffer(
2126 VkCommandBuffer commandBuffer
,
2127 const VkCommandBufferBeginInfo
* pBeginInfo
)
2129 struct command_buffer_data
*cmd_buffer_data
=
2130 FIND(struct command_buffer_data
, commandBuffer
);
2131 struct device_data
*device_data
= cmd_buffer_data
->device
;
2133 memset(&cmd_buffer_data
->stats
, 0, sizeof(cmd_buffer_data
->stats
));
2135 /* We don't record any query in secondary command buffers, just make sure
2136 * we have the right inheritance.
2138 if (cmd_buffer_data
->level
== VK_COMMAND_BUFFER_LEVEL_SECONDARY
) {
2139 VkCommandBufferBeginInfo
*begin_info
= (VkCommandBufferBeginInfo
*)
2140 clone_chain((const struct VkBaseInStructure
*)pBeginInfo
);
2141 VkCommandBufferInheritanceInfo
*parent_inhe_info
= (VkCommandBufferInheritanceInfo
*)
2142 vk_find_struct(begin_info
, COMMAND_BUFFER_INHERITANCE_INFO
);
2143 VkCommandBufferInheritanceInfo inhe_info
= {
2144 VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO
,
2151 overlay_query_flags
,
2154 if (parent_inhe_info
)
2155 parent_inhe_info
->pipelineStatistics
= overlay_query_flags
;
2157 inhe_info
.pNext
= begin_info
->pNext
;
2158 begin_info
->pNext
= &inhe_info
;
2161 VkResult result
= device_data
->vtable
.BeginCommandBuffer(commandBuffer
, pBeginInfo
);
2163 if (!parent_inhe_info
)
2164 begin_info
->pNext
= inhe_info
.pNext
;
2166 free_chain((struct VkBaseOutStructure
*)begin_info
);
2171 /* Otherwise record a begin query as first command. */
2172 VkResult result
= device_data
->vtable
.BeginCommandBuffer(commandBuffer
, pBeginInfo
);
2174 if (result
== VK_SUCCESS
) {
2175 if (cmd_buffer_data
->pipeline_query_pool
) {
2176 device_data
->vtable
.CmdResetQueryPool(commandBuffer
,
2177 cmd_buffer_data
->pipeline_query_pool
,
2178 cmd_buffer_data
->query_index
, 1);
2180 if (cmd_buffer_data
->timestamp_query_pool
) {
2181 device_data
->vtable
.CmdResetQueryPool(commandBuffer
,
2182 cmd_buffer_data
->timestamp_query_pool
,
2183 cmd_buffer_data
->query_index
* 2, 2);
2185 if (cmd_buffer_data
->pipeline_query_pool
) {
2186 device_data
->vtable
.CmdBeginQuery(commandBuffer
,
2187 cmd_buffer_data
->pipeline_query_pool
,
2188 cmd_buffer_data
->query_index
, 0);
2190 if (cmd_buffer_data
->timestamp_query_pool
) {
2191 device_data
->vtable
.CmdWriteTimestamp(commandBuffer
,
2192 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT
,
2193 cmd_buffer_data
->timestamp_query_pool
,
2194 cmd_buffer_data
->query_index
* 2);
2201 static VkResult
overlay_EndCommandBuffer(
2202 VkCommandBuffer commandBuffer
)
2204 struct command_buffer_data
*cmd_buffer_data
=
2205 FIND(struct command_buffer_data
, commandBuffer
);
2206 struct device_data
*device_data
= cmd_buffer_data
->device
;
2208 if (cmd_buffer_data
->timestamp_query_pool
) {
2209 device_data
->vtable
.CmdWriteTimestamp(commandBuffer
,
2210 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT
,
2211 cmd_buffer_data
->timestamp_query_pool
,
2212 cmd_buffer_data
->query_index
* 2 + 1);
2214 if (cmd_buffer_data
->pipeline_query_pool
) {
2215 device_data
->vtable
.CmdEndQuery(commandBuffer
,
2216 cmd_buffer_data
->pipeline_query_pool
,
2217 cmd_buffer_data
->query_index
);
2220 return device_data
->vtable
.EndCommandBuffer(commandBuffer
);
2223 static VkResult
overlay_ResetCommandBuffer(
2224 VkCommandBuffer commandBuffer
,
2225 VkCommandBufferResetFlags flags
)
2227 struct command_buffer_data
*cmd_buffer_data
=
2228 FIND(struct command_buffer_data
, commandBuffer
);
2229 struct device_data
*device_data
= cmd_buffer_data
->device
;
2231 memset(&cmd_buffer_data
->stats
, 0, sizeof(cmd_buffer_data
->stats
));
2233 return device_data
->vtable
.ResetCommandBuffer(commandBuffer
, flags
);
2236 static void overlay_CmdExecuteCommands(
2237 VkCommandBuffer commandBuffer
,
2238 uint32_t commandBufferCount
,
2239 const VkCommandBuffer
* pCommandBuffers
)
2241 struct command_buffer_data
*cmd_buffer_data
=
2242 FIND(struct command_buffer_data
, commandBuffer
);
2243 struct device_data
*device_data
= cmd_buffer_data
->device
;
2245 /* Add the stats of the executed command buffers to the primary one. */
2246 for (uint32_t c
= 0; c
< commandBufferCount
; c
++) {
2247 struct command_buffer_data
*sec_cmd_buffer_data
=
2248 FIND(struct command_buffer_data
, pCommandBuffers
[c
]);
2250 for (uint32_t s
= 0; s
< OVERLAY_PARAM_ENABLED_MAX
; s
++)
2251 cmd_buffer_data
->stats
.stats
[s
] += sec_cmd_buffer_data
->stats
.stats
[s
];
2254 device_data
->vtable
.CmdExecuteCommands(commandBuffer
, commandBufferCount
, pCommandBuffers
);
2257 static VkResult
overlay_AllocateCommandBuffers(
2259 const VkCommandBufferAllocateInfo
* pAllocateInfo
,
2260 VkCommandBuffer
* pCommandBuffers
)
2262 struct device_data
*device_data
= FIND(struct device_data
, device
);
2264 device_data
->vtable
.AllocateCommandBuffers(device
, pAllocateInfo
, pCommandBuffers
);
2265 if (result
!= VK_SUCCESS
)
2268 VkQueryPool pipeline_query_pool
= VK_NULL_HANDLE
;
2269 VkQueryPool timestamp_query_pool
= VK_NULL_HANDLE
;
2270 if (device_data
->instance
->pipeline_statistics_enabled
&&
2271 pAllocateInfo
->level
== VK_COMMAND_BUFFER_LEVEL_PRIMARY
) {
2272 VkQueryPoolCreateInfo pool_info
= {
2273 VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO
,
2276 VK_QUERY_TYPE_PIPELINE_STATISTICS
,
2277 pAllocateInfo
->commandBufferCount
,
2278 overlay_query_flags
,
2280 VK_CHECK(device_data
->vtable
.CreateQueryPool(device_data
->device
, &pool_info
,
2281 NULL
, &pipeline_query_pool
));
2283 if (device_data
->instance
->params
.enabled
[OVERLAY_PARAM_ENABLED_gpu_timing
]) {
2284 VkQueryPoolCreateInfo pool_info
= {
2285 VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO
,
2288 VK_QUERY_TYPE_TIMESTAMP
,
2289 pAllocateInfo
->commandBufferCount
* 2,
2292 VK_CHECK(device_data
->vtable
.CreateQueryPool(device_data
->device
, &pool_info
,
2293 NULL
, ×tamp_query_pool
));
2296 for (uint32_t i
= 0; i
< pAllocateInfo
->commandBufferCount
; i
++) {
2297 new_command_buffer_data(pCommandBuffers
[i
], pAllocateInfo
->level
,
2298 pipeline_query_pool
, timestamp_query_pool
,
2302 if (pipeline_query_pool
)
2303 map_object(HKEY(pipeline_query_pool
), (void *)(uintptr_t) pAllocateInfo
->commandBufferCount
);
2304 if (timestamp_query_pool
)
2305 map_object(HKEY(timestamp_query_pool
), (void *)(uintptr_t) pAllocateInfo
->commandBufferCount
);
2310 static void overlay_FreeCommandBuffers(
2312 VkCommandPool commandPool
,
2313 uint32_t commandBufferCount
,
2314 const VkCommandBuffer
* pCommandBuffers
)
2316 struct device_data
*device_data
= FIND(struct device_data
, device
);
2317 for (uint32_t i
= 0; i
< commandBufferCount
; i
++) {
2318 struct command_buffer_data
*cmd_buffer_data
=
2319 FIND(struct command_buffer_data
, pCommandBuffers
[i
]);
2321 /* It is legal to free a NULL command buffer*/
2322 if (!cmd_buffer_data
)
2325 uint64_t count
= (uintptr_t)find_object_data(HKEY(cmd_buffer_data
->pipeline_query_pool
));
2327 unmap_object(HKEY(cmd_buffer_data
->pipeline_query_pool
));
2328 device_data
->vtable
.DestroyQueryPool(device_data
->device
,
2329 cmd_buffer_data
->pipeline_query_pool
, NULL
);
2330 } else if (count
!= 0) {
2331 map_object(HKEY(cmd_buffer_data
->pipeline_query_pool
), (void *)(uintptr_t)(count
- 1));
2333 count
= (uintptr_t)find_object_data(HKEY(cmd_buffer_data
->timestamp_query_pool
));
2335 unmap_object(HKEY(cmd_buffer_data
->timestamp_query_pool
));
2336 device_data
->vtable
.DestroyQueryPool(device_data
->device
,
2337 cmd_buffer_data
->timestamp_query_pool
, NULL
);
2338 } else if (count
!= 0) {
2339 map_object(HKEY(cmd_buffer_data
->timestamp_query_pool
), (void *)(uintptr_t)(count
- 1));
2341 destroy_command_buffer_data(cmd_buffer_data
);
2344 device_data
->vtable
.FreeCommandBuffers(device
, commandPool
,
2345 commandBufferCount
, pCommandBuffers
);
2348 static VkResult
overlay_QueueSubmit(
2350 uint32_t submitCount
,
2351 const VkSubmitInfo
* pSubmits
,
2354 struct queue_data
*queue_data
= FIND(struct queue_data
, queue
);
2355 struct device_data
*device_data
= queue_data
->device
;
2357 device_data
->frame_stats
.stats
[OVERLAY_PARAM_ENABLED_submit
]++;
2359 for (uint32_t s
= 0; s
< submitCount
; s
++) {
2360 for (uint32_t c
= 0; c
< pSubmits
[s
].commandBufferCount
; c
++) {
2361 struct command_buffer_data
*cmd_buffer_data
=
2362 FIND(struct command_buffer_data
, pSubmits
[s
].pCommandBuffers
[c
]);
2364 /* Merge the submitted command buffer stats into the device. */
2365 for (uint32_t st
= 0; st
< OVERLAY_PARAM_ENABLED_MAX
; st
++)
2366 device_data
->frame_stats
.stats
[st
] += cmd_buffer_data
->stats
.stats
[st
];
2368 /* Attach the command buffer to the queue so we remember to read its
2369 * pipeline statistics & timestamps at QueuePresent().
2371 if (!cmd_buffer_data
->pipeline_query_pool
&&
2372 !cmd_buffer_data
->timestamp_query_pool
)
2375 if (list_is_empty(&cmd_buffer_data
->link
)) {
2376 list_addtail(&cmd_buffer_data
->link
,
2377 &queue_data
->running_command_buffer
);
2379 fprintf(stderr
, "Command buffer submitted multiple times before present.\n"
2380 "This could lead to invalid data.\n");
2385 return device_data
->vtable
.QueueSubmit(queue
, submitCount
, pSubmits
, fence
);
2388 static VkResult
overlay_CreateDevice(
2389 VkPhysicalDevice physicalDevice
,
2390 const VkDeviceCreateInfo
* pCreateInfo
,
2391 const VkAllocationCallbacks
* pAllocator
,
2394 struct instance_data
*instance_data
=
2395 FIND(struct instance_data
, physicalDevice
);
2396 VkLayerDeviceCreateInfo
*chain_info
=
2397 get_device_chain_info(pCreateInfo
, VK_LAYER_LINK_INFO
);
2399 assert(chain_info
->u
.pLayerInfo
);
2400 PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr
= chain_info
->u
.pLayerInfo
->pfnNextGetInstanceProcAddr
;
2401 PFN_vkGetDeviceProcAddr fpGetDeviceProcAddr
= chain_info
->u
.pLayerInfo
->pfnNextGetDeviceProcAddr
;
2402 PFN_vkCreateDevice fpCreateDevice
= (PFN_vkCreateDevice
)fpGetInstanceProcAddr(NULL
, "vkCreateDevice");
2403 if (fpCreateDevice
== NULL
) {
2404 return VK_ERROR_INITIALIZATION_FAILED
;
2407 // Advance the link info for the next element on the chain
2408 chain_info
->u
.pLayerInfo
= chain_info
->u
.pLayerInfo
->pNext
;
2410 VkPhysicalDeviceFeatures device_features
= {};
2411 VkDeviceCreateInfo device_info
= *pCreateInfo
;
2413 if (pCreateInfo
->pEnabledFeatures
)
2414 device_features
= *(pCreateInfo
->pEnabledFeatures
);
2415 if (instance_data
->pipeline_statistics_enabled
) {
2416 device_features
.inheritedQueries
= true;
2417 device_features
.pipelineStatisticsQuery
= true;
2419 device_info
.pEnabledFeatures
= &device_features
;
2422 VkResult result
= fpCreateDevice(physicalDevice
, &device_info
, pAllocator
, pDevice
);
2423 if (result
!= VK_SUCCESS
) return result
;
2425 struct device_data
*device_data
= new_device_data(*pDevice
, instance_data
);
2426 device_data
->physical_device
= physicalDevice
;
2427 vk_load_device_commands(*pDevice
, fpGetDeviceProcAddr
, &device_data
->vtable
);
2429 instance_data
->vtable
.GetPhysicalDeviceProperties(device_data
->physical_device
,
2430 &device_data
->properties
);
2432 VkLayerDeviceCreateInfo
*load_data_info
=
2433 get_device_chain_info(pCreateInfo
, VK_LOADER_DATA_CALLBACK
);
2434 device_data
->set_device_loader_data
= load_data_info
->u
.pfnSetDeviceLoaderData
;
2436 device_map_queues(device_data
, pCreateInfo
);
2441 static void overlay_DestroyDevice(
2443 const VkAllocationCallbacks
* pAllocator
)
2445 struct device_data
*device_data
= FIND(struct device_data
, device
);
2446 device_unmap_queues(device_data
);
2447 device_data
->vtable
.DestroyDevice(device
, pAllocator
);
2448 destroy_device_data(device_data
);
2451 static VkResult
overlay_CreateInstance(
2452 const VkInstanceCreateInfo
* pCreateInfo
,
2453 const VkAllocationCallbacks
* pAllocator
,
2454 VkInstance
* pInstance
)
2456 VkLayerInstanceCreateInfo
*chain_info
=
2457 get_instance_chain_info(pCreateInfo
, VK_LAYER_LINK_INFO
);
2459 assert(chain_info
->u
.pLayerInfo
);
2460 PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr
=
2461 chain_info
->u
.pLayerInfo
->pfnNextGetInstanceProcAddr
;
2462 PFN_vkCreateInstance fpCreateInstance
=
2463 (PFN_vkCreateInstance
)fpGetInstanceProcAddr(NULL
, "vkCreateInstance");
2464 if (fpCreateInstance
== NULL
) {
2465 return VK_ERROR_INITIALIZATION_FAILED
;
2468 // Advance the link info for the next element on the chain
2469 chain_info
->u
.pLayerInfo
= chain_info
->u
.pLayerInfo
->pNext
;
2471 VkResult result
= fpCreateInstance(pCreateInfo
, pAllocator
, pInstance
);
2472 if (result
!= VK_SUCCESS
) return result
;
2474 struct instance_data
*instance_data
= new_instance_data(*pInstance
);
2475 vk_load_instance_commands(instance_data
->instance
,
2476 fpGetInstanceProcAddr
,
2477 &instance_data
->vtable
);
2478 instance_data_map_physical_devices(instance_data
, true);
2480 parse_overlay_env(&instance_data
->params
, getenv("VK_LAYER_MESA_OVERLAY_CONFIG"));
2482 /* If there's no control file, and an output_file was specified, start
2483 * capturing fps data right away.
2485 instance_data
->capture_enabled
=
2486 instance_data
->params
.output_file
&& instance_data
->params
.control
< 0;
2487 instance_data
->capture_started
= instance_data
->capture_enabled
;
2489 for (int i
= OVERLAY_PARAM_ENABLED_vertices
;
2490 i
<= OVERLAY_PARAM_ENABLED_compute_invocations
; i
++) {
2491 if (instance_data
->params
.enabled
[i
]) {
2492 instance_data
->pipeline_statistics_enabled
= true;
2500 static void overlay_DestroyInstance(
2501 VkInstance instance
,
2502 const VkAllocationCallbacks
* pAllocator
)
2504 struct instance_data
*instance_data
= FIND(struct instance_data
, instance
);
2505 instance_data_map_physical_devices(instance_data
, false);
2506 instance_data
->vtable
.DestroyInstance(instance
, pAllocator
);
2507 destroy_instance_data(instance_data
);
2510 static const struct {
2513 } name_to_funcptr_map
[] = {
2514 { "vkGetDeviceProcAddr", (void *) vkGetDeviceProcAddr
},
2515 #define ADD_HOOK(fn) { "vk" # fn, (void *) overlay_ ## fn }
2516 ADD_HOOK(AllocateCommandBuffers
),
2517 ADD_HOOK(FreeCommandBuffers
),
2518 ADD_HOOK(ResetCommandBuffer
),
2519 ADD_HOOK(BeginCommandBuffer
),
2520 ADD_HOOK(EndCommandBuffer
),
2521 ADD_HOOK(CmdExecuteCommands
),
2524 ADD_HOOK(CmdDrawIndexed
),
2525 ADD_HOOK(CmdDrawIndirect
),
2526 ADD_HOOK(CmdDrawIndexedIndirect
),
2527 ADD_HOOK(CmdDispatch
),
2528 ADD_HOOK(CmdDispatchIndirect
),
2529 ADD_HOOK(CmdDrawIndirectCountKHR
),
2530 ADD_HOOK(CmdDrawIndexedIndirectCountKHR
),
2532 ADD_HOOK(CmdBindPipeline
),
2534 ADD_HOOK(CreateSwapchainKHR
),
2535 ADD_HOOK(QueuePresentKHR
),
2536 ADD_HOOK(DestroySwapchainKHR
),
2537 ADD_HOOK(AcquireNextImageKHR
),
2538 ADD_HOOK(AcquireNextImage2KHR
),
2540 ADD_HOOK(QueueSubmit
),
2542 ADD_HOOK(CreateDevice
),
2543 ADD_HOOK(DestroyDevice
),
2545 ADD_HOOK(CreateInstance
),
2546 ADD_HOOK(DestroyInstance
),
2550 static void *find_ptr(const char *name
)
2552 for (uint32_t i
= 0; i
< ARRAY_SIZE(name_to_funcptr_map
); i
++) {
2553 if (strcmp(name
, name_to_funcptr_map
[i
].name
) == 0)
2554 return name_to_funcptr_map
[i
].ptr
;
2560 VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL
vkGetDeviceProcAddr(VkDevice dev
,
2561 const char *funcName
)
2563 void *ptr
= find_ptr(funcName
);
2564 if (ptr
) return reinterpret_cast<PFN_vkVoidFunction
>(ptr
);
2566 if (dev
== NULL
) return NULL
;
2568 struct device_data
*device_data
= FIND(struct device_data
, dev
);
2569 if (device_data
->vtable
.GetDeviceProcAddr
== NULL
) return NULL
;
2570 return device_data
->vtable
.GetDeviceProcAddr(dev
, funcName
);
2573 VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL
vkGetInstanceProcAddr(VkInstance instance
,
2574 const char *funcName
)
2576 void *ptr
= find_ptr(funcName
);
2577 if (ptr
) return reinterpret_cast<PFN_vkVoidFunction
>(ptr
);
2579 if (instance
== NULL
) return NULL
;
2581 struct instance_data
*instance_data
= FIND(struct instance_data
, instance
);
2582 if (instance_data
->vtable
.GetInstanceProcAddr
== NULL
) return NULL
;
2583 return instance_data
->vtable
.GetInstanceProcAddr(instance
, funcName
);