Geometry shader demo program.
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

geometry.cc 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. #include <png.h>
  2. #include <vulkan/vulkan.h>
  3. #include <array>
  4. #include <fstream>
  5. #include <iostream>
  6. #include <sstream>
  7. #include <string>
  8. #include <vector>
  9. const uint32_t kWidth = 256;
  10. const uint32_t kHeight = 256;
  11. const VkFormat kVulkanDepthFormat = VK_FORMAT_D32_SFLOAT;
  12. const VkFormat kVulkanFormat = VK_FORMAT_A8B8G8R8_UNORM_PACK32;
  13. const std::string kVertexShaderPath = "geometry.vert.spv";
  14. const std::string kGeometryShaderPath = "geometry.geom.spv";
  15. const std::string kFragmentShaderPath = "geometry.frag.spv";
  16. #define ERROR(message) \
  17. std::cerr << message << std::endl; \
  18. std::exit(EXIT_FAILURE)
  19. struct Vertex {
  20. float position[3];
  21. float color[3];
  22. };
  23. VkInstance CreateVkInstance() {
  24. VkApplicationInfo app_info = {};
  25. app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
  26. app_info.apiVersion = VK_API_VERSION_1_1;
  27. VkInstanceCreateInfo create_info = {};
  28. create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  29. create_info.pApplicationInfo = &app_info;
  30. create_info.enabledExtensionCount = 0;
  31. create_info.ppEnabledExtensionNames = nullptr;
  32. create_info.enabledLayerCount = 0;
  33. create_info.ppEnabledLayerNames = nullptr;
  34. VkInstance instance;
  35. VkResult result = vkCreateInstance(&create_info, nullptr, &instance);
  36. if (result != VK_SUCCESS) {
  37. ERROR("Error creating VkInstance: " << result);
  38. }
  39. return instance;
  40. }
  41. VkPhysicalDevice ChooseVkPhysicalDevice(VkInstance instance) {
  42. uint32_t device_count = 0;
  43. VkResult result = vkEnumeratePhysicalDevices(instance, &device_count, nullptr);
  44. if (result != VK_SUCCESS) {
  45. ERROR("Error enumerating VkPhysicalDevices: " << result);
  46. }
  47. if (device_count == 0) {
  48. ERROR("No available VkPhysicalDevices");
  49. }
  50. std::vector<VkPhysicalDevice> devices(device_count);
  51. result = vkEnumeratePhysicalDevices(instance, &device_count, devices.data());
  52. if (result != VK_SUCCESS) {
  53. ERROR("Error fetching VkPhysicalDevices: " << result);
  54. }
  55. std::cout << "Found " << device_count << " device(s):" << std::endl;
  56. VkPhysicalDevice chosen_device = VK_NULL_HANDLE;
  57. for (VkPhysicalDevice device : devices) {
  58. VkPhysicalDeviceProperties device_props;
  59. vkGetPhysicalDeviceProperties(device, &device_props);
  60. std::cout << "\t- " << device_props.deviceName << " [V: " <<
  61. VK_VERSION_MAJOR(device_props.apiVersion) << "." <<
  62. VK_VERSION_MINOR(device_props.apiVersion) << "." <<
  63. VK_VERSION_PATCH(device_props.apiVersion) << "]" << std::endl;
  64. // Currently, any device with Vulkan API version 1.1 is fine.
  65. if (chosen_device == VK_NULL_HANDLE && device_props.apiVersion >= VK_API_VERSION_1_1) {
  66. chosen_device = device;
  67. }
  68. }
  69. if (chosen_device == VK_NULL_HANDLE) {
  70. ERROR("Unable to find suitable VkPhysicalDevice");
  71. }
  72. return chosen_device;
  73. }
  74. uint32_t ChooseDeviceQueueFamilyIndex(VkPhysicalDevice physical_device) {
  75. uint32_t props_count;
  76. vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &props_count, nullptr);
  77. std::vector<VkQueueFamilyProperties> props(props_count);
  78. vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &props_count, props.data());
  79. // Simply choose the first graphics queue.
  80. for (size_t i = 0; i < props_count; i++) {
  81. const VkQueueFamilyProperties& prop = props[i];
  82. if ((prop.queueFlags & VK_QUEUE_GRAPHICS_BIT) && prop.queueCount > 0) {
  83. return i;
  84. }
  85. }
  86. ERROR("Unable to find suitable queue family");
  87. }
  88. VkDevice CreateVkDevice(VkPhysicalDevice physical_device, uint32_t device_queue_family_index) {
  89. VkDeviceQueueCreateInfo queue_create_info = {};
  90. queue_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  91. queue_create_info.queueFamilyIndex = device_queue_family_index;
  92. queue_create_info.queueCount = 1;
  93. float queue_priority = 1.0f;
  94. queue_create_info.pQueuePriorities = &queue_priority;
  95. VkDeviceCreateInfo device_create_info = {};
  96. device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
  97. device_create_info.queueCreateInfoCount = 1;
  98. device_create_info.pQueueCreateInfos = &queue_create_info;
  99. // Let's not use any device extensions for now.
  100. device_create_info.enabledExtensionCount = 0;
  101. device_create_info.ppEnabledExtensionNames = nullptr;
  102. VkDevice device;
  103. VkResult result = vkCreateDevice(physical_device, &device_create_info, nullptr, &device);
  104. if (result != VK_SUCCESS) {
  105. ERROR("Unable to create logical device: " << result);
  106. }
  107. return device;
  108. }
  109. VkQueue GetVkQueue(VkDevice device, uint32_t device_queue_family_index) {
  110. VkQueue queue;
  111. vkGetDeviceQueue(device, device_queue_family_index, /*queueIndex*/ 0, &queue);
  112. return queue;
  113. }
  114. VkCommandPool CreateVkCommandPool(VkDevice device, uint32_t device_queue_family_index) {
  115. VkCommandPool command_pool;
  116. VkCommandPoolCreateInfo create_info = {};
  117. create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  118. create_info.flags = 0;
  119. create_info.queueFamilyIndex = device_queue_family_index;
  120. VkResult result = vkCreateCommandPool(device, &create_info, nullptr, &command_pool);
  121. if (result != VK_SUCCESS) {
  122. ERROR("Unable to create command pool: " << result);
  123. }
  124. return command_pool;
  125. }
  126. uint32_t FindMemoryType(uint32_t valid_image_memory_types,
  127. VkPhysicalDeviceMemoryProperties device_memory_properties,
  128. VkMemoryPropertyFlags memory_property_flags) {
  129. for (uint32_t i = 0; i < device_memory_properties.memoryTypeCount; i++) {
  130. // We don't care about performance, so just choose the first mappable memory type.
  131. if ((valid_image_memory_types & (1 << i)) &&
  132. ((device_memory_properties.memoryTypes[i].propertyFlags & memory_property_flags) ==
  133. memory_property_flags)) {
  134. return i;
  135. }
  136. }
  137. ERROR("Unable to find suitable memory type index");
  138. }
  139. VkBuffer CreateVertexBuffer(VkPhysicalDevice physical_device, VkDevice device) {
  140. std::array<Vertex, 3> vertices = {};
  141. vertices[0].position[0] = 0.0f;
  142. vertices[0].position[1] = -0.5f;
  143. vertices[0].position[2] = 0.9f;
  144. vertices[0].color[0] = 1.0f;
  145. vertices[0].color[1] = 0.0f;
  146. vertices[0].color[2] = 0.0f;
  147. vertices[1].position[0] = 0.5f;
  148. vertices[1].position[1] = 0.5f;
  149. vertices[1].position[2] = 0.9f;
  150. vertices[1].color[0] = 0.0f;
  151. vertices[1].color[1] = 1.0f;
  152. vertices[1].color[2] = 0.0f;
  153. vertices[2].position[0] = -0.5f;
  154. vertices[2].position[1] = 0.5f;
  155. vertices[2].position[2] = 0.9f;
  156. vertices[2].color[0] = 0.0f;
  157. vertices[2].color[1] = 0.0f;
  158. vertices[2].color[2] = 1.0f;
  159. VkBufferCreateInfo buffer_info = {};
  160. buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  161. buffer_info.size = sizeof(vertices);
  162. buffer_info.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
  163. buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  164. buffer_info.flags = 0;
  165. VkBuffer buffer;
  166. VkResult result = vkCreateBuffer(device, &buffer_info, nullptr, &buffer);
  167. if (result != VK_SUCCESS) {
  168. ERROR("Unable to create VkBuffer: " << result);
  169. }
  170. VkPhysicalDeviceMemoryProperties device_memory_properties;
  171. vkGetPhysicalDeviceMemoryProperties(physical_device, &device_memory_properties);
  172. VkMemoryRequirements buffer_memory_requirements;
  173. vkGetBufferMemoryRequirements(device, buffer, &buffer_memory_requirements);
  174. VkMemoryAllocateInfo allocate_info = {};
  175. allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  176. allocate_info.allocationSize = buffer_memory_requirements.size;
  177. allocate_info.memoryTypeIndex = FindMemoryType(
  178. buffer_memory_requirements.memoryTypeBits,
  179. device_memory_properties,
  180. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
  181. VkDeviceMemory memory;
  182. result = vkAllocateMemory(device, &allocate_info, nullptr, &memory);
  183. if (result != VK_SUCCESS) {
  184. ERROR("Unable to allocate memory: " << result);
  185. }
  186. vkBindBufferMemory(device, buffer, memory, 0);
  187. void* data = nullptr;
  188. vkMapMemory(device, memory, 0, buffer_info.size, 0, &data);
  189. memcpy(data, vertices.data(), buffer_info.size);
  190. vkUnmapMemory(device, memory);
  191. return buffer;
  192. }
  193. VkCommandBuffer CreateVkCommandBuffer(VkDevice device, VkCommandPool command_pool) {
  194. VkCommandBufferAllocateInfo allocate_info = {};
  195. allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  196. allocate_info.commandPool = command_pool;
  197. allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  198. allocate_info.commandBufferCount = 1;
  199. VkCommandBuffer command_buffer;
  200. VkResult result = vkAllocateCommandBuffers( device, &allocate_info, &command_buffer);
  201. if (result != VK_SUCCESS) {
  202. ERROR("Unable to create VkCommandBuffer: " << result);
  203. }
  204. return command_buffer;
  205. }
  206. VkRenderPass CreateVkRenderPass(VkDevice device) {
  207. std::array<VkAttachmentDescription, 2> attachment_descriptions = {};
  208. VkAttachmentDescription* color_attachment_description = &attachment_descriptions[0];
  209. color_attachment_description->format = kVulkanFormat;
  210. color_attachment_description->samples = VK_SAMPLE_COUNT_1_BIT;
  211. color_attachment_description->loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  212. color_attachment_description->storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  213. color_attachment_description->stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  214. color_attachment_description->stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  215. color_attachment_description->initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  216. color_attachment_description->finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  217. VkAttachmentReference color_attachment_reference = {};
  218. color_attachment_reference.attachment = 0;
  219. color_attachment_reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  220. VkAttachmentDescription* depth_attachment_description = &attachment_descriptions[1];
  221. depth_attachment_description->format = kVulkanDepthFormat;
  222. depth_attachment_description->samples = VK_SAMPLE_COUNT_1_BIT;
  223. depth_attachment_description->loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  224. depth_attachment_description->storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  225. depth_attachment_description->stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  226. depth_attachment_description->stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  227. depth_attachment_description->initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  228. depth_attachment_description->finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  229. VkAttachmentReference depth_attachment_reference = {};
  230. depth_attachment_reference.attachment = 1;
  231. depth_attachment_reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  232. VkSubpassDescription subpass_description = {};
  233. subpass_description.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  234. subpass_description.colorAttachmentCount = 1;
  235. subpass_description.pColorAttachments = &color_attachment_reference;
  236. subpass_description.pDepthStencilAttachment = &depth_attachment_reference;
  237. VkSubpassDependency subpass_dependency = {};
  238. subpass_dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
  239. subpass_dependency.dstSubpass = 0;
  240. subpass_dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  241. subpass_dependency.srcAccessMask = 0;
  242. subpass_dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  243. subpass_dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  244. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  245. VkRenderPassCreateInfo render_pass_info = {};
  246. render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  247. render_pass_info.attachmentCount = attachment_descriptions.size();
  248. render_pass_info.pAttachments = attachment_descriptions.data();
  249. render_pass_info.subpassCount = 1;
  250. render_pass_info.pSubpasses = &subpass_description;
  251. render_pass_info.dependencyCount = 1;
  252. render_pass_info.pDependencies = &subpass_dependency;
  253. VkRenderPass render_pass;
  254. VkResult result = vkCreateRenderPass(device, &render_pass_info, nullptr, &render_pass);
  255. if (result != VK_SUCCESS) {
  256. ERROR("Unable to create render pass: " << result);
  257. }
  258. return render_pass;
  259. }
  260. VkShaderModule CreateVkShaderModule(VkDevice device, std::string path) {
  261. std::ifstream fstream(path);
  262. if (!fstream) {
  263. ERROR("Unable to open: " << path);
  264. }
  265. std::stringstream buffer;
  266. buffer << fstream.rdbuf();
  267. std::string spirv_source = buffer.str();
  268. VkShaderModuleCreateInfo create_info = {};
  269. create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  270. create_info.codeSize = spirv_source.length();
  271. create_info.pCode = (const uint32_t*)spirv_source.c_str();
  272. VkShaderModule shader_module;
  273. VkResult result = vkCreateShaderModule(device, &create_info, nullptr, &shader_module);
  274. if (result != VK_SUCCESS) {
  275. ERROR("Unable to create shader module for " << path << ": ");
  276. }
  277. return shader_module;
  278. }
  279. VkPipeline CreateVkPipeline(VkDevice device, VkRenderPass render_pass) {
  280. VkShaderModule vertex_shader_module = CreateVkShaderModule(device, kVertexShaderPath);
  281. VkShaderModule geometry_shader_module = CreateVkShaderModule(device, kGeometryShaderPath);
  282. VkShaderModule fragment_shader_module = CreateVkShaderModule(device, kFragmentShaderPath);
  283. VkPipelineShaderStageCreateInfo vertex_shader_stage_info = {};
  284. vertex_shader_stage_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  285. vertex_shader_stage_info.stage = VK_SHADER_STAGE_VERTEX_BIT;
  286. vertex_shader_stage_info.module = vertex_shader_module;
  287. vertex_shader_stage_info.pName = "main";
  288. VkPipelineShaderStageCreateInfo geometry_shader_stage_info = {};
  289. geometry_shader_stage_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  290. geometry_shader_stage_info.stage = VK_SHADER_STAGE_GEOMETRY_BIT;
  291. geometry_shader_stage_info.module = geometry_shader_module;
  292. geometry_shader_stage_info.pName = "main";
  293. VkPipelineShaderStageCreateInfo fragment_shader_stage_info = {};
  294. fragment_shader_stage_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  295. fragment_shader_stage_info.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
  296. fragment_shader_stage_info.module = fragment_shader_module;
  297. fragment_shader_stage_info.pName = "main";
  298. std::vector<VkPipelineShaderStageCreateInfo> shader_stages =
  299. {vertex_shader_stage_info, geometry_shader_stage_info, fragment_shader_stage_info};
  300. VkVertexInputBindingDescription binding_description = {};
  301. binding_description.binding = 0;
  302. binding_description.stride = sizeof(Vertex);
  303. binding_description.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  304. std::array<VkVertexInputAttributeDescription, 2> attribute_descriptions = {};
  305. attribute_descriptions[0].binding = 0;
  306. attribute_descriptions[0].location = 0;
  307. attribute_descriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;
  308. attribute_descriptions[0].offset = offsetof(Vertex, position);
  309. attribute_descriptions[1].binding = 0;
  310. attribute_descriptions[1].location = 1;
  311. attribute_descriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
  312. attribute_descriptions[1].offset = offsetof(Vertex, color);
  313. VkPipelineVertexInputStateCreateInfo vertex_input_info = {};
  314. vertex_input_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  315. vertex_input_info.vertexBindingDescriptionCount = 1;
  316. vertex_input_info.pVertexBindingDescriptions = &binding_description;
  317. vertex_input_info.vertexAttributeDescriptionCount = attribute_descriptions.size();
  318. vertex_input_info.pVertexAttributeDescriptions = attribute_descriptions.data();
  319. VkPipelineInputAssemblyStateCreateInfo input_assembly_info = {};
  320. input_assembly_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  321. input_assembly_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
  322. input_assembly_info.primitiveRestartEnable = VK_FALSE;
  323. VkViewport viewport = {};
  324. viewport.x = 0.0f;
  325. viewport.y = 0.0f;
  326. viewport.width = (float)kWidth;
  327. viewport.height = (float)kHeight;
  328. viewport.minDepth = 0.0f;
  329. viewport.maxDepth = 1.0f;
  330. VkExtent2D extent = {};
  331. extent.width = kWidth;
  332. extent.height = kHeight;
  333. VkRect2D scissor = {};
  334. scissor.offset = {0, 0};
  335. scissor.extent = extent;
  336. VkPipelineViewportStateCreateInfo viewport_state_info = {};
  337. viewport_state_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  338. viewport_state_info.viewportCount = 1;
  339. viewport_state_info.pViewports = &viewport;
  340. viewport_state_info.scissorCount = 1;
  341. viewport_state_info.pScissors = &scissor;
  342. VkPipelineRasterizationStateCreateInfo rasterization_state_info = {};
  343. rasterization_state_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  344. rasterization_state_info.depthClampEnable = VK_FALSE;
  345. rasterization_state_info.rasterizerDiscardEnable = VK_FALSE;
  346. rasterization_state_info.polygonMode = VK_POLYGON_MODE_FILL;
  347. rasterization_state_info.lineWidth = 1.0f;
  348. rasterization_state_info.cullMode = VK_CULL_MODE_BACK_BIT;
  349. rasterization_state_info.frontFace = VK_FRONT_FACE_CLOCKWISE;
  350. rasterization_state_info.depthBiasEnable = VK_FALSE;
  351. VkPipelineMultisampleStateCreateInfo multisampling_state_info = {};
  352. multisampling_state_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  353. multisampling_state_info.sampleShadingEnable = VK_FALSE;
  354. multisampling_state_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
  355. VkPipelineDepthStencilStateCreateInfo depth_stencil_create_info = {};
  356. depth_stencil_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
  357. depth_stencil_create_info.depthTestEnable = VK_TRUE;
  358. depth_stencil_create_info.depthWriteEnable = VK_TRUE;
  359. depth_stencil_create_info.depthCompareOp = VK_COMPARE_OP_LESS;
  360. // TODO(brkho): Test depth bounds functionality.
  361. depth_stencil_create_info.depthBoundsTestEnable = VK_FALSE;
  362. depth_stencil_create_info.minDepthBounds = 0.0f;
  363. depth_stencil_create_info.maxDepthBounds = 1.0f;
  364. depth_stencil_create_info.stencilTestEnable = VK_FALSE;
  365. VkPipelineColorBlendAttachmentState color_blend_attachment_state = {};
  366. color_blend_attachment_state.colorWriteMask = VK_COLOR_COMPONENT_R_BIT |
  367. VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
  368. color_blend_attachment_state.blendEnable = VK_FALSE;
  369. VkPipelineColorBlendStateCreateInfo color_blend_state = {};
  370. color_blend_state.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  371. color_blend_state.logicOpEnable = VK_FALSE;
  372. color_blend_state.attachmentCount = 1;
  373. color_blend_state.pAttachments = &color_blend_attachment_state;
  374. VkPipelineLayoutCreateInfo pipeline_layout_create_info = {};
  375. pipeline_layout_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  376. VkPipelineLayout pipeline_layout;
  377. VkResult result = vkCreatePipelineLayout(device, &pipeline_layout_create_info, nullptr,
  378. &pipeline_layout);
  379. if (result != VK_SUCCESS) {
  380. ERROR("Unable to create VkPipelineLayout: " << result);
  381. }
  382. VkGraphicsPipelineCreateInfo pipeline_create_info = {};
  383. pipeline_create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  384. pipeline_create_info.stageCount = shader_stages.size();
  385. pipeline_create_info.pStages = shader_stages.data();
  386. pipeline_create_info.pVertexInputState = &vertex_input_info;
  387. pipeline_create_info.pInputAssemblyState = &input_assembly_info;
  388. pipeline_create_info.pViewportState = &viewport_state_info;
  389. pipeline_create_info.pRasterizationState = &rasterization_state_info;
  390. pipeline_create_info.pMultisampleState = &multisampling_state_info;
  391. pipeline_create_info.pDepthStencilState = &depth_stencil_create_info;
  392. pipeline_create_info.pColorBlendState = &color_blend_state;
  393. pipeline_create_info.pDynamicState = nullptr;
  394. pipeline_create_info.layout = pipeline_layout;
  395. pipeline_create_info.renderPass = render_pass;
  396. pipeline_create_info.subpass = 0;
  397. pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE;
  398. pipeline_create_info.basePipelineIndex = -1;
  399. VkPipeline pipeline;
  400. result = vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipeline_create_info, nullptr,
  401. &pipeline);
  402. if (result != VK_SUCCESS) {
  403. ERROR("Unable to create VkPipeline: " << result);
  404. }
  405. return pipeline;
  406. }
  407. VkImage CreateVkImage(VkDevice device, VkFormat format, VkImageTiling image_tiling,
  408. VkImageUsageFlags usage) {
  409. VkImageCreateInfo create_info = {};
  410. create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  411. create_info.pNext = nullptr;
  412. create_info.imageType = VK_IMAGE_TYPE_2D;
  413. create_info.format = format;
  414. VkExtent3D extent = {};
  415. extent.width = kWidth;
  416. extent.height = kHeight;
  417. extent.depth = 1;
  418. create_info.extent = extent;
  419. create_info.mipLevels = 1;
  420. create_info.arrayLayers = 1;
  421. create_info.samples = VK_SAMPLE_COUNT_1_BIT;
  422. create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  423. create_info.tiling = image_tiling;
  424. create_info.usage = usage;
  425. create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  426. VkImage image;
  427. VkResult result = vkCreateImage(device, &create_info, nullptr, &image);
  428. if (result != VK_SUCCESS) {
  429. ERROR("Unable to create VkImage: " << result);
  430. }
  431. return image;
  432. }
  433. inline VkImage CreateRenderVkImage(VkDevice device) {
  434. return CreateVkImage(device, kVulkanFormat, VK_IMAGE_TILING_OPTIMAL,
  435. VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
  436. }
  437. inline VkImage CreateDepthVkImage(VkDevice device) {
  438. return CreateVkImage(device, kVulkanDepthFormat, VK_IMAGE_TILING_OPTIMAL,
  439. VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
  440. }
  441. inline VkImage CreateScanoutVkImage(VkDevice device) {
  442. return CreateVkImage(device, kVulkanFormat, VK_IMAGE_TILING_LINEAR,
  443. VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
  444. }
  445. VkDeviceMemory AllocateAndBindMemory(VkPhysicalDevice physical_device, VkDevice device,
  446. VkImage image, VkMemoryPropertyFlags memory_property_flags) {
  447. VkMemoryRequirements image_memory_requirements;
  448. vkGetImageMemoryRequirements(device, image, &image_memory_requirements);
  449. VkPhysicalDeviceMemoryProperties device_memory_properties;
  450. vkGetPhysicalDeviceMemoryProperties(physical_device, &device_memory_properties);
  451. VkMemoryAllocateInfo memory_allocate_info = {};
  452. memory_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  453. memory_allocate_info.allocationSize = image_memory_requirements.size;
  454. memory_allocate_info.memoryTypeIndex = FindMemoryType(
  455. image_memory_requirements.memoryTypeBits, device_memory_properties,
  456. memory_property_flags);
  457. VkDeviceMemory image_memory;
  458. VkResult result = vkAllocateMemory(device, &memory_allocate_info, nullptr, &image_memory);
  459. if (result != VK_SUCCESS) {
  460. ERROR("Unable to allocate image memory: " << result);
  461. }
  462. result = vkBindImageMemory(device, image, image_memory, 0);
  463. if (result != VK_SUCCESS) {
  464. ERROR("Unable to bind image memory: " << result);
  465. }
  466. return image_memory;
  467. }
  468. inline VkDeviceMemory AllocateAndBindRenderMemory(VkPhysicalDevice physical_device,
  469. VkDevice device, VkImage image) {
  470. return AllocateAndBindMemory(physical_device, device, image, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
  471. }
  472. inline VkDeviceMemory AllocateAndBindDepthMemory(VkPhysicalDevice physical_device,
  473. VkDevice device, VkImage image) {
  474. return AllocateAndBindMemory(physical_device, device, image, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
  475. }
  476. inline VkDeviceMemory AllocateAndBindScanoutMemory(VkPhysicalDevice physical_device,
  477. VkDevice device, VkImage image) {
  478. return AllocateAndBindMemory(physical_device, device, image, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
  479. }
  480. VkImageView CreateVkImageView(VkDevice device, VkImage image, VkFormat format,
  481. VkImageAspectFlags aspect) {
  482. VkImageViewCreateInfo create_info = {};
  483. create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  484. create_info.image = image;
  485. create_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
  486. create_info.format = format;
  487. VkComponentMapping component_mapping = {};
  488. component_mapping.r = VK_COMPONENT_SWIZZLE_IDENTITY;
  489. component_mapping.b = VK_COMPONENT_SWIZZLE_IDENTITY;
  490. component_mapping.g = VK_COMPONENT_SWIZZLE_IDENTITY;
  491. component_mapping.a = VK_COMPONENT_SWIZZLE_IDENTITY;
  492. create_info.components = component_mapping;
  493. VkImageSubresourceRange subresource_range = {};
  494. subresource_range.aspectMask = aspect;
  495. subresource_range.baseMipLevel = 0;
  496. subresource_range.levelCount = 1;
  497. subresource_range.baseArrayLayer = 0;
  498. subresource_range.layerCount = 1;
  499. create_info.subresourceRange = subresource_range;
  500. VkImageView image_view;
  501. VkResult result = vkCreateImageView(device, &create_info, nullptr, &image_view);
  502. if (result != VK_SUCCESS) {
  503. ERROR("Unable to create VkImageView: " << result);
  504. }
  505. return image_view;
  506. }
  507. VkImageView CreateRenderVkImageView(VkDevice device, VkImage image) {
  508. return CreateVkImageView(device, image, kVulkanFormat, VK_IMAGE_ASPECT_COLOR_BIT);
  509. }
  510. VkImageView CreateDepthVkImageView(VkDevice device, VkImage image) {
  511. return CreateVkImageView(device, image, kVulkanDepthFormat, VK_IMAGE_ASPECT_DEPTH_BIT);
  512. }
  513. VkFramebuffer CreateVkFramebuffer(VkDevice device, VkRenderPass render_pass,
  514. VkImageView render_image_view, VkImageView depth_image_view) {
  515. std::array<VkImageView, 2> attachments = { render_image_view, depth_image_view };
  516. VkFramebufferCreateInfo create_info = {};
  517. create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  518. create_info.renderPass = render_pass;
  519. create_info.attachmentCount = attachments.size();
  520. create_info.pAttachments = attachments.data();
  521. create_info.width = kWidth;
  522. create_info.height = kHeight;
  523. create_info.layers = 1;
  524. VkFramebuffer framebuffer;
  525. VkResult result = vkCreateFramebuffer(device, &create_info, nullptr, &framebuffer);
  526. if (result != VK_SUCCESS) {
  527. ERROR("Unable to create VkFramebuffer: " << result);
  528. }
  529. return framebuffer;
  530. }
  531. void BeginCommandBuffer(VkCommandBuffer command_buffer) {
  532. VkCommandBufferBeginInfo command_buffer_begin_info = {};
  533. command_buffer_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  534. command_buffer_begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  535. VkResult result = vkBeginCommandBuffer(command_buffer, &command_buffer_begin_info);
  536. if (result != VK_SUCCESS) {
  537. ERROR("Unable to begin command buffer recording: " << result);
  538. }
  539. }
  540. void EndCommandBufferAndSubmit(VkCommandBuffer command_buffer, VkQueue queue) {
  541. VkResult result = vkEndCommandBuffer(command_buffer);
  542. if (result != VK_SUCCESS) {
  543. ERROR("Unable to end command buffer recording: " << result);
  544. }
  545. VkSubmitInfo submit_info = {};
  546. submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  547. submit_info.commandBufferCount = 1;
  548. submit_info.pCommandBuffers = &command_buffer;
  549. result = vkQueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
  550. if (result != VK_SUCCESS) {
  551. ERROR("Error in submitting command buffer to queue: " << result);
  552. }
  553. }
  554. void WaitForIdle(VkQueue queue) {
  555. // In a real application, we should use real synchronization primitives to figure out when the
  556. // command buffers have been executed. Waiting on an idle queue is simple, but it can cause
  557. // deadlock if we continue to submit to the queue while we wait for idle.
  558. VkResult result = vkQueueWaitIdle(queue);
  559. if (result != VK_SUCCESS) {
  560. ERROR("Error in waiting for graphics queue to reach idle state: " << result);
  561. }
  562. }
  563. void Draw(VkDevice device, VkQueue queue, VkBuffer vertex_buffer, VkRenderPass render_pass,
  564. VkPipeline pipeline, VkFramebuffer framebuffer, VkCommandBuffer command_buffer) {
  565. BeginCommandBuffer(command_buffer);
  566. VkRenderPassBeginInfo render_pass_begin_info = {};
  567. render_pass_begin_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  568. render_pass_begin_info.renderPass = render_pass;
  569. render_pass_begin_info.framebuffer = framebuffer;
  570. VkRect2D render_area = {};
  571. render_area.offset = { 0, 0 };
  572. render_area.extent = { kWidth, kHeight };
  573. render_pass_begin_info.renderArea = render_area;
  574. std::array<VkClearValue, 2> clear_values = {};
  575. clear_values[0].color.float32[0] = 1.0f;
  576. clear_values[0].color.float32[1] = 1.0f;
  577. clear_values[0].color.float32[2] = 0.0f;
  578. clear_values[0].color.float32[3] = 1.0f;
  579. clear_values[1].depthStencil.depth = 1.0f;
  580. clear_values[1].depthStencil.stencil = 0.0f;
  581. render_pass_begin_info.clearValueCount = clear_values.size();
  582. render_pass_begin_info.pClearValues = clear_values.data();
  583. vkCmdBeginRenderPass(command_buffer, &render_pass_begin_info, VK_SUBPASS_CONTENTS_INLINE);
  584. vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
  585. VkDeviceSize offset = 0;
  586. vkCmdBindVertexBuffers(command_buffer, 0, 1, &vertex_buffer, &offset);
  587. vkCmdDraw(command_buffer, 3, 1, 0, 0);
  588. vkCmdEndRenderPass(command_buffer);
  589. }
  590. void BlitToScanoutImage(VkQueue queue, VkCommandBuffer command_buffer, VkImage source_image,
  591. VkImage dest_image) {
  592. // We need to make sure the writes of the render pass have executed before actually scanning out
  593. // the rendered image. Also, we need to transition the layout of the scanout image to
  594. // VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL.
  595. VkImageMemoryBarrier image_memory_barrier = {};
  596. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
  597. image_memory_barrier.pNext = nullptr;
  598. image_memory_barrier.srcAccessMask = 0;
  599. image_memory_barrier.dstAccessMask = 0;
  600. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  601. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  602. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  603. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  604. image_memory_barrier.image = dest_image;
  605. VkImageSubresourceRange subresource_range = {};
  606. subresource_range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  607. subresource_range.baseMipLevel = 0;
  608. subresource_range.levelCount = 1;
  609. subresource_range.baseArrayLayer = 0;
  610. subresource_range.layerCount = 1;
  611. image_memory_barrier.subresourceRange = subresource_range;
  612. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
  613. VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  614. VkOffset3D blit_start = {};
  615. blit_start.x = 0;
  616. blit_start.y = 0;
  617. blit_start.z = 0;
  618. VkOffset3D blit_end = {};
  619. blit_end.x = kWidth;
  620. blit_end.y = kHeight;
  621. blit_end.z = 1;
  622. VkImageSubresourceLayers subresource_layers = {};
  623. subresource_layers.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  624. subresource_layers.mipLevel = 0;
  625. subresource_layers.baseArrayLayer = 0;
  626. subresource_layers.layerCount = 1;
  627. VkImageBlit image_blit = {};
  628. image_blit.srcSubresource = subresource_layers;
  629. image_blit.srcOffsets[0] = blit_start;
  630. image_blit.srcOffsets[1] = blit_end;
  631. image_blit.dstSubresource = subresource_layers;
  632. image_blit.dstOffsets[0] = blit_start;
  633. image_blit.dstOffsets[1] = blit_end;
  634. // TODO(brkho): Support multi-planar formats.
  635. vkCmdBlitImage(command_buffer, source_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dest_image,
  636. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_blit, VK_FILTER_NEAREST);
  637. EndCommandBufferAndSubmit(command_buffer, queue);
  638. }
  639. uint8_t* MapVkDeviceMemory(VkDevice device, VkDeviceMemory image_memory) {
  640. void* mapped_memory = nullptr;
  641. VkResult result = vkMapMemory(device, image_memory, 0, kWidth * kHeight * 4, 0, &mapped_memory);
  642. if (result != VK_SUCCESS) {
  643. ERROR("Unable to map device memory: " << result);
  644. }
  645. return static_cast<uint8_t*>(mapped_memory);
  646. }
  647. void WriteImage(uint8_t* pixels) {
  648. FILE *f = fopen("geometry.png", "wb");
  649. png_image image_info = {};
  650. image_info.version = PNG_IMAGE_VERSION;
  651. image_info.width = kWidth;
  652. image_info.height = kHeight;
  653. image_info.format = PNG_FORMAT_RGBA;
  654. if (png_image_write_to_stdio(&image_info, f, 0, pixels, kWidth * 4, nullptr) == 0) {
  655. ERROR("Error writing PNG: " << image_info.message);
  656. }
  657. fclose(f);
  658. }
  659. int main() {
  660. VkInstance instance = CreateVkInstance();
  661. VkPhysicalDevice physical_device = ChooseVkPhysicalDevice(instance);
  662. uint32_t device_queue_family_index = ChooseDeviceQueueFamilyIndex(physical_device);
  663. VkDevice device = CreateVkDevice(physical_device, device_queue_family_index);
  664. VkQueue queue = GetVkQueue(device, device_queue_family_index);
  665. VkCommandPool command_pool = CreateVkCommandPool(device, device_queue_family_index);
  666. VkBuffer vertex_buffer = CreateVertexBuffer(physical_device, device);
  667. VkCommandBuffer command_buffer = CreateVkCommandBuffer(device, command_pool);
  668. VkRenderPass render_pass = CreateVkRenderPass(device);
  669. VkPipeline pipeline = CreateVkPipeline(device, render_pass);
  670. VkImage render_image = CreateRenderVkImage(device);
  671. AllocateAndBindRenderMemory(physical_device, device, render_image);
  672. VkImageView render_image_view = CreateRenderVkImageView(device, render_image);
  673. VkImage depth_image = CreateDepthVkImage(device);
  674. AllocateAndBindDepthMemory(physical_device, device, depth_image);
  675. VkImageView depth_image_view = CreateDepthVkImageView(device, depth_image);
  676. VkFramebuffer framebuffer = CreateVkFramebuffer(device, render_pass, render_image_view,
  677. depth_image_view);
  678. VkImage scanout_image = CreateScanoutVkImage(device);
  679. VkDeviceMemory scanout_image_memory =
  680. AllocateAndBindScanoutMemory(physical_device, device, scanout_image);
  681. Draw(device, queue, vertex_buffer, render_pass, pipeline, framebuffer, command_buffer);
  682. // Since the render target is created with VK_IMAGE_TILING_OPTIMAL, we need to copy it to a linear
  683. // format before scanning out.
  684. BlitToScanoutImage(queue, command_buffer, render_image, scanout_image);
  685. WaitForIdle(queue);
  686. uint8_t* pixels = MapVkDeviceMemory(device, scanout_image_memory);
  687. WriteImage(pixels);
  688. return EXIT_SUCCESS;
  689. }