imgui_impl_vulkan.cpp 65 KB

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