imgui_impl_vulkan.cpp 62 KB

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