imgui_impl_vulkan.cpp 97 KB

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