source: opengl-game/IMGUI/imgui_impl_vulkan.cpp@ 3b7d497

feature/imgui-sdl
Last change on this file since 3b7d497 was 3b7d497, checked in by Dmitry Portnoy <dportnoy@…>, 4 years ago

Start implementing an ImGUI ui on top of SDL and Vulkan using some example code

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