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

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

Show the score and frame rate on the game screen

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