Polyphase Game Engine
Loading...
Searching...
No Matches
VulkanContext.h
Go to the documentation of this file.
1#pragma once
2
3#if API_VULKAN
4
5#include <vulkan/vulkan.h>
6#include <stb_image.h>
7
8#include "VulkanUtils.h"
9#include "MultiBuffer.h"
10#include "DescriptorSet.h"
11#include "Pipeline.h"
12#include "PipelineConfigs.h"
13#include "VramAllocator.h"
14#include "DestroyQueue.h"
15#include "Buffer.h"
16#include "Image.h"
17#include "Line.h"
18#include "SmartPointer.h"
19#include "RayTracer.h"
20#include "Profiler.h"
21#include "DescriptorPool.h"
23#include "PipelineCache.h"
24#include "RenderPassCache.h"
25#include "PostProcessChain.h"
26
27#if PLATFORM_LINUX
28#include <xcb/xcb.h>
29#include <vulkan/vulkan_xcb.h>
30#endif
31
32struct EngineState;
33class World;
34
35struct QueueFamilyIndices
36{
37 int32_t mGraphicsFamily = -1;
38 int32_t mPresentFamily = -1;
39
40 bool IsComplete()
41 {
42 return mGraphicsFamily >= 0 &&
43 mPresentFamily >= 0;
44 }
45};
46
47struct SwapChainSupportDetails
48{
49 VkSurfaceCapabilitiesKHR capabilities;
50 std::vector<VkSurfaceFormatKHR> formats;
51 std::vector<VkPresentModeKHR> presentModes;
52};
53
54struct GpuTimespan
55{
56 std::string mName;
57 int32_t mStartIndex = -1;
58 int32_t mEndIndex = -1;
59};
60
61class VulkanContext
62{
63
64public:
65
66 VulkanContext();
67 ~VulkanContext();
68
69 void Initialize();
70 void Destroy();
71
72 void BeginFrame();
73 void EndFrame();
74 void BeginRenderPass(RenderPassId id);
75 void BeginVkRenderPass(const RenderPassSetup& rpSetup, bool insertBarrier, glm::vec4 clearColor = {});
76 void EndRenderPass();
77 void EndVkRenderPass();
78 bool IsVkRenderPassActive() const { return mVkRenderPassActive; }
79 void CommitPipeline();
80 void DrawLines(const std::vector<Line>& lines);
81 void DrawSplats(const struct GaussianSplatInstance* instances, uint32_t count,
82 const glm::vec3& cameraRight, const glm::vec3& cameraUp);
83 void DrawFullscreen();
84 void BindFullscreenVertexBuffer(VkCommandBuffer cb);
85
86 VkDevice GetDevice();
87 void CreateSwapchain();
88 void RecreateSwapchain(bool recreateSurface);
89
90 VkPhysicalDevice GetPhysicalDevice();
91 DescriptorPool& GetDescriptorPool();
92 DescriptorLayoutCache& GetDescriptorLayoutCache();
93
94 DestroyQueue* GetDestroyQueue();
95
96 VkExtent2D& GetSwapchainExtent();
97 VkFormat GetSwapchainFormat();
98 VkFormat GetSceneColorFormat();
99 Image* GetSceneColorImage();
100 Image* GetSwapchainImage();
101
102 Pipeline* GetBoundPipeline();
103 PipelineCache& GetPipelineCache();
104 void SavePipelineCacheToFile();
105
106 void SetViewport(int32_t x, int32_t y, int32_t width, int32_t height, bool handlePrerotation, bool useSceneRes);
107 void SetScissor(int32_t x, int32_t y, int32_t width, int32_t height, bool handlePrerotation, bool useSceneRes);
108
109 void CreateCommandBuffers();
110
111 uint32_t GetFrameIndex() const;
112 uint32_t GetFrameNumber() const;
113
114 void SetMultiBufferFrameOffset(uint32_t offset) { mMultiBufferFrameOffset = offset; }
115 uint32_t GetMultiBufferFrameOffset() const { return mMultiBufferFrameOffset; }
116 RenderPassId GetCurrentRenderPassId() const;
117
118 Image* GetShadowMapImage();
119
120 VkCommandBuffer GetCommandBuffer();
121 VkCommandPool GetCommandPool();
122 VkQueue GetGraphicsQueue();
123
124 // Used by GFX_GetVulkanAddonHandles — exposes the render pass the engine
125 // is mid-recording on so an addon can build a pipeline compatible with it.
126 // Defined out-of-line below so it can see mPipelineState (declared private,
127 // further down in this header). GetFrameIndex() already exists at line 110.
128 VkRenderPass GetCurrentRenderPass() const;
129
130 void UpdateGlobalDescriptorSet();
131 void UpdateGlobalUniformData();
132
133 void BindGlobalDescriptorSet();
134
135 GlobalUniformData& GetGlobalUniformData();
136
137 bool IsValidationEnabled() const;
138 bool IsRayTracingSupported() const;
139 bool HasFeatureWideLines() const;
140 bool HasFeatureFillModeNonSolid() const;
141
142 bool AreMaterialsEnabled() const;
143 void EnableMaterials(bool enable);
144
145 void BeginGpuTimestamp(const char* name);
146 void EndGpuTimestamp(const char* name);
147 void ReadTimeQueryResults();
148
149 RayTracer* GetRayTracer();
150 PostProcessChain* GetPostProcessChain();
151
152 void RenderPostProcessChain();
153
154 VkSurfaceTransformFlagBitsKHR GetPreTransformFlag() const;
155
156 uint32_t GetSceneWidth();
157 uint32_t GetSceneHeight();
158
159 const VkPhysicalDeviceProperties& GetDeviceProperties() const;
160 UniformBuffer* GetFrameUniformBuffer();
161
162 Shader* GetGlobalShader(const std::string& name);
163
164 // Pipeline State
165 const PipelineState& GetPipelineState() const;
166 void SetPipelineState(const PipelineState& state);
167 void SetVertexShader(Shader* shader);
168 void SetFragmentShader(Shader* shader);
169 void SetComputeShader(Shader* shader);
170 void SetVertexShader(const std::string& globalName);
171 void SetFragmentShader(const std::string& globalName);
172 void SetComputeShader(const std::string& globalName);
173 void SetRenderPass(VkRenderPass renderPass);
174 void SetVertexType(VertexType vertexType);
175 void SetRasterizerDiscard(bool discard);
176 void SetPrimitiveTopology(VkPrimitiveTopology primitiveToplogy);
177 void SetPolygonMode(VkPolygonMode polygonMode);
178 void SetLineWidth(float lineWidth);
179 void SetDynamicLineWidth(bool dynamicLineWidth);
180 void SetCullMode(VkCullModeFlags cullMode);
181 void SetFrontFace(VkFrontFace frontFace);
182 void SetDepthBias(float depthBias);
183 void SetDepthTestEnabled(bool enabled);
184 void SetDepthWriteEnabled(bool enabled);
185 void SetDepthCompareOp(VkCompareOp compareOp);
186 void SetBlendState(VkPipelineColorBlendAttachmentState blendState, uint32_t index = 0);
187 void SetBlendState(BasicBlendState basicBlendState, uint32_t index = 0);
188 void SetBlendEnable(bool enable, uint32_t index = 0);
189 void SetBlendColorOp(VkBlendFactor src, VkBlendFactor dst, VkBlendOp op, uint32_t index = 0);
190 void SetBlendAlphaOp(VkBlendFactor src, VkBlendFactor dst, VkBlendOp op, uint32_t index = 0);
191 void SetColorWriteMask(VkColorComponentFlags writeMask, uint32_t index = 0);
192
193
194private:
195
196 static VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallback(
197 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
198 VkDebugUtilsMessageTypeFlagsEXT messageType,
199 const VkDebugUtilsMessengerCallbackDataEXT* callbackData,
200 void* userData);
201
202 void CreateInstance();
203 void CreateDebugCallback();
204 void CreateSurface();
205 void CreateLogicalDevice();
206 void CreateFrameUniformBuffer();
207 void DestroyFrameUniformBuffer();
208 void CreateRenderPasses();
209 void DestroyRenderPasses();
210 void CreateCommandPool();
211 void CreateSemaphores();
212 void CreateFences();
213 void CreateDescriptorPools();
214 void DestroyDescriptorPools();
215 void CreateDepthImage();
216 void CreateSceneColorImage();
217 void CreateShadowMapImage();
218 void CreateQueryPools();
219 void DestroyQueryPools();
220 void RecreateSurface();
221 void CreateGlobalShaders();
222 void DestroyGlobalShaders();
223 void CreateMisc();
224 void DestroyMisc();
225
226 void PickPhysicalDevice();
227 bool IsDeviceSuitable(VkPhysicalDevice device);
228 VkSurfaceFormatKHR ChooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
229 VkPresentModeKHR ChooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availableModes);
230 VkExtent2D ChooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities);
231 QueueFamilyIndices FindQueueFamilies(VkPhysicalDevice device);
232 SwapChainSupportDetails QuerySwapChainSupport(VkPhysicalDevice device);
233
234 bool CheckValidationLayerSupport(
235 const char** layers,
236 uint32_t count);
237 bool CheckDeviceExtensionSupport(
238 VkPhysicalDevice device,
239 const char** extensions,
240 uint32_t count);
241
242 void DestroySwapchain();
243 void DestroyDebugCallback();
244
245private:
246
247 // Core
248 VkInstance mInstance = VK_NULL_HANDLE;
249 VkDebugReportCallbackEXT mCallback = VK_NULL_HANDLE;
250 VkPhysicalDevice mPhysicalDevice = VK_NULL_HANDLE;
251 VkDevice mDevice = VK_NULL_HANDLE;
252 VkQueue mGraphicsQueue = VK_NULL_HANDLE;
253 VkQueue mPresentQueue = VK_NULL_HANDLE;
254 VkSurfaceKHR mSurface = VK_NULL_HANDLE;
255 uint32_t mGraphicsQueueFamily = 0;
256 uint32_t mPresentQueueFamily = 0;
257
258 // Descriptors
259 DescriptorPool mDescriptorPools[MAX_FRAMES];
260 DescriptorLayoutCache mDescriptorLayoutCache;
261 VkDescriptorPool mImguiDescriptorPool = VK_NULL_HANDLE;
262
263 // Command Buffers
264 VkCommandPool mCommandPool = VK_NULL_HANDLE;
265 std::vector<VkCommandBuffer> mCommandBuffers;
266
267 // Swapchain
268 VkSwapchainKHR mSwapchain = VK_NULL_HANDLE;
269 std::vector<VkImage> mSwapchainImages;
270 std::vector<VkImageView> mSwapchainImageViews;
271 VkFormat mSwapchainImageFormat = VK_FORMAT_UNDEFINED;
272 VkExtent2D mSwapchainExtent = {};
273 std::vector<Image*> mExtSwapchainImages;
274
275 // RenderPasses
276 RenderPassCache mRenderPassCache;
277 VkRenderPass mImguiRenderPass = VK_NULL_HANDLE;
278
279 // Images
280 Image* mShadowMapImage = nullptr;
281 Image* mSceneColorImage = nullptr;
282 VkFormat mSceneColorImageFormat;
283 Image* mDepthImage = nullptr;
284 VkFormat mDepthImageFormat = VK_FORMAT_D32_SFLOAT_S8_UINT;
285
286 // Synchronization
287 VkSemaphore mImageAvailableSemaphore[MAX_FRAMES] = {};
288 VkSemaphore mRenderFinishedSemaphore[MAX_FRAMES] = {};
289 VkFence mWaitFences[MAX_FRAMES] = {};
290
291 // Pipelines
292 PipelineCache mPipelineCache;
293 Pipeline* mBoundPipeline = nullptr;
294
295 // Shader Data
296 std::unordered_map<std::string, Shader*> mGlobalShaders;
297 DescriptorSet mGlobalDescriptorSet;
298 DescriptorSet mDebugDescriptorSet;
299 DescriptorSet mPostProcessDescriptorSet;
300 UniformBuffer* mFrameUniformBuffer = nullptr;
301 GlobalUniformData mGlobalUniformData;
302
303 // Destroy Queue
304 DestroyQueue mDestroyQueue;
305
306 // Ray Tracer
307 RayTracer mRayTracer;
308
309 // Debug
310 bool mValidate;
311 VkDebugUtilsMessengerEXT mDebugMessenger = VK_NULL_HANDLE;
312 uint32_t mEnabledExtensionCount = 0;
313 const char* mEnabledExtensions[MAX_ENABLED_EXTENSIONS] = { };
314 uint32_t mEnabledLayersCount = 0;
315 const char* mEnabledLayers[MAX_ENABLED_LAYERS] = { };
316
317 // Timestamp Queries
318 std::vector<GpuTimespan> mGpuTimespans[MAX_FRAMES];
319 VkQueryPool mTimeQueryPools[MAX_FRAMES] = { };
320 int32_t mNumTimestamps[MAX_FRAMES] = { };
321 float mTimestampPeriod = 0.0f;
322 bool mTimestampsSupported = false;
323
324 //Pipeline State
325 PipelineState mPipelineState;
326
327 // PostProcess
328 PostProcessChain mPostProcessChain;
329
330 // Misc
331 int32_t mFrameIndex = 0;
332 int32_t mFrameNumber = 0;
333 uint32_t mSwapchainImageIndex = 0;
334 RenderPassId mCurrentRenderPassId = RenderPassId::Count;
335 bool mVkRenderPassActive = false;
336 int32_t mNumLinesAllocated = 0;
337 Buffer* mLineVertexBuffer = nullptr;
338 int32_t mNumSplatsAllocated = 0;
339 Buffer* mSplatVertexBuffer = nullptr;
340 bool mInitialized = false;
341 bool mEnableMaterials = false;
342 bool mSupportsRayTracing = false;
343 bool mFeatureWideLines = false;
344 bool mFeatureFillModeNonSolid = false;
345 EngineState* mEngineState = nullptr;
346 VkSurfaceTransformFlagBitsKHR mPreTransformFlag = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
347 uint32_t mMultiBufferFrameOffset = 0;
348 float mResolutionScale = 1.0f;
349 uint32_t mSceneWidth = 0;
350 uint32_t mSceneHeight = 0;
351 VkPhysicalDeviceProperties mDeviceProperties;
352 Buffer* mFullScreenVertexBuffer = nullptr;
353
354#if EDITOR
355public:
356 class Node3D* ProcessHitCheck(World* world, int32_t pixelX, int32_t pixelY, uint32_t* outInstance = nullptr);
357private:
358 void CreateHitCheck();
359 void DestroyHitCheck();
360
361 Image* mHitCheckImage = nullptr;
362 Buffer* mHitCheckBuffer = nullptr;
363#endif
364
365};
366
367void CreateVulkanContext();
368void DestroyVulkanContext();
369VulkanContext* GetVulkanContext();
370
371#endif
bool Initialize()
Definition Engine.cpp:545
RenderPassId
Definition GraphicsTypes.h:90
VertexType
Definition Vertex.h:7
#define MAX_ENABLED_LAYERS
Definition VulkanConstants.h:4
#define MAX_ENABLED_EXTENSIONS
Definition VulkanConstants.h:3
BasicBlendState
Definition VulkanTypes.h:21
uint32_t GetFrameNumber()
Definition VulkanUtils.cpp:326
VkCommandBuffer GetCommandBuffer()
Definition VulkanUtils.cpp:341
uint32_t GetFrameIndex()
Definition VulkanUtils.cpp:321
DestroyQueue * GetDestroyQueue()
Definition VulkanUtils.cpp:331
Definition DescriptorLayoutCache.h:8
Definition DescriptorPool.h:7
Definition Node3d.h:14
Definition PipelineCache.h:9
Definition PostProcessChain.h:10
Definition RayTracer.h:15
Definition RenderPassCache.h:59
Definition Shader.h:18
Definition World.h:24
void BeginFrame()
Definition ImGuizmo.cpp:982
Definition EngineTypes.h:483
Definition Graphics.h:65
Definition VulkanTypes.h:120
Definition VulkanTypes.h:30
Definition VulkanTypes.h:85