imgui_impl_vulkan.cpp 65 KB

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