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