2
0

imgui_impl_vulkan.cpp 101 KB

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