source: opengl-game/vulkan-game.hpp@ 699e83a

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

Add a GameScreen class to render the main gameplay

  • 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 GraphicsPipeline_Vulkan<OverlayVertex, void*> overlayPipeline;
207
208 GraphicsPipeline_Vulkan<ModelVertex, SSBO_ModelObject> modelPipeline;
209
210 GraphicsPipeline_Vulkan<ShipVertex, SSBO_ModelObject> shipPipeline;
211
212 GraphicsPipeline_Vulkan<AsteroidVertex, SSBO_Asteroid> asteroidPipeline;
213
214 GraphicsPipeline_Vulkan<LaserVertex, SSBO_Laser> laserPipeline;
215
216 GraphicsPipeline_Vulkan<ExplosionVertex, SSBO_Explosion> explosionPipeline;
217
218 private:
219 // TODO: Make these consts static
220 // Also, maybe move them into consts.hpp
221
222 const int MAX_FRAMES_IN_FLIGHT;
223
224 const float NEAR_CLIP = 0.1f;
225 const float FAR_CLIP = 100.0f;
226 const float FOV_ANGLE = 67.0f; // means the camera lens goes from -33 deg to 33 def
227
228 const int EXPLOSION_PARTICLE_COUNT = 300;
229 const vec3 LASER_COLOR = vec3(0.2f, 1.0f, 0.2f);
230
231 bool quit;
232
233 vec3 cam_pos;
234
235 // TODO: Good place to start using smart pointers
236 GameGui* gui;
237
238 SDL_version sdlVersion;
239 SDL_Window* window = nullptr;
240 SDL_Renderer* renderer = nullptr;
241
242 SDL_Texture* uiOverlay = nullptr;
243
244 VkInstance instance;
245 VkDebugUtilsMessengerEXT debugMessenger;
246 VkSurfaceKHR surface; // TODO: Change the variable name to vulkanSurface
247 VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
248 VkDevice device;
249
250 VkQueue graphicsQueue;
251 VkQueue presentQueue;
252
253 VkSwapchainKHR swapChain;
254 vector<VkImage> swapChainImages;
255 VkFormat swapChainImageFormat;
256 VkExtent2D swapChainExtent;
257 vector<VkImageView> swapChainImageViews;
258 vector<VkFramebuffer> swapChainFramebuffers;
259
260 VkRenderPass renderPass;
261 VkCommandPool commandPool;
262 vector<VkCommandBuffer> commandBuffers;
263
264 VulkanImage depthImage;
265
266 vector<VkSemaphore> imageAvailableSemaphores;
267 vector<VkSemaphore> renderFinishedSemaphores;
268 vector<VkFence> inFlightFences;
269
270 size_t currentFrame;
271
272 bool framebufferResized;
273
274 VkSampler textureSampler;
275
276 VulkanImage sdlOverlayImage;
277 VkDescriptorImageInfo sdlOverlayImageDescriptor;
278
279 VulkanImage floorTextureImage;
280 VkDescriptorImageInfo floorTextureImageDescriptor;
281
282 VulkanImage laserTextureImage;
283 VkDescriptorImageInfo laserTextureImageDescriptor;
284
285 TTF_Font* font;
286 SDL_Texture* fontSDLTexture;
287
288 SDL_Texture* imageSDLTexture;
289
290 mat4 viewMat, projMat;
291
292 // TODO: Maybe make the ubo objects part of the pipeline class since there's only one ubo
293 // per pipeline.
294 // Or maybe create a higher level wrapper around GraphicsPipeline_Vulkan to hold things like
295 // the objects vector, the ubo, and the ssbo
296
297 // TODO: Rename *_VP_mats to *_uniforms and possibly use different types for each one
298 // if there is a need to add other uniform variables to one or more of the shaders
299
300 vector<SceneObject<OverlayVertex, void*>> overlayObjects;
301
302 vector<SceneObject<ModelVertex, SSBO_ModelObject>> modelObjects;
303
304 vector<VkBuffer> uniformBuffers_modelPipeline;
305 vector<VkDeviceMemory> uniformBuffersMemory_modelPipeline;
306 vector<VkDescriptorBufferInfo> uniformBufferInfoList_modelPipeline;
307
308 UBO_VP_mats object_VP_mats;
309
310 vector<SceneObject<ShipVertex, SSBO_ModelObject>> shipObjects;
311
312 vector<VkBuffer> uniformBuffers_shipPipeline;
313 vector<VkDeviceMemory> uniformBuffersMemory_shipPipeline;
314 vector<VkDescriptorBufferInfo> uniformBufferInfoList_shipPipeline;
315
316 UBO_VP_mats ship_VP_mats;
317
318 vector<SceneObject<AsteroidVertex, SSBO_Asteroid>> asteroidObjects;
319
320 vector<VkBuffer> uniformBuffers_asteroidPipeline;
321 vector<VkDeviceMemory> uniformBuffersMemory_asteroidPipeline;
322 vector<VkDescriptorBufferInfo> uniformBufferInfoList_asteroidPipeline;
323
324 UBO_VP_mats asteroid_VP_mats;
325
326 vector<SceneObject<LaserVertex, SSBO_Laser>> laserObjects;
327
328 vector<VkBuffer> uniformBuffers_laserPipeline;
329 vector<VkDeviceMemory> uniformBuffersMemory_laserPipeline;
330 vector<VkDescriptorBufferInfo> uniformBufferInfoList_laserPipeline;
331
332 UBO_VP_mats laser_VP_mats;
333
334 vector<SceneObject<ExplosionVertex, SSBO_Explosion>> explosionObjects;
335
336 vector<VkBuffer> uniformBuffers_explosionPipeline;
337 vector<VkDeviceMemory> uniformBuffersMemory_explosionPipeline;
338 vector<VkDescriptorBufferInfo> uniformBufferInfoList_explosionPipeline;
339
340 UBO_Explosion explosion_UBO;
341
342 vector<BaseEffectOverTime*> effects;
343
344 time_point<steady_clock> startTime;
345 float prevTime, elapsedTime;
346
347 float shipSpeed = 0.5f;
348 float asteroidSpeed = 2.0f;
349
350 float spawnRate_asteroid = 0.5;
351 float lastSpawn_asteroid;
352
353 unsigned int leftLaserIdx = -1;
354 EffectOverTime<AsteroidVertex, SSBO_Asteroid>* leftLaserEffect = nullptr;
355
356 unsigned int rightLaserIdx = -1;
357 EffectOverTime<AsteroidVertex, SSBO_Asteroid>* rightLaserEffect = nullptr;
358
359 bool initUI(int width, int height, unsigned char guiFlags);
360 void initVulkan();
361 void initGraphicsPipelines();
362 void initMatrices();
363 void mainLoop();
364 void updateScene(uint32_t currentImage);
365 void renderUI();
366 void renderScene();
367 void cleanup();
368
369 void createVulkanInstance(const vector<const char*> &validationLayers);
370 void setupDebugMessenger();
371 void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo);
372 void createVulkanSurface();
373 void pickPhysicalDevice(const vector<const char*>& deviceExtensions);
374 bool isDeviceSuitable(VkPhysicalDevice physicalDevice, const vector<const char*>& deviceExtensions);
375 void createLogicalDevice(
376 const vector<const char*> validationLayers,
377 const vector<const char*>& deviceExtensions);
378 void createSwapChain();
379 void createImageViews();
380 void createRenderPass();
381 VkFormat findDepthFormat();
382 void createCommandPool();
383 void createImageResources();
384
385 void createTextureSampler();
386 void createFramebuffers();
387 void createCommandBuffers();
388 void createSyncObjects();
389
390 // TODO: Since addObject() returns a reference to the new object now,
391 // stop using objects.back() to access the object that was just created
392 template<class VertexType, class SSBOType>
393 SceneObject<VertexType, SSBOType>& addObject(
394 vector<SceneObject<VertexType, SSBOType>>& objects,
395 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
396 const vector<VertexType>& vertices, vector<uint16_t> indices, SSBOType ssbo,
397 bool pipelinesCreated);
398
399 template<class VertexType, class SSBOType>
400 void updateObject(vector<SceneObject<VertexType, SSBOType>>& objects,
401 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline, size_t index);
402
403 template<class VertexType, class SSBOType>
404 void updateObjectVertices(GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
405 SceneObject<VertexType, SSBOType>& obj, size_t index);
406
407 template<class VertexType>
408 vector<VertexType> addVertexNormals(vector<VertexType> vertices);
409
410 template<class VertexType>
411 vector<VertexType> addObjectIndex(unsigned int objIndex, vector<VertexType> vertices);
412
413 template<class VertexType, class SSBOType>
414 void centerObject(SceneObject<VertexType, SSBOType>& object);
415
416 void addLaser(vec3 start, vec3 end, vec3 color, float width);
417 void translateLaser(size_t index, const vec3& translation);
418 void updateLaserTarget(size_t index);
419 bool getLaserAndAsteroidIntersection(SceneObject<AsteroidVertex, SSBO_Asteroid>& asteroid,
420 vec3& start, vec3& end, vec3& intersection);
421
422 void addExplosion(mat4 model_mat, float duration, float cur_time);
423
424 void createBufferSet(VkDeviceSize bufferSize, VkBufferUsageFlags flags,
425 vector<VkBuffer>& buffers, vector<VkDeviceMemory>& buffersMemory,
426 vector<VkDescriptorBufferInfo>& bufferInfoList);
427
428 void recreateSwapChain();
429
430 void cleanupSwapChain();
431
432 static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
433 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
434 VkDebugUtilsMessageTypeFlagsEXT messageType,
435 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
436 void* pUserData);
437};
438
439// Start of specialized no-op functions
440
441template<>
442inline void VulkanGame::centerObject(SceneObject<ExplosionVertex, SSBO_Explosion>& object) {
443}
444
445// End of specialized no-op functions
446
447// TODO: Right now, it's basically necessary to pass the identity matrix in for ssbo.model
448// and to change the model matrix later by setting model_transform and then calling updateObject()
449// Figure out a better way to allow the model matrix to be set during objecting creation
450
451// TODO: Maybe return a reference to the object from this method if I decide that updating it
452// immediately after creation is a good idea (such as setting model_base)
453// Currently, model_base is set like this in a few places and the radius is set for asteroids
454// to account for scaling
455template<class VertexType, class SSBOType>
456SceneObject<VertexType, SSBOType>& VulkanGame::addObject(
457 vector<SceneObject<VertexType, SSBOType>>& objects,
458 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
459 const vector<VertexType>& vertices, vector<uint16_t> indices, SSBOType ssbo,
460 bool pipelinesCreated) {
461 // TODO: Use the model field of ssbo to set the object's model_base
462 // currently, the passed in model is useless since it gets overridden in updateObject() anyway
463 size_t numVertices = pipeline.getNumVertices();
464
465 for (uint16_t& idx : indices) {
466 idx += numVertices;
467 }
468
469 objects.push_back({ vertices, indices, ssbo, mat4(1.0f), mat4(1.0f), false });
470
471 SceneObject<VertexType, SSBOType>& obj = objects.back();
472
473 if (!is_same_v<VertexType, LaserVertex> && !is_same_v<VertexType, ExplosionVertex>) {
474 centerObject(obj);
475 }
476
477 bool storageBufferResized = pipeline.addObject(obj.vertices, obj.indices, obj.ssbo,
478 this->commandPool, this->graphicsQueue);
479
480 if (pipelinesCreated) {
481 vkDeviceWaitIdle(device);
482 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
483
484 // TODO: The pipeline recreation only has to be done once per frame where at least
485 // one SSBO is resized.
486 // Refactor the logic to check for any resized SSBOs after all objects for the frame
487 // are created and then recreate each of the corresponding pipelines only once per frame
488 if (storageBufferResized) {
489 pipeline.createPipeline(pipeline.vertShaderFile, pipeline.fragShaderFile);
490 pipeline.createDescriptorPool(swapChainImages);
491 pipeline.createDescriptorSets(swapChainImages);
492 }
493
494 createCommandBuffers();
495 }
496
497 return obj;
498}
499
500// TODO: Just pass in the single object instead of a list of all of them
501template<class VertexType, class SSBOType>
502void VulkanGame::updateObject(vector<SceneObject<VertexType, SSBOType>>& objects,
503 GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline, size_t index) {
504 SceneObject<VertexType, SSBOType>& obj = objects[index];
505
506 obj.ssbo.model = obj.model_transform * obj.model_base;
507 obj.center = vec3(obj.ssbo.model * vec4(0.0f, 0.0f, 0.0f, 1.0f));
508
509 pipeline.updateObject(index, obj.ssbo);
510
511 obj.modified = false;
512}
513
514template<class VertexType, class SSBOType>
515void VulkanGame::updateObjectVertices(GraphicsPipeline_Vulkan<VertexType, SSBOType>& pipeline,
516 SceneObject<VertexType, SSBOType>& obj, size_t index) {
517 pipeline.updateObjectVertices(index, obj.vertices, this->commandPool, this->graphicsQueue);
518}
519
520template<class VertexType>
521vector<VertexType> VulkanGame::addVertexNormals(vector<VertexType> vertices) {
522 for (unsigned int i = 0; i < vertices.size(); i += 3) {
523 vec3 p1 = vertices[i].pos;
524 vec3 p2 = vertices[i+1].pos;
525 vec3 p3 = vertices[i+2].pos;
526
527 vec3 normal = normalize(cross(p2 - p1, p3 - p1));
528
529 // Add the same normal for all 3 vertices
530 vertices[i].normal = normal;
531 vertices[i+1].normal = normal;
532 vertices[i+2].normal = normal;
533 }
534
535 return vertices;
536}
537
538template<class VertexType>
539vector<VertexType> VulkanGame::addObjectIndex(unsigned int objIndex, vector<VertexType> vertices) {
540 for (VertexType& vertex : vertices) {
541 vertex.objIndex = objIndex;
542 }
543
544 return vertices;
545}
546
547template<class VertexType, class SSBOType>
548void VulkanGame::centerObject(SceneObject<VertexType, SSBOType>& object) {
549 vector<VertexType>& vertices = object.vertices;
550
551 float min_x = vertices[0].pos.x;
552 float max_x = vertices[0].pos.x;
553 float min_y = vertices[0].pos.y;
554 float max_y = vertices[0].pos.y;
555 float min_z = vertices[0].pos.z;
556 float max_z = vertices[0].pos.z;
557
558 // start from the second point
559 for (unsigned int i = 1; i < vertices.size(); i++) {
560 vec3& pos = vertices[i].pos;
561
562 if (min_x > pos.x) {
563 min_x = pos.x;
564 } else if (max_x < pos.x) {
565 max_x = pos.x;
566 }
567
568 if (min_y > pos.y) {
569 min_y = pos.y;
570 } else if (max_y < pos.y) {
571 max_y = pos.y;
572 }
573
574 if (min_z > pos.z) {
575 min_z = pos.z;
576 } else if (max_z < pos.z) {
577 max_z = pos.z;
578 }
579 }
580
581 vec3 center = vec3(min_x + max_x, min_y + max_y, min_z + max_z) / 2.0f;
582
583 for (unsigned int i = 0; i < vertices.size(); i++) {
584 vertices[i].pos -= center;
585 }
586
587 object.radius = std::max(max_x - center.x, max_y - center.y);
588 object.radius = std::max(object.radius, max_z - center.z);
589
590 object.center = vec3(0.0f, 0.0f, 0.0f);
591}
592
593#endif // _VULKAN_GAME_H
Note: See TracBrowser for help on using the repository browser.