imgui_impl_vulkan.cpp 83 KB

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