source: opengl-game/vulkan-game.hpp@ 914bb99

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

In VulkanGame, specify each vertex explicitly for the model pipeline instead of using the same index multiple times, in order to support the current approach to normal calculation.

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