source: opengl-game/vulkan-game.hpp@ 52a02e6

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

Add a primitive topology parameter to the GraphicsPipeline_Vulkan constructor

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