source: opengl-game/vulkan-game.hpp@ 4e705d6

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

Rename initWindow to initUI and move code for initializing the UI overlay into it

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