source: opengl-game/vulkan-game.hpp

feature/imgui-sdl
Last change on this file was 27e580e, checked in by Dmitry Portnoy <dportnoy@…>, 2 years ago

Stop using SDL_ttf

  • Property mode set to 100644
File size: 20.4 KB
Line 
1#ifndef _VULKAN_GAME_H
2#define _VULKAN_GAME_H
3
4#include <algorithm>
5#include <chrono>
6#include <map>
7#include <vector>
8
9#include <vulkan/vulkan.h>
10
11#include <SDL2/SDL.h>
12
13#define GLM_FORCE_RADIANS
14#define GLM_FORCE_DEPTH_ZERO_TO_ONE // Since, in Vulkan, the depth range is 0 to 1 instead of -1 to 1
15#define GLM_FORCE_RIGHT_HANDED
16
17#include <glm/glm.hpp>
18#include <glm/gtc/matrix_transform.hpp>
19
20#include "IMGUI/imgui_impl_vulkan.h"
21
22#include "consts.hpp"
23#include "utils.hpp"
24#include "game-gui-sdl.hpp"
25#include "vulkan-utils.hpp"
26#include "graphics-pipeline_vulkan.hpp"
27#include "vulkan-buffer.hpp"
28
29using namespace glm;
30using namespace std::chrono;
31
32#ifdef NDEBUG
33 const bool ENABLE_VALIDATION_LAYERS = false;
34#else
35 const bool ENABLE_VALIDATION_LAYERS = true;
36#endif
37
38// TODO: Consider if there is a better way of dealing with all the vertex types and ssbo types, maybe
39// by consolidating some and trying to keep new ones to a minimum
40
41struct ModelVertex {
42 vec3 pos;
43 vec3 color;
44 vec2 texCoord;
45 vec3 normal;
46 unsigned int objIndex;
47};
48
49struct LaserVertex {
50 vec3 pos;
51 vec2 texCoord;
52 unsigned int objIndex;
53};
54
55struct ExplosionVertex {
56 vec3 particleStartVelocity;
57 float particleStartTime;
58 unsigned int objIndex;
59};
60
61struct SSBO_ModelObject {
62 alignas(16) mat4 model;
63};
64
65struct SSBO_Asteroid {
66 alignas(16) mat4 model;
67 alignas(4) float hp;
68 alignas(4) unsigned int deleted;
69};
70
71struct SSBO_Laser {
72 alignas(16) mat4 model;
73 alignas(4) vec3 color;
74 alignas(4) unsigned int deleted;
75};
76
77struct SSBO_Explosion {
78 alignas(16) mat4 model;
79 alignas(4) float explosionStartTime;
80 alignas(4) float explosionDuration;
81 alignas(4) unsigned int deleted;
82};
83
84struct UBO_VP_mats {
85 alignas(16) mat4 view;
86 alignas(16) mat4 proj;
87};
88
89struct UBO_Explosion {
90 alignas(16) mat4 view;
91 alignas(16) mat4 proj;
92 alignas(4) float cur_time;
93};
94
95// TODO: Use this struct for uniform buffers as well and probably combine it with the VulkanBuffer class
96// Also, probably better to make this a vector of structs where each struct
97// has a VkBuffer, VkDeviceMemory, and VkDescriptorBufferInfo
98// TODO: Maybe change the structure here since VkDescriptorBufferInfo already stores a reference to the VkBuffer
99struct BufferSet {
100 vector<VkBuffer> buffers;
101 vector<VkDeviceMemory> memory;
102 vector<VkDescriptorBufferInfo> infoSet;
103 VkBufferUsageFlags usages;
104 VkMemoryPropertyFlags properties;
105};
106
107// TODO: Change the index type to uint32_t and check the Vulkan Tutorial loading model section as a reference
108// TODO: Create a typedef for index type so I can easily change uin16_t to something else later
109// TODO: Maybe create a typedef for each of the templated SceneObject types
110template<class VertexType>
111struct SceneObject {
112 vector<VertexType> vertices;
113 vector<uint16_t> indices;
114
115 mat4 model_base;
116 mat4 model_transform;
117
118 // TODO: Figure out if I should make child classes that have these fields instead of putting them in the
119 // parent class
120 vec3 center; // currently only matters for asteroids
121 float radius; // currently only matters for asteroids
122
123 // Move the targetAsteroid stuff out of this class since it is very specific to lasers
124 // and makes moving SceneObject into its own header file more problematic
125 SceneObject<ModelVertex>* targetAsteroid; // currently only used for lasers
126};
127
128// TODO: Figure out how to include an optional ssbo parameter for each object
129// Could probably use the same approach to make indices optional
130// Figure out if there are sufficient use cases to make either of these optional or is it fine to make
131// them mandatory
132
133
134// TODO: Look into using dynamic_cast to check types of SceneObject and EffectOverTime
135
136struct BaseEffectOverTime {
137 bool deleted;
138
139 virtual void applyEffect(float curTime) = 0;
140
141 BaseEffectOverTime() :
142 deleted(false) {
143 }
144
145 virtual ~BaseEffectOverTime() {
146 }
147};
148
149// TODO: Move this into its own hpp and cpp files
150// TODO: Actually, since this is only used to make lasers deal damage to asteroids, review the logic
151// and see if there is a more straightforward way of implementing this.
152// If there is a simple and straightforward way to implement this in updateScene(), I should just do that instead of
153// using this class. A general feature like this is useful, but, depending on the actual game, it might not be used
154// that often, and using this class might actually make things more complicated if it doesn't quite implement the
155// desired features
156template<class SSBOType>
157struct EffectOverTime : public BaseEffectOverTime {
158 VulkanBuffer<SSBOType> &buffer;
159 uint32_t objectIndex;
160 size_t effectedFieldOffset;
161 float startValue;
162 float startTime;
163 float changePerSecond;
164
165 EffectOverTime(VulkanBuffer<SSBOType> &buffer, uint32_t objectIndex, size_t effectedFieldOffset, float startTime,
166 float changePerSecond)
167 : buffer(buffer)
168 , objectIndex(objectIndex)
169 , effectedFieldOffset(effectedFieldOffset)
170 , startTime(startTime)
171 , changePerSecond(changePerSecond) {
172 startValue = *reinterpret_cast<float*>(getEffectedFieldPtr());
173 }
174
175 unsigned char* getEffectedFieldPtr() {
176 return reinterpret_cast<unsigned char*>(&buffer.get(objectIndex)) + effectedFieldOffset;
177 }
178
179 void applyEffect(float curTime) {
180 if (buffer.get(objectIndex).deleted) {
181 deleted = true;
182 return;
183 }
184
185 *reinterpret_cast<float*>(getEffectedFieldPtr()) = startValue + (curTime - startTime) * changePerSecond;
186 }
187};
188
189// TODO: Maybe move this to a different header
190
191enum UIValueType {
192 UIVALUE_INT,
193 UIVALUE_DOUBLE,
194};
195
196struct UIValue {
197 UIValueType type;
198 string label;
199 void* value;
200
201 UIValue(UIValueType _type, string _label, void* _value) : type(_type), label(_label), value(_value) {}
202};
203
204/* TODO: The following syntax (note the const keyword) means the function will not modify
205 * its params. I should use this where appropriate
206 *
207 * [return-type] [func-name](params...) const { ... }
208 */
209
210class VulkanGame {
211
212 public:
213
214 VulkanGame();
215 ~VulkanGame();
216
217 void run(int width, int height, unsigned char guiFlags);
218
219 private:
220
221 static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
222 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
223 VkDebugUtilsMessageTypeFlagsEXT messageType,
224 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
225 void* pUserData);
226
227 // TODO: Maybe pass these in as parameters to some Camera class
228 const float NEAR_CLIP = 0.1f;
229 const float FAR_CLIP = 100.0f;
230 const float FOV_ANGLE = 67.0f; // means the camera lens goes from -33 deg to 33 deg
231
232 const int EXPLOSION_PARTICLE_COUNT = 300;
233 const vec3 LASER_COLOR = vec3(0.2f, 1.0f, 0.2f);
234
235 bool done;
236
237 vec3 cam_pos;
238
239 // TODO: Good place to start using smart pointers
240 GameGui* gui;
241
242 SDL_version sdlVersion;
243 SDL_Window* window = nullptr;
244
245 int drawableWidth, drawableHeight;
246
247 VkInstance instance;
248 VkDebugUtilsMessengerEXT debugMessenger;
249 VkSurfaceKHR vulkanSurface;
250 VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
251 VkDevice device;
252
253 VkQueue graphicsQueue;
254 VkQueue presentQueue;
255
256 // TODO: Maybe make a swapchain struct for convenience
257 VkSurfaceFormatKHR swapChainSurfaceFormat;
258 VkPresentModeKHR swapChainPresentMode;
259 VkExtent2D swapChainExtent;
260 uint32_t swapChainMinImageCount;
261 uint32_t swapChainImageCount;
262 VkSwapchainKHR swapChain;
263 vector<VkImage> swapChainImages;
264 vector<VkImageView> swapChainImageViews;
265 vector<VkFramebuffer> swapChainFramebuffers;
266
267 VkRenderPass renderPass;
268
269 VkCommandPool resourceCommandPool;
270
271 vector<VkCommandPool> commandPools;
272 vector<VkCommandBuffer> commandBuffers;
273
274 VulkanImage depthImage;
275
276 // These are per frame
277 vector<VkSemaphore> imageAcquiredSemaphores;
278 vector<VkSemaphore> renderCompleteSemaphores;
279
280 // These are per swap chain image
281 vector<VkFence> inFlightFences;
282
283 uint32_t imageIndex;
284 uint32_t currentFrame;
285
286 bool shouldRecreateSwapChain;
287
288 VkSampler textureSampler;
289
290 VulkanImage floorTextureImage;
291 VkDescriptorImageInfo floorTextureImageDescriptor;
292
293 VulkanImage laserTextureImage;
294 VkDescriptorImageInfo laserTextureImageDescriptor;
295
296 mat4 viewMat, projMat;
297
298 // Maybe at some point create an imgui pipeline class, but I don't think it makes sense right now
299 VkDescriptorPool imguiDescriptorPool;
300
301 // TODO: Probably restructure the GraphicsPipeline_Vulkan class based on what I learned about descriptors and textures
302 // while working on graphics-library. Double-check exactly what this was and note it down here.
303 // Basically, I think the point was that if I have several modesl that all use the same shaders and, therefore,
304 // the same pipeline, but use different textures, the approach I took when initially creating GraphicsPipeline_Vulkan
305 // wouldn't work since the whole pipeline couldn't have a common set of descriptors for the textures
306 GraphicsPipeline_Vulkan<ModelVertex> modelPipeline;
307 GraphicsPipeline_Vulkan<ModelVertex> shipPipeline;
308 GraphicsPipeline_Vulkan<ModelVertex> asteroidPipeline;
309 GraphicsPipeline_Vulkan<LaserVertex> laserPipeline;
310 GraphicsPipeline_Vulkan<ExplosionVertex> explosionPipeline;
311
312 BufferSet uniformBuffers_modelPipeline;
313 BufferSet objectBuffers_modelPipeline;
314
315 VulkanBuffer<UBO_VP_mats> uniforms_modelPipeline;
316 VulkanBuffer<SSBO_ModelObject> objects_modelPipeline;
317
318 BufferSet uniformBuffers_shipPipeline;
319 BufferSet objectBuffers_shipPipeline;
320
321 VulkanBuffer<UBO_VP_mats> uniforms_shipPipeline;
322 VulkanBuffer<SSBO_ModelObject> objects_shipPipeline;
323
324 BufferSet uniformBuffers_asteroidPipeline;
325 BufferSet objectBuffers_asteroidPipeline;
326
327 VulkanBuffer<UBO_VP_mats> uniforms_asteroidPipeline;
328 VulkanBuffer<SSBO_Asteroid> objects_asteroidPipeline;
329
330 BufferSet uniformBuffers_laserPipeline;
331 BufferSet objectBuffers_laserPipeline;
332
333 VulkanBuffer<UBO_VP_mats> uniforms_laserPipeline;
334 VulkanBuffer<SSBO_Laser> objects_laserPipeline;
335
336 BufferSet uniformBuffers_explosionPipeline;
337 BufferSet objectBuffers_explosionPipeline;
338
339 VulkanBuffer<UBO_Explosion> uniforms_explosionPipeline;
340 VulkanBuffer<SSBO_Explosion> objects_explosionPipeline;
341
342 // TODO: Maybe make the ubo objects part of the pipeline class since there's only one ubo
343 // per pipeline.
344 // Or maybe create a higher level wrapper around GraphicsPipeline_Vulkan to hold things like
345 // the objects vector, the ubo, and the ssbo
346
347 // TODO: Rename *_VP_mats to *_uniforms and possibly use different types for each one
348 // if there is a need to add other uniform variables to one or more of the shaders
349
350 vector<SceneObject<ModelVertex>> modelObjects;
351 vector<SceneObject<ModelVertex>> shipObjects;
352 vector<SceneObject<ModelVertex>> asteroidObjects;
353 vector<SceneObject<LaserVertex>> laserObjects;
354 vector<SceneObject<ExplosionVertex>> explosionObjects;
355
356 //UBO_Explosion explosion_UBO;
357
358 vector<BaseEffectOverTime*> effects;
359
360 float shipSpeed = 0.5f;
361 float asteroidSpeed = 2.0f;
362
363 float spawnRate_asteroid = 0.5;
364 float lastSpawn_asteroid;
365
366 unsigned int leftLaserIdx = -1;
367 EffectOverTime<SSBO_Asteroid>* leftLaserEffect = nullptr;
368
369 unsigned int rightLaserIdx = -1;
370 EffectOverTime<SSBO_Asteroid>* rightLaserEffect = nullptr;
371
372 /*** High-level vars ***/
373
374 // TODO: Just typedef the type of this function to RenderScreenFn or something since it's used in a few places
375 void (VulkanGame::* currentRenderScreenFn)(int width, int height);
376
377 map<string, vector<UIValue>> valueLists;
378
379 int score;
380 float fps;
381
382 // TODO: Make a separate TImer class
383 time_point<steady_clock> startTime;
384 float fpsStartTime, curTime, prevTime, elapsedTime;
385
386 int frameCount;
387
388 /*** Functions ***/
389
390 bool initUI(int width, int height, unsigned char guiFlags);
391 void initVulkan();
392 void initGraphicsPipelines();
393 void initMatrices();
394 void renderLoop();
395 void updateScene();
396 void cleanup();
397
398 void createVulkanInstance(const vector<const char*>& validationLayers);
399 void setupDebugMessenger();
400 void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo);
401 void createVulkanSurface();
402 void pickPhysicalDevice(const vector<const char*>& deviceExtensions);
403 bool isDeviceSuitable(VkPhysicalDevice physicalDevice, const vector<const char*>& deviceExtensions);
404 void createLogicalDevice(const vector<const char*>& validationLayers,
405 const vector<const char*>& deviceExtensions);
406 void chooseSwapChainProperties();
407 void createSwapChain();
408 void createImageViews();
409 void createResourceCommandPool();
410 void createImageResources();
411 VkFormat findDepthFormat(); // TODO: Declare/define (in the cpp file) this function in some util functions section
412 void createRenderPass();
413 void createCommandPools();
414 void createFramebuffers();
415 void createCommandBuffers();
416 void createSyncObjects();
417
418 void createTextureSampler();
419
420 void initImGuiOverlay();
421 void cleanupImGuiOverlay();
422
423 // TODO: Maybe move these to a different class, possibly VulkanBuffer or some new related class
424
425 void createBufferSet(VkDeviceSize bufferSize, VkBufferUsageFlags usages, VkMemoryPropertyFlags properties,
426 BufferSet& set);
427
428 void resizeBufferSet(BufferSet& set, VkDeviceSize newSize, VkCommandPool commandPool, VkQueue graphicsQueue,
429 bool copyData);
430
431 // TODO: Since addObject() returns a reference to the new object now,
432 // stop using objects.back() to access the object that was just created
433 template<class VertexType, class SSBOType>
434 SceneObject<VertexType>& addObject(vector<SceneObject<VertexType>>& objects,
435 GraphicsPipeline_Vulkan<VertexType>& pipeline,
436 const vector<VertexType>& vertices, vector<uint16_t> indices,
437 VulkanBuffer<SSBOType>& objectBuffer, SSBOType ssbo);
438
439 template<class VertexType>
440 vector<VertexType> addObjectIndex(unsigned int objIndex, vector<VertexType> vertices);
441
442 template<class VertexType>
443 vector<VertexType> addVertexNormals(vector<VertexType> vertices);
444
445 template<class VertexType>
446 void centerObject(SceneObject<VertexType>& object);
447
448 template<class VertexType>
449 void updateObjectVertices(GraphicsPipeline_Vulkan<VertexType>& pipeline, SceneObject<VertexType>& obj,
450 size_t index);
451
452 void addLaser(vec3 start, vec3 end, vec3 color, float width);
453 void translateLaser(size_t index, const vec3& translation);
454 void updateLaserTarget(size_t index);
455 bool getLaserAndAsteroidIntersection(SceneObject<ModelVertex>& asteroid, vec3& start, vec3& end,
456 vec3& intersection);
457
458 void addExplosion(mat4 model_mat, float duration, float cur_time);
459
460 void renderFrame(ImDrawData* draw_data);
461 void presentFrame();
462
463 void recreateSwapChain();
464
465 void cleanupSwapChain();
466
467 /*** High-level functions ***/
468
469 void renderMainScreen(int width, int height);
470 void renderGameScreen(int width, int height);
471
472 void initGuiValueLists(map<string, vector<UIValue>>& valueLists);
473 void renderGuiValueList(vector<UIValue>& values);
474
475 void goToScreen(void (VulkanGame::* renderScreenFn)(int width, int height));
476 void quitGame();
477};
478
479// Start of specialized no-op functions
480
481template<>
482inline void VulkanGame::centerObject(SceneObject<ExplosionVertex>& object) {
483}
484
485// End of specialized no-op functions
486
487// TODO: Right now, it's basically necessary to pass the identity matrix in for ssbo.model and to change
488// the model matrix later by setting model_transform and then calculating the new ssbo.model.
489// Figure out a better way to allow the model matrix to be set during object creation
490template<class VertexType, class SSBOType>
491SceneObject<VertexType>& VulkanGame::addObject(vector<SceneObject<VertexType>>& objects,
492 GraphicsPipeline_Vulkan<VertexType>& pipeline,
493 const vector<VertexType>& vertices, vector<uint16_t> indices,
494 VulkanBuffer<SSBOType>& objectBuffer, SSBOType ssbo) {
495 // TODO: Use the model field of ssbo to set the object's model_base
496 // currently, the passed-in model is useless since it gets overridden when ssbo.model is recalculated
497 size_t numVertices = pipeline.getNumVertices();
498
499 for (uint16_t& idx : indices) {
500 idx += numVertices;
501 }
502
503 objects.push_back({ vertices, indices, mat4(1.0f), mat4(1.0f) });
504 objectBuffer.add(ssbo);
505
506 SceneObject<VertexType>& obj = objects.back();
507
508 // TODO: Specify whether to center the object outside of this function or, worst case, maybe
509 // with a boolean being passed in here, so that I don't have to rely on checking the specific object
510 // type
511 // TODO: Actually, I've already defined a no-op centerObject method for explosions
512 // Maybe I should do the same for lasers and remove this conditional altogether
513 if (!is_same_v<VertexType, LaserVertex> && !is_same_v<VertexType, ExplosionVertex>) {
514 centerObject(obj);
515 }
516
517 pipeline.addObject(obj.vertices, obj.indices, resourceCommandPool, graphicsQueue);
518
519 return obj;
520}
521
522template<class VertexType>
523vector<VertexType> VulkanGame::addObjectIndex(unsigned int objIndex, vector<VertexType> vertices) {
524 for (VertexType& vertex : vertices) {
525 vertex.objIndex = objIndex;
526 }
527
528 return vertices;
529}
530
531// This function sets all the normals for a face to be parallel
532// This is good for models that should have distinct faces, but bad for models that should appear smooth
533// Maybe add an option to set all copies of a point to have the same normal and have the direction of
534// that normal be the weighted average of all the faces it is a part of, where the weight from each face
535// is its surface area.
536
537// TODO: Since the current approach to normal calculation basicaly makes indexed drawing useless, see if it's
538// feasible to automatically enable/disable indexed drawing based on which approach is used
539template<class VertexType>
540vector<VertexType> VulkanGame::addVertexNormals(vector<VertexType> vertices) {
541 for (unsigned int i = 0; i < vertices.size(); i += 3) {
542 vec3 p1 = vertices[i].pos;
543 vec3 p2 = vertices[i + 1].pos;
544 vec3 p3 = vertices[i + 2].pos;
545
546 vec3 normal = normalize(cross(p2 - p1, p3 - p1));
547
548 // Add the same normal for all 3 vertices
549 vertices[i].normal = normal;
550 vertices[i + 1].normal = normal;
551 vertices[i + 2].normal = normal;
552 }
553
554 return vertices;
555}
556
557template<class VertexType>
558void VulkanGame::centerObject(SceneObject<VertexType>& object) {
559 vector<VertexType>& vertices = object.vertices;
560
561 float min_x = vertices[0].pos.x;
562 float max_x = vertices[0].pos.x;
563 float min_y = vertices[0].pos.y;
564 float max_y = vertices[0].pos.y;
565 float min_z = vertices[0].pos.z;
566 float max_z = vertices[0].pos.z;
567
568 // start from the second point
569 for (unsigned int i = 1; i < vertices.size(); i++) {
570 vec3& pos = vertices[i].pos;
571
572 if (min_x > pos.x) {
573 min_x = pos.x;
574 } else if (max_x < pos.x) {
575 max_x = pos.x;
576 }
577
578 if (min_y > pos.y) {
579 min_y = pos.y;
580 } else if (max_y < pos.y) {
581 max_y = pos.y;
582 }
583
584 if (min_z > pos.z) {
585 min_z = pos.z;
586 } else if (max_z < pos.z) {
587 max_z = pos.z;
588 }
589 }
590
591 vec3 center = vec3(min_x + max_x, min_y + max_y, min_z + max_z) / 2.0f;
592
593 for (unsigned int i = 0; i < vertices.size(); i++) {
594 vertices[i].pos -= center;
595 }
596
597 object.radius = std::max(max_x - center.x, max_y - center.y);
598 object.radius = std::max(object.radius, max_z - center.z);
599
600 object.center = vec3(0.0f, 0.0f, 0.0f);
601}
602
603template<class VertexType>
604void VulkanGame::updateObjectVertices(GraphicsPipeline_Vulkan<VertexType>& pipeline, SceneObject<VertexType>& obj,
605 size_t index) {
606 pipeline.updateObjectVertices(index, obj.vertices, resourceCommandPool, graphicsQueue);
607}
608
609#endif // _VULKAN_GAME_H
Note: See TracBrowser for help on using the repository browser.