imgui_impl_vulkan.cpp 95 KB

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