main.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. // ImGui - standalone example application for Glfw + Vulkan, using programmable pipeline
  2. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  3. #include <imgui.h>
  4. #include <stdio.h> // printf, fprintf
  5. #include <stdlib.h> // abort
  6. #define GLFW_INCLUDE_NONE
  7. #define GLFW_INCLUDE_VULKAN
  8. #include <GLFW/glfw3.h>
  9. #include "imgui_impl_glfw_vulkan.h"
  10. #define IMGUI_MAX_POSSIBLE_BACK_BUFFERS 16
  11. #define IMGUI_UNLIMITED_FRAME_RATE
  12. #define IMGUI_VULKAN_DEBUG_REPORT
  13. static VkAllocationCallbacks* g_Allocator = NULL;
  14. static VkInstance g_Instance = VK_NULL_HANDLE;
  15. static VkSurfaceKHR g_Surface = VK_NULL_HANDLE;
  16. static VkPhysicalDevice g_Gpu = VK_NULL_HANDLE;
  17. static VkDevice g_Device = VK_NULL_HANDLE;
  18. static VkSwapchainKHR g_Swapchain = VK_NULL_HANDLE;
  19. static VkRenderPass g_RenderPass = VK_NULL_HANDLE;
  20. static uint32_t g_QueueFamily = 0;
  21. static VkQueue g_Queue = VK_NULL_HANDLE;
  22. static VkDebugReportCallbackEXT g_Debug_Report = VK_NULL_HANDLE;
  23. static VkFormat g_ImageFormat = VK_FORMAT_B8G8R8A8_UNORM;
  24. static VkFormat g_ViewFormat = VK_FORMAT_B8G8R8A8_UNORM;
  25. static VkColorSpaceKHR g_ColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
  26. static VkImageSubresourceRange g_ImageRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
  27. static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE;
  28. static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE;
  29. static int fb_width, fb_height;
  30. static uint32_t g_BackBufferIndex = 0;
  31. static uint32_t g_BackBufferCount = 0;
  32. static VkImage g_BackBuffer[IMGUI_MAX_POSSIBLE_BACK_BUFFERS] = {};
  33. static VkImageView g_BackBufferView[IMGUI_MAX_POSSIBLE_BACK_BUFFERS] = {};
  34. static VkFramebuffer g_Framebuffer[IMGUI_MAX_POSSIBLE_BACK_BUFFERS] = {};
  35. static uint32_t g_FrameIndex = 0;
  36. static VkCommandPool g_CommandPool[IMGUI_VK_QUEUED_FRAMES];
  37. static VkCommandBuffer g_CommandBuffer[IMGUI_VK_QUEUED_FRAMES];
  38. static VkFence g_Fence[IMGUI_VK_QUEUED_FRAMES];
  39. static VkSemaphore g_Semaphore[IMGUI_VK_QUEUED_FRAMES];
  40. static VkClearValue g_ClearValue = {};
  41. static void check_vk_result(VkResult err)
  42. {
  43. if (err == 0) return;
  44. printf("VkResult %d\n", err);
  45. if (err < 0)
  46. abort();
  47. }
  48. static void resize_vulkan(GLFWwindow* /*window*/, int w, int h)
  49. {
  50. VkResult err;
  51. VkSwapchainKHR old_swapchain = g_Swapchain;
  52. err = vkDeviceWaitIdle(g_Device);
  53. check_vk_result(err);
  54. // Destroy old Framebuffer:
  55. for (uint32_t i = 0; i < g_BackBufferCount; i++)
  56. if (g_BackBufferView[i])
  57. vkDestroyImageView(g_Device, g_BackBufferView[i], g_Allocator);
  58. for (uint32_t i = 0; i < g_BackBufferCount; i++)
  59. if (g_Framebuffer[i])
  60. vkDestroyFramebuffer(g_Device, g_Framebuffer[i], g_Allocator);
  61. if (g_RenderPass)
  62. vkDestroyRenderPass(g_Device, g_RenderPass, g_Allocator);
  63. // Create Swapchain:
  64. {
  65. VkSwapchainCreateInfoKHR info = {};
  66. info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
  67. info.surface = g_Surface;
  68. info.imageFormat = g_ImageFormat;
  69. info.imageColorSpace = g_ColorSpace;
  70. info.imageArrayLayers = 1;
  71. info.imageUsage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  72. info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
  73. info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
  74. info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  75. #ifdef IMGUI_UNLIMITED_FRAME_RATE
  76. info.presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
  77. #else
  78. info.presentMode = VK_PRESENT_MODE_FIFO_KHR;
  79. #endif // IMGUI_UNLIMITED_FRAME_RATE
  80. info.clipped = VK_TRUE;
  81. info.oldSwapchain = old_swapchain;
  82. VkSurfaceCapabilitiesKHR cap;
  83. err = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(g_Gpu, g_Surface, &cap);
  84. check_vk_result(err);
  85. if (cap.maxImageCount > 0)
  86. info.minImageCount = (cap.minImageCount + 2 < cap.maxImageCount) ? (cap.minImageCount + 2) : cap.maxImageCount;
  87. else
  88. info.minImageCount = cap.minImageCount + 2;
  89. if (cap.currentExtent.width == 0xffffffff)
  90. {
  91. fb_width = w;
  92. fb_height = h;
  93. info.imageExtent.width = fb_width;
  94. info.imageExtent.height = fb_height;
  95. }
  96. else
  97. {
  98. fb_width = cap.currentExtent.width;
  99. fb_height = cap.currentExtent.height;
  100. info.imageExtent.width = fb_width;
  101. info.imageExtent.height = fb_height;
  102. }
  103. err = vkCreateSwapchainKHR(g_Device, &info, g_Allocator, &g_Swapchain);
  104. check_vk_result(err);
  105. err = vkGetSwapchainImagesKHR(g_Device, g_Swapchain, &g_BackBufferCount, NULL);
  106. check_vk_result(err);
  107. err = vkGetSwapchainImagesKHR(g_Device, g_Swapchain, &g_BackBufferCount, g_BackBuffer);
  108. check_vk_result(err);
  109. }
  110. if (old_swapchain)
  111. vkDestroySwapchainKHR(g_Device, old_swapchain, g_Allocator);
  112. // Create the Render Pass:
  113. {
  114. VkAttachmentDescription attachment = {};
  115. attachment.format = g_ViewFormat;
  116. attachment.samples = VK_SAMPLE_COUNT_1_BIT;
  117. attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  118. attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  119. attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  120. attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  121. attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  122. attachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  123. VkAttachmentReference color_attachment = {};
  124. color_attachment.attachment = 0;
  125. color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  126. VkSubpassDescription subpass = {};
  127. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  128. subpass.colorAttachmentCount = 1;
  129. subpass.pColorAttachments = &color_attachment;
  130. VkRenderPassCreateInfo info = {};
  131. info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  132. info.attachmentCount = 1;
  133. info.pAttachments = &attachment;
  134. info.subpassCount = 1;
  135. info.pSubpasses = &subpass;
  136. err = vkCreateRenderPass(g_Device, &info, g_Allocator, &g_RenderPass);
  137. check_vk_result(err);
  138. }
  139. // Create The Image Views
  140. {
  141. VkImageViewCreateInfo info = {};
  142. info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  143. info.viewType = VK_IMAGE_VIEW_TYPE_2D;
  144. info.format = g_ViewFormat;
  145. info.components.r = VK_COMPONENT_SWIZZLE_R;
  146. info.components.g = VK_COMPONENT_SWIZZLE_G;
  147. info.components.b = VK_COMPONENT_SWIZZLE_B;
  148. info.components.a = VK_COMPONENT_SWIZZLE_A;
  149. info.subresourceRange = g_ImageRange;
  150. for (uint32_t i = 0; i < g_BackBufferCount; i++)
  151. {
  152. info.image = g_BackBuffer[i];
  153. err = vkCreateImageView(g_Device, &info, g_Allocator, &g_BackBufferView[i]);
  154. check_vk_result(err);
  155. }
  156. }
  157. // Create Framebuffer:
  158. {
  159. VkImageView attachment[1];
  160. VkFramebufferCreateInfo info = {};
  161. info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  162. info.renderPass = g_RenderPass;
  163. info.attachmentCount = 1;
  164. info.pAttachments = attachment;
  165. info.width = fb_width;
  166. info.height = fb_height;
  167. info.layers = 1;
  168. for (uint32_t i = 0; i < g_BackBufferCount; i++)
  169. {
  170. attachment[0] = g_BackBufferView[i];
  171. err = vkCreateFramebuffer(g_Device, &info, g_Allocator, &g_Framebuffer[i]);
  172. check_vk_result(err);
  173. }
  174. }
  175. }
  176. #ifdef IMGUI_VULKAN_DEBUG_REPORT
  177. static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(
  178. VkDebugReportFlagsEXT, //flags,
  179. VkDebugReportObjectTypeEXT objectType,
  180. uint64_t, //object,
  181. size_t, //location,
  182. int32_t, //messageCode,
  183. const char*, //pLayerPrefix,
  184. const char* pMessage,
  185. void*) //pUserData)
  186. {
  187. printf( "ObjectType : %i\nMessage : %s\n\n", objectType, pMessage );
  188. return VK_FALSE;
  189. }
  190. #endif // IMGUI_VULKAN_DEBUG_REPORT
  191. static void setup_vulkan(GLFWwindow* window)
  192. {
  193. VkResult err;
  194. // Create Vulkan Instance
  195. {
  196. uint32_t extensions_count;
  197. const char** glfw_extensions = glfwGetRequiredInstanceExtensions(&extensions_count);
  198. VkInstanceCreateInfo create_info = {};
  199. create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  200. #ifdef IMGUI_VULKAN_DEBUG_REPORT
  201. // enabling multiple validation layers grouped as lunarg standard validation
  202. const char* layers[] = {"VK_LAYER_LUNARG_standard_validation"};
  203. create_info.enabledLayerCount = 1;
  204. create_info.ppEnabledLayerNames = layers;
  205. // need additional storage for char pointer to debug report extension
  206. const char** extensions = (const char**)malloc(sizeof(const char*) * (extensions_count + 1));
  207. for(size_t i = 0; i < extensions_count; i++)
  208. extensions[i] = glfw_extensions[i];
  209. extensions[ extensions_count ] = "VK_EXT_debug_report";
  210. create_info.enabledExtensionCount = extensions_count+1;
  211. create_info.ppEnabledExtensionNames = extensions;
  212. #elif
  213. create_info.enabledExtensionCount = extensions_count;
  214. create_info.ppEnabledExtensionNames = glfw_extensions;
  215. #endif // IMGUI_VULKAN_DEBUG_REPORT
  216. err = vkCreateInstance(&create_info, g_Allocator, &g_Instance);
  217. check_vk_result(err);
  218. #ifdef IMGUI_VULKAN_DEBUG_REPORT
  219. free(extensions);
  220. // create the debug report callback
  221. VkDebugReportCallbackCreateInfoEXT debug_report_ci ={};
  222. debug_report_ci.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
  223. debug_report_ci.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
  224. debug_report_ci.pfnCallback = debug_report;
  225. debug_report_ci.pUserData = NULL;
  226. // get the proc address of the function pointer, required for used extensions
  227. PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT =
  228. (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT");
  229. err = vkCreateDebugReportCallbackEXT( g_Instance, &debug_report_ci, g_Allocator, &g_Debug_Report );
  230. check_vk_result( err );
  231. #endif // IMGUI_VULKAN_DEBUG_REPORT
  232. }
  233. // Create Window Surface
  234. {
  235. err = glfwCreateWindowSurface(g_Instance, window, g_Allocator, &g_Surface);
  236. check_vk_result(err);
  237. }
  238. // Get GPU (WARNING here we assume the first gpu is one we can use)
  239. {
  240. uint32_t count = 1;
  241. err = vkEnumeratePhysicalDevices(g_Instance, &count, &g_Gpu);
  242. check_vk_result(err);
  243. }
  244. // Get queue
  245. {
  246. uint32_t count;
  247. vkGetPhysicalDeviceQueueFamilyProperties(g_Gpu, &count, NULL);
  248. VkQueueFamilyProperties* queues = (VkQueueFamilyProperties*)malloc(sizeof(VkQueueFamilyProperties) * count);
  249. vkGetPhysicalDeviceQueueFamilyProperties(g_Gpu, &count, queues);
  250. for (uint32_t i = 0; i < count; i++)
  251. {
  252. if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)
  253. {
  254. g_QueueFamily = i;
  255. break;
  256. }
  257. }
  258. free(queues);
  259. }
  260. // Check for WSI support
  261. {
  262. VkBool32 res;
  263. vkGetPhysicalDeviceSurfaceSupportKHR(g_Gpu, g_QueueFamily, g_Surface, &res);
  264. if (res != VK_TRUE)
  265. {
  266. fprintf(stderr, "Error no WSI support on physical device 0\n");
  267. exit(-1);
  268. }
  269. }
  270. // Get Surface Format
  271. {
  272. VkFormat image_view_format[][2] = {{VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_UNORM}, {VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_B8G8R8A8_UNORM}};
  273. uint32_t count;
  274. vkGetPhysicalDeviceSurfaceFormatsKHR(g_Gpu, g_Surface, &count, NULL);
  275. VkSurfaceFormatKHR *formats = (VkSurfaceFormatKHR*)malloc(sizeof(VkSurfaceFormatKHR) * count);
  276. vkGetPhysicalDeviceSurfaceFormatsKHR(g_Gpu, g_Surface, &count, formats);
  277. for (size_t i = 0; i < sizeof(image_view_format) / sizeof(image_view_format[0]); i++)
  278. {
  279. for (uint32_t j = 0; j < count; j++)
  280. {
  281. if (formats[j].format == image_view_format[i][0])
  282. {
  283. g_ImageFormat = image_view_format[i][0];
  284. g_ViewFormat = image_view_format[i][1];
  285. g_ColorSpace = formats[j].colorSpace;
  286. }
  287. }
  288. }
  289. free(formats);
  290. }
  291. // Create Logical Device
  292. {
  293. int device_extension_count = 1;
  294. const char* device_extensions[] = {"VK_KHR_swapchain"};
  295. const uint32_t queue_index = 0;
  296. const uint32_t queue_count = 1;
  297. const float queue_priority[] = {1.0f};
  298. VkDeviceQueueCreateInfo queue_info[1] = {};
  299. queue_info[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  300. queue_info[0].queueFamilyIndex = g_QueueFamily;
  301. queue_info[0].queueCount = queue_count;
  302. queue_info[0].pQueuePriorities = queue_priority;
  303. VkDeviceCreateInfo create_info = {};
  304. create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
  305. create_info.queueCreateInfoCount = sizeof(queue_info)/sizeof(queue_info[0]);
  306. create_info.pQueueCreateInfos = queue_info;
  307. create_info.enabledExtensionCount = device_extension_count;
  308. create_info.ppEnabledExtensionNames = device_extensions;
  309. err = vkCreateDevice(g_Gpu, &create_info, g_Allocator, &g_Device);
  310. check_vk_result(err);
  311. vkGetDeviceQueue(g_Device, g_QueueFamily, queue_index, &g_Queue);
  312. }
  313. // Create Framebuffers
  314. {
  315. int w, h;
  316. glfwGetFramebufferSize(window, &w, &h);
  317. resize_vulkan(window, w, h);
  318. glfwSetFramebufferSizeCallback(window, resize_vulkan);
  319. }
  320. // Create Command Buffers
  321. for (int i = 0; i < IMGUI_VK_QUEUED_FRAMES; i++)
  322. {
  323. {
  324. VkCommandPoolCreateInfo info = {};
  325. info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  326. info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  327. info.queueFamilyIndex = g_QueueFamily;
  328. err = vkCreateCommandPool(g_Device, &info, g_Allocator, &g_CommandPool[i]);
  329. check_vk_result(err);
  330. }
  331. {
  332. VkCommandBufferAllocateInfo info = {};
  333. info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  334. info.commandPool = g_CommandPool[i];
  335. info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  336. info.commandBufferCount = 1;
  337. err = vkAllocateCommandBuffers(g_Device, &info, &g_CommandBuffer[i]);
  338. check_vk_result(err);
  339. }
  340. {
  341. VkFenceCreateInfo info = {};
  342. info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  343. info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
  344. err = vkCreateFence(g_Device, &info, g_Allocator, &g_Fence[i]);
  345. check_vk_result(err);
  346. }
  347. {
  348. VkSemaphoreCreateInfo info = {};
  349. info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  350. err = vkCreateSemaphore(g_Device, &info, g_Allocator, &g_Semaphore[i]);
  351. check_vk_result(err);
  352. }
  353. }
  354. // Create Descriptor Pool
  355. {
  356. VkDescriptorPoolSize pool_size[11] =
  357. {
  358. { VK_DESCRIPTOR_TYPE_SAMPLER, 1000 },
  359. { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000 },
  360. { VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000 },
  361. { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000 },
  362. { VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000 },
  363. { VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000 },
  364. { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000 },
  365. { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000 },
  366. { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000 },
  367. { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000 },
  368. { VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000 }
  369. };
  370. VkDescriptorPoolCreateInfo pool_info = {};
  371. pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
  372. pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
  373. pool_info.maxSets = 1000 * 11;
  374. pool_info.poolSizeCount = 11;
  375. pool_info.pPoolSizes = pool_size;
  376. err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool);
  377. check_vk_result(err);
  378. }
  379. }
  380. static void cleanup_vulkan()
  381. {
  382. vkDestroyDescriptorPool(g_Device, g_DescriptorPool, g_Allocator);
  383. for (int i = 0; i < IMGUI_VK_QUEUED_FRAMES; i++)
  384. {
  385. vkDestroyFence(g_Device, g_Fence[i], g_Allocator);
  386. vkFreeCommandBuffers(g_Device, g_CommandPool[i], 1, &g_CommandBuffer[i]);
  387. vkDestroyCommandPool(g_Device, g_CommandPool[i], g_Allocator);
  388. vkDestroySemaphore(g_Device, g_Semaphore[i], g_Allocator);
  389. }
  390. for (uint32_t i = 0; i < g_BackBufferCount; i++)
  391. {
  392. vkDestroyImageView(g_Device, g_BackBufferView[i], g_Allocator);
  393. vkDestroyFramebuffer(g_Device, g_Framebuffer[i], g_Allocator);
  394. }
  395. vkDestroyRenderPass(g_Device, g_RenderPass, g_Allocator);
  396. vkDestroySwapchainKHR(g_Device, g_Swapchain, g_Allocator);
  397. vkDestroySurfaceKHR(g_Instance, g_Surface, g_Allocator);
  398. #ifdef IMGUI_VULKAN_DEBUG_REPORT
  399. // get the proc address of the function pointer, required for used extensions
  400. auto vkDestroyDebugReportCallbackEXT =
  401. (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkDestroyDebugReportCallbackEXT");
  402. vkDestroyDebugReportCallbackEXT(g_Instance, g_Debug_Report, g_Allocator);
  403. #endif // IMGUI_VULKAN_DEBUG_REPORT
  404. vkDestroyDevice(g_Device, g_Allocator);
  405. vkDestroyInstance(g_Instance, g_Allocator);
  406. }
  407. static void frame_begin()
  408. {
  409. VkResult err;
  410. while (true)
  411. {
  412. err = vkWaitForFences(g_Device, 1, &g_Fence[g_FrameIndex], VK_TRUE, 100);
  413. if (err == VK_SUCCESS) break;
  414. if (err == VK_TIMEOUT) continue;
  415. check_vk_result(err);
  416. }
  417. {
  418. err = vkAcquireNextImageKHR(g_Device, g_Swapchain, UINT64_MAX, g_Semaphore[g_FrameIndex], VK_NULL_HANDLE, &g_BackBufferIndex);
  419. check_vk_result(err);
  420. }
  421. {
  422. err = vkResetCommandPool(g_Device, g_CommandPool[g_FrameIndex], 0);
  423. check_vk_result(err);
  424. VkCommandBufferBeginInfo info = {};
  425. info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  426. info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  427. err = vkBeginCommandBuffer(g_CommandBuffer[g_FrameIndex], &info);
  428. check_vk_result(err);
  429. }
  430. {
  431. VkRenderPassBeginInfo info = {};
  432. info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  433. info.renderPass = g_RenderPass;
  434. info.framebuffer = g_Framebuffer[g_BackBufferIndex];
  435. info.renderArea.extent.width = fb_width;
  436. info.renderArea.extent.height = fb_height;
  437. info.clearValueCount = 1;
  438. info.pClearValues = &g_ClearValue;
  439. vkCmdBeginRenderPass(g_CommandBuffer[g_FrameIndex], &info, VK_SUBPASS_CONTENTS_INLINE);
  440. }
  441. }
  442. static void frame_end()
  443. {
  444. VkResult err;
  445. vkCmdEndRenderPass(g_CommandBuffer[g_FrameIndex]);
  446. {
  447. VkImageMemoryBarrier barrier = {};
  448. barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  449. barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  450. barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
  451. barrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  452. barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
  453. barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  454. barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  455. barrier.image = g_BackBuffer[g_BackBufferIndex];
  456. barrier.subresourceRange = g_ImageRange;
  457. vkCmdPipelineBarrier(g_CommandBuffer[g_FrameIndex], VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &barrier);
  458. }
  459. {
  460. VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  461. VkSubmitInfo info = {};
  462. info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  463. info.waitSemaphoreCount = 1;
  464. info.pWaitSemaphores = &g_Semaphore[g_FrameIndex];
  465. info.pWaitDstStageMask = &wait_stage;
  466. info.commandBufferCount = 1;
  467. info.pCommandBuffers = &g_CommandBuffer[g_FrameIndex];
  468. err = vkEndCommandBuffer(g_CommandBuffer[g_FrameIndex]);
  469. check_vk_result(err);
  470. err = vkResetFences(g_Device, 1, &g_Fence[g_FrameIndex]);
  471. check_vk_result(err);
  472. err = vkQueueSubmit(g_Queue, 1, &info, g_Fence[g_FrameIndex]);
  473. check_vk_result(err);
  474. }
  475. {
  476. VkResult res;
  477. VkSwapchainKHR swapchains[1] = {g_Swapchain};
  478. uint32_t indices[1] = {g_BackBufferIndex};
  479. VkPresentInfoKHR info = {};
  480. info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
  481. info.swapchainCount = 1;
  482. info.pSwapchains = swapchains;
  483. info.pImageIndices = indices;
  484. info.pResults = &res;
  485. err = vkQueuePresentKHR(g_Queue, &info);
  486. check_vk_result(err);
  487. check_vk_result(res);
  488. }
  489. g_FrameIndex = (g_FrameIndex+1) % IMGUI_VK_QUEUED_FRAMES;
  490. }
  491. static void error_callback(int error, const char* description)
  492. {
  493. fprintf(stderr, "Error %d: %s\n", error, description);
  494. }
  495. int main(int, char**)
  496. {
  497. // Setup window
  498. glfwSetErrorCallback(error_callback);
  499. if (!glfwInit())
  500. return 1;
  501. glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
  502. GLFWwindow* window = glfwCreateWindow(1280, 720, "ImGui Vulkan example", NULL, NULL);
  503. // Setup Vulkan
  504. if (!glfwVulkanSupported())
  505. {
  506. printf("GLFW: Vulkan Not Supported\n");
  507. return 1;
  508. }
  509. setup_vulkan(window);
  510. // Setup ImGui binding
  511. ImGui_ImplGlfwVulkan_Init_Data init_data = {};
  512. init_data.allocator = g_Allocator;
  513. init_data.gpu = g_Gpu;
  514. init_data.device = g_Device;
  515. init_data.render_pass = g_RenderPass;
  516. init_data.pipeline_cache = g_PipelineCache;
  517. init_data.descriptor_pool = g_DescriptorPool;
  518. init_data.check_vk_result = check_vk_result;
  519. ImGui_ImplGlfwVulkan_Init(window, true, &init_data);
  520. // Load Fonts
  521. // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
  522. //ImGuiIO& io = ImGui::GetIO();
  523. //io.Fonts->AddFontDefault();
  524. //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
  525. //io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
  526. //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
  527. //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
  528. //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
  529. // Upload Fonts
  530. {
  531. VkResult err;
  532. err = vkResetCommandPool(g_Device, g_CommandPool[g_FrameIndex], 0);
  533. check_vk_result(err);
  534. VkCommandBufferBeginInfo begin_info = {};
  535. begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  536. begin_info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  537. err = vkBeginCommandBuffer(g_CommandBuffer[g_FrameIndex], &begin_info);
  538. check_vk_result(err);
  539. ImGui_ImplGlfwVulkan_CreateFontsTexture(g_CommandBuffer[g_FrameIndex]);
  540. VkSubmitInfo end_info = {};
  541. end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  542. end_info.commandBufferCount = 1;
  543. end_info.pCommandBuffers = &g_CommandBuffer[g_FrameIndex];
  544. err = vkEndCommandBuffer(g_CommandBuffer[g_FrameIndex]);
  545. check_vk_result(err);
  546. err = vkQueueSubmit(g_Queue, 1, &end_info, VK_NULL_HANDLE);
  547. check_vk_result(err);
  548. err = vkDeviceWaitIdle(g_Device);
  549. check_vk_result(err);
  550. ImGui_ImplGlfwVulkan_InvalidateFontUploadObjects();
  551. }
  552. bool show_test_window = true;
  553. bool show_another_window = false;
  554. ImVec4 clear_color = ImColor(114, 144, 154);
  555. // Main loop
  556. while (!glfwWindowShouldClose(window))
  557. {
  558. glfwPollEvents();
  559. ImGui_ImplGlfwVulkan_NewFrame();
  560. // 1. Show a simple window
  561. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
  562. {
  563. static float f = 0.0f;
  564. ImGui::Text("Hello, world!");
  565. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  566. ImGui::ColorEdit3("clear color", (float*)&clear_color);
  567. if (ImGui::Button("Test Window")) show_test_window ^= 1;
  568. if (ImGui::Button("Another Window")) show_another_window ^= 1;
  569. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
  570. }
  571. // 2. Show another simple window, this time using an explicit Begin/End pair
  572. if (show_another_window)
  573. {
  574. ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
  575. ImGui::Begin("Another Window", &show_another_window);
  576. ImGui::Text("Hello");
  577. ImGui::End();
  578. }
  579. // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
  580. if (show_test_window)
  581. {
  582. ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
  583. ImGui::ShowTestWindow(&show_test_window);
  584. }
  585. g_ClearValue.color.float32[0] = clear_color.x;
  586. g_ClearValue.color.float32[1] = clear_color.y;
  587. g_ClearValue.color.float32[2] = clear_color.z;
  588. g_ClearValue.color.float32[3] = clear_color.w;
  589. frame_begin();
  590. ImGui_ImplGlfwVulkan_Render(g_CommandBuffer[g_FrameIndex]);
  591. frame_end();
  592. }
  593. // Cleanup
  594. VkResult err = vkDeviceWaitIdle(g_Device);
  595. check_vk_result(err);
  596. ImGui_ImplGlfwVulkan_Shutdown();
  597. cleanup_vulkan();
  598. glfwTerminate();
  599. return 0;
  600. }