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

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

Make lasers deal damage to asteroids and eventually destroy them

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