imgui_impl_vulkan.cpp 50 KB

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