imgui_impl_vulkan.cpp 80 KB

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