source: opengl-game/vulkan-game.hpp@ 5ea0a37

feature/imgui-sdl
Last change on this file since 5ea0a37 was 5ea0a37, checked in by Dmitry Portnoy <dportnoy@…>, 3 years ago

Add a function to VulkanBuffer to return a pointer to the buffer memory, and replace the use of updateBufferSet with copyDataToMemory to update all the data for a single pipeline in one call

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