• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // dear imgui: Renderer for Vulkan
2 // This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..)
3 
4 // Missing features:
5 //  [ ] Renderer: User texture binding. Changes of ImTextureID aren't supported by this binding! See https://github.com/ocornut/imgui/pull/914
6 
7 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
8 // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
9 // https://github.com/ocornut/imgui
10 
11 // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification.
12 // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
13 
14 // CHANGELOG
15 // (minor and older changes stripped away, please see git history for details)
16 //  2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
17 //  2018-08-25: Vulkan: Fixed mishandled VkSurfaceCapabilitiesKHR::maxImageCount=0 case.
18 //  2018-06-22: Inverted the parameters to ImGui_ImplVulkan_RenderDrawData() to be consistent with other bindings.
19 //  2018-06-08: Misc: Extracted imgui_impl_vulkan.cpp/.h away from the old combined GLFW+Vulkan example.
20 //  2018-06-08: Vulkan: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
21 //  2018-03-03: Vulkan: Various refactor, created a couple of ImGui_ImplVulkanH_XXX helper that the example can use and that viewport support will use.
22 //  2018-03-01: Vulkan: Renamed ImGui_ImplVulkan_Init_Info to ImGui_ImplVulkan_InitInfo and fields to match more closely Vulkan terminology.
23 //  2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback, ImGui_ImplVulkan_Render() calls ImGui_ImplVulkan_RenderDrawData() itself.
24 //  2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
25 //  2017-05-15: Vulkan: Fix scissor offset being negative. Fix new Vulkan validation warnings. Set required depth member for buffer image copy.
26 //  2016-11-13: Vulkan: Fix validation layer warnings and errors and redeclare gl_PerVertex.
27 //  2016-10-18: Vulkan: Add location decorators & change to use structs as in/out in glsl, update embedded spv (produced with glslangValidator -x). Null the released resources.
28 //  2016-08-27: Vulkan: Fix Vulkan example for use when a depth buffer is active.
29 
30 #include "imgui.h"
31 #include "imgui_impl_vulkan.h"
32 #include <stdio.h>
33 
34 // Vulkan data
35 static const VkAllocationCallbacks* g_Allocator = NULL;
36 static VkPhysicalDevice             g_PhysicalDevice = VK_NULL_HANDLE;
37 static VkInstance                   g_Instance = VK_NULL_HANDLE;
38 static VkDevice                     g_Device = VK_NULL_HANDLE;
39 static uint32_t                     g_QueueFamily = (uint32_t)-1;
40 static VkQueue                      g_Queue = VK_NULL_HANDLE;
41 static VkPipelineCache              g_PipelineCache = VK_NULL_HANDLE;
42 static VkDescriptorPool             g_DescriptorPool = VK_NULL_HANDLE;
43 static VkRenderPass                 g_RenderPass = VK_NULL_HANDLE;
44 static void                         (*g_CheckVkResultFn)(VkResult err) = NULL;
45 
46 static VkDeviceSize                 g_BufferMemoryAlignment = 256;
47 static VkPipelineCreateFlags        g_PipelineCreateFlags = 0;
48 
49 static VkDescriptorSetLayout        g_DescriptorSetLayout = VK_NULL_HANDLE;
50 static VkPipelineLayout             g_PipelineLayout = VK_NULL_HANDLE;
51 static VkDescriptorSet              g_DescriptorSet = VK_NULL_HANDLE;
52 static VkPipeline                   g_Pipeline = VK_NULL_HANDLE;
53 
54 // Frame data
55 struct FrameDataForRender
56 {
57     VkDeviceMemory  VertexBufferMemory;
58     VkDeviceMemory  IndexBufferMemory;
59     VkDeviceSize    VertexBufferSize;
60     VkDeviceSize    IndexBufferSize;
61     VkBuffer        VertexBuffer;
62     VkBuffer        IndexBuffer;
63 };
64 static int                    g_FrameIndex = 0;
65 static FrameDataForRender     g_FramesDataBuffers[IMGUI_VK_QUEUED_FRAMES] = {};
66 
67 // Font data
68 static VkSampler              g_FontSampler = VK_NULL_HANDLE;
69 static VkDeviceMemory         g_FontMemory = VK_NULL_HANDLE;
70 static VkImage                g_FontImage = VK_NULL_HANDLE;
71 static VkImageView            g_FontView = VK_NULL_HANDLE;
72 static VkDeviceMemory         g_UploadBufferMemory = VK_NULL_HANDLE;
73 static VkBuffer               g_UploadBuffer = VK_NULL_HANDLE;
74 
75 // glsl_shader.vert, compiled with:
76 // # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert
77 static uint32_t __glsl_shader_vert_spv[] =
78 {
79     0x07230203,0x00010000,0x00080001,0x0000002e,0x00000000,0x00020011,0x00000001,0x0006000b,
80     0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
81     0x000a000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000b,0x0000000f,0x00000015,
82     0x0000001b,0x0000001c,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
83     0x00000000,0x00030005,0x00000009,0x00000000,0x00050006,0x00000009,0x00000000,0x6f6c6f43,
84     0x00000072,0x00040006,0x00000009,0x00000001,0x00005655,0x00030005,0x0000000b,0x0074754f,
85     0x00040005,0x0000000f,0x6c6f4361,0x0000726f,0x00030005,0x00000015,0x00565561,0x00060005,
86     0x00000019,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000019,0x00000000,
87     0x505f6c67,0x7469736f,0x006e6f69,0x00030005,0x0000001b,0x00000000,0x00040005,0x0000001c,
88     0x736f5061,0x00000000,0x00060005,0x0000001e,0x73755075,0x6e6f4368,0x6e617473,0x00000074,
89     0x00050006,0x0000001e,0x00000000,0x61635375,0x0000656c,0x00060006,0x0000001e,0x00000001,
90     0x61725475,0x616c736e,0x00006574,0x00030005,0x00000020,0x00006370,0x00040047,0x0000000b,
91     0x0000001e,0x00000000,0x00040047,0x0000000f,0x0000001e,0x00000002,0x00040047,0x00000015,
92     0x0000001e,0x00000001,0x00050048,0x00000019,0x00000000,0x0000000b,0x00000000,0x00030047,
93     0x00000019,0x00000002,0x00040047,0x0000001c,0x0000001e,0x00000000,0x00050048,0x0000001e,
94     0x00000000,0x00000023,0x00000000,0x00050048,0x0000001e,0x00000001,0x00000023,0x00000008,
95     0x00030047,0x0000001e,0x00000002,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,
96     0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040017,
97     0x00000008,0x00000006,0x00000002,0x0004001e,0x00000009,0x00000007,0x00000008,0x00040020,
98     0x0000000a,0x00000003,0x00000009,0x0004003b,0x0000000a,0x0000000b,0x00000003,0x00040015,
99     0x0000000c,0x00000020,0x00000001,0x0004002b,0x0000000c,0x0000000d,0x00000000,0x00040020,
100     0x0000000e,0x00000001,0x00000007,0x0004003b,0x0000000e,0x0000000f,0x00000001,0x00040020,
101     0x00000011,0x00000003,0x00000007,0x0004002b,0x0000000c,0x00000013,0x00000001,0x00040020,
102     0x00000014,0x00000001,0x00000008,0x0004003b,0x00000014,0x00000015,0x00000001,0x00040020,
103     0x00000017,0x00000003,0x00000008,0x0003001e,0x00000019,0x00000007,0x00040020,0x0000001a,
104     0x00000003,0x00000019,0x0004003b,0x0000001a,0x0000001b,0x00000003,0x0004003b,0x00000014,
105     0x0000001c,0x00000001,0x0004001e,0x0000001e,0x00000008,0x00000008,0x00040020,0x0000001f,
106     0x00000009,0x0000001e,0x0004003b,0x0000001f,0x00000020,0x00000009,0x00040020,0x00000021,
107     0x00000009,0x00000008,0x0004002b,0x00000006,0x00000028,0x00000000,0x0004002b,0x00000006,
108     0x00000029,0x3f800000,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,
109     0x00000005,0x0004003d,0x00000007,0x00000010,0x0000000f,0x00050041,0x00000011,0x00000012,
110     0x0000000b,0x0000000d,0x0003003e,0x00000012,0x00000010,0x0004003d,0x00000008,0x00000016,
111     0x00000015,0x00050041,0x00000017,0x00000018,0x0000000b,0x00000013,0x0003003e,0x00000018,
112     0x00000016,0x0004003d,0x00000008,0x0000001d,0x0000001c,0x00050041,0x00000021,0x00000022,
113     0x00000020,0x0000000d,0x0004003d,0x00000008,0x00000023,0x00000022,0x00050085,0x00000008,
114     0x00000024,0x0000001d,0x00000023,0x00050041,0x00000021,0x00000025,0x00000020,0x00000013,
115     0x0004003d,0x00000008,0x00000026,0x00000025,0x00050081,0x00000008,0x00000027,0x00000024,
116     0x00000026,0x00050051,0x00000006,0x0000002a,0x00000027,0x00000000,0x00050051,0x00000006,
117     0x0000002b,0x00000027,0x00000001,0x00070050,0x00000007,0x0000002c,0x0000002a,0x0000002b,
118     0x00000028,0x00000029,0x00050041,0x00000011,0x0000002d,0x0000001b,0x0000000d,0x0003003e,
119     0x0000002d,0x0000002c,0x000100fd,0x00010038
120 };
121 
122 // glsl_shader.frag, compiled with:
123 // # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag
124 static uint32_t __glsl_shader_frag_spv[] =
125 {
126     0x07230203,0x00010000,0x00080001,0x0000001e,0x00000000,0x00020011,0x00000001,0x0006000b,
127     0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
128     0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x0000000d,0x00030010,
129     0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
130     0x00000000,0x00040005,0x00000009,0x6c6f4366,0x0000726f,0x00030005,0x0000000b,0x00000000,
131     0x00050006,0x0000000b,0x00000000,0x6f6c6f43,0x00000072,0x00040006,0x0000000b,0x00000001,
132     0x00005655,0x00030005,0x0000000d,0x00006e49,0x00050005,0x00000016,0x78655473,0x65727574,
133     0x00000000,0x00040047,0x00000009,0x0000001e,0x00000000,0x00040047,0x0000000d,0x0000001e,
134     0x00000000,0x00040047,0x00000016,0x00000022,0x00000000,0x00040047,0x00000016,0x00000021,
135     0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,
136     0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040020,0x00000008,0x00000003,
137     0x00000007,0x0004003b,0x00000008,0x00000009,0x00000003,0x00040017,0x0000000a,0x00000006,
138     0x00000002,0x0004001e,0x0000000b,0x00000007,0x0000000a,0x00040020,0x0000000c,0x00000001,
139     0x0000000b,0x0004003b,0x0000000c,0x0000000d,0x00000001,0x00040015,0x0000000e,0x00000020,
140     0x00000001,0x0004002b,0x0000000e,0x0000000f,0x00000000,0x00040020,0x00000010,0x00000001,
141     0x00000007,0x00090019,0x00000013,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000,
142     0x00000001,0x00000000,0x0003001b,0x00000014,0x00000013,0x00040020,0x00000015,0x00000000,
143     0x00000014,0x0004003b,0x00000015,0x00000016,0x00000000,0x0004002b,0x0000000e,0x00000018,
144     0x00000001,0x00040020,0x00000019,0x00000001,0x0000000a,0x00050036,0x00000002,0x00000004,
145     0x00000000,0x00000003,0x000200f8,0x00000005,0x00050041,0x00000010,0x00000011,0x0000000d,
146     0x0000000f,0x0004003d,0x00000007,0x00000012,0x00000011,0x0004003d,0x00000014,0x00000017,
147     0x00000016,0x00050041,0x00000019,0x0000001a,0x0000000d,0x00000018,0x0004003d,0x0000000a,
148     0x0000001b,0x0000001a,0x00050057,0x00000007,0x0000001c,0x00000017,0x0000001b,0x00050085,
149     0x00000007,0x0000001d,0x00000012,0x0000001c,0x0003003e,0x00000009,0x0000001d,0x000100fd,
150     0x00010038
151 };
152 
ImGui_ImplVulkan_MemoryType(VkMemoryPropertyFlags properties,uint32_t type_bits)153 static uint32_t ImGui_ImplVulkan_MemoryType(VkMemoryPropertyFlags properties, uint32_t type_bits)
154 {
155     VkPhysicalDeviceMemoryProperties prop;
156     vkGetPhysicalDeviceMemoryProperties(g_PhysicalDevice, &prop);
157     for (uint32_t i = 0; i < prop.memoryTypeCount; i++)
158         if ((prop.memoryTypes[i].propertyFlags & properties) == properties && type_bits & (1<<i))
159             return i;
160     return 0xFFFFFFFF; // Unable to find memoryType
161 }
162 
check_vk_result(VkResult err)163 static void check_vk_result(VkResult err)
164 {
165     if (g_CheckVkResultFn)
166         g_CheckVkResultFn(err);
167 }
168 
CreateOrResizeBuffer(VkBuffer & buffer,VkDeviceMemory & buffer_memory,VkDeviceSize & p_buffer_size,size_t new_size,VkBufferUsageFlagBits usage)169 static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory, VkDeviceSize& p_buffer_size, size_t new_size, VkBufferUsageFlagBits usage)
170 {
171     VkResult err;
172     if (buffer != VK_NULL_HANDLE)
173         vkDestroyBuffer(g_Device, buffer, g_Allocator);
174     if (buffer_memory)
175         vkFreeMemory(g_Device, buffer_memory, g_Allocator);
176 
177     VkDeviceSize vertex_buffer_size_aligned = ((new_size - 1) / g_BufferMemoryAlignment + 1) * g_BufferMemoryAlignment;
178     VkBufferCreateInfo buffer_info = {};
179     buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
180     buffer_info.size = vertex_buffer_size_aligned;
181     buffer_info.usage = usage;
182     buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
183     err = vkCreateBuffer(g_Device, &buffer_info, g_Allocator, &buffer);
184     check_vk_result(err);
185 
186     VkMemoryRequirements req;
187     vkGetBufferMemoryRequirements(g_Device, buffer, &req);
188     g_BufferMemoryAlignment = (g_BufferMemoryAlignment > req.alignment) ? g_BufferMemoryAlignment : req.alignment;
189     VkMemoryAllocateInfo alloc_info = {};
190     alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
191     alloc_info.allocationSize = req.size;
192     alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits);
193     err = vkAllocateMemory(g_Device, &alloc_info, g_Allocator, &buffer_memory);
194     check_vk_result(err);
195 
196     err = vkBindBufferMemory(g_Device, buffer, buffer_memory, 0);
197     check_vk_result(err);
198     p_buffer_size = new_size;
199 }
200 
201 // Render function
202 // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
ImGui_ImplVulkan_RenderDrawData(ImDrawData * draw_data,VkCommandBuffer command_buffer)203 void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer)
204 {
205     VkResult err;
206     if (draw_data->TotalVtxCount == 0)
207         return;
208 
209     FrameDataForRender* fd = &g_FramesDataBuffers[g_FrameIndex];
210     g_FrameIndex = (g_FrameIndex + 1) % IMGUI_VK_QUEUED_FRAMES;
211 
212     // Create the Vertex and Index buffers:
213     size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert);
214     size_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx);
215     if (!fd->VertexBuffer || fd->VertexBufferSize < vertex_size)
216         CreateOrResizeBuffer(fd->VertexBuffer, fd->VertexBufferMemory, fd->VertexBufferSize, vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
217     if (!fd->IndexBuffer || fd->IndexBufferSize < index_size)
218         CreateOrResizeBuffer(fd->IndexBuffer, fd->IndexBufferMemory, fd->IndexBufferSize, index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
219 
220     // Upload Vertex and index Data:
221     {
222         ImDrawVert* vtx_dst = NULL;
223         ImDrawIdx* idx_dst = NULL;
224         err = vkMapMemory(g_Device, fd->VertexBufferMemory, 0, vertex_size, 0, (void**)(&vtx_dst));
225         check_vk_result(err);
226         err = vkMapMemory(g_Device, fd->IndexBufferMemory, 0, index_size, 0, (void**)(&idx_dst));
227         check_vk_result(err);
228         for (int n = 0; n < draw_data->CmdListsCount; n++)
229         {
230             const ImDrawList* cmd_list = draw_data->CmdLists[n];
231             memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
232             memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
233             vtx_dst += cmd_list->VtxBuffer.Size;
234             idx_dst += cmd_list->IdxBuffer.Size;
235         }
236         VkMappedMemoryRange range[2] = {};
237         range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
238         range[0].memory = fd->VertexBufferMemory;
239         range[0].size = VK_WHOLE_SIZE;
240         range[1].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
241         range[1].memory = fd->IndexBufferMemory;
242         range[1].size = VK_WHOLE_SIZE;
243         err = vkFlushMappedMemoryRanges(g_Device, 2, range);
244         check_vk_result(err);
245         vkUnmapMemory(g_Device, fd->VertexBufferMemory);
246         vkUnmapMemory(g_Device, fd->IndexBufferMemory);
247     }
248 
249     // Bind pipeline and descriptor sets:
250     {
251         vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, g_Pipeline);
252         VkDescriptorSet desc_set[1] = { g_DescriptorSet };
253         vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, g_PipelineLayout, 0, 1, desc_set, 0, NULL);
254     }
255 
256     // Bind Vertex And Index Buffer:
257     {
258         VkBuffer vertex_buffers[1] = { fd->VertexBuffer };
259         VkDeviceSize vertex_offset[1] = { 0 };
260         vkCmdBindVertexBuffers(command_buffer, 0, 1, vertex_buffers, vertex_offset);
261         vkCmdBindIndexBuffer(command_buffer, fd->IndexBuffer, 0, VK_INDEX_TYPE_UINT16);
262     }
263 
264     // Setup viewport:
265     {
266         VkViewport viewport;
267         viewport.x = 0;
268         viewport.y = 0;
269         viewport.width = draw_data->DisplaySize.x;
270         viewport.height = draw_data->DisplaySize.y;
271         viewport.minDepth = 0.0f;
272         viewport.maxDepth = 1.0f;
273         vkCmdSetViewport(command_buffer, 0, 1, &viewport);
274     }
275 
276     // Setup scale and translation:
277     // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps.
278     {
279         float scale[2];
280         scale[0] = 2.0f / draw_data->DisplaySize.x;
281         scale[1] = 2.0f / draw_data->DisplaySize.y;
282         float translate[2];
283         translate[0] = -1.0f - draw_data->DisplayPos.x * scale[0];
284         translate[1] = -1.0f - draw_data->DisplayPos.y * scale[1];
285         vkCmdPushConstants(command_buffer, g_PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 0, sizeof(float) * 2, scale);
286         vkCmdPushConstants(command_buffer, g_PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 2, sizeof(float) * 2, translate);
287     }
288 
289     // Render the command lists:
290     int vtx_offset = 0;
291     int idx_offset = 0;
292     ImVec2 display_pos = draw_data->DisplayPos;
293     for (int n = 0; n < draw_data->CmdListsCount; n++)
294     {
295         const ImDrawList* cmd_list = draw_data->CmdLists[n];
296         for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
297         {
298             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
299             if (pcmd->UserCallback)
300             {
301                 pcmd->UserCallback(cmd_list, pcmd);
302             }
303             else
304             {
305                 // Apply scissor/clipping rectangle
306                 // FIXME: We could clamp width/height based on clamped min/max values.
307                 VkRect2D scissor;
308                 scissor.offset.x = (int32_t)(pcmd->ClipRect.x - display_pos.x) > 0 ? (int32_t)(pcmd->ClipRect.x - display_pos.x) : 0;
309                 scissor.offset.y = (int32_t)(pcmd->ClipRect.y - display_pos.y) > 0 ? (int32_t)(pcmd->ClipRect.y - display_pos.y) : 0;
310                 scissor.extent.width = (uint32_t)(pcmd->ClipRect.z - pcmd->ClipRect.x);
311                 scissor.extent.height = (uint32_t)(pcmd->ClipRect.w - pcmd->ClipRect.y + 1); // FIXME: Why +1 here?
312                 vkCmdSetScissor(command_buffer, 0, 1, &scissor);
313 
314                 // Draw
315                 vkCmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, idx_offset, vtx_offset, 0);
316             }
317             idx_offset += pcmd->ElemCount;
318         }
319         vtx_offset += cmd_list->VtxBuffer.Size;
320     }
321 }
322 
ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer)323 bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer)
324 {
325     ImGuiIO& io = ImGui::GetIO();
326 
327     unsigned char* pixels;
328     int width, height;
329     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
330     size_t upload_size = width*height*4*sizeof(char);
331 
332     VkResult err;
333 
334     // Create the Image:
335     {
336         VkImageCreateInfo info = {};
337         info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
338         info.imageType = VK_IMAGE_TYPE_2D;
339         info.format = VK_FORMAT_R8G8B8A8_UNORM;
340         info.extent.width = width;
341         info.extent.height = height;
342         info.extent.depth = 1;
343         info.mipLevels = 1;
344         info.arrayLayers = 1;
345         info.samples = VK_SAMPLE_COUNT_1_BIT;
346         info.tiling = VK_IMAGE_TILING_OPTIMAL;
347         info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
348         info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
349         info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
350         err = vkCreateImage(g_Device, &info, g_Allocator, &g_FontImage);
351         check_vk_result(err);
352         VkMemoryRequirements req;
353         vkGetImageMemoryRequirements(g_Device, g_FontImage, &req);
354         VkMemoryAllocateInfo alloc_info = {};
355         alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
356         alloc_info.allocationSize = req.size;
357         alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, req.memoryTypeBits);
358         err = vkAllocateMemory(g_Device, &alloc_info, g_Allocator, &g_FontMemory);
359         check_vk_result(err);
360         err = vkBindImageMemory(g_Device, g_FontImage, g_FontMemory, 0);
361         check_vk_result(err);
362     }
363 
364     // Create the Image View:
365     {
366         VkImageViewCreateInfo info = {};
367         info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
368         info.image = g_FontImage;
369         info.viewType = VK_IMAGE_VIEW_TYPE_2D;
370         info.format = VK_FORMAT_R8G8B8A8_UNORM;
371         info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
372         info.subresourceRange.levelCount = 1;
373         info.subresourceRange.layerCount = 1;
374         err = vkCreateImageView(g_Device, &info, g_Allocator, &g_FontView);
375         check_vk_result(err);
376     }
377 
378     // Update the Descriptor Set:
379     {
380         VkDescriptorImageInfo desc_image[1] = {};
381         desc_image[0].sampler = g_FontSampler;
382         desc_image[0].imageView = g_FontView;
383         desc_image[0].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
384         VkWriteDescriptorSet write_desc[1] = {};
385         write_desc[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
386         write_desc[0].dstSet = g_DescriptorSet;
387         write_desc[0].descriptorCount = 1;
388         write_desc[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
389         write_desc[0].pImageInfo = desc_image;
390         vkUpdateDescriptorSets(g_Device, 1, write_desc, 0, NULL);
391     }
392 
393     // Create the Upload Buffer:
394     {
395         VkBufferCreateInfo buffer_info = {};
396         buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
397         buffer_info.size = upload_size;
398         buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
399         buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
400         err = vkCreateBuffer(g_Device, &buffer_info, g_Allocator, &g_UploadBuffer);
401         check_vk_result(err);
402         VkMemoryRequirements req;
403         vkGetBufferMemoryRequirements(g_Device, g_UploadBuffer, &req);
404         g_BufferMemoryAlignment = (g_BufferMemoryAlignment > req.alignment) ? g_BufferMemoryAlignment : req.alignment;
405         VkMemoryAllocateInfo alloc_info = {};
406         alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
407         alloc_info.allocationSize = req.size;
408         alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits);
409         err = vkAllocateMemory(g_Device, &alloc_info, g_Allocator, &g_UploadBufferMemory);
410         check_vk_result(err);
411         err = vkBindBufferMemory(g_Device, g_UploadBuffer, g_UploadBufferMemory, 0);
412         check_vk_result(err);
413     }
414 
415     // Upload to Buffer:
416     {
417         char* map = NULL;
418         err = vkMapMemory(g_Device, g_UploadBufferMemory, 0, upload_size, 0, (void**)(&map));
419         check_vk_result(err);
420         memcpy(map, pixels, upload_size);
421         VkMappedMemoryRange range[1] = {};
422         range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
423         range[0].memory = g_UploadBufferMemory;
424         range[0].size = upload_size;
425         err = vkFlushMappedMemoryRanges(g_Device, 1, range);
426         check_vk_result(err);
427         vkUnmapMemory(g_Device, g_UploadBufferMemory);
428     }
429 
430     // Copy to Image:
431     {
432         VkImageMemoryBarrier copy_barrier[1] = {};
433         copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
434         copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
435         copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
436         copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
437         copy_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
438         copy_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
439         copy_barrier[0].image = g_FontImage;
440         copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
441         copy_barrier[0].subresourceRange.levelCount = 1;
442         copy_barrier[0].subresourceRange.layerCount = 1;
443         vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, copy_barrier);
444 
445         VkBufferImageCopy region = {};
446         region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
447         region.imageSubresource.layerCount = 1;
448         region.imageExtent.width = width;
449         region.imageExtent.height = height;
450         region.imageExtent.depth = 1;
451         vkCmdCopyBufferToImage(command_buffer, g_UploadBuffer, g_FontImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);
452 
453         VkImageMemoryBarrier use_barrier[1] = {};
454         use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
455         use_barrier[0].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
456         use_barrier[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
457         use_barrier[0].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
458         use_barrier[0].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
459         use_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
460         use_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
461         use_barrier[0].image = g_FontImage;
462         use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
463         use_barrier[0].subresourceRange.levelCount = 1;
464         use_barrier[0].subresourceRange.layerCount = 1;
465         vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, NULL, 0, NULL, 1, use_barrier);
466     }
467 
468     // Store our identifier
469     io.Fonts->TexID = (ImTextureID)(intptr_t)g_FontImage;
470 
471     return true;
472 }
473 
ImGui_ImplVulkan_CreateDeviceObjects()474 bool ImGui_ImplVulkan_CreateDeviceObjects()
475 {
476     VkResult err;
477     VkShaderModule vert_module;
478     VkShaderModule frag_module;
479 
480     // Create The Shader Modules:
481     {
482         VkShaderModuleCreateInfo vert_info = {};
483         vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
484         vert_info.codeSize = sizeof(__glsl_shader_vert_spv);
485         vert_info.pCode = (uint32_t*)__glsl_shader_vert_spv;
486         err = vkCreateShaderModule(g_Device, &vert_info, g_Allocator, &vert_module);
487         check_vk_result(err);
488         VkShaderModuleCreateInfo frag_info = {};
489         frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
490         frag_info.codeSize = sizeof(__glsl_shader_frag_spv);
491         frag_info.pCode = (uint32_t*)__glsl_shader_frag_spv;
492         err = vkCreateShaderModule(g_Device, &frag_info, g_Allocator, &frag_module);
493         check_vk_result(err);
494     }
495 
496     if (!g_FontSampler)
497     {
498         VkSamplerCreateInfo info = {};
499         info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
500         info.magFilter = VK_FILTER_LINEAR;
501         info.minFilter = VK_FILTER_LINEAR;
502         info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
503         info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
504         info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
505         info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
506         info.minLod = -1000;
507         info.maxLod = 1000;
508         info.maxAnisotropy = 1.0f;
509         err = vkCreateSampler(g_Device, &info, g_Allocator, &g_FontSampler);
510         check_vk_result(err);
511     }
512 
513     if (!g_DescriptorSetLayout)
514     {
515         VkSampler sampler[1] = {g_FontSampler};
516         VkDescriptorSetLayoutBinding binding[1] = {};
517         binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
518         binding[0].descriptorCount = 1;
519         binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
520         binding[0].pImmutableSamplers = sampler;
521         VkDescriptorSetLayoutCreateInfo info = {};
522         info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
523         info.bindingCount = 1;
524         info.pBindings = binding;
525         err = vkCreateDescriptorSetLayout(g_Device, &info, g_Allocator, &g_DescriptorSetLayout);
526         check_vk_result(err);
527     }
528 
529     // Create Descriptor Set:
530     {
531         VkDescriptorSetAllocateInfo alloc_info = {};
532         alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
533         alloc_info.descriptorPool = g_DescriptorPool;
534         alloc_info.descriptorSetCount = 1;
535         alloc_info.pSetLayouts = &g_DescriptorSetLayout;
536         err = vkAllocateDescriptorSets(g_Device, &alloc_info, &g_DescriptorSet);
537         check_vk_result(err);
538     }
539 
540     if (!g_PipelineLayout)
541     {
542         // Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full 3d projection matrix
543         VkPushConstantRange push_constants[1] = {};
544         push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
545         push_constants[0].offset = sizeof(float) * 0;
546         push_constants[0].size = sizeof(float) * 4;
547         VkDescriptorSetLayout set_layout[1] = { g_DescriptorSetLayout };
548         VkPipelineLayoutCreateInfo layout_info = {};
549         layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
550         layout_info.setLayoutCount = 1;
551         layout_info.pSetLayouts = set_layout;
552         layout_info.pushConstantRangeCount = 1;
553         layout_info.pPushConstantRanges = push_constants;
554         err = vkCreatePipelineLayout(g_Device, &layout_info, g_Allocator, &g_PipelineLayout);
555         check_vk_result(err);
556     }
557 
558     VkPipelineShaderStageCreateInfo stage[2] = {};
559     stage[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
560     stage[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
561     stage[0].module = vert_module;
562     stage[0].pName = "main";
563     stage[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
564     stage[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
565     stage[1].module = frag_module;
566     stage[1].pName = "main";
567 
568     VkVertexInputBindingDescription binding_desc[1] = {};
569     binding_desc[0].stride = sizeof(ImDrawVert);
570     binding_desc[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
571 
572     VkVertexInputAttributeDescription attribute_desc[3] = {};
573     attribute_desc[0].location = 0;
574     attribute_desc[0].binding = binding_desc[0].binding;
575     attribute_desc[0].format = VK_FORMAT_R32G32_SFLOAT;
576     attribute_desc[0].offset = IM_OFFSETOF(ImDrawVert, pos);
577     attribute_desc[1].location = 1;
578     attribute_desc[1].binding = binding_desc[0].binding;
579     attribute_desc[1].format = VK_FORMAT_R32G32_SFLOAT;
580     attribute_desc[1].offset = IM_OFFSETOF(ImDrawVert, uv);
581     attribute_desc[2].location = 2;
582     attribute_desc[2].binding = binding_desc[0].binding;
583     attribute_desc[2].format = VK_FORMAT_R8G8B8A8_UNORM;
584     attribute_desc[2].offset = IM_OFFSETOF(ImDrawVert, col);
585 
586     VkPipelineVertexInputStateCreateInfo vertex_info = {};
587     vertex_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
588     vertex_info.vertexBindingDescriptionCount = 1;
589     vertex_info.pVertexBindingDescriptions = binding_desc;
590     vertex_info.vertexAttributeDescriptionCount = 3;
591     vertex_info.pVertexAttributeDescriptions = attribute_desc;
592 
593     VkPipelineInputAssemblyStateCreateInfo ia_info = {};
594     ia_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
595     ia_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
596 
597     VkPipelineViewportStateCreateInfo viewport_info = {};
598     viewport_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
599     viewport_info.viewportCount = 1;
600     viewport_info.scissorCount = 1;
601 
602     VkPipelineRasterizationStateCreateInfo raster_info = {};
603     raster_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
604     raster_info.polygonMode = VK_POLYGON_MODE_FILL;
605     raster_info.cullMode = VK_CULL_MODE_NONE;
606     raster_info.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
607     raster_info.lineWidth = 1.0f;
608 
609     VkPipelineMultisampleStateCreateInfo ms_info = {};
610     ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
611     ms_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
612 
613     VkPipelineColorBlendAttachmentState color_attachment[1] = {};
614     color_attachment[0].blendEnable = VK_TRUE;
615     color_attachment[0].srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
616     color_attachment[0].dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
617     color_attachment[0].colorBlendOp = VK_BLEND_OP_ADD;
618     color_attachment[0].srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
619     color_attachment[0].dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
620     color_attachment[0].alphaBlendOp = VK_BLEND_OP_ADD;
621     color_attachment[0].colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
622 
623     VkPipelineDepthStencilStateCreateInfo depth_info = {};
624     depth_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
625 
626     VkPipelineColorBlendStateCreateInfo blend_info = {};
627     blend_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
628     blend_info.attachmentCount = 1;
629     blend_info.pAttachments = color_attachment;
630 
631     VkDynamicState dynamic_states[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
632     VkPipelineDynamicStateCreateInfo dynamic_state = {};
633     dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
634     dynamic_state.dynamicStateCount = (uint32_t)IM_ARRAYSIZE(dynamic_states);
635     dynamic_state.pDynamicStates = dynamic_states;
636 
637     VkGraphicsPipelineCreateInfo info = {};
638     info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
639     info.flags = g_PipelineCreateFlags;
640     info.stageCount = 2;
641     info.pStages = stage;
642     info.pVertexInputState = &vertex_info;
643     info.pInputAssemblyState = &ia_info;
644     info.pViewportState = &viewport_info;
645     info.pRasterizationState = &raster_info;
646     info.pMultisampleState = &ms_info;
647     info.pDepthStencilState = &depth_info;
648     info.pColorBlendState = &blend_info;
649     info.pDynamicState = &dynamic_state;
650     info.layout = g_PipelineLayout;
651     info.renderPass = g_RenderPass;
652     err = vkCreateGraphicsPipelines(g_Device, g_PipelineCache, 1, &info, g_Allocator, &g_Pipeline);
653     check_vk_result(err);
654 
655     vkDestroyShaderModule(g_Device, vert_module, g_Allocator);
656     vkDestroyShaderModule(g_Device, frag_module, g_Allocator);
657 
658     return true;
659 }
660 
ImGui_ImplVulkan_InvalidateFontUploadObjects()661 void    ImGui_ImplVulkan_InvalidateFontUploadObjects()
662 {
663     if (g_UploadBuffer)
664     {
665         vkDestroyBuffer(g_Device, g_UploadBuffer, g_Allocator);
666         g_UploadBuffer = VK_NULL_HANDLE;
667     }
668     if (g_UploadBufferMemory)
669     {
670         vkFreeMemory(g_Device, g_UploadBufferMemory, g_Allocator);
671         g_UploadBufferMemory = VK_NULL_HANDLE;
672     }
673 }
674 
ImGui_ImplVulkan_InvalidateDeviceObjects()675 void    ImGui_ImplVulkan_InvalidateDeviceObjects()
676 {
677     ImGui_ImplVulkan_InvalidateFontUploadObjects();
678 
679     for (int i = 0; i < IMGUI_VK_QUEUED_FRAMES; i++)
680     {
681         FrameDataForRender* fd = &g_FramesDataBuffers[i];
682         if (fd->VertexBuffer)       { vkDestroyBuffer   (g_Device, fd->VertexBuffer,        g_Allocator); fd->VertexBuffer = VK_NULL_HANDLE; }
683         if (fd->VertexBufferMemory) { vkFreeMemory      (g_Device, fd->VertexBufferMemory,  g_Allocator); fd->VertexBufferMemory = VK_NULL_HANDLE; }
684         if (fd->IndexBuffer)        { vkDestroyBuffer   (g_Device, fd->IndexBuffer,         g_Allocator); fd->IndexBuffer = VK_NULL_HANDLE; }
685         if (fd->IndexBufferMemory)  { vkFreeMemory      (g_Device, fd->IndexBufferMemory,   g_Allocator); fd->IndexBufferMemory = VK_NULL_HANDLE; }
686     }
687 
688     if (g_FontView)             { vkDestroyImageView(g_Device, g_FontView, g_Allocator); g_FontView = VK_NULL_HANDLE; }
689     if (g_FontImage)            { vkDestroyImage(g_Device, g_FontImage, g_Allocator); g_FontImage = VK_NULL_HANDLE; }
690     if (g_FontMemory)           { vkFreeMemory(g_Device, g_FontMemory, g_Allocator); g_FontMemory = VK_NULL_HANDLE; }
691     if (g_FontSampler)          { vkDestroySampler(g_Device, g_FontSampler, g_Allocator); g_FontSampler = VK_NULL_HANDLE; }
692     if (g_DescriptorSetLayout)  { vkDestroyDescriptorSetLayout(g_Device, g_DescriptorSetLayout, g_Allocator); g_DescriptorSetLayout = VK_NULL_HANDLE; }
693     if (g_PipelineLayout)       { vkDestroyPipelineLayout(g_Device, g_PipelineLayout, g_Allocator); g_PipelineLayout = VK_NULL_HANDLE; }
694     if (g_Pipeline)             { vkDestroyPipeline(g_Device, g_Pipeline, g_Allocator); g_Pipeline = VK_NULL_HANDLE; }
695 }
696 
ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo * info,VkRenderPass render_pass)697 bool    ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass)
698 {
699     ImGuiIO& io = ImGui::GetIO();
700     io.BackendRendererName = "imgui_impl_vulkan";
701 
702     IM_ASSERT(info->Instance != VK_NULL_HANDLE);
703     IM_ASSERT(info->PhysicalDevice != VK_NULL_HANDLE);
704     IM_ASSERT(info->Device != VK_NULL_HANDLE);
705     IM_ASSERT(info->Queue != VK_NULL_HANDLE);
706     IM_ASSERT(info->DescriptorPool != VK_NULL_HANDLE);
707     IM_ASSERT(render_pass != VK_NULL_HANDLE);
708 
709     g_Instance = info->Instance;
710     g_PhysicalDevice = info->PhysicalDevice;
711     g_Device = info->Device;
712     g_QueueFamily = info->QueueFamily;
713     g_Queue = info->Queue;
714     g_RenderPass = render_pass;
715     g_PipelineCache = info->PipelineCache;
716     g_DescriptorPool = info->DescriptorPool;
717     g_Allocator = info->Allocator;
718     g_CheckVkResultFn = info->CheckVkResultFn;
719 
720     ImGui_ImplVulkan_CreateDeviceObjects();
721 
722     return true;
723 }
724 
ImGui_ImplVulkan_Shutdown()725 void ImGui_ImplVulkan_Shutdown()
726 {
727     ImGui_ImplVulkan_InvalidateDeviceObjects();
728 }
729 
ImGui_ImplVulkan_NewFrame()730 void ImGui_ImplVulkan_NewFrame()
731 {
732 }
733 
734 
735 //-------------------------------------------------------------------------
736 // Internal / Miscellaneous Vulkan Helpers
737 //-------------------------------------------------------------------------
738 // You probably do NOT need to use or care about those functions.
739 // Those functions only exist because:
740 //   1) they facilitate the readability and maintenance of the multiple main.cpp examples files.
741 //   2) the upcoming multi-viewport feature will need them internally.
742 // Generally we avoid exposing any kind of superfluous high-level helpers in the bindings,
743 // but it is too much code to duplicate everywhere so we exceptionally expose them.
744 // Your application/engine will likely already have code to setup all that stuff (swap chain, render pass, frame buffers, etc.).
745 // You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work.
746 // (those functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions)
747 //-------------------------------------------------------------------------
748 
749 #include <stdlib.h> // malloc
750 
ImGui_ImplVulkanH_FrameData()751 ImGui_ImplVulkanH_FrameData::ImGui_ImplVulkanH_FrameData()
752 {
753     BackbufferIndex = 0;
754     CommandPool = VK_NULL_HANDLE;
755     CommandBuffer = VK_NULL_HANDLE;
756     Fence = VK_NULL_HANDLE;
757     ImageAcquiredSemaphore = VK_NULL_HANDLE;
758     RenderCompleteSemaphore = VK_NULL_HANDLE;
759 }
760 
ImGui_ImplVulkanH_WindowData()761 ImGui_ImplVulkanH_WindowData::ImGui_ImplVulkanH_WindowData()
762 {
763     Width = Height = 0;
764     Swapchain = VK_NULL_HANDLE;
765     Surface = VK_NULL_HANDLE;
766     memset(&SurfaceFormat, 0, sizeof(SurfaceFormat));
767     PresentMode = VK_PRESENT_MODE_MAX_ENUM_KHR;
768     RenderPass = VK_NULL_HANDLE;
769     ClearEnable = true;
770     memset(&ClearValue, 0, sizeof(ClearValue));
771     BackBufferCount = 0;
772     memset(&BackBuffer, 0, sizeof(BackBuffer));
773     memset(&BackBufferView, 0, sizeof(BackBufferView));
774     memset(&Framebuffer, 0, sizeof(Framebuffer));
775     FrameIndex = 0;
776 }
777 
ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device,VkSurfaceKHR surface,const VkFormat * request_formats,int request_formats_count,VkColorSpaceKHR request_color_space)778 VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space)
779 {
780     IM_ASSERT(request_formats != NULL);
781     IM_ASSERT(request_formats_count > 0);
782 
783     // Per Spec Format and View Format are expected to be the same unless VK_IMAGE_CREATE_MUTABLE_BIT was set at image creation
784     // Assuming that the default behavior is without setting this bit, there is no need for separate Swapchain image and image view format
785     // Additionally several new color spaces were introduced with Vulkan Spec v1.0.40,
786     // hence we must make sure that a format with the mostly available color space, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, is found and used.
787     uint32_t avail_count;
788     vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, NULL);
789     ImVector<VkSurfaceFormatKHR> avail_format;
790     avail_format.resize((int)avail_count);
791     vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, avail_format.Data);
792 
793     // First check if only one format, VK_FORMAT_UNDEFINED, is available, which would imply that any format is available
794     if (avail_count == 1)
795     {
796         if (avail_format[0].format == VK_FORMAT_UNDEFINED)
797         {
798             VkSurfaceFormatKHR ret;
799             ret.format = request_formats[0];
800             ret.colorSpace = request_color_space;
801             return ret;
802         }
803         else
804         {
805             // No point in searching another format
806             return avail_format[0];
807         }
808     }
809     else
810     {
811         // Request several formats, the first found will be used
812         for (int request_i = 0; request_i < request_formats_count; request_i++)
813             for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++)
814                 if (avail_format[avail_i].format == request_formats[request_i] && avail_format[avail_i].colorSpace == request_color_space)
815                     return avail_format[avail_i];
816 
817         // If none of the requested image formats could be found, use the first available
818         return avail_format[0];
819     }
820 }
821 
ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device,VkSurfaceKHR surface,const VkPresentModeKHR * request_modes,int request_modes_count)822 VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count)
823 {
824     IM_ASSERT(request_modes != NULL);
825     IM_ASSERT(request_modes_count > 0);
826 
827     // Request a certain mode and confirm that it is available. If not use VK_PRESENT_MODE_FIFO_KHR which is mandatory
828     uint32_t avail_count = 0;
829     vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &avail_count, NULL);
830     ImVector<VkPresentModeKHR> avail_modes;
831     avail_modes.resize((int)avail_count);
832     vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &avail_count, avail_modes.Data);
833     //for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++)
834     //    printf("[vulkan] avail_modes[%d] = %d\n", avail_i, avail_modes[avail_i]);
835 
836     for (int request_i = 0; request_i < request_modes_count; request_i++)
837         for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++)
838             if (request_modes[request_i] == avail_modes[avail_i])
839                 return request_modes[request_i];
840 
841     return VK_PRESENT_MODE_FIFO_KHR; // Always available
842 }
843 
ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkPhysicalDevice physical_device,VkDevice device,uint32_t queue_family,ImGui_ImplVulkanH_WindowData * wd,const VkAllocationCallbacks * allocator)844 void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, uint32_t queue_family, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator)
845 {
846     IM_ASSERT(physical_device != VK_NULL_HANDLE && device != VK_NULL_HANDLE);
847     (void)physical_device;
848     (void)allocator;
849 
850     // Create Command Buffers
851     VkResult err;
852     for (int i = 0; i < IMGUI_VK_QUEUED_FRAMES; i++)
853     {
854         ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i];
855         {
856             VkCommandPoolCreateInfo info = {};
857             info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
858             info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
859             info.queueFamilyIndex = queue_family;
860             err = vkCreateCommandPool(device, &info, allocator, &fd->CommandPool);
861             check_vk_result(err);
862         }
863         {
864             VkCommandBufferAllocateInfo info = {};
865             info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
866             info.commandPool = fd->CommandPool;
867             info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
868             info.commandBufferCount = 1;
869             err = vkAllocateCommandBuffers(device, &info, &fd->CommandBuffer);
870             check_vk_result(err);
871         }
872         {
873             VkFenceCreateInfo info = {};
874             info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
875             info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
876             err = vkCreateFence(device, &info, allocator, &fd->Fence);
877             check_vk_result(err);
878         }
879         {
880             VkSemaphoreCreateInfo info = {};
881             info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
882             err = vkCreateSemaphore(device, &info, allocator, &fd->ImageAcquiredSemaphore);
883             check_vk_result(err);
884             err = vkCreateSemaphore(device, &info, allocator, &fd->RenderCompleteSemaphore);
885             check_vk_result(err);
886         }
887     }
888 }
889 
ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode)890 int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode)
891 {
892     if (present_mode == VK_PRESENT_MODE_MAILBOX_KHR)
893         return 3;
894     if (present_mode == VK_PRESENT_MODE_FIFO_KHR || present_mode == VK_PRESENT_MODE_FIFO_RELAXED_KHR)
895         return 2;
896     if (present_mode == VK_PRESENT_MODE_IMMEDIATE_KHR)
897         return 1;
898     IM_ASSERT(0);
899     return 1;
900 }
901 
ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice physical_device,VkDevice device,ImGui_ImplVulkanH_WindowData * wd,const VkAllocationCallbacks * allocator,int w,int h)902 void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h)
903 {
904     uint32_t min_image_count = 2;	// FIXME: this should become a function parameter
905 
906     VkResult err;
907     VkSwapchainKHR old_swapchain = wd->Swapchain;
908     err = vkDeviceWaitIdle(device);
909     check_vk_result(err);
910 
911     // Destroy old Framebuffer
912     for (uint32_t i = 0; i < wd->BackBufferCount; i++)
913     {
914         if (wd->BackBufferView[i])
915             vkDestroyImageView(device, wd->BackBufferView[i], allocator);
916         if (wd->Framebuffer[i])
917             vkDestroyFramebuffer(device, wd->Framebuffer[i], allocator);
918     }
919     wd->BackBufferCount = 0;
920     if (wd->RenderPass)
921         vkDestroyRenderPass(device, wd->RenderPass, allocator);
922 
923     // If min image count was not specified, request different count of images dependent on selected present mode
924     if (min_image_count == 0)
925         min_image_count = ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(wd->PresentMode);
926 
927     // Create Swapchain
928     {
929         VkSwapchainCreateInfoKHR info = {};
930         info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
931         info.surface = wd->Surface;
932 		info.minImageCount = min_image_count;
933         info.imageFormat = wd->SurfaceFormat.format;
934         info.imageColorSpace = wd->SurfaceFormat.colorSpace;
935         info.imageArrayLayers = 1;
936         info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
937         info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;           // Assume that graphics family == present family
938         info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
939         info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
940         info.presentMode = wd->PresentMode;
941         info.clipped = VK_TRUE;
942         info.oldSwapchain = old_swapchain;
943         VkSurfaceCapabilitiesKHR cap;
944         err = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device, wd->Surface, &cap);
945         check_vk_result(err);
946         if (info.minImageCount < cap.minImageCount)
947 			info.minImageCount = cap.minImageCount;
948 		else if (cap.maxImageCount != 0 && info.minImageCount > cap.maxImageCount)
949 			info.minImageCount = cap.maxImageCount;
950 
951         if (cap.currentExtent.width == 0xffffffff)
952         {
953             info.imageExtent.width = wd->Width = w;
954             info.imageExtent.height = wd->Height = h;
955         }
956         else
957         {
958             info.imageExtent.width = wd->Width = cap.currentExtent.width;
959             info.imageExtent.height = wd->Height = cap.currentExtent.height;
960         }
961         err = vkCreateSwapchainKHR(device, &info, allocator, &wd->Swapchain);
962         check_vk_result(err);
963         err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->BackBufferCount, NULL);
964         check_vk_result(err);
965         err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->BackBufferCount, wd->BackBuffer);
966         check_vk_result(err);
967     }
968     if (old_swapchain)
969         vkDestroySwapchainKHR(device, old_swapchain, allocator);
970 
971     // Create the Render Pass
972     {
973         VkAttachmentDescription attachment = {};
974         attachment.format = wd->SurfaceFormat.format;
975         attachment.samples = VK_SAMPLE_COUNT_1_BIT;
976         attachment.loadOp = wd->ClearEnable ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_DONT_CARE;
977         attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
978         attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
979         attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
980         attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
981         attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
982         VkAttachmentReference color_attachment = {};
983         color_attachment.attachment = 0;
984         color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
985         VkSubpassDescription subpass = {};
986         subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
987         subpass.colorAttachmentCount = 1;
988         subpass.pColorAttachments = &color_attachment;
989         VkSubpassDependency dependency = {};
990         dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
991         dependency.dstSubpass = 0;
992         dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
993         dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
994         dependency.srcAccessMask = 0;
995         dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
996         VkRenderPassCreateInfo info = {};
997         info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
998         info.attachmentCount = 1;
999         info.pAttachments = &attachment;
1000         info.subpassCount = 1;
1001         info.pSubpasses = &subpass;
1002         info.dependencyCount = 1;
1003         info.pDependencies = &dependency;
1004         err = vkCreateRenderPass(device, &info, allocator, &wd->RenderPass);
1005         check_vk_result(err);
1006     }
1007 
1008     // Create The Image Views
1009     {
1010         VkImageViewCreateInfo info = {};
1011         info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1012         info.viewType = VK_IMAGE_VIEW_TYPE_2D;
1013         info.format = wd->SurfaceFormat.format;
1014         info.components.r = VK_COMPONENT_SWIZZLE_R;
1015         info.components.g = VK_COMPONENT_SWIZZLE_G;
1016         info.components.b = VK_COMPONENT_SWIZZLE_B;
1017         info.components.a = VK_COMPONENT_SWIZZLE_A;
1018         VkImageSubresourceRange image_range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
1019         info.subresourceRange = image_range;
1020         for (uint32_t i = 0; i < wd->BackBufferCount; i++)
1021         {
1022             info.image = wd->BackBuffer[i];
1023             err = vkCreateImageView(device, &info, allocator, &wd->BackBufferView[i]);
1024             check_vk_result(err);
1025         }
1026     }
1027 
1028     // Create Framebuffer
1029     {
1030         VkImageView attachment[1];
1031         VkFramebufferCreateInfo info = {};
1032         info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
1033         info.renderPass = wd->RenderPass;
1034         info.attachmentCount = 1;
1035         info.pAttachments = attachment;
1036         info.width = wd->Width;
1037         info.height = wd->Height;
1038         info.layers = 1;
1039         for (uint32_t i = 0; i < wd->BackBufferCount; i++)
1040         {
1041             attachment[0] = wd->BackBufferView[i];
1042             err = vkCreateFramebuffer(device, &info, allocator, &wd->Framebuffer[i]);
1043             check_vk_result(err);
1044         }
1045     }
1046 }
1047 
ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance,VkDevice device,ImGui_ImplVulkanH_WindowData * wd,const VkAllocationCallbacks * allocator)1048 void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator)
1049 {
1050     vkDeviceWaitIdle(device); // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals)
1051     //vkQueueWaitIdle(g_Queue);
1052 
1053     for (int i = 0; i < IMGUI_VK_QUEUED_FRAMES; i++)
1054     {
1055         ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i];
1056         vkDestroyFence(device, fd->Fence, allocator);
1057         vkFreeCommandBuffers(device, fd->CommandPool, 1, &fd->CommandBuffer);
1058         vkDestroyCommandPool(device, fd->CommandPool, allocator);
1059         vkDestroySemaphore(device, fd->ImageAcquiredSemaphore, allocator);
1060         vkDestroySemaphore(device, fd->RenderCompleteSemaphore, allocator);
1061     }
1062     for (uint32_t i = 0; i < wd->BackBufferCount; i++)
1063     {
1064         vkDestroyImageView(device, wd->BackBufferView[i], allocator);
1065         vkDestroyFramebuffer(device, wd->Framebuffer[i], allocator);
1066     }
1067     vkDestroyRenderPass(device, wd->RenderPass, allocator);
1068     vkDestroySwapchainKHR(device, wd->Swapchain, allocator);
1069     vkDestroySurfaceKHR(instance, wd->Surface, allocator);
1070     *wd = ImGui_ImplVulkanH_WindowData();
1071 }
1072