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

feature/imgui-sdl
Last change on this file since aa7707d was aa7707d, checked in by Dmitry Portnoy <dmp1488@…>, 4 years ago

Update the Vulkan SDK version and get the latest code compiling on Windows

  • Property mode set to 100644
File size: 18.6 KB
Line 
1#ifndef _VULKAN_GAME_H
2#define _VULKAN_GAME_H
3
4#include <algorithm>
5#include <chrono>
6#include <map>
7
8#define GLM_FORCE_RADIANS
9#define GLM_FORCE_DEPTH_ZERO_TO_ONE // Since, in Vulkan, the depth range is 0 to 1 instead of -1 to 1
10#define GLM_FORCE_RIGHT_HANDED
11
12#include <glm/glm.hpp>
13#include <glm/gtc/matrix_transform.hpp>
14
15#include <vulkan/vulkan.h>
16
17#include <SDL2/SDL_ttf.h>
18
19#include "consts.hpp"
20#include "vulkan-utils.hpp"
21#include "graphics-pipeline_vulkan.hpp"
22
23#include "game-gui-sdl.hpp"
24
25#include "gui/screen.hpp"
26
27using namespace glm;
28using namespace std::chrono;
29
30#ifdef NDEBUG
31 const bool ENABLE_VALIDATION_LAYERS = false;
32#else
33 const bool ENABLE_VALIDATION_LAYERS = true;
34#endif
35
36struct OverlayVertex {
37 vec3 pos;
38 vec2 texCoord;
39};
40
41struct ModelVertex {
42 vec3 pos;
43 vec3 color;
44 vec2 texCoord;
45 unsigned int objIndex;
46};
47
48struct ShipVertex {
49 vec3 pos;
50 vec3 color;
51 vec3 normal;
52 unsigned int objIndex;
53};
54
55struct AsteroidVertex {
56 vec3 pos;
57 vec3 color;
58 vec3 normal;
59 unsigned int objIndex;
60};
61
62struct LaserVertex {
63 vec3 pos;
64 vec2 texCoord;
65 unsigned int objIndex;
66};
67
68struct ExplosionVertex {
69 vec3 particleStartVelocity;
70 float particleStartTime;
71 unsigned int objIndex;
72};
73
74struct SSBO_ModelObject {
75 alignas(16) mat4 model;
76};
77
78struct SSBO_Asteroid {
79 alignas(16) mat4 model;
80 alignas(4) float hp;
81 alignas(4) unsigned int deleted;
82};
83
84struct SSBO_Laser {
85 alignas(16) mat4 model;
86 alignas(4) vec3 color;
87 alignas(4) unsigned int deleted;
88};
89
90struct SSBO_Explosion {
91 alignas(16) mat4 model;
92 alignas(4) float explosionStartTime;
93 alignas(4) float explosionDuration;
94 alignas(4) unsigned int deleted;
95};
96
97struct UBO_VP_mats {
98 alignas(16) mat4 view;
99 alignas(16) mat4 proj;
100};
101
102struct UBO_Explosion {
103 alignas(16) mat4 view;
104 alignas(16) mat4 proj;
105 alignas(4) float cur_time;
106};
107
108// TODO: Change the index type to uint32_t and check the Vulkan Tutorial loading model section as a reference
109// TODO: Create a typedef for index type so I can easily change uin16_t to something else later
110// TODO: Maybe create a typedef for each of the templated SceneObject types
111template<class VertexType, class SSBOType>
112struct SceneObject {
113 vector<VertexType> vertices;
114 vector<uint16_t> indices;
115 SSBOType ssbo;
116
117 mat4 model_base;
118 mat4 model_transform;
119
120 bool modified;
121
122 // TODO: Figure out if I should make child classes that have these fields instead of putting them in the
123 // parent class
124 vec3 center; // currently only matters for asteroids
125 float radius; // currently only matters for asteroids
126 SceneObject<AsteroidVertex, SSBO_Asteroid>* targetAsteroid; // currently only used for lasers
127};
128
129// TODO: Have to figure out how to include an optional ssbo parameter for each object
130// Could probably use the same approach to make indices optional
131// Figure out if there are sufficient use cases to make either of these optional or is it fine to make
132// them mamdatory
133
134// TODO: Make a singleton timer class instead
135static float curTime;
136
137
138// TODO: Look into using dynamic_cast to check types of SceneObject and EffectOverTime
139
140struct BaseEffectOverTime {
141 bool deleted;
142
143 virtual void applyEffect() = 0;
144
145 BaseEffectOverTime() :
146 deleted(false) {
147 }
148
149 virtual ~BaseEffectOverTime() {
150 }
151};
152
153template<class VertexType, class SSBOType>
154struct EffectOverTime : public BaseEffectOverTime {
155 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline;
156 vector<SceneObject<VertexType, SSBOType>>& objects;
157 unsigned int objectIndex;
158 size_t effectedFieldOffset;
159 float startValue;
160 float startTime;
161 float changePerSecond;
162
163 EffectOverTime(GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
164 vector<SceneObject<VertexType, SSBOType>>& objects, unsigned int objectIndex,
165 size_t effectedFieldOffset, float changePerSecond) :
166 pipeline(pipeline),
167 objects(objects),
168 objectIndex(objectIndex),
169 effectedFieldOffset(effectedFieldOffset),
170 startTime(curTime),
171 changePerSecond(changePerSecond) {
172 size_t ssboOffset = offset_of(&SceneObject<VertexType, SSBOType>::ssbo);
173
174 unsigned char* effectedFieldPtr = reinterpret_cast<unsigned char*>(&objects[objectIndex]) +
175 ssboOffset + effectedFieldOffset;
176
177 startValue = *reinterpret_cast<float*>(effectedFieldPtr);
178 }
179
180 void applyEffect() {
181 if (objects[objectIndex].ssbo.deleted) {
182 this->deleted = true;
183 return;
184 }
185
186 size_t ssboOffset = offset_of(&SceneObject<VertexType, SSBOType>::ssbo);
187
188 unsigned char* effectedFieldPtr = reinterpret_cast<unsigned char*>(&objects[objectIndex]) +
189 ssboOffset + effectedFieldOffset;
190
191 *reinterpret_cast<float*>(effectedFieldPtr) = startValue + (curTime - startTime) * changePerSecond;
192
193 objects[objectIndex].modified = true;
194 }
195};
196
197class VulkanGame {
198 public:
199 VulkanGame(int maxFramesInFlight);
200 ~VulkanGame();
201
202 void run(int width, int height, unsigned char guiFlags);
203
204 void goToScreen(Screen* screen);
205 void quitGame();
206
207 map<ScreenType, Screen*> screens;
208 Screen* currentScreen;
209
210 TTF_Font* lazyFont;
211 TTF_Font* proggyFont;
212
213 int score;
214 float fps;
215
216 GraphicsPipeline_Vulkan<OverlayVertex, void*> overlayPipeline;
217
218 GraphicsPipeline_Vulkan<ModelVertex, SSBO_ModelObject> modelPipeline;
219
220 GraphicsPipeline_Vulkan<ShipVertex, SSBO_ModelObject> shipPipeline;
221
222 GraphicsPipeline_Vulkan<AsteroidVertex, SSBO_Asteroid> asteroidPipeline;
223
224 GraphicsPipeline_Vulkan<LaserVertex, SSBO_Laser> laserPipeline;
225
226 GraphicsPipeline_Vulkan<ExplosionVertex, SSBO_Explosion> explosionPipeline;
227
228 private:
229 // TODO: Make these consts static
230 // Also, maybe move them into consts.hpp
231
232 const int MAX_FRAMES_IN_FLIGHT;
233
234 const float NEAR_CLIP = 0.1f;
235 const float FAR_CLIP = 100.0f;
236 const float FOV_ANGLE = 67.0f; // means the camera lens goes from -33 deg to 33 def
237
238 const int EXPLOSION_PARTICLE_COUNT = 300;
239 const vec3 LASER_COLOR = vec3(0.2f, 1.0f, 0.2f);
240
241 bool quit;
242
243 vec3 cam_pos;
244
245 // TODO: Good place to start using smart pointers
246 GameGui* gui;
247
248 SDL_version sdlVersion;
249 SDL_Window* window = nullptr;
250 SDL_Renderer* renderer = nullptr;
251
252 SDL_Texture* uiOverlay = nullptr;
253
254 VkInstance instance;
255 VkDebugUtilsMessengerEXT debugMessenger;
256 VkSurfaceKHR surface; // TODO: Change the variable name to vulkanSurface
257 VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
258 VkDevice device;
259
260 VkQueue graphicsQueue;
261 VkQueue presentQueue;
262
263 VkSwapchainKHR swapChain;
264 vector<VkImage> swapChainImages;
265 VkFormat swapChainImageFormat;
266 VkExtent2D swapChainExtent;
267 vector<VkImageView> swapChainImageViews;
268 vector<VkFramebuffer> swapChainFramebuffers;
269
270 VkRenderPass renderPass;
271 VkCommandPool commandPool;
272 vector<VkCommandBuffer> commandBuffers;
273
274 VulkanImage depthImage;
275
276 vector<VkSemaphore> imageAvailableSemaphores;
277 vector<VkSemaphore> renderFinishedSemaphores;
278 vector<VkFence> inFlightFences;
279
280 size_t currentFrame;
281
282 bool framebufferResized;
283
284 VkSampler textureSampler;
285
286 VulkanImage sdlOverlayImage;
287 VkDescriptorImageInfo sdlOverlayImageDescriptor;
288
289 VulkanImage floorTextureImage;
290 VkDescriptorImageInfo floorTextureImageDescriptor;
291
292 VulkanImage laserTextureImage;
293 VkDescriptorImageInfo laserTextureImageDescriptor;
294
295 mat4 viewMat, projMat;
296
297 // TODO: Maybe make the ubo objects part of the pipeline class since there's only one ubo
298 // per pipeline.
299 // Or maybe create a higher level wrapper around GraphicsPipeline_Vulkan to hold things like
300 // the objects vector, the ubo, and the ssbo
301
302 // TODO: Rename *_VP_mats to *_uniforms and possibly use different types for each one
303 // if there is a need to add other uniform variables to one or more of the shaders
304
305 vector<SceneObject<OverlayVertex, void*>> overlayObjects;
306
307 vector<SceneObject<ModelVertex, SSBO_ModelObject>> modelObjects;
308
309 vector<VkBuffer> uniformBuffers_modelPipeline;
310 vector<VkDeviceMemory> uniformBuffersMemory_modelPipeline;
311 vector<VkDescriptorBufferInfo> uniformBufferInfoList_modelPipeline;
312
313 UBO_VP_mats object_VP_mats;
314
315 vector<SceneObject<ShipVertex, SSBO_ModelObject>> shipObjects;
316
317 vector<VkBuffer> uniformBuffers_shipPipeline;
318 vector<VkDeviceMemory> uniformBuffersMemory_shipPipeline;
319 vector<VkDescriptorBufferInfo> uniformBufferInfoList_shipPipeline;
320
321 UBO_VP_mats ship_VP_mats;
322
323 vector<SceneObject<AsteroidVertex, SSBO_Asteroid>> asteroidObjects;
324
325 vector<VkBuffer> uniformBuffers_asteroidPipeline;
326 vector<VkDeviceMemory> uniformBuffersMemory_asteroidPipeline;
327 vector<VkDescriptorBufferInfo> uniformBufferInfoList_asteroidPipeline;
328
329 UBO_VP_mats asteroid_VP_mats;
330
331 vector<SceneObject<LaserVertex, SSBO_Laser>> laserObjects;
332
333 vector<VkBuffer> uniformBuffers_laserPipeline;
334 vector<VkDeviceMemory> uniformBuffersMemory_laserPipeline;
335 vector<VkDescriptorBufferInfo> uniformBufferInfoList_laserPipeline;
336
337 UBO_VP_mats laser_VP_mats;
338
339 vector<SceneObject<ExplosionVertex, SSBO_Explosion>> explosionObjects;
340
341 vector<VkBuffer> uniformBuffers_explosionPipeline;
342 vector<VkDeviceMemory> uniformBuffersMemory_explosionPipeline;
343 vector<VkDescriptorBufferInfo> uniformBufferInfoList_explosionPipeline;
344
345 UBO_Explosion explosion_UBO;
346
347 vector<BaseEffectOverTime*> effects;
348
349 time_point<steady_clock> startTime;
350 float prevTime, elapsedTime;
351
352 float fpsStartTime;
353 int frameCount;
354
355 float shipSpeed = 0.5f;
356 float asteroidSpeed = 2.0f;
357
358 float spawnRate_asteroid = 0.5;
359 float lastSpawn_asteroid;
360
361 unsigned int leftLaserIdx = -1;
362 EffectOverTime<AsteroidVertex, SSBO_Asteroid>* leftLaserEffect = nullptr;
363
364 unsigned int rightLaserIdx = -1;
365 EffectOverTime<AsteroidVertex, SSBO_Asteroid>* rightLaserEffect = nullptr;
366
367 bool initUI(int width, int height, unsigned char guiFlags);
368 void initVulkan();
369 void initGraphicsPipelines();
370 void initMatrices();
371 void mainLoop();
372 void updateScene(uint32_t currentImage);
373 void renderScene();
374 void cleanup();
375
376 void createVulkanInstance(const vector<const char*> &validationLayers);
377 void setupDebugMessenger();
378 void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo);
379 void createVulkanSurface();
380 void pickPhysicalDevice(const vector<const char*>& deviceExtensions);
381 bool isDeviceSuitable(VkPhysicalDevice physicalDevice, const vector<const char*>& deviceExtensions);
382 void createLogicalDevice(
383 const vector<const char*> validationLayers,
384 const vector<const char*>& deviceExtensions);
385 void createSwapChain();
386 void createImageViews();
387 void createRenderPass();
388 VkFormat findDepthFormat();
389 void createCommandPool();
390 void createImageResources();
391
392 void createTextureSampler();
393 void createFramebuffers();
394 void createCommandBuffers();
395 void createSyncObjects();
396
397 // TODO: Since addObject() returns a reference to the new object now,
398 // stop using objects.back() to access the object that was just created
399 template<class VertexType, class SSBOType>
400 SceneObject<VertexType, SSBOType>& addObject(
401 vector<SceneObject<VertexType, SSBOType>>& objects,
402 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
403 const vector<VertexType>& vertices, vector<uint16_t> indices, SSBOType ssbo,
404 bool pipelinesCreated);
405
406 template<class VertexType, class SSBOType>
407 void updateObject(vector<SceneObject<VertexType, SSBOType>>& objects,
408 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline, size_t index);
409
410 template<class VertexType, class SSBOType>
411 void updateObjectVertices(GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
412 SceneObject<VertexType, SSBOType>& obj, size_t index);
413
414 template<class VertexType>
415 vector<VertexType> addVertexNormals(vector<VertexType> vertices);
416
417 template<class VertexType>
418 vector<VertexType> addObjectIndex(unsigned int objIndex, vector<VertexType> vertices);
419
420 template<class VertexType, class SSBOType>
421 void centerObject(SceneObject<VertexType, SSBOType>& object);
422
423 void addLaser(vec3 start, vec3 end, vec3 color, float width);
424 void translateLaser(size_t index, const vec3& translation);
425 void updateLaserTarget(size_t index);
426 bool getLaserAndAsteroidIntersection(SceneObject<AsteroidVertex, SSBO_Asteroid>& asteroid,
427 vec3& start, vec3& end, vec3& intersection);
428
429 void addExplosion(mat4 model_mat, float duration, float cur_time);
430
431 void createBufferSet(VkDeviceSize bufferSize, VkBufferUsageFlags flags,
432 vector<VkBuffer>& buffers, vector<VkDeviceMemory>& buffersMemory,
433 vector<VkDescriptorBufferInfo>& bufferInfoList);
434
435 void recreateSwapChain();
436
437 void cleanupSwapChain();
438
439 static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
440 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
441 VkDebugUtilsMessageTypeFlagsEXT messageType,
442 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
443 void* pUserData);
444};
445
446// Start of specialized no-op functions
447
448template<>
449inline void VulkanGame::centerObject(SceneObject<ExplosionVertex, SSBO_Explosion>& object) {
450}
451
452// End of specialized no-op functions
453
454// TODO: Right now, it's basically necessary to pass the identity matrix in for ssbo.model
455// and to change the model matrix later by setting model_transform and then calling updateObject()
456// Figure out a better way to allow the model matrix to be set during objecting creation
457
458// TODO: Maybe return a reference to the object from this method if I decide that updating it
459// immediately after creation is a good idea (such as setting model_base)
460// Currently, model_base is set like this in a few places and the radius is set for asteroids
461// to account for scaling
462template<class VertexType, class SSBOType>
463SceneObject<VertexType, SSBOType>& VulkanGame::addObject(
464 vector<SceneObject<VertexType, SSBOType>>& objects,
465 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
466 const vector<VertexType>& vertices, vector<uint16_t> indices, SSBOType ssbo,
467 bool pipelinesCreated) {
468 // TODO: Use the model field of ssbo to set the object's model_base
469 // currently, the passed in model is useless since it gets overridden in updateObject() anyway
470 size_t numVertices = pipeline.getNumVertices();
471
472 for (uint16_t& idx : indices) {
473 idx += numVertices;
474 }
475
476 objects.push_back({ vertices, indices, ssbo, mat4(1.0f), mat4(1.0f), false });
477
478 SceneObject<VertexType, SSBOType>& obj = objects.back();
479
480 if (!is_same_v<VertexType, LaserVertex> && !is_same_v<VertexType, ExplosionVertex>) {
481 centerObject(obj);
482 }
483
484 bool storageBufferResized = pipeline.addObject(obj.vertices, obj.indices, obj.ssbo,
485 this->commandPool, this->graphicsQueue);
486
487 if (pipelinesCreated) {
488 vkDeviceWaitIdle(device);
489 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
490
491 // TODO: The pipeline recreation only has to be done once per frame where at least
492 // one SSBO is resized.
493 // Refactor the logic to check for any resized SSBOs after all objects for the frame
494 // are created and then recreate each of the corresponding pipelines only once per frame
495 if (storageBufferResized) {
496 pipeline.createPipeline(pipeline.vertShaderFile, pipeline.fragShaderFile);
497 pipeline.createDescriptorPool(swapChainImages);
498 pipeline.createDescriptorSets(swapChainImages);
499 }
500
501 createCommandBuffers();
502 }
503
504 return obj;
505}
506
507// TODO: Just pass in the single object instead of a list of all of them
508template<class VertexType, class SSBOType>
509void VulkanGame::updateObject(vector<SceneObject<VertexType, SSBOType>>& objects,
510 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline, size_t index) {
511 SceneObject<VertexType, SSBOType>& obj = objects[index];
512
513 obj.ssbo.model = obj.model_transform * obj.model_base;
514 obj.center = vec3(obj.ssbo.model * vec4(0.0f, 0.0f, 0.0f, 1.0f));
515
516 pipeline.updateObject(index, obj.ssbo);
517
518 obj.modified = false;
519}
520
521template<class VertexType, class SSBOType>
522void VulkanGame::updateObjectVertices(GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
523 SceneObject<VertexType, SSBOType>& obj, size_t index) {
524 pipeline.updateObjectVertices(index, obj.vertices, this->commandPool, this->graphicsQueue);
525}
526
527template<class VertexType>
528vector<VertexType> VulkanGame::addVertexNormals(vector<VertexType> vertices) {
529 for (unsigned int i = 0; i < vertices.size(); i += 3) {
530 vec3 p1 = vertices[i].pos;
531 vec3 p2 = vertices[i+1].pos;
532 vec3 p3 = vertices[i+2].pos;
533
534 vec3 normal = normalize(cross(p2 - p1, p3 - p1));
535
536 // Add the same normal for all 3 vertices
537 vertices[i].normal = normal;
538 vertices[i+1].normal = normal;
539 vertices[i+2].normal = normal;
540 }
541
542 return vertices;
543}
544
545template<class VertexType>
546vector<VertexType> VulkanGame::addObjectIndex(unsigned int objIndex, vector<VertexType> vertices) {
547 for (VertexType& vertex : vertices) {
548 vertex.objIndex = objIndex;
549 }
550
551 return vertices;
552}
553
554template<class VertexType, class SSBOType>
555void VulkanGame::centerObject(SceneObject<VertexType, SSBOType>& object) {
556 vector<VertexType>& vertices = object.vertices;
557
558 float min_x = vertices[0].pos.x;
559 float max_x = vertices[0].pos.x;
560 float min_y = vertices[0].pos.y;
561 float max_y = vertices[0].pos.y;
562 float min_z = vertices[0].pos.z;
563 float max_z = vertices[0].pos.z;
564
565 // start from the second point
566 for (unsigned int i = 1; i < vertices.size(); i++) {
567 vec3& pos = vertices[i].pos;
568
569 if (min_x > pos.x) {
570 min_x = pos.x;
571 } else if (max_x < pos.x) {
572 max_x = pos.x;
573 }
574
575 if (min_y > pos.y) {
576 min_y = pos.y;
577 } else if (max_y < pos.y) {
578 max_y = pos.y;
579 }
580
581 if (min_z > pos.z) {
582 min_z = pos.z;
583 } else if (max_z < pos.z) {
584 max_z = pos.z;
585 }
586 }
587
588 vec3 center = vec3(min_x + max_x, min_y + max_y, min_z + max_z) / 2.0f;
589
590 for (unsigned int i = 0; i < vertices.size(); i++) {
591 vertices[i].pos -= center;
592 }
593
594 object.radius = std::max(max_x - center.x, max_y - center.y);
595 object.radius = std::max(object.radius, max_z - center.z);
596
597 object.center = vec3(0.0f, 0.0f, 0.0f);
598}
599
600#endif // _VULKAN_GAME_H
Note: See TracBrowser for help on using the repository browser.