Advertisement
Guest User

Application.h

a guest
Mar 16th, 2019
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 8.12 KB | None | 0 0
  1. #pragma once
  2.  
  3. // Definitions
  4. #define MANUALPHYSICALDEVICE    1
  5. #define LOGEXTENSIONS           0
  6.  
  7. // C++ Includes
  8. #include <algorithm>
  9. #include <cstdlib>
  10. #include <functional>
  11. #include <iostream>
  12. #include <optional>
  13. #include <set>
  14. #include <stdexcept>
  15. #include <vector>
  16. #include <fstream>
  17. #include <chrono>
  18.  
  19. // External Includes
  20. #define GLFW_INCLUDE_VULKAN
  21. #define GLM_FORCE_RADIANS
  22. #include <spdlog/spdlog.h>
  23. #include <GLFW/glfw3.h>
  24. #include <glm/glm.hpp>
  25. #include <glm/gtc/matrix_transform.hpp>
  26. #include <vulkan/vulkan.h>
  27. #include <shaderc/shaderc.hpp>
  28.  
  29. static std::vector<char> readFile(const std::string& filename)
  30. {
  31.     std::ifstream file(filename, std::ios::ate | std::ios::binary);
  32.    
  33.     if (!file.is_open())
  34.         spdlog::info("Failed to open file!");
  35.  
  36.     size_t fileSize = (size_t)file.tellg();
  37.     std::vector<char> buffer(fileSize);
  38.  
  39.     file.seekg(0);
  40.     file.read(buffer.data(), fileSize);
  41.  
  42.     file.close();
  43.  
  44.     return buffer;
  45. }
  46.  
  47. static std::string readFile_string(const char* filename)
  48. {
  49.     std::ifstream t(filename);
  50.     std::string str;
  51.  
  52.     t.seekg(0, std::ios::end);
  53.     str.reserve(t.tellg());
  54.     t.seekg(0, std::ios::beg);
  55.  
  56.     str.assign((std::istreambuf_iterator<char>(t)),
  57.         std::istreambuf_iterator<char>());
  58.  
  59.     return str;
  60.  
  61. }
  62.  
  63. class Timer {
  64. public:
  65.     Timer() : beg_(clock_::now()) {}
  66.  
  67.     void reset() { beg_ = clock_::now(); }
  68.  
  69.     double elapsed() const {
  70.         return std::chrono::duration_cast<second_> (clock_::now() - beg_).count();
  71.     }
  72.  
  73. private:
  74.     typedef std::chrono::high_resolution_clock clock_;
  75.     typedef std::chrono::duration<double, std::ratio<1> > second_;
  76.     std::chrono::time_point<clock_> beg_;
  77. };
  78.  
  79. struct Vertex
  80. {
  81.     glm::vec2 pos;
  82.     glm::vec3 color;
  83.  
  84.     static VkVertexInputBindingDescription getBindingDescription()
  85.     {
  86.         VkVertexInputBindingDescription bindingDescription = {};
  87.         bindingDescription.binding = 0;
  88.         bindingDescription.stride = sizeof(Vertex);
  89.         bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  90.  
  91.         return bindingDescription;
  92.     }
  93.  
  94.     static std::array<VkVertexInputAttributeDescription, 2> getAttributeDescriptions()
  95.     {
  96.         std::array<VkVertexInputAttributeDescription, 2> attributeDescription;
  97.         attributeDescription[0].binding = 0;
  98.         attributeDescription[0].location = 0;
  99.         attributeDescription[0].format = VK_FORMAT_R32G32_SFLOAT;
  100.         attributeDescription[0].offset = offsetof(Vertex, pos);
  101.  
  102.         attributeDescription[1].binding = 0;
  103.         attributeDescription[1].location = 1;
  104.         attributeDescription[1].format = VK_FORMAT_R32G32B32_SFLOAT;
  105.         attributeDescription[1].offset = offsetof(Vertex, color);
  106.  
  107.         return attributeDescription;
  108.     }
  109. };
  110.  
  111. struct UniformBufferObject
  112. {
  113.     alignas(16) glm::mat4 model;
  114.     alignas(16) glm::mat4 view;
  115.     alignas(16) glm::mat4 proj;
  116. };
  117.  
  118. struct QueueFamilyIndices
  119. {
  120.     std::optional<uint32_t> graphicsFamily;
  121.     std::optional<uint32_t> presentFamily;
  122.  
  123.     bool isComplete()
  124.     {
  125.         return graphicsFamily.has_value() && presentFamily.has_value();
  126.     }
  127. };
  128.  
  129. struct SwapChainSupportDetails
  130. {
  131.     VkSurfaceCapabilitiesKHR capabilities;
  132.     std::vector<VkSurfaceFormatKHR> formats;
  133.     std::vector<VkPresentModeKHR> presentModes;
  134. };
  135.  
  136. const int WIDTH = 800;
  137. const int HEIGHT = 600;
  138. const int MAX_FRAMES_IN_FLIGHT = 2;
  139.  
  140. const std::vector<Vertex> vertices
  141. {
  142.     // Top-Left
  143.     {
  144.         // Position
  145.         { -0.5f, -0.5f },
  146.         // Color
  147.         { 1.0f, 0.0f, 0.0f }
  148.     },
  149.     // Top-Right
  150.     {
  151.         // Position
  152.         { 0.5f, -0.5f },
  153.         // Color
  154.         { 0.0f, 1.0f, 0.0f }
  155.     },
  156.     // Bottom-Right
  157.     {
  158.         // Position
  159.         { 0.5f, 0.5f },
  160.         // Color
  161.         { 0.0f, 0.0f, 1.0f }
  162.     },
  163.     // Bottom-Left
  164.     {
  165.         // Position
  166.         { -0.5f, 0.5f },
  167.         // Color
  168.         { 1.0f, 1.0f, 1.0f }
  169.     }
  170. };
  171.  
  172. const std::vector<uint16_t> indices =
  173. {
  174.     0, 1, 2,
  175.     2, 3, 0
  176. };
  177.  
  178. #ifdef NDEBUG
  179. const bool enableValidationLayers = false;
  180. #else
  181. const bool enableValidationLayers = true;
  182. #endif
  183.  
  184. const std::vector <const char*> validationLayers =
  185. {
  186.     "VK_LAYER_LUNARG_standard_validation"
  187. };
  188.  
  189. const std::vector<const char*> deviceExtensions =
  190. {
  191.     VK_KHR_SWAPCHAIN_EXTENSION_NAME
  192. };
  193.  
  194. // Class
  195. class Application
  196. {
  197. // Private members
  198. private:
  199.     GLFWwindow*                     m_window;
  200.     int                             m_framebufferWidth;
  201.     int                             m_framebufferHeight;
  202.     VkInstance                      m_instance;
  203.     VkDebugUtilsMessengerEXT        m_debugMessenger;
  204.     VkSurfaceKHR                    m_surface;
  205.     VkPhysicalDevice                m_physicalDevice = VK_NULL_HANDLE;
  206.     VkDevice                        m_device;
  207.     VkQueue                         m_graphicsQueue;
  208.     VkQueue                         m_presentQueue;
  209.     QueueFamilyIndices              m_indices;
  210.     VkSwapchainKHR                  m_swapChain;
  211.     std::vector<VkImage>            m_swapChainImages;
  212.     VkFormat                        m_swapChainImageFormat;
  213.     VkExtent2D                      m_swapChainExtent;
  214.     std::vector<VkImageView>        m_swapChainImageViews;
  215.     VkRenderPass                    m_renderPass;
  216.     VkDescriptorSetLayout           m_descriptorSetLayout;
  217.     VkPipelineLayout                m_pipelineLayout;
  218.     VkPipeline                      m_graphicsPipeline;
  219.     std::vector<VkFramebuffer>      m_swapChainFramebuffers;
  220.     VkCommandPool                   m_commandPool;
  221.     VkCommandPool                   m_tempCommandPool;
  222.     std::vector<VkCommandBuffer>    m_commandBuffers;
  223.     std::vector<VkSemaphore>        m_imageAvailableSemaphores;
  224.     std::vector<VkSemaphore>        m_renderFinishedSemaphores;
  225.     std::vector<VkFence>            m_inFlightFences;
  226.     VkBuffer                        m_vertexBuffer;
  227.     VkDeviceMemory                  m_vertexBufferMemory;
  228.     VkBuffer                        m_indexBuffer;
  229.     VkDeviceMemory                  m_indexBufferMemory;   
  230.     std::vector<VkBuffer>           m_uniformBuffers;
  231.     std::vector<VkDeviceMemory>     m_uniformBuffersMemory;
  232.     VkDescriptorPool                m_descriptorPool;
  233.     std::vector<VkDescriptorSet>    m_descriptorSets;
  234.     size_t                          m_currentFrame = 0;
  235.     bool                            m_framebufferResized = false;
  236.     bool                            m_recreatingSwapChain = false;
  237.  
  238. // Private functions
  239. private:
  240.     void initWindow();
  241.     void initVulkan();
  242.     void createInstance();
  243.     void setupDebugMessenger();
  244.     void createSurface();
  245.     void pickPhysicalDevice();
  246.     void createLogicalDevice();
  247.     void createSwapChain();
  248.     void createImageViews();
  249.     void createRenderPass();
  250.     void createDescriptorSetLayout();
  251.     void createGraphicsPipeline();
  252.     void createFramebuffers();
  253.     void createCommandPools();
  254.     void createVertexBuffers();
  255.     void createIndexBuffer();
  256.     void createUniformBuffers();
  257.     void createDescriptorPool();
  258.     void createDescriptorSets();
  259.     void createCommandBuffers();
  260.     void createSyncObjects();
  261.  
  262.     void mainLoop();
  263.     void drawFrame();
  264.    
  265.     void cleanup();
  266.  
  267.     void cleanupSwapChain();
  268.     void recreateSwapChain();
  269.  
  270.     bool checkValidationLayerSupport();
  271.     bool isDeviceSuitable(VkPhysicalDevice device);
  272.     bool checkDeviceExtensionSupport(VkPhysicalDevice device);
  273.    
  274.     std::vector<const char*> getRequiredExtensions();
  275.  
  276.     VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pDebugMessenger);
  277.     void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, const VkAllocationCallbacks* pAllocator);
  278.  
  279.     QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device);
  280.     SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device);
  281.  
  282.     VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
  283.     VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR> availablePresentModes);
  284.     VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities);
  285.  
  286.     VkShaderModule createShaderModule(const std::vector<char>& code);
  287.     void compileShaders(const char* vertPath, const char* fragPath);
  288.  
  289.     void createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory);
  290.     void copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
  291.     uint32_t findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties);
  292.  
  293.     void updateUniformBuffers(uint32_t currentImage);
  294.  
  295.     static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
  296.         VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
  297.         VkDebugUtilsMessageTypeFlagsEXT messageType,
  298.         const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
  299.         void* pUserData
  300.     );
  301.  
  302.     static void framebufferResizeCallback(GLFWwindow* window, int width, int height);
  303.  
  304. // Public functions
  305. public:
  306.     Application();
  307.     ~Application();
  308.  
  309.     void init();
  310.     void run();
  311. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement