Crimson Engine 1.0.0
A high-performance C++20 game engine prototype showcasing a custom ECS, Vulkan renderer, and ImGui editor.
Loading...
Searching...
No Matches
VulkanRenderer.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <vulkan/vulkan.h>
4#include <GLFW/glfw3.h>
5#include <vector>
6#include <stdexcept>
7#include <glm/glm.hpp>
8
12#include "core/VulkanBuffer.hpp"
16
21#include "../soa/MeshSoA.hpp"
22
29 VkPipeline pipeline = VK_NULL_HANDLE;
31 VkPipelineLayout layout = VK_NULL_HANDLE;
32};
33
38struct CameraUBO {
40 glm::mat4 viewProj;
41 glm::vec4 camPos; // camPos.xyz, w unused
42 glm::vec4 ambientLight; // Ambient light color/intensity from the renderer fallback sun
43 glm::vec4 lightDir; // Direction in xyz, type in w
44 glm::vec4 lightColor; // Color in xyz, intensity in w
45};
46
51struct InstanceData {
53 glm::mat4 model;
55 uint32_t materialID;
57 uint32_t meshID;
59 glm::vec4 color;
60};
61
68 std::vector<glm::mat4> models;
70 std::vector<uint32_t> materialIDs;
72 std::vector<uint32_t> meshIDs;
74 std::vector<glm::vec4> colors;
75
79 void clear() {
80 models.clear();
81 materialIDs.clear();
82 meshIDs.clear();
83 colors.clear();
84 }
85
91 size_t push(const InstanceData& inst) {
92 models.push_back(inst.model);
93 meshIDs.push_back(inst.meshID);
94 materialIDs.push_back(inst.materialID);
95 colors.push_back(inst.color);
96 return models.size() - 1;
97 }
98
103 size_t size() const { return models.size(); }
104
110 InstanceDataGPU get(size_t i) const {
111 return {
112 models[i],
113 colors[i],
114 meshIDs[i],
115 materialIDs[i]
116 };
117 }
118};
119
120
121class ResourceManager;
122
128public:
129 VulkanRenderer(GLFWwindow* win, const std::string& exeDir = "", bool enableValidationLayers = true);
134
140 std::string resolveShaderPath(const std::string& originalPath) const;
141
145 const std::string& getExeDir() const { return exeDir; }
146
150 void beginFrame();
154 void endFrame();
155
162 void drawMesh(const Mesh& mesh, const Material& mat, const Transform& transform);
167
172 void createInstanceBuffer(size_t maxInstances);
177
181 void createCameraUBO();
185 void updateCameraUBO(const CameraUBO& ubo);
186
190 void recreateSwapchain();
194 void cleanup();
195
202 PipelineHandle createPipelineForShaders(const std::string& vertPath, const std::string& fragPath);
207 void uploadMesh(size_t id);
212 bool shouldClose() const;
217 float getDeltaTime();
218
223 GLFWwindow* getWindow() const { return window; }
229 bool getKey(int key) const;
235 bool getMouseButton(int button) const;
241 void getMousePosition(double* xpos, double* ypos) const;
247 void getWindowSize(int* width, int* height) const;
252 VkRenderPass getRenderPass() const { return swapchain.getRenderPass(); }
257 VkPipeline getPipeline() const { return pipeline.get(); }
262 VkPipelineLayout getPipelineLayout() const { return pipeline.getLayout(); }
267 VkExtent2D getSwapchainExtent() const { return swapchain.getExtent(); }
268
273 VkCommandBuffer getCurrentCommandBuffer() {
274 return cmdManager.getCurrentCommandBuffer();
275 }
276
280 VkCommandBuffer beginSingleUseCommands() {
281 return cmdManager.beginOneTimeCommand();
282 }
283
287 void endSingleUseCommands(VkCommandBuffer commandBuffer) {
288 cmdManager.endOneTimeCommand(commandBuffer, device.getGraphicsQueue());
289 }
290
294 VkDescriptorSet getCameraDescriptorSet() const {
295 return cameraDescriptorSet;
296 }
297
301 VkDescriptorSetLayout getTextureDescriptorSetLayout() const {
302 return descriptors.getTextureDescriptorSetLayout();
303 }
304
308 VkDescriptorSet getDefaultTextureSet() const;
309
315 void setActiveCamera(const glm::mat4& viewProj, const glm::vec3& position) {
316 activeCameraViewProj = viewProj;
317 activeCameraPosition = position;
318 hasActiveCameraData = true;
319 }
320
326 void setActiveCamera(const glm::mat4& projection, const glm::vec3& position, const glm::mat4& view)
327 {
328 activeCameraView = view;
329 activeCameraProjection = projection;
330 activeCameraViewProj = projection * view;
331 activeCameraPosition = position;
332 hasActiveCameraData = true;
333 }
334
339 bool hasActiveCamera() const { return hasActiveCameraData; }
344 const glm::mat4& getActiveCameraViewProj() const { return activeCameraViewProj; }
349 const glm::vec3& getActiveCameraPosition() const { return activeCameraPosition; }
354 const glm::mat4& getActiveCameraView() const { return activeCameraView; }
359 const glm::mat4& getActiveCameraProjection() const { return activeCameraProjection; }
360
361 glm::mat4 gameplayCameraViewProj = glm::mat4(1.0f);
362 glm::vec3 gameplayCameraPosition = glm::vec3(0.0f);
363
364 void setGameplayCamera(const glm::mat4& viewProj, const glm::vec3& position) {
365 gameplayCameraViewProj = viewProj;
366 gameplayCameraPosition = position;
367 }
368 const glm::mat4& getGameplayCameraViewProj() const { return gameplayCameraViewProj; }
369 const glm::vec3& getGameplayCameraPosition() const { return gameplayCameraPosition; }
370
372 std::vector<std::unique_ptr<VulkanPipeline>> pipelines;
375
380
388 std::unique_ptr<ResourceManager> resourceManager;
389
390private:
392 GLFWwindow* window = nullptr;
394 std::string exeDir;
395
396
398 VkDebugUtilsMessengerEXT debugMessenger = VK_NULL_HANDLE;
399#ifdef DEBUG
401 bool enableValidationLayers = true; // turn off for release
402#else
405#endif
413 VkSurfaceKHR surface = VK_NULL_HANDLE;
415 uint32_t currentImageIndex = 0;
416
419
421 VkDescriptorSet cameraDescriptorSet = VK_NULL_HANDLE;
422
424 bool framebufferResized = false;
426 double lastTime = 0.0;
428 glm::mat4 activeCameraViewProj{ 1.0f };
430 glm::vec3 activeCameraPosition{ 0.0f };
432 glm::mat4 activeCameraView{};
437
438private:
440 void initVulkan();
442 void createPipeline();
444 void createWindowSurface();
446 VkDebugUtilsMessengerCreateInfoEXT populateDebugMessengerCreateInfo();
448 void setupDebugMessenger();
456 void setupDescriptors();
458 void createSwapchain();
464 void submitAndPresent();
465};
Manages loading, caching, and GPU memory uploads for textures and glTF model meshes.
Definition ResourceManager.hpp:46
Inline wrapper class for managing a Vulkan buffer and its associated device memory.
Definition Buffer.hpp:10
Manages the command pool, frame command buffers, and one-time utility command buffer operations.
Definition VulkanCommandManager.hpp:10
Manages the descriptor pool, descriptor layouts, and descriptor set allocations for UBO resources.
Definition VulkanDescriptors.hpp:10
Encapsulates Vulkan Instance creation, physical device selection, queue family discovery,...
Definition VulkanDevice.hpp:11
Manages Vulkan semaphores and fences to synchronize frames in flight.
Definition VulkanFrameSync.hpp:10
Manages the compilation, configuration, and execution layout of a graphics pipeline.
Definition VulkanPipeline.hpp:14
VkExtent2D getSwapchainExtent() const
Gets Swapchain Extent.
Definition VulkanRenderer.hpp:267
void beginFrame()
Starts render pass recording for the current frame.
Definition VulkanRenderer.cpp:202
VkDebugUtilsMessengerCreateInfoEXT populateDebugMessengerCreateInfo()
Populates the Vulkan debug messenger structure parameters.
Definition VulkanRenderer.cpp:540
glm::mat4 activeCameraProjection
Active camera projection matrix cache.
Definition VulkanRenderer.hpp:434
std::string exeDir
Directory where the executable is located.
Definition VulkanRenderer.hpp:394
~VulkanRenderer()
Destroy the Vulkan Renderer object and free resources.
Definition VulkanRenderer.cpp:31
VulkanDescriptors descriptors
Global Vulkan descriptor set management module.
Definition VulkanRenderer.hpp:386
const glm::mat4 & getGameplayCameraViewProj() const
Definition VulkanRenderer.hpp:368
void createSwapchain()
Configures swapchain render targets.
Definition VulkanRenderer.cpp:142
void updateCameraUBO(const CameraUBO &ubo)
Refreshes active camera matrix attributes in UBO.
Definition VulkanRenderer.cpp:353
const glm::vec3 & getActiveCameraPosition() const
Gets active camera position.
Definition VulkanRenderer.hpp:349
void submitAndPresent()
Submits command buffers to graphic queue and schedules screen presentation.
Definition VulkanRenderer.cpp:273
VulkanRenderer(GLFWwindow *win, const std::string &exeDir="", bool enableValidationLayers=true)
Construct a new Vulkan Renderer:: Vulkan Renderer object.
Definition VulkanRenderer.cpp:10
VkSurfaceKHR surface
Presentation surface binding window and Vulkan instance.
Definition VulkanRenderer.hpp:413
bool framebufferResized
Flag checking if window resized.
Definition VulkanRenderer.hpp:424
bool hasActiveCamera() const
Checks if a camera is currently active.
Definition VulkanRenderer.hpp:339
const std::string & getExeDir() const
Gets the directory where the active executable resides.
Definition VulkanRenderer.hpp:145
VkDescriptorSet getDefaultTextureSet() const
Gets Default White Texture Descriptor Set fallback.
Definition VulkanRenderer.cpp:593
std::vector< std::unique_ptr< VulkanPipeline > > pipelines
Storage vector of created custom Vulkan pipelines.
Definition VulkanRenderer.hpp:372
VkCommandBuffer beginSingleUseCommands()
Begins command recording on a temporary command buffer.
Definition VulkanRenderer.hpp:280
glm::vec3 activeCameraPosition
Active camera world space position cache.
Definition VulkanRenderer.hpp:430
void createCommandsAndSync()
Sets up command buffers, pools, and sync fences.
Definition VulkanRenderer.cpp:182
PipelineHandle createPipelineForShaders(const std::string &vertPath, const std::string &fragPath)
Creates a graphic pipeline custom-configured with specified shader source files.
Definition VulkanRenderer.cpp:436
void setupDebugMessenger()
Attaches validation layer logger callbacks.
Definition VulkanRenderer.cpp:563
void updateInstanceBuffer()
Transfers CPU instances down to the GPU instance buffer.
Definition VulkanRenderer.cpp:328
double lastTime
Previous frame time stamp.
Definition VulkanRenderer.hpp:426
VkCommandBuffer getCurrentCommandBuffer()
Retrieves active Vulkan command buffer for current frame.
Definition VulkanRenderer.hpp:273
void setupDescriptors()
Initializes descriptor pools and configurations.
Definition VulkanRenderer.cpp:157
void getMousePosition(double *xpos, double *ypos) const
Gets the mouse cursor position (executes within engine.dll context).
Definition VulkanRenderer.cpp:482
VulkanBuffer cameraBuffer
GPU buffer for the camera UBO.
Definition VulkanRenderer.hpp:418
uint32_t currentImageIndex
Swapchain index of next image to render.
Definition VulkanRenderer.hpp:415
VulkanSwapchain swapchain
Swapchain manager module.
Definition VulkanRenderer.hpp:384
const glm::mat4 & getActiveCameraView() const
Gets active camera view matrix.
Definition VulkanRenderer.hpp:354
void createInstanceBuffer(size_t maxInstances)
Creates the GPU buffers for batch instancing.
Definition VulkanRenderer.cpp:318
glm::mat4 activeCameraViewProj
Active camera view proj matrix cache.
Definition VulkanRenderer.hpp:428
VkRenderPass getRenderPass() const
Gets Vulkan RenderPass.
Definition VulkanRenderer.hpp:252
void drawInstances()
Performs drawing of instanced mesh batches.
void createDeviceAndQueues()
Creates physical/logical devices and queue interfaces.
Definition VulkanRenderer.cpp:129
void setActiveCamera(const glm::mat4 &viewProj, const glm::vec3 &position)
Configures active camera matrices.
Definition VulkanRenderer.hpp:315
void createInstanceAndDebug()
Instantiates the root Vulkan API instance.
Definition VulkanRenderer.cpp:107
VkPipeline getPipeline() const
Gets Vulkan Pipeline.
Definition VulkanRenderer.hpp:257
VulkanCommandManager cmdManager
Command pool and command buffer allocator.
Definition VulkanRenderer.hpp:409
void drawMesh(const Mesh &mesh, const Material &mat, const Transform &transform)
Submits draw commands for a single mesh.
float getDeltaTime()
Calculates delta time since the previous frame.
Definition VulkanRenderer.cpp:457
VulkanDevice device
Core logical and physical Vulkan device interface.
Definition VulkanRenderer.hpp:382
VkDescriptorSet cameraDescriptorSet
descriptor set representing active camera.
Definition VulkanRenderer.hpp:421
void uploadMesh(size_t id)
Allocates and uploads GPU buffers for a specific mesh loaded on the CPU.
Definition VulkanRenderer.cpp:504
bool getKey(int key) const
Checks if a key is currently pressed (executes within engine.dll context).
Definition VulkanRenderer.cpp:472
glm::mat4 activeCameraView
Active camera view matrix cache.
Definition VulkanRenderer.hpp:432
MeshSoA meshSoA
Mesh database components in SoA layout.
Definition VulkanRenderer.hpp:377
std::unique_ptr< ResourceManager > resourceManager
Global Resource Manager instance.
Definition VulkanRenderer.hpp:388
bool shouldClose() const
Returns window close request status.
Definition VulkanRenderer.cpp:468
GLFWwindow * window
Pointer to GLFW window.
Definition VulkanRenderer.hpp:392
bool getMouseButton(int button) const
Checks if a mouse button is currently pressed (executes within engine.dll context).
Definition VulkanRenderer.cpp:477
const glm::mat4 & getActiveCameraProjection() const
Gets active camera projection matrix.
Definition VulkanRenderer.hpp:359
void endSingleUseCommands(VkCommandBuffer commandBuffer)
Finalizes and submits a temporary command buffer.
Definition VulkanRenderer.hpp:287
VkDescriptorSetLayout getTextureDescriptorSetLayout() const
Gets Descriptor Set Layout for Textures.
Definition VulkanRenderer.hpp:301
void setGameplayCamera(const glm::mat4 &viewProj, const glm::vec3 &position)
Definition VulkanRenderer.hpp:364
bool hasActiveCameraData
Flag checking if active camera is initialized.
Definition VulkanRenderer.hpp:436
void setActiveCamera(const glm::mat4 &projection, const glm::vec3 &position, const glm::mat4 &view)
Configures active camera view, projection, and position.
Definition VulkanRenderer.hpp:326
VkPipelineLayout getPipelineLayout() const
Gets Vulkan Pipeline Layout.
Definition VulkanRenderer.hpp:262
VulkanBuffer instanceBuffer
Vulkan GPU buffer for instance matrices.
Definition VulkanRenderer.hpp:379
std::string resolveShaderPath(const std::string &originalPath) const
Resolves a shader path relative to the executable or CWD to support packaged/SDK builds.
Definition VulkanRenderer.cpp:37
VkDescriptorSet getCameraDescriptorSet() const
Gets Camera Descriptor Set.
Definition VulkanRenderer.hpp:294
VulkanFrameSync frameSync
Synchronization fences and semaphores management.
Definition VulkanRenderer.hpp:411
void createCameraUBO()
Instantiates uniform buffers for camera view and projection matrices.
Definition VulkanRenderer.cpp:344
void getWindowSize(int *width, int *height) const
Gets the window size (executes within engine.dll context).
Definition VulkanRenderer.cpp:491
void destroyDebugMessenger()
Cleans up messenger validation logs.
Definition VulkanRenderer.cpp:579
VkDebugUtilsMessengerEXT debugMessenger
Debug messenger handle for validation layer callbacks.
Definition VulkanRenderer.hpp:398
bool enableValidationLayers
Flag denoting validation checks state.
Definition VulkanRenderer.hpp:404
void createWindowSurface()
Couples window handle with Vulkan instance context.
Definition VulkanRenderer.cpp:119
const glm::mat4 & getActiveCameraViewProj() const
Gets active camera view projection matrix.
Definition VulkanRenderer.hpp:344
void recreateSwapchain()
Recreates the swapchain when window resizing occurs.
Definition VulkanRenderer.cpp:361
void initVulkan()
Initializes main Vulkan instance, debuggers, devices, surfaces, and pipelines.
Definition VulkanRenderer.cpp:89
void createPipeline()
Prepares and compiles graphics pipeline configurations.
Definition VulkanRenderer.cpp:191
void cleanup()
Deallocates all Vulkan rendering state and resource bindings.
Definition VulkanRenderer.cpp:390
InstanceDataSoA instanceDataCPU
CPU-side instancing data in Structure-of-Arrays format.
Definition VulkanRenderer.hpp:374
glm::mat4 gameplayCameraViewProj
Definition VulkanRenderer.hpp:361
void endFrame()
Submits command buffers and presents the rendered swapchain image.
Definition VulkanRenderer.cpp:262
VulkanPipeline pipeline
Default graphics pipeline state manager.
Definition VulkanRenderer.hpp:407
GLFWwindow * getWindow() const
Gets GLFW window pointer.
Definition VulkanRenderer.hpp:223
const glm::vec3 & getGameplayCameraPosition() const
Definition VulkanRenderer.hpp:369
glm::vec3 gameplayCameraPosition
Definition VulkanRenderer.hpp:362
void createBuffersAndPipelines()
Instantiates buffers and pipelines.
Definition VulkanRenderer.cpp:167
Handles creation, extent negotiation, rendering passes, and framebuffer generation for Vulkan Swapcha...
Definition VulkanSwapChain.hpp:11
Uniform Buffer Object containing view and projection matrices.
Definition uniforms.hpp:9
glm::mat4 viewProj
View-projection matrix.
Definition VulkanRenderer.hpp:40
glm::vec4 camPos
Definition VulkanRenderer.hpp:41
glm::vec4 lightColor
Definition VulkanRenderer.hpp:44
glm::vec4 ambientLight
Definition VulkanRenderer.hpp:42
glm::vec4 lightDir
Definition VulkanRenderer.hpp:43
Layout of per-instance data uploaded to the GPU for instanced rendering.
Definition pushconstants.hpp:29
Represents per-instance model data for rendering.
Definition instanceData.hpp:8
uint32_t meshID
Identifier of the associated mesh.
Definition VulkanRenderer.hpp:57
glm::vec4 color
Instance color tint.
Definition VulkanRenderer.hpp:59
glm::mat4 model
Model transform matrix of the instance.
Definition instanceData.hpp:10
uint32_t materialID
Identifier of the associated material.
Definition VulkanRenderer.hpp:55
CPU-side representation of batch-rendering instances organized as a Structure of Arrays.
Definition VulkanRenderer.hpp:66
std::vector< uint32_t > materialIDs
Material IDs of all instances.
Definition VulkanRenderer.hpp:70
std::vector< glm::mat4 > models
Model matrices of all instances.
Definition VulkanRenderer.hpp:68
size_t size() const
Retrieves total active instance count.
Definition VulkanRenderer.hpp:103
std::vector< glm::vec4 > colors
Colors of all instances.
Definition VulkanRenderer.hpp:74
size_t push(const InstanceData &inst)
Appends a new instance.
Definition VulkanRenderer.hpp:91
void clear()
Clears all array allocations.
Definition VulkanRenderer.hpp:79
std::vector< uint32_t > meshIDs
Mesh IDs of all instances.
Definition VulkanRenderer.hpp:72
InstanceDataGPU get(size_t i) const
Retrieves CPU instancing details at index formatted for GPU.
Definition VulkanRenderer.hpp:110
Represents a material component defining rendering properties.
Definition Material.hpp:17
Represents a mesh component that holds geometry data and its Vulkan buffers.
Definition Mesh.hpp:95
Structure of Arrays representing mesh buffers and geometry information.
Definition MeshSoA.hpp:10
Holds a compiled graphics pipeline and its layout.
Definition VulkanRenderer.hpp:27
VkPipeline pipeline
Vulkan pipeline object.
Definition VulkanRenderer.hpp:29
VkPipelineLayout layout
Vulkan pipeline layout.
Definition VulkanRenderer.hpp:31
Represents the position, rotation, and scale of an entity in 3D space.
Definition Transform.hpp:127
const ufbx_keyframe * key
Definition ufbx.cpp:25982