Graphics.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. #pragma once
  2. // löve
  3. #include "common/config.h"
  4. #include "graphics/Graphics.h"
  5. #include "StreamBuffer.h"
  6. #include "ShaderStage.h"
  7. #include "Shader.h"
  8. #include "Texture.h"
  9. // libraries
  10. #include "VulkanWrapper.h"
  11. #include "libraries/xxHash/xxhash.h"
  12. // c++
  13. #include <optional>
  14. #include <iostream>
  15. #include <memory>
  16. #include <functional>
  17. #include <set>
  18. namespace love
  19. {
  20. namespace graphics
  21. {
  22. namespace vulkan
  23. {
  24. struct RenderPassAttachment
  25. {
  26. VkFormat format = VK_FORMAT_UNDEFINED;
  27. bool discard = true;
  28. VkSampleCountFlagBits msaaSamples = VK_SAMPLE_COUNT_1_BIT;
  29. bool operator==(const RenderPassAttachment &attachment) const
  30. {
  31. return format == attachment.format &&
  32. discard == attachment.discard &&
  33. msaaSamples == attachment.msaaSamples;
  34. }
  35. };
  36. struct RenderPassConfiguration
  37. {
  38. std::vector<RenderPassAttachment> colorAttachments;
  39. struct StaticRenderPassConfiguration
  40. {
  41. RenderPassAttachment depthAttachment;
  42. bool resolve = false;
  43. } staticData;
  44. bool operator==(const RenderPassConfiguration &conf) const
  45. {
  46. return colorAttachments == conf.colorAttachments &&
  47. (memcmp(&staticData, &conf.staticData, sizeof(StaticRenderPassConfiguration)) == 0);
  48. }
  49. };
  50. struct RenderPassConfigurationHasher
  51. {
  52. size_t operator()(const RenderPassConfiguration &configuration) const
  53. {
  54. size_t hashes[] = {
  55. XXH32(configuration.colorAttachments.data(), configuration.colorAttachments.size() * sizeof(VkFormat), 0),
  56. XXH32(&configuration.staticData, sizeof(configuration.staticData), 0),
  57. };
  58. return XXH32(hashes, sizeof(hashes), 0);
  59. }
  60. };
  61. struct FramebufferConfiguration
  62. {
  63. std::vector<VkImageView> colorViews;
  64. struct StaticFramebufferConfiguration
  65. {
  66. VkImageView depthView = VK_NULL_HANDLE;
  67. VkImageView resolveView = VK_NULL_HANDLE;
  68. uint32_t width = 0;
  69. uint32_t height = 0;
  70. VkRenderPass renderPass = VK_NULL_HANDLE;
  71. } staticData;
  72. bool operator==(const FramebufferConfiguration &conf) const
  73. {
  74. return colorViews == conf.colorViews &&
  75. (memcmp(&staticData, &conf.staticData, sizeof(StaticFramebufferConfiguration)) == 0);
  76. }
  77. };
  78. struct FramebufferConfigurationHasher
  79. {
  80. size_t operator()(const FramebufferConfiguration &configuration) const
  81. {
  82. size_t hashes[] = {
  83. XXH32(configuration.colorViews.data(), configuration.colorViews.size() * sizeof(VkImageView), 0),
  84. XXH32(&configuration.staticData, sizeof(configuration.staticData), 0),
  85. };
  86. return XXH32(hashes, sizeof(hashes), 0);
  87. }
  88. };
  89. struct OptionalInstanceExtensions
  90. {
  91. bool physicalDeviceProperties2 = false;
  92. };
  93. struct OptionalDeviceFeatures
  94. {
  95. // VK_EXT_extended_dynamic_state
  96. bool extendedDynamicState = false;
  97. // VK_KHR_get_memory_requirements2
  98. bool memoryRequirements2 = false;
  99. // VK_KHR_dedicated_allocation
  100. bool dedicatedAllocation = false;
  101. // VK_KHR_buffer_device_address
  102. bool bufferDeviceAddress = false;
  103. // VK_EXT_memory_budget
  104. bool memoryBudget = false;
  105. // VK_KHR_shader_float_controls
  106. bool shaderFloatControls = false;
  107. // VK_KHR_spirv_1_4
  108. bool spirv14 = false;
  109. };
  110. struct GraphicsPipelineConfiguration
  111. {
  112. VkRenderPass renderPass;
  113. VertexAttributes vertexAttributes;
  114. Shader *shader = nullptr;
  115. bool wireFrame;
  116. BlendState blendState;
  117. ColorChannelMask colorChannelMask;
  118. VkSampleCountFlagBits msaaSamples;
  119. uint32_t numColorAttachments;
  120. PrimitiveType primitiveType;
  121. struct DynamicState
  122. {
  123. CullMode cullmode = CULL_NONE;
  124. Winding winding = WINDING_MAX_ENUM;
  125. StencilAction stencilAction = STENCIL_MAX_ENUM;
  126. CompareMode stencilCompare = COMPARE_MAX_ENUM;
  127. DepthState depthState{};
  128. } dynamicState;
  129. GraphicsPipelineConfiguration()
  130. {
  131. memset(this, 0, sizeof(GraphicsPipelineConfiguration));
  132. }
  133. bool operator==(const GraphicsPipelineConfiguration &other) const
  134. {
  135. return memcmp(this, &other, sizeof(GraphicsPipelineConfiguration)) == 0;
  136. }
  137. };
  138. struct GraphicsPipelineConfigurationHasher
  139. {
  140. size_t operator() (const GraphicsPipelineConfiguration &configuration) const
  141. {
  142. return XXH32(&configuration, sizeof(GraphicsPipelineConfiguration), 0);
  143. }
  144. };
  145. struct SamplerStateHasher
  146. {
  147. size_t operator()(const SamplerState &samplerState) const
  148. {
  149. return XXH32(&samplerState, sizeof(SamplerState), 0);
  150. }
  151. };
  152. struct BatchedDrawBuffers
  153. {
  154. StreamBuffer *vertexBuffer1;
  155. StreamBuffer *vertexBuffer2;
  156. StreamBuffer *indexBuffer;
  157. StreamBuffer *constantColorBuffer;
  158. ~BatchedDrawBuffers()
  159. {
  160. delete vertexBuffer1;
  161. delete vertexBuffer2;
  162. delete indexBuffer;
  163. delete constantColorBuffer;
  164. }
  165. };
  166. struct QueueFamilyIndices
  167. {
  168. std::optional<uint32_t> graphicsFamily;
  169. std::optional<uint32_t> presentFamily;
  170. bool isComplete() const
  171. {
  172. return graphicsFamily.has_value() && presentFamily.has_value();
  173. }
  174. };
  175. struct SwapChainSupportDetails
  176. {
  177. VkSurfaceCapabilitiesKHR capabilities{};
  178. std::vector<VkSurfaceFormatKHR> formats;
  179. std::vector<VkPresentModeKHR> presentModes;
  180. };
  181. struct RenderpassState
  182. {
  183. bool active = false;
  184. VkRenderPassBeginInfo beginInfo{};
  185. bool useConfigurations = false;
  186. RenderPassConfiguration renderPassConfiguration{};
  187. FramebufferConfiguration framebufferConfiguration{};
  188. VkPipeline pipeline = VK_NULL_HANDLE;
  189. std::vector<VkImage> transitionImages;
  190. uint32_t numColorAttachments = 0;
  191. float width = 0.0f;
  192. float height = 0.0f;
  193. VkSampleCountFlagBits msaa = VK_SAMPLE_COUNT_1_BIT;
  194. };
  195. struct ScreenshotReadbackBuffer
  196. {
  197. VkBuffer buffer;
  198. VmaAllocation allocation;
  199. VmaAllocationInfo allocationInfo;
  200. VkImage image;
  201. VmaAllocation imageAllocation;
  202. };
  203. class Graphics final : public love::graphics::Graphics
  204. {
  205. public:
  206. Graphics();
  207. ~Graphics();
  208. const char *getName() const override;
  209. const VkDevice getDevice() const;
  210. const VmaAllocator getVmaAllocator() const;
  211. // implementation for virtual functions
  212. love::graphics::Texture *newTexture(const love::graphics::Texture::Settings &settings, const love::graphics::Texture::Slices *data) override;
  213. love::graphics::Buffer *newBuffer(const love::graphics::Buffer::Settings &settings, const std::vector<love::graphics::Buffer::DataDeclaration>& format, const void *data, size_t size, size_t arraylength) override;
  214. void clear(OptionalColorD color, OptionalInt stencil, OptionalDouble depth) override;
  215. void clear(const std::vector<OptionalColorD> &colors, OptionalInt stencil, OptionalDouble depth) override;
  216. Matrix4 computeDeviceProjection(const Matrix4 &projection, bool rendertotexture) const override;
  217. void discard(const std::vector<bool>& colorbuffers, bool depthstencil) override;
  218. void present(void *screenshotCallbackdata) override;
  219. void setViewportSize(int width, int height, int pixelwidth, int pixelheight) override;
  220. bool setMode(void *context, int width, int height, int pixelwidth, int pixelheight, bool windowhasstencil, int msaa) override;
  221. void unSetMode() override;
  222. void setActive(bool active) override;
  223. int getRequestedBackbufferMSAA() const override;
  224. int getBackbufferMSAA() const override;
  225. void setColor(Colorf c) override;
  226. void setScissor(const Rect &rect) override;
  227. void setScissor() override;
  228. void setStencilMode(StencilAction action, CompareMode compare, int value, love::uint32 readmask, love::uint32 writemask) override;
  229. void setDepthMode(CompareMode compare, bool write) override;
  230. void setFrontFaceWinding(Winding winding) override;
  231. void setColorMask(ColorChannelMask mask) override;
  232. void setBlendState(const BlendState &blend) override;
  233. void setPointSize(float size) override;
  234. void setWireframe(bool enable) override;
  235. PixelFormat getSizedFormat(PixelFormat format, bool rendertarget, bool readable) const override;
  236. bool isPixelFormatSupported(PixelFormat format, uint32 usage, bool sRGB) override;
  237. Renderer getRenderer() const override;
  238. bool usesGLSLES() const override;
  239. RendererInfo getRendererInfo() const override;
  240. void draw(const DrawCommand &cmd) override;
  241. void draw(const DrawIndexedCommand &cmd) override;
  242. void drawQuads(int start, int count, const VertexAttributes &attributes, const BufferBindings &buffers, graphics::Texture *texture) override;
  243. graphics::GraphicsReadback *newReadbackInternal(ReadbackMethod method, love::graphics::Buffer *buffer, size_t offset, size_t size, data::ByteData *dest, size_t destoffset) override;
  244. graphics::GraphicsReadback *newReadbackInternal(ReadbackMethod method, love::graphics::Texture *texture, int slice, int mipmap, const Rect &rect, image::ImageData *dest, int destx, int desty) override;
  245. // internal functions.
  246. VkCommandBuffer getCommandBufferForDataTransfer();
  247. void queueCleanUp(std::function<void()> cleanUp);
  248. void addReadbackCallback(std::function<void()> callback);
  249. void submitGpuCommands(bool present, void *screenshotCallbackData = nullptr);
  250. uint32_t getNumImagesInFlight() const;
  251. uint32_t getFrameIndex() const;
  252. const VkDeviceSize getMinUniformBufferOffsetAlignment() const;
  253. graphics::Texture *getDefaultTexture() const;
  254. VkSampler getCachedSampler(const SamplerState &samplerState);
  255. void setComputeShader(Shader *computeShader);
  256. std::set<Shader*> &getUsedShadersInFrame();
  257. graphics::Shader::BuiltinUniformData getCurrentBuiltinUniformData();
  258. const OptionalDeviceFeatures &getEnabledOptionalDeviceExtensions() const;
  259. VkSampleCountFlagBits getMsaaCount(int requestedMsaa) const;
  260. protected:
  261. graphics::ShaderStage *newShaderStageInternal(ShaderStageType stage, const std::string &cachekey, const std::string &source, bool gles) override;
  262. graphics::Shader *newShaderInternal(StrongRef<love::graphics::ShaderStage> stages[SHADERSTAGE_MAX_ENUM]) override;
  263. graphics::StreamBuffer *newStreamBuffer(BufferUsage type, size_t size) override;
  264. bool dispatch(int x, int y, int z) override;
  265. void initCapabilities() override;
  266. void getAPIStats(int &shaderswitches) const override;
  267. void setRenderTargetsInternal(const RenderTargets &rts, int pixelw, int pixelh, bool hasSRGBtexture) override;
  268. private:
  269. void createVulkanInstance();
  270. bool checkValidationSupport();
  271. void pickPhysicalDevice();
  272. int rateDeviceSuitability(VkPhysicalDevice device);
  273. QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device);
  274. void createLogicalDevice();
  275. void initVMA();
  276. void createSurface();
  277. bool checkDeviceExtensionSupport(VkPhysicalDevice device);
  278. SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device);
  279. VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR> &availableFormats);
  280. VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR> &availablePresentModes);
  281. VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR &capabilities);
  282. VkCompositeAlphaFlagBitsKHR chooseCompositeAlpha(const VkSurfaceCapabilitiesKHR &capabilities);
  283. void createSwapChain();
  284. void createImageViews();
  285. void createScreenshotCallbackBuffers();
  286. void createDefaultRenderPass();
  287. void createDefaultFramebuffers();
  288. VkFramebuffer createFramebuffer(FramebufferConfiguration &configuration);
  289. VkFramebuffer getFramebuffer(FramebufferConfiguration &configuration);
  290. void createDefaultShaders();
  291. VkRenderPass createRenderPass(RenderPassConfiguration &configuration);
  292. VkPipeline createGraphicsPipeline(GraphicsPipelineConfiguration &configuration);
  293. void createColorResources();
  294. VkFormat findSupportedFormat(const std::vector<VkFormat> &candidates, VkImageTiling tiling, VkFormatFeatureFlags features);
  295. VkFormat findDepthFormat();
  296. void createDepthResources();
  297. void createCommandPool();
  298. void createCommandBuffers();
  299. void createSyncObjects();
  300. void createDefaultTexture();
  301. void cleanup();
  302. void cleanupSwapChain();
  303. void recreateSwapChain();
  304. void initDynamicState();
  305. void beginFrame();
  306. void startRecordingGraphicsCommands(bool newFrame);
  307. void endRecordingGraphicsCommands(bool present);
  308. void ensureGraphicsPipelineConfiguration(GraphicsPipelineConfiguration &configuration);
  309. void updatedBatchedDrawBuffers();
  310. bool usesConstantVertexColor(const VertexAttributes &attribs);
  311. void createVulkanVertexFormat(
  312. VertexAttributes vertexAttributes,
  313. std::vector<VkVertexInputBindingDescription> &bindingDescriptions,
  314. std::vector<VkVertexInputAttributeDescription> &attributeDescriptions);
  315. void prepareDraw(
  316. const VertexAttributes &attributes,
  317. const BufferBindings &buffers, graphics::Texture *texture,
  318. PrimitiveType, CullMode);
  319. void setRenderPass(const RenderTargets &rts, int pixelw, int pixelh, bool hasSRGBtexture);
  320. void setDefaultRenderPass();
  321. void startRenderPass();
  322. void endRenderPass();
  323. VkSampler createSampler(const SamplerState &samplerState);
  324. uint32_t vulkanApiVersion = VK_VERSION_1_0;
  325. VkInstance instance = VK_NULL_HANDLE;
  326. VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
  327. bool canUsePushConstants = false;
  328. int requestedMsaa = 0;
  329. VkDevice device = VK_NULL_HANDLE;
  330. OptionalInstanceExtensions optionalInstanceExtensions;
  331. OptionalDeviceFeatures optionalDeviceFeatures;
  332. VkQueue graphicsQueue = VK_NULL_HANDLE;
  333. VkQueue presentQueue = VK_NULL_HANDLE;
  334. VkSurfaceKHR surface = VK_NULL_HANDLE;
  335. VkSwapchainKHR swapChain = VK_NULL_HANDLE;
  336. VkSurfaceTransformFlagBitsKHR preTransform = {};
  337. Matrix4 displayRotation;
  338. std::vector<VkImage> swapChainImages;
  339. VkFormat swapChainImageFormat = VK_FORMAT_UNDEFINED;
  340. VkExtent2D swapChainExtent = VkExtent2D();
  341. std::vector<VkImageView> swapChainImageViews;
  342. VkSampleCountFlagBits msaaSamples = VK_SAMPLE_COUNT_1_BIT;
  343. VkImage colorImage = VK_NULL_HANDLE;
  344. VkImageView colorImageView = VK_NULL_HANDLE;
  345. VmaAllocation colorImageAllocation = VK_NULL_HANDLE;
  346. VkImage depthImage = VK_NULL_HANDLE;
  347. VkImageView depthImageView = VK_NULL_HANDLE;
  348. VmaAllocation depthImageAllocation = VK_NULL_HANDLE;
  349. VkRenderPass defaultRenderPass = VK_NULL_HANDLE;
  350. std::vector<VkFramebuffer> defaultFramebuffers;
  351. std::unordered_map<RenderPassConfiguration, VkRenderPass, RenderPassConfigurationHasher> renderPasses;
  352. std::unordered_map<FramebufferConfiguration, VkFramebuffer, FramebufferConfigurationHasher> framebuffers;
  353. std::unordered_map<GraphicsPipelineConfiguration, VkPipeline, GraphicsPipelineConfigurationHasher> graphicsPipelines;
  354. std::unordered_map<SamplerState, VkSampler, SamplerStateHasher> samplers;
  355. VkCommandPool commandPool = VK_NULL_HANDLE;
  356. std::vector<VkCommandBuffer> commandBuffers;
  357. Shader* computeShader = nullptr;
  358. std::vector<VkSemaphore> imageAvailableSemaphores;
  359. std::vector<VkSemaphore> renderFinishedSemaphores;
  360. std::vector<VkFence> inFlightFences;
  361. std::vector<VkFence> imagesInFlight;
  362. VkDeviceSize minUniformBufferOffsetAlignment = 0;
  363. bool imageRequested = false;
  364. size_t currentFrame = 0;
  365. uint32_t imageIndex = 0;
  366. bool framebufferResized = false;
  367. bool transitionColorDepthLayouts = false;
  368. VmaAllocator vmaAllocator = VK_NULL_HANDLE;
  369. std::unique_ptr<Texture> standardTexture = nullptr;
  370. // we need an array of draw buffers, since the frames are being rendered asynchronously
  371. // and we can't (or shouldn't) update the contents of the buffers while they're still in flight / being rendered.
  372. std::vector<BatchedDrawBuffers> batchedDrawBuffers;
  373. // functions that need to be called to cleanup objects that were needed for rendering a frame.
  374. // just like batchedDrawBuffers we need a vector for each frame in flight.
  375. std::vector<std::vector<std::function<void()>>> cleanUpFunctions;
  376. std::vector<std::vector<std::function<void()>>> readbackCallbacks;
  377. std::vector<ScreenshotReadbackBuffer> screenshotReadbackBuffers;
  378. std::set<Shader*> usedShadersInFrame;
  379. RenderpassState renderPassState;
  380. };
  381. } // vulkan
  382. } // graphics
  383. } // love