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