imgui_impl_vulkan.cpp 51 KB

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