imgui_impl_vulkan.cpp 82 KB

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