imgui_impl_vulkan.cpp 49 KB

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