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

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

Create a pipeline and shaders to render explosions

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