source: opengl-game/vulkan-game.hpp@ 1f81ecc

feature/imgui-sdl points-test
Last change on this file since 1f81ecc was 1f81ecc, checked in by Dmitry Portnoy <dmitry.portnoy@…>, 5 years ago

Add the ability for the ship to fire a laser from either of its wings

  • Property mode set to 100644
File size: 14.7 KB
RevLine 
[99d44b2]1#ifndef _VULKAN_GAME_H
2#define _VULKAN_GAME_H
[e8ebc76]3
[0807aeb]4#include <chrono>
5
[60578ce]6#define GLM_FORCE_RADIANS
7#define GLM_FORCE_DEPTH_ZERO_TO_ONE // Since, in Vulkan, the depth range is 0 to 1 instead of -1 to 1
[a79be34]8#define GLM_FORCE_RIGHT_HANDED
[60578ce]9
[771b33a]10#include <glm/glm.hpp>
[15104a8]11#include <glm/gtc/matrix_transform.hpp>
[771b33a]12
[0df3c9a]13#include "game-gui-sdl.hpp"
[7d2b0b9]14#include "graphics-pipeline_vulkan.hpp"
[0df3c9a]15
[b794178]16#include "vulkan-utils.hpp"
17
[15104a8]18using namespace glm;
[0807aeb]19using namespace std::chrono;
[15104a8]20
[2e77b3f]21#ifdef NDEBUG
22 const bool ENABLE_VALIDATION_LAYERS = false;
23#else
24 const bool ENABLE_VALIDATION_LAYERS = true;
25#endif
26
[5a1ace0]27struct OverlayVertex {
[15104a8]28 vec3 pos;
29 vec2 texCoord;
[771b33a]30};
31
[5a1ace0]32struct ModelVertex {
[15104a8]33 vec3 pos;
[5a1ace0]34 vec3 color;
[15104a8]35 vec2 texCoord;
[5a1ace0]36 unsigned int objIndex;
[15104a8]37};
38
[3782d66]39struct ShipVertex {
40 vec3 pos;
41 vec3 color;
[06d959f]42 vec3 normal;
[cf727ca]43 unsigned int objIndex;
[3782d66]44};
45
[3e8cc8b]46struct AsteroidVertex {
47 vec3 pos;
48 vec3 color;
49 vec3 normal;
50 unsigned int objIndex;
51};
52
[237cbec]53struct LaserVertex {
54 vec3 pos;
55 vec2 texCoord;
56 unsigned int objIndex;
57};
58
[055750a]59struct UBO_VP_mats {
[15104a8]60 alignas(16) mat4 view;
61 alignas(16) mat4 proj;
[771b33a]62};
63
[2d87297]64struct SSBO_ModelObject {
[055750a]65 alignas(16) mat4 model;
66};
67
[2d87297]68struct SSBO_Asteroid {
[3e8cc8b]69 alignas(16) mat4 model;
70 alignas(4) float hp;
[4ece3bf]71 alignas(4) unsigned int deleted;
[3e8cc8b]72};
73
[237cbec]74struct SSBO_Laser {
75 alignas(16) mat4 model;
76 alignas(4) vec3 color;
77 alignas(4) unsigned int deleted;
78};
79
[4994692]80// TODO: Change the index type to uint32_t and check the Vulkan Tutorial loading model section as a reference
81// TODO: Create a typedef for index type so I can easily change uin16_t to something else later
82// TODO: Maybe create a typedef for each of the templated SceneObject types
83template<class VertexType, class SSBOType>
84struct SceneObject {
85 vector<VertexType> vertices;
86 vector<uint16_t> indices;
87 SSBOType ssbo;
88
89 mat4 model_base;
90 mat4 model_transform;
91
[5ba732a]92 bool modified;
93
[4994692]94 // TODO: Figure out if I should make child classes that have these fields instead of putting them in the
95 // parent class
96 vec3 center; // currently only matters for asteroids
97 float radius; // currently only matters for asteroids
98};
99
100// TODO: Have to figure out how to include an optional ssbo parameter for each object
[2da64ef]101// Could probably use the same approach to make indices optional
[4994692]102// Figure out if there are sufficient use cases to make either of these optional or is it fine to make
103// them mamdatory
[2da64ef]104
[6104594]105// TODO: Make a singleton timer class instead
106static float curTime;
107
[99d44b2]108class VulkanGame {
[e8ebc76]109 public:
[34bdf3a]110 VulkanGame(int maxFramesInFlight);
[99d44b2]111 ~VulkanGame();
[0df3c9a]112
[b6e60b4]113 void run(int width, int height, unsigned char guiFlags);
[0df3c9a]114
115 private:
[34bdf3a]116 const int MAX_FRAMES_IN_FLIGHT;
117
[5ab1b20]118 const float NEAR_CLIP = 0.1f;
119 const float FAR_CLIP = 100.0f;
[60578ce]120 const float FOV_ANGLE = 67.0f; // means the camera lens goes from -33 deg to 33 def
[5ab1b20]121
[15104a8]122 vec3 cam_pos;
123
[0df3c9a]124 GameGui* gui;
[c559904]125
126 SDL_version sdlVersion;
[b794178]127 SDL_Window* window = nullptr;
128 SDL_Renderer* renderer = nullptr;
129
130 SDL_Texture* uiOverlay = nullptr;
[c1d9b2a]131
132 VkInstance instance;
133 VkDebugUtilsMessengerEXT debugMessenger;
[fe5c3ba]134 VkSurfaceKHR surface; // TODO: Change the variable name to vulkanSurface
[90a424f]135 VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
[c1c2021]136 VkDevice device;
137
138 VkQueue graphicsQueue;
139 VkQueue presentQueue;
[0df3c9a]140
[502bd0b]141 VkSwapchainKHR swapChain;
142 vector<VkImage> swapChainImages;
143 VkFormat swapChainImageFormat;
[603b5bc]144 VkExtent2D swapChainExtent;
[f94eea9]145 vector<VkImageView> swapChainImageViews;
[603b5bc]146 vector<VkFramebuffer> swapChainFramebuffers;
[fa9fa1c]147
[6fc24c7]148 VkRenderPass renderPass;
[fa9fa1c]149 VkCommandPool commandPool;
[603b5bc]150 vector<VkCommandBuffer> commandBuffers;
[502bd0b]151
[603b5bc]152 VulkanImage depthImage;
[b794178]153
154 VkSampler textureSampler;
155
[0fe8433]156 VulkanImage sdlOverlayImage;
157 VkDescriptorImageInfo sdlOverlayImageDescriptor;
158
[4994692]159 VulkanImage floorTextureImage;
160 VkDescriptorImageInfo floorTextureImageDescriptor;
161
[237cbec]162 VulkanImage laserTextureImage;
163 VkDescriptorImageInfo laserTextureImageDescriptor;
164
[0fe8433]165 TTF_Font* font;
166 SDL_Texture* fontSDLTexture;
167
168 SDL_Texture* imageSDLTexture;
169
170 vector<VkSemaphore> imageAvailableSemaphores;
171 vector<VkSemaphore> renderFinishedSemaphores;
172 vector<VkFence> inFlightFences;
173
174 size_t currentFrame;
175
176 bool framebufferResized;
177
[22217d4]178 mat4 viewMat, projMat;
179
[2d87297]180 GraphicsPipeline_Vulkan<OverlayVertex, void*> overlayPipeline;
181 vector<SceneObject<OverlayVertex, void*>> overlayObjects;
[0fe8433]182
[860a0da]183 // TODO: Maybe make the ubo objects part of the pipeline class since there's only one ubo
184 // per pipeline.
185 // Or maybe create a higher level wrapper around GraphicsPipeline_Vulkan to hold things like
186 // the objects vector, the ubo, and the ssbo
187
[2ba5617]188 // TODO: Rename *_VP_mats to *_uniforms and possibly use different types for each one
189 // if there is a need to add other uniform variables to one or more of the shaders
190
[2d87297]191 GraphicsPipeline_Vulkan<ModelVertex, SSBO_ModelObject> modelPipeline;
192 vector<SceneObject<ModelVertex, SSBO_ModelObject>> modelObjects;
[0fe8433]193
[d25381b]194 vector<VkBuffer> uniformBuffers_modelPipeline;
195 vector<VkDeviceMemory> uniformBuffersMemory_modelPipeline;
196 vector<VkDescriptorBufferInfo> uniformBufferInfoList_modelPipeline;
[b794178]197
[0fe8433]198 UBO_VP_mats object_VP_mats;
199
[2d87297]200 GraphicsPipeline_Vulkan<ShipVertex, SSBO_ModelObject> shipPipeline;
201 vector<SceneObject<ShipVertex, SSBO_ModelObject>> shipObjects;
[0fe8433]202
[3782d66]203 vector<VkBuffer> uniformBuffers_shipPipeline;
204 vector<VkDeviceMemory> uniformBuffersMemory_shipPipeline;
205 vector<VkDescriptorBufferInfo> uniformBufferInfoList_shipPipeline;
206
[0fe8433]207 UBO_VP_mats ship_VP_mats;
[0e09340]208
[2d87297]209 GraphicsPipeline_Vulkan<AsteroidVertex, SSBO_Asteroid> asteroidPipeline;
210 vector<SceneObject<AsteroidVertex, SSBO_Asteroid>> asteroidObjects;
[3e8cc8b]211
212 vector<VkBuffer> uniformBuffers_asteroidPipeline;
213 vector<VkDeviceMemory> uniformBuffersMemory_asteroidPipeline;
214 vector<VkDescriptorBufferInfo> uniformBufferInfoList_asteroidPipeline;
215
216 UBO_VP_mats asteroid_VP_mats;
217
[237cbec]218 GraphicsPipeline_Vulkan<LaserVertex, SSBO_Laser> laserPipeline;
219 vector<SceneObject<LaserVertex, SSBO_Laser>> laserObjects;
220
221 vector<VkBuffer> uniformBuffers_laserPipeline;
222 vector<VkDeviceMemory> uniformBuffersMemory_laserPipeline;
223 vector<VkDescriptorBufferInfo> uniformBufferInfoList_laserPipeline;
224
225 UBO_VP_mats laser_VP_mats;
226
[0807aeb]227 time_point<steady_clock> startTime;
[6104594]228 float prevTime, elapsedTime;
[0807aeb]229
230 float shipSpeed = 0.5f;
231 float asteroidSpeed = 2.0f;
232
233 float spawnRate_asteroid = 0.5;
234 float lastSpawn_asteroid;
[4ece3bf]235
[1f81ecc]236 unsigned int leftLaserIdx = -1;
237
238 unsigned int rightLaserIdx = -1;
239
[b6e60b4]240 bool initWindow(int width, int height, unsigned char guiFlags);
[0df3c9a]241 void initVulkan();
[f97c5e7]242 void initGraphicsPipelines();
[15104a8]243 void initMatrices();
[0df3c9a]244 void mainLoop();
[8e02b6b]245 void updateScene(uint32_t currentImage);
[a0c5f28]246 void renderUI();
247 void renderScene();
[0df3c9a]248 void cleanup();
[c1d9b2a]249
250 void createVulkanInstance(const vector<const char*> &validationLayers);
251 void setupDebugMessenger();
252 void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo);
[90a424f]253 void createVulkanSurface();
[fe5c3ba]254 void pickPhysicalDevice(const vector<const char*>& deviceExtensions);
[fa9fa1c]255 bool isDeviceSuitable(VkPhysicalDevice physicalDevice, const vector<const char*>& deviceExtensions);
[c1c2021]256 void createLogicalDevice(
257 const vector<const char*> validationLayers,
258 const vector<const char*>& deviceExtensions);
[502bd0b]259 void createSwapChain();
[f94eea9]260 void createImageViews();
[6fc24c7]261 void createRenderPass();
262 VkFormat findDepthFormat();
[fa9fa1c]263 void createCommandPool();
[603b5bc]264 void createImageResources();
265
[b794178]266 void createTextureSampler();
[603b5bc]267 void createFramebuffers();
268 void createCommandBuffers();
[34bdf3a]269 void createSyncObjects();
[f94eea9]270
[1f81ecc]271 void addLaser(vec3 start, vec3 end, vec3 color, float width);
272 void translateLaser(size_t index, const vec3& translation);
273
[4994692]274 // TODO: Since addObject() returns a reference to the new object now,
275 // stop using objects.back() to access the object that was just created
[2d87297]276 template<class VertexType, class SSBOType>
[4994692]277 SceneObject<VertexType, SSBOType>& addObject(
278 vector<SceneObject<VertexType, SSBOType>>& objects,
279 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
280 const vector<VertexType>& vertices, vector<uint16_t> indices, SSBOType ssbo,
281 bool pipelinesCreated);
[0fe8433]282
[2da64ef]283 template<class VertexType, class SSBOType>
284 void updateObject(vector<SceneObject<VertexType, SSBOType>>& objects,
[4994692]285 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline, size_t index);
[2da64ef]286
[1f81ecc]287 template<class VertexType, class SSBOType>
288 void updateObjectVertices(GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
289 SceneObject<VertexType, SSBOType>& obj, size_t index);
290
[06d959f]291 template<class VertexType>
292 vector<VertexType> addVertexNormals(vector<VertexType> vertices);
293
[cf727ca]294 template<class VertexType>
295 vector<VertexType> addObjectIndex(unsigned int objIndex, vector<VertexType> vertices);
296
[3b84bb6]297 template<class VertexType, class SSBOType>
298 void centerObject(SceneObject<VertexType, SSBOType>& object);
[a79be34]299
[055750a]300 void createBufferSet(VkDeviceSize bufferSize, VkBufferUsageFlags flags,
[4994692]301 vector<VkBuffer>& buffers, vector<VkDeviceMemory>& buffersMemory,
302 vector<VkDescriptorBufferInfo>& bufferInfoList);
[f97c5e7]303
[d2d9286]304 void recreateSwapChain();
305
[c1c2021]306 void cleanupSwapChain();
[c1d9b2a]307
308 static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
309 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
310 VkDebugUtilsMessageTypeFlagsEXT messageType,
311 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
312 void* pUserData);
[e8ebc76]313};
314
[3b84bb6]315// TODO: Right now, it's basically necessary to pass the identity matrix in for ssbo.model
316// and to change the model matrix later by setting model_transform and then calling updateObject()
317// Figure out a better way to allow the model matrix to be set during objecting creation
[2ba5617]318
319// TODO: Maybe return a reference to the object from this method if I decide that updating it
320// immediately after creation is a good idea (such as setting model_base)
321// Currently, model_base is set like this in a few places and the radius is set for asteroids
322// to account for scaling
[2d87297]323template<class VertexType, class SSBOType>
[4994692]324SceneObject<VertexType, SSBOType>& VulkanGame::addObject(
325 vector<SceneObject<VertexType, SSBOType>>& objects,
[2d87297]326 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
[3b84bb6]327 const vector<VertexType>& vertices, vector<uint16_t> indices, SSBOType ssbo,
328 bool pipelinesCreated) {
[2ba5617]329 // TODO: Use the model field of ssbo to set the object's model_base
330 // currently, the passed in model is useless since it gets overridden in updateObject() anyway
[0fe8433]331 size_t numVertices = pipeline.getNumVertices();
332
333 for (uint16_t& idx : indices) {
334 idx += numVertices;
335 }
336
[5ba732a]337 objects.push_back({ vertices, indices, ssbo, mat4(1.0f), mat4(1.0f), false });
[3b84bb6]338
[2ba5617]339 SceneObject<VertexType, SSBOType>& obj = objects.back();
[1f81ecc]340
341 if (!is_same_v<VertexType, LaserVertex>) {
342 centerObject(obj);
343 }
[2ba5617]344
[4994692]345 bool storageBufferResized = pipeline.addObject(obj.vertices, obj.indices, obj.ssbo,
346 this->commandPool, this->graphicsQueue);
[0fe8433]347
[3b84bb6]348 if (pipelinesCreated) {
[44f23af]349 vkDeviceWaitIdle(device);
350 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
351
352 // TODO: The pipeline recreation only has to be done once per frame where at least
353 // one SSBO is resized.
354 // Refactor the logic to check for any resized SSBOs after all objects for the frame
355 // are created and then recreate each of the corresponding pipelines only once per frame
[3b84bb6]356 if (storageBufferResized) {
[44f23af]357 pipeline.createPipeline(pipeline.vertShaderFile, pipeline.fragShaderFile);
358 pipeline.createDescriptorPool(swapChainImages);
359 pipeline.createDescriptorSets(swapChainImages);
[3b84bb6]360 }
361
362 createCommandBuffers();
363 }
[4994692]364
365 return obj;
[0fe8433]366}
367
[0807aeb]368// TODO: Just pass in the single object instead of a list of all of them
[2da64ef]369template<class VertexType, class SSBOType>
370void VulkanGame::updateObject(vector<SceneObject<VertexType, SSBOType>>& objects,
371 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline, size_t index) {
372 SceneObject<VertexType, SSBOType>& obj = objects[index];
373
374 obj.ssbo.model = obj.model_transform * obj.model_base;
[2ba5617]375 obj.center = vec3(obj.ssbo.model * vec4(0.0f, 0.0f, 0.0f, 1.0f));
[2da64ef]376
377 pipeline.updateObject(index, obj.ssbo);
[5ba732a]378
379 obj.modified = false;
[2da64ef]380}
381
[1f81ecc]382template<class VertexType, class SSBOType>
383void VulkanGame::updateObjectVertices(GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
384 SceneObject<VertexType, SSBOType>& obj, size_t index) {
385 pipeline.updateObjectVertices(index, obj.vertices, this->commandPool, this->graphicsQueue);
386}
387
[06d959f]388template<class VertexType>
389vector<VertexType> VulkanGame::addVertexNormals(vector<VertexType> vertices) {
390 for (unsigned int i = 0; i < vertices.size(); i += 3) {
391 vec3 p1 = vertices[i].pos;
392 vec3 p2 = vertices[i+1].pos;
393 vec3 p3 = vertices[i+2].pos;
394
[a79be34]395 vec3 normal = normalize(cross(p2 - p1, p3 - p1));
[06d959f]396
397 // Add the same normal for all 3 vertices
398 vertices[i].normal = normal;
399 vertices[i+1].normal = normal;
400 vertices[i+2].normal = normal;
401 }
402
403 return vertices;
404}
405
[cf727ca]406template<class VertexType>
407vector<VertexType> VulkanGame::addObjectIndex(unsigned int objIndex, vector<VertexType> vertices) {
408 for (VertexType& vertex : vertices) {
409 vertex.objIndex = objIndex;
410 }
411
412 return vertices;
413}
414
[3b84bb6]415template<class VertexType, class SSBOType>
416void VulkanGame::centerObject(SceneObject<VertexType, SSBOType>& object) {
417 vector<VertexType>& vertices = object.vertices;
418
[a79be34]419 float min_x = vertices[0].pos.x;
420 float max_x = vertices[0].pos.x;
421 float min_y = vertices[0].pos.y;
422 float max_y = vertices[0].pos.y;
423 float min_z = vertices[0].pos.z;
424 float max_z = vertices[0].pos.z;
425
426 // start from the second point
427 for (unsigned int i = 1; i < vertices.size(); i++) {
[3b84bb6]428 vec3& pos = vertices[i].pos;
429
430 if (min_x > pos.x) {
431 min_x = pos.x;
432 } else if (max_x < pos.x) {
433 max_x = pos.x;
[a79be34]434 }
435
[3b84bb6]436 if (min_y > pos.y) {
437 min_y = pos.y;
438 } else if (max_y < pos.y) {
439 max_y = pos.y;
[a79be34]440 }
441
[3b84bb6]442 if (min_z > pos.z) {
443 min_z = pos.z;
444 } else if (max_z < pos.z) {
445 max_z = pos.z;
[a79be34]446 }
447 }
448
449 vec3 center = vec3(min_x + max_x, min_y + max_y, min_z + max_z) / 2.0f;
450
451 for (unsigned int i = 0; i < vertices.size(); i++) {
452 vertices[i].pos -= center;
453 }
454
[2ba5617]455 object.radius = std::max(max_x - center.x, max_y - center.y);
456 object.radius = std::max(object.radius, max_z - center.z);
457
[3b84bb6]458 object.center = vec3(0.0f, 0.0f, 0.0f);
[a79be34]459}
460
[3b84bb6]461#endif // _VULKAN_GAME_H
Note: See TracBrowser for help on using the repository browser.