source: opengl-game/vulkan-game.hpp@ 3950236

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

Make a laser stop when it hits an asteroid

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