diff --git a/.clang-format b/.clang-format index a02bad13..b92adbb4 100644 --- a/.clang-format +++ b/.clang-format @@ -38,7 +38,7 @@ BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: false BreakAfterJavaFieldAnnotations: false BreakStringLiterals: true -ColumnLimit: 80 +ColumnLimit: 160 CommentPragmas: '^ IWYU pragma:' ConstructorInitializerAllOnOneLineOrOnePerLine: true ConstructorInitializerIndentWidth: 4 diff --git a/Includes/VoxFlow/Core/Devices/Context.hpp b/Includes/VoxFlow/Core/Devices/Context.hpp index 65c479ea..d3401a54 100644 --- a/Includes/VoxFlow/Core/Devices/Context.hpp +++ b/Includes/VoxFlow/Core/Devices/Context.hpp @@ -19,26 +19,17 @@ struct Context void addInstanceLayer(const char* name, bool isOptional = false); void addInstanceExtension(const char* name, bool isOptional = false); - void addDeviceExtension(const char* name, bool isOptional = false, - void* pFeatureStruct = nullptr, - uint32_t version = 0); + void addDeviceExtension(const char* name, bool isOptional = false, void* pFeatureStruct = nullptr, uint32_t version = 0); - void addRequiredQueue(std::string&& queueName, VkQueueFlags queueFlag, - uint32_t queueCount, float queuePriority, - bool isMainQueue); + void addRequiredQueue(std::string&& queueName, VkQueueFlags queueFlag, uint32_t queueCount, float queuePriority, bool isMainQueue); std::string appEngine = "VoxFlow"; std::string appTitle = "VoxFlow"; struct Entry { - explicit Entry(const char* entryName, const bool isOptional = false, - void* pFeatureStruct = nullptr, - const uint32_t version = 0) - : entryName(entryName), - isOptional(isOptional), - pFeatureStruct(pFeatureStruct), - version(version){}; + explicit Entry(const char* entryName, const bool isOptional = false, void* pFeatureStruct = nullptr, const uint32_t version = 0) + : entryName(entryName), isOptional(isOptional), pFeatureStruct(pFeatureStruct), version(version){}; const char* entryName{ nullptr }; bool isOptional{ false }; @@ -52,14 +43,8 @@ struct Context struct QueueSetup { - explicit QueueSetup(std::string&& queueName, const VkQueueFlags flag, - const uint32_t queueCount, const float priority, - bool isMainQueue) - : queueName(std::move(queueName)), - flag(flag), - queueCount(queueCount), - priority(priority), - isMainQueue(isMainQueue) + explicit QueueSetup(std::string&& queueName, const VkQueueFlags flag, const uint32_t queueCount, const float priority, bool isMainQueue) + : queueName(std::move(queueName)), flag(flag), queueCount(queueCount), priority(priority), isMainQueue(isMainQueue) { } diff --git a/Includes/VoxFlow/Core/Devices/LogicalDevice.hpp b/Includes/VoxFlow/Core/Devices/LogicalDevice.hpp index 687f5836..155dc45d 100644 --- a/Includes/VoxFlow/Core/Devices/LogicalDevice.hpp +++ b/Includes/VoxFlow/Core/Devices/LogicalDevice.hpp @@ -32,8 +32,7 @@ class PipelineStreamingContext; class LogicalDevice : NonCopyable { public: - LogicalDevice(const Context& ctx, PhysicalDevice* physicalDevice, - Instance* instance, const LogicalDeviceType deviceType); + LogicalDevice(const Context& ctx, PhysicalDevice* physicalDevice, Instance* instance, const LogicalDeviceType deviceType); ~LogicalDevice() override; LogicalDevice(LogicalDevice&& other) noexcept; LogicalDevice& operator=(LogicalDevice&& other) noexcept; @@ -77,8 +76,7 @@ class LogicalDevice : NonCopyable * @return descriptor set allocator pool which manage set and pool laid in * each layout */ - [[nodiscard]] DescriptorSetAllocatorPool* getDescriptorSetAllocatorPool() - const + [[nodiscard]] DescriptorSetAllocatorPool* getDescriptorSetAllocatorPool() const { return _descriptorSetAllocatorPool; } @@ -89,19 +87,15 @@ class LogicalDevice : NonCopyable * @param resolution window resolution to create * @return swapchain wrappging class instance */ - std::shared_ptr addSwapChain(const char* title, - const glm::ivec2 resolution); + std::shared_ptr addSwapChain(const char* title, const glm::ivec2 resolution); /** * @param swapChainIndex swapchain index to querying * @return swapchain ref-counted instance matched to given index */ - [[nodiscard]] inline const std::shared_ptr& getSwapChain( - const uint32_t swapChainIndex) const + [[nodiscard]] inline const std::shared_ptr& getSwapChain(const uint32_t swapChainIndex) const { - VOX_ASSERT(swapChainIndex < _swapChains.size(), - "Given Index({}), Num SwapChains({})", swapChainIndex, - _swapChains.size()); + VOX_ASSERT(swapChainIndex < _swapChains.size(), "Given Index({}), Num SwapChains({})", swapChainIndex, _swapChains.size()); return _swapChains[swapChainIndex]; } diff --git a/Includes/VoxFlow/Core/Devices/PhysicalDevice.hpp b/Includes/VoxFlow/Core/Devices/PhysicalDevice.hpp index b6cff960..3797547a 100644 --- a/Includes/VoxFlow/Core/Devices/PhysicalDevice.hpp +++ b/Includes/VoxFlow/Core/Devices/PhysicalDevice.hpp @@ -18,13 +18,10 @@ class PhysicalDevice : NonCopyable ~PhysicalDevice() override = default; [[nodiscard]] std::vector getPossibleLayers() const; - [[nodiscard]] std::vector getPossibleExtensions() - const; + [[nodiscard]] std::vector getPossibleExtensions() const; [[nodiscard]] VkPhysicalDeviceMemoryProperties getMemoryProperty() const; - [[nodiscard]] std::vector - getQueueFamilyProperties() const; - [[nodiscard]] VkPhysicalDeviceProperties getPhysicalDeviceProperties() - const; + [[nodiscard]] std::vector getQueueFamilyProperties() const; + [[nodiscard]] VkPhysicalDeviceProperties getPhysicalDeviceProperties() const; [[nodiscard]] VkPhysicalDevice get() const noexcept { diff --git a/Includes/VoxFlow/Core/Devices/Queue.hpp b/Includes/VoxFlow/Core/Devices/Queue.hpp index 68200d7a..d86e2fb4 100644 --- a/Includes/VoxFlow/Core/Devices/Queue.hpp +++ b/Includes/VoxFlow/Core/Devices/Queue.hpp @@ -21,8 +21,7 @@ class SwapChain; class Queue : private NonCopyable { public: - explicit Queue(const std::string& debugName, LogicalDevice* logicalDevice, VkQueueFlags queueTypeFlags, - VkQueue _queueTypeBits, uint32_t familyIndex, + explicit Queue(const std::string& debugName, LogicalDevice* logicalDevice, VkQueueFlags queueTypeFlags, VkQueue _queueTypeBits, uint32_t familyIndex, uint32_t queueIndex) noexcept; ~Queue(); Queue(Queue&& other) noexcept; @@ -55,17 +54,13 @@ class Queue : private NonCopyable // Submit given single command buffer to queue and returns FenceObject for // waiting submission completed - FenceObject submitCommandBuffer( - const std::shared_ptr& commandBuffer, - SwapChain* swapChain, const FrameContext* frameContext, - const bool waitCompletion); + FenceObject submitCommandBuffer(const std::shared_ptr& commandBuffer, SwapChain* swapChain, const FrameContext* frameContext, + const bool waitCompletion); // Submit given command buffers to queue and returns FenceObject for waiting // submission completed - FenceObject submitCommandBufferBatch( - std::vector>&& batchedCommandBuffers, - SwapChain* swapChain, const FrameContext* frameContext, - const bool waitAllCompletion); + FenceObject submitCommandBufferBatch(std::vector>&& batchedCommandBuffers, SwapChain* swapChain, + const FrameContext* frameContext, const bool waitAllCompletion); // Returns Timeline semaphore which synchronized with queue submission [[nodiscard]] inline VkSemaphore* getSubmitTimelineSemaphore() diff --git a/Includes/VoxFlow/Core/Devices/RenderDevice.hpp b/Includes/VoxFlow/Core/Devices/RenderDevice.hpp index 240366c1..18d4ab8b 100644 --- a/Includes/VoxFlow/Core/Devices/RenderDevice.hpp +++ b/Includes/VoxFlow/Core/Devices/RenderDevice.hpp @@ -35,8 +35,7 @@ class RenderDevice final : private NonCopyable return _physicalDevice; } - [[nodiscard]] inline LogicalDevice* getLogicalDevice( - const LogicalDeviceType deviceType) const + [[nodiscard]] inline LogicalDevice* getLogicalDevice(const LogicalDeviceType deviceType) const { return _logicalDevices.at(static_cast(deviceType)).get(); } diff --git a/Includes/VoxFlow/Core/Devices/SwapChain.hpp b/Includes/VoxFlow/Core/Devices/SwapChain.hpp index eaff9563..f6b1e04b 100644 --- a/Includes/VoxFlow/Core/Devices/SwapChain.hpp +++ b/Includes/VoxFlow/Core/Devices/SwapChain.hpp @@ -22,9 +22,8 @@ class Texture; class SwapChain : private NonCopyable { public: - explicit SwapChain(Instance* instance, PhysicalDevice* physicalDevice, - LogicalDevice* logicalDevice, Queue* presentSupportQueue, - std::string&& titleName, const glm::uvec2 resolution) noexcept; + explicit SwapChain(Instance* instance, PhysicalDevice* physicalDevice, LogicalDevice* logicalDevice, Queue* presentSupportQueue, std::string&& titleName, + const glm::uvec2 resolution) noexcept; ~SwapChain(); SwapChain(SwapChain&& other) noexcept; SwapChain& operator=(SwapChain&& other) noexcept; @@ -58,9 +57,7 @@ class SwapChain : private NonCopyable // Add semaphores and waiting values from queue which use swapchain's back // buffer to submit command - void addWaitSemaphores(const uint32_t frameIndex, - VkSemaphore timelineSemaphore, - const uint64_t waitingValue); + void addWaitSemaphores(const uint32_t frameIndex, VkSemaphore timelineSemaphore, const uint64_t waitingValue); // Wait all semaphores added with frameIndex void waitForGpuComplete(const uint32_t frameIndex); @@ -68,9 +65,8 @@ class SwapChain : private NonCopyable // Returns whether swapChain window should be removed. bool shouldDestroySwapChain() const; -private: - void querySwapChainCapability( - VkSwapchainCreateInfoKHR& swapChainCreateInfo, const bool vsync); + private: + void querySwapChainCapability(VkSwapchainCreateInfoKHR& swapChainCreateInfo, const bool vsync); private: Instance* _instance = nullptr; @@ -106,7 +102,6 @@ class SwapChain : private NonCopyable std::array _waitSemaphoreInfos; }; - inline VkSwapchainKHR SwapChain::get() const noexcept { return _swapChain; @@ -135,12 +130,9 @@ inline uint32_t SwapChain::getFrameIndex() const noexcept { return _frameIndex; } -inline std::shared_ptr SwapChain::getSwapChainImage( - const uint32_t index) const +inline std::shared_ptr SwapChain::getSwapChainImage(const uint32_t index) const { - VOX_ASSERT(index < static_cast(_swapChainImages.size()), - "Given Index ({}), Num SwapChain Images ({})", index, - _swapChainImages.size()); + VOX_ASSERT(index < static_cast(_swapChainImages.size()), "Given Index ({}), Num SwapChain Images ({})", index, _swapChainImages.size()); return _swapChainImages[index]; } inline glm::uvec2 SwapChain::getResolution() const noexcept diff --git a/Includes/VoxFlow/Core/FrameGraph/BlackBoard.hpp b/Includes/VoxFlow/Core/FrameGraph/BlackBoard.hpp index 96ec5bb6..93d47daa 100644 --- a/Includes/VoxFlow/Core/FrameGraph/BlackBoard.hpp +++ b/Includes/VoxFlow/Core/FrameGraph/BlackBoard.hpp @@ -48,8 +48,7 @@ class BlackBoard : private NonCopyable } ResourceHandle& operator[](std::string_view name) { - auto [iter, _] = - _handleContainer.insert_or_assign(name, INVALID_RESOURCE_HANDLE); + auto [iter, _] = _handleContainer.insert_or_assign(name, INVALID_RESOURCE_HANDLE); return iter->second; } diff --git a/Includes/VoxFlow/Core/FrameGraph/DependencyGraph.hpp b/Includes/VoxFlow/Core/FrameGraph/DependencyGraph.hpp index 6f0e99cd..94614353 100644 --- a/Includes/VoxFlow/Core/FrameGraph/DependencyGraph.hpp +++ b/Includes/VoxFlow/Core/FrameGraph/DependencyGraph.hpp @@ -121,9 +121,7 @@ class DependencyGraph : private NonCopyable EdgeContainer getIncomingEdges(NodeID id); EdgeContainer getOutgoingEdges(NodeID id); - template , - bool> = true> + template , bool> = true> DependencyGraph::Edge* link(NodeID fromID, NodeID toID, Args... args) { Node* fromNode = getNode(fromID); diff --git a/Includes/VoxFlow/Core/FrameGraph/FrameGraph-Impl.hpp b/Includes/VoxFlow/Core/FrameGraph/FrameGraph-Impl.hpp index a620faff..6af8d7bb 100644 --- a/Includes/VoxFlow/Core/FrameGraph/FrameGraph-Impl.hpp +++ b/Includes/VoxFlow/Core/FrameGraph/FrameGraph-Impl.hpp @@ -16,58 +16,40 @@ namespace RenderGraph constexpr uint32_t EXECUTION_LAMBDA_SIZE_LIMIT = 1024U; template -ResourceHandle FrameGraphBuilder::allocate( - std::string&& resourceName, - typename ResourceDataType::Descriptor&& initArgs) +ResourceHandle FrameGraphBuilder::allocate(std::string&& resourceName, typename ResourceDataType::Descriptor&& initArgs) { - return _frameGraph->create(std::move(resourceName), - std::move(initArgs)); + return _frameGraph->create(std::move(resourceName), std::move(initArgs)); } template -ResourceHandle FrameGraphBuilder::read(ResourceHandle id, - typename ResourceDataType::Usage usage) +ResourceHandle FrameGraphBuilder::read(ResourceHandle id, typename ResourceDataType::Usage usage) { - return _frameGraph->readInternal( - id, _currentPassNode, - [this, usage](ResourceNode* node, VirtualResource* vResource) { - Resource* resource = - static_cast*>(vResource); - return resource->connect(_frameGraph->getDependencyGraph(), node, - _currentPassNode, usage); - }); + return _frameGraph->readInternal(id, _currentPassNode, [this, usage](ResourceNode* node, VirtualResource* vResource) { + Resource* resource = static_cast*>(vResource); + return resource->connect(_frameGraph->getDependencyGraph(), node, _currentPassNode, usage); + }); } template -ResourceHandle FrameGraphBuilder::write(ResourceHandle id, - typename ResourceDataType::Usage usage) +ResourceHandle FrameGraphBuilder::write(ResourceHandle id, typename ResourceDataType::Usage usage) { - return _frameGraph->writeInternal( - id, _currentPassNode, - [this, usage](ResourceNode* node, VirtualResource* vResource) { - Resource* resource = - static_cast*>(vResource); - return resource->connect(_frameGraph->getDependencyGraph(), - _currentPassNode, node, usage); - }); + return _frameGraph->writeInternal(id, _currentPassNode, [this, usage](ResourceNode* node, VirtualResource* vResource) { + Resource* resource = static_cast*>(vResource); + return resource->connect(_frameGraph->getDependencyGraph(), _currentPassNode, node, usage); + }); } template -const PassDataType& FrameGraph::addCallbackPass(std::string_view&& passName, - SetupPhase&& setup, - ExecutePhase&& execute) +const PassDataType& FrameGraph::addCallbackPass(std::string_view&& passName, SetupPhase&& setup, ExecutePhase&& execute) { - static_assert(sizeof(ExecutePhase) < EXECUTION_LAMBDA_SIZE_LIMIT, - "ExecutePhase() lambda captures too much data"); + static_assert(sizeof(ExecutePhase) < EXECUTION_LAMBDA_SIZE_LIMIT, "ExecutePhase() lambda captures too much data"); std::unique_ptr> pass = - std::make_unique>( - std::forward(execute)); + std::make_unique>(std::forward(execute)); PassDataType& passData = pass->getPassData(); - _passNodes.emplace_back( - new RenderPassNode(this, std::move(passName), std::move(pass))); + _passNodes.emplace_back(new RenderPassNode(this, std::move(passName), std::move(pass))); FrameGraphBuilder builder(this, _passNodes.back()); std::invoke(setup, builder, passData); @@ -76,23 +58,19 @@ const PassDataType& FrameGraph::addCallbackPass(std::string_view&& passName, } template -void FrameGraph::addCallbackPass(std::string_view&& passName, - SetupPhase&& setup, ExecutePhase&& execute) +void FrameGraph::addCallbackPass(std::string_view&& passName, SetupPhase&& setup, ExecutePhase&& execute) { - struct EmptyPassData {}; + struct EmptyPassData + { + }; - [[maybe_unused]] auto _ = - addCallbackPass( - std::move(passName), std::move(setup), std::move(execute)); + [[maybe_unused]] auto _ = addCallbackPass(std::move(passName), std::move(setup), std::move(execute)); } template -void FrameGraph::addPresentPass(std::string_view&& passName, SetupPhase&& setup, - SwapChain* swapChain, - const FrameContext& frameContext) +void FrameGraph::addPresentPass(std::string_view&& passName, SetupPhase&& setup, SwapChain* swapChain, const FrameContext& frameContext) { - _passNodes.emplace_back(new PresentPassNode(this, std::move(passName), - swapChain, frameContext)); + _passNodes.emplace_back(new PresentPassNode(this, std::move(passName), swapChain, frameContext)); FrameGraphBuilder builder(this, _passNodes.back()); std::invoke(setup, builder); @@ -100,51 +78,39 @@ void FrameGraph::addPresentPass(std::string_view&& passName, SetupPhase&& setup, } template -ResourceHandle FrameGraph::create( - std::string&& resourceName, - typename ResourceDataType::Descriptor&& resourceDescArgs) +ResourceHandle FrameGraph::create(std::string&& resourceName, typename ResourceDataType::Descriptor&& resourceDescArgs) { - VirtualResource* virtualResource = new Resource( - std::move(resourceName), std::move(resourceDescArgs)); + VirtualResource* virtualResource = new Resource(std::move(resourceName), std::move(resourceDescArgs)); ResourceHandle resourceHandle(_resources.size()); - _resourceSlots.push_back( - { ._resourceIndex = - static_cast(_resourceNodes.size()), - ._nodeIndex = static_cast(_resources.size()), - ._version = static_cast(0) }); + _resourceSlots.push_back({ ._resourceIndex = static_cast(_resourceNodes.size()), + ._nodeIndex = static_cast(_resources.size()), + ._version = static_cast(0) }); _resources.push_back(virtualResource); - ResourceNode* resourceNode = - new ResourceNode(&_dependencyGraph, resourceHandle); + ResourceNode* resourceNode = new ResourceNode(&_dependencyGraph, resourceHandle); _resourceNodes.push_back(resourceNode); return resourceHandle; } template -const typename ResourceDataType::Descriptor FrameGraph::getResourceDescriptor( - ResourceHandle id) const +const typename ResourceDataType::Descriptor FrameGraph::getResourceDescriptor(ResourceHandle id) const { const ResourceSlot& resourceSlot = getResourceSlot(id); - auto resource = static_cast*>( - _resources[resourceSlot._resourceIndex]); + auto resource = static_cast*>(_resources[resourceSlot._resourceIndex]); return resource->getDescriptor(); } template -bool Resource::connect(DependencyGraph* dependencyGraph, - ResourceNode* node, PassNode* passNode, - typename ResourceDataType::Usage usage) +bool Resource::connect(DependencyGraph* dependencyGraph, ResourceNode* node, PassNode* passNode, typename ResourceDataType::Usage usage) { - ResourceEdge* edge = - static_cast(node->getReaderEdgeForPassNode(passNode)); + ResourceEdge* edge = static_cast(node->getReaderEdgeForPassNode(passNode)); if (edge == nullptr) { - edge = static_cast(dependencyGraph->link( - node->getNodeID(), passNode->getNodeID(), usage)); + edge = static_cast(dependencyGraph->link(node->getNodeID(), passNode->getNodeID(), usage)); } else { @@ -156,17 +122,13 @@ bool Resource::connect(DependencyGraph* dependencyGraph, } template -bool Resource::connect(DependencyGraph* dependencyGraph, - PassNode* passNode, ResourceNode* node, - typename ResourceDataType::Usage usage) +bool Resource::connect(DependencyGraph* dependencyGraph, PassNode* passNode, ResourceNode* node, typename ResourceDataType::Usage usage) { - ResourceEdge* edge = - static_cast(node->getWriterEdgeForPassNode(passNode)); + ResourceEdge* edge = static_cast(node->getWriterEdgeForPassNode(passNode)); if (edge == nullptr) { - edge = static_cast(dependencyGraph->link( - passNode->getNodeID(), node->getNodeID(), usage)); + edge = static_cast(dependencyGraph->link(passNode->getNodeID(), node->getNodeID(), usage)); } else { @@ -178,10 +140,7 @@ bool Resource::connect(DependencyGraph* dependencyGraph, } template -void Resource::resolveUsage( - DependencyGraph* dependencyGraph, - const DependencyGraph::EdgeContainer& edges, - DependencyGraph::Edge* writerEdge) +void Resource::resolveUsage(DependencyGraph* dependencyGraph, const DependencyGraph::EdgeContainer& edges, DependencyGraph::Edge* writerEdge) { for (DependencyGraph::Edge* edge : edges) { @@ -199,14 +158,11 @@ void Resource::resolveUsage( } template -[[nodiscard]] inline const Resource& -FrameGraphResources::getResource(ResourceHandle handle) const +[[nodiscard]] inline const Resource& FrameGraphResources::getResource(ResourceHandle handle) const { #if defined(VOXFLOW_DEBUG) auto declaredHandles = _passNode->getDeclaredHandles(); - VOX_ASSERT( - declaredHandles.find(handle) != declaredHandles.end(), - "Should not try to get resource that is not declared in this pass"); + VOX_ASSERT(declaredHandles.find(handle) != declaredHandles.end(), "Should not try to get resource that is not declared in this pass"); #endif VirtualResource* vresource = _frameGraph->getVirtualResource(handle); @@ -214,14 +170,11 @@ FrameGraphResources::getResource(ResourceHandle handle) const } template -[[nodiscard]] inline const typename ResourceDataType::Descriptor -FrameGraphResources::getResourceDescriptor(ResourceHandle handle) const +[[nodiscard]] inline const typename ResourceDataType::Descriptor FrameGraphResources::getResourceDescriptor(ResourceHandle handle) const { #if defined(VOXFLOW_DEBUG) auto declaredHandles = _passNode->getDeclaredHandles(); - VOX_ASSERT( - declaredHandles.find(handle) != declaredHandles.end(), - "Should not try to get resource that is not declared in this pass"); + VOX_ASSERT(declaredHandles.find(handle) != declaredHandles.end(), "Should not try to get resource that is not declared in this pass"); #endif return _frameGraph->getResourceDescriptor(handle); diff --git a/Includes/VoxFlow/Core/FrameGraph/FrameGraph.hpp b/Includes/VoxFlow/Core/FrameGraph/FrameGraph.hpp index 1e9ca059..fdf2a9fe 100644 --- a/Includes/VoxFlow/Core/FrameGraph/FrameGraph.hpp +++ b/Includes/VoxFlow/Core/FrameGraph/FrameGraph.hpp @@ -3,20 +3,20 @@ #ifndef VOXEL_FLOW_FRAME_GRAPH_HPP #define VOXEL_FLOW_FRAME_GRAPH_HPP -#include +#include #include #include #include -#include #include -#include +#include +#include #include +#include +#include #include #include #include #include -#include -#include namespace VoxFlow { @@ -44,28 +44,21 @@ class FrameGraphBuilder FrameGraphBuilder& operator=(FrameGraphBuilder&&) = delete; private: - FrameGraphBuilder(FrameGraph* frameGraph, PassNode* passNode) - : _frameGraph(frameGraph), _currentPassNode(passNode) + FrameGraphBuilder(FrameGraph* frameGraph, PassNode* passNode) : _frameGraph(frameGraph), _currentPassNode(passNode) { } public: template - [[nodiscard]] ResourceHandle allocate( - std::string&& resourceName, - typename ResourceDataType::Descriptor&& initArgs); + [[nodiscard]] ResourceHandle allocate(std::string&& resourceName, typename ResourceDataType::Descriptor&& initArgs); template - ResourceHandle read(ResourceHandle id, - typename ResourceDataType::Usage usage); + ResourceHandle read(ResourceHandle id, typename ResourceDataType::Usage usage); template - ResourceHandle write(ResourceHandle id, - typename ResourceDataType::Usage usage); + ResourceHandle write(ResourceHandle id, typename ResourceDataType::Usage usage); - [[nodiscard]] uint32_t declareRenderPass( - std::string_view&& passName, - typename FrameGraphRenderPass::Descriptor&& initArgs); + [[nodiscard]] uint32_t declareRenderPass(std::string_view&& passName, typename FrameGraphRenderPass::Descriptor&& initArgs); inline void setSideEffectPass() { @@ -97,28 +90,19 @@ class FrameGraph : private NonCopyable public: template - const PassDataType& addCallbackPass(std::string_view&& passName, - SetupPhase&& setup, - ExecutePhase&& execute); + const PassDataType& addCallbackPass(std::string_view&& passName, SetupPhase&& setup, ExecutePhase&& execute); template - void addCallbackPass(std::string_view&& passName, SetupPhase&& setup, - ExecutePhase&& execute); + void addCallbackPass(std::string_view&& passName, SetupPhase&& setup, ExecutePhase&& execute); template - void addPresentPass(std::string_view&& passName, SetupPhase&& setup, - SwapChain* swapChain, const FrameContext& frameContext); + void addPresentPass(std::string_view&& passName, SetupPhase&& setup, SwapChain* swapChain, const FrameContext& frameContext); template - [[nodiscard]] ResourceHandle create( - std::string&& resourceName, - typename ResourceDataType::Descriptor&& resourceDescArgs); + [[nodiscard]] ResourceHandle create(std::string&& resourceName, typename ResourceDataType::Descriptor&& resourceDescArgs); - [[nodiscard]] ResourceHandle importRenderTarget( - std::string&& resourceName, - FrameGraphTexture::Descriptor&& resourceDescArgs, - typename FrameGraphRenderPass::ImportedDescriptor&& importedDesc, - TextureView* textureView); + [[nodiscard]] ResourceHandle importRenderTarget(std::string&& resourceName, FrameGraphTexture::Descriptor&& resourceDescArgs, + typename FrameGraphRenderPass::ImportedDescriptor&& importedDesc, TextureView* textureView); // Compile given frame graph bool compile(); @@ -130,8 +114,7 @@ class FrameGraph : private NonCopyable void clear(); // - void reset(CommandStream* cmdStream, - RenderResourceAllocator* renderResourceAllocator); + void reset(CommandStream* cmdStream, RenderResourceAllocator* renderResourceAllocator); /** * Dump compiled graph as graphviz text into given string stream @@ -176,10 +159,9 @@ class FrameGraph : private NonCopyable } template - const typename ResourceDataType::Descriptor getResourceDescriptor( - ResourceHandle id) const; + const typename ResourceDataType::Descriptor getResourceDescriptor(ResourceHandle id) const; -private: + private: const ResourceSlot& getResourceSlot(ResourceHandle id) const { return _resourceSlots[id.get()]; @@ -200,17 +182,13 @@ class FrameGraph : private NonCopyable private: friend class FrameGraphBuilder; - ResourceHandle readInternal( - ResourceHandle id, [[maybe_unused]] PassNode* passNode, - std::function&& connect); - ResourceHandle writeInternal( - ResourceHandle id, PassNode* passNode, - std::function&& connect); + ResourceHandle readInternal(ResourceHandle id, [[maybe_unused]] PassNode* passNode, std::function&& connect); + ResourceHandle writeInternal(ResourceHandle id, PassNode* passNode, std::function&& connect); private: std::vector _resourceSlots; std::vector _passNodes; - std::vector::iterator _passNodeLast; + std::vector::iterator _passNodeLast; std::vector _resourceNodes; std::vector _resources; @@ -226,7 +204,7 @@ class FrameGraph : private NonCopyable RenderResourceAllocator* _renderResourceAllocator = nullptr; FenceObject _lastSubmitFence = FenceObject::Default(); }; -} +} // namespace RenderGraph } // namespace VoxFlow #endif diff --git a/Includes/VoxFlow/Core/FrameGraph/FrameGraphPass-Impl.hpp b/Includes/VoxFlow/Core/FrameGraph/FrameGraphPass-Impl.hpp index d6ae44df..33af3cd5 100644 --- a/Includes/VoxFlow/Core/FrameGraph/FrameGraphPass-Impl.hpp +++ b/Includes/VoxFlow/Core/FrameGraph/FrameGraphPass-Impl.hpp @@ -10,9 +10,7 @@ namespace VoxFlow namespace RenderGraph { template -FrameGraphPass::FrameGraphPass( - ExecutePhase&& executePhase) - : _executionPhaseLambda(std::move(executePhase)) +FrameGraphPass::FrameGraphPass(ExecutePhase&& executePhase) : _executionPhaseLambda(std::move(executePhase)) { } template diff --git a/Includes/VoxFlow/Core/FrameGraph/FrameGraphPass.hpp b/Includes/VoxFlow/Core/FrameGraph/FrameGraphPass.hpp index ba8c3b78..a32d3203 100644 --- a/Includes/VoxFlow/Core/FrameGraph/FrameGraphPass.hpp +++ b/Includes/VoxFlow/Core/FrameGraph/FrameGraphPass.hpp @@ -3,12 +3,12 @@ #ifndef VOXEL_FLOW_FRAME_GRAPH_PASS_HPP #define VOXEL_FLOW_FRAME_GRAPH_PASS_HPP -#include #include +#include #include -#include #include #include +#include #include #include #include @@ -36,8 +36,7 @@ class FrameGraphPassBase : private NonCopyable explicit FrameGraphPassBase(); ~FrameGraphPassBase(); - virtual void execute(const FrameGraphResources* resources, - CommandStream* cmdStream) = 0; + virtual void execute(const FrameGraphResources* resources, CommandStream* cmdStream) = 0; }; template @@ -56,8 +55,7 @@ class FrameGraphPass : public FrameGraphPassBase return _resourceData; } - void execute(const FrameGraphResources* resources, - CommandStream* cmdStream) final + void execute(const FrameGraphResources* resources, CommandStream* cmdStream) final { std::invoke(_executionPhaseLambda, resources, _resourceData, cmdStream); } @@ -70,14 +68,12 @@ class FrameGraphPass : public FrameGraphPassBase class PassNode : public DependencyGraph::Node { public: - explicit PassNode( - FrameGraph* ownerFrameGraph, std::string_view&& passName); + explicit PassNode(FrameGraph* ownerFrameGraph, std::string_view&& passName); ~PassNode() override; PassNode(PassNode&& passNode); PassNode& operator=(PassNode&& passNode); - virtual void execute(const FrameGraphResources* resources, - CommandStream* cmdStream) = 0; + virtual void execute(const FrameGraphResources* resources, CommandStream* cmdStream) = 0; void setSideEffectPass() { @@ -132,15 +128,12 @@ struct RenderPassData class RenderPassNode final : public PassNode { public: - explicit RenderPassNode(FrameGraph* ownerFrameGraph, - std::string_view&& passName, - std::unique_ptr&& pass); + explicit RenderPassNode(FrameGraph* ownerFrameGraph, std::string_view&& passName, std::unique_ptr&& pass); ~RenderPassNode() override; RenderPassNode(RenderPassNode&& passNode); RenderPassNode& operator=(RenderPassNode&& passNode); - void execute(const FrameGraphResources* resources, - CommandStream* cmdStream) final; + void execute(const FrameGraphResources* resources, CommandStream* cmdStream) final; /** * @param frameGraph owner frameGraph of this node @@ -149,10 +142,8 @@ class RenderPassNode final : public PassNode * @param descriptor render pass descriptor to declare * @return resource handle of created render pass data */ - [[nodiscard]] uint32_t declareRenderPass( - FrameGraph* frameGraph, FrameGraphBuilder* builder, - std::string_view&& name, - typename FrameGraphRenderPass::Descriptor&& descriptor); + [[nodiscard]] uint32_t declareRenderPass(FrameGraph* frameGraph, FrameGraphBuilder* builder, std::string_view&& name, + typename FrameGraphRenderPass::Descriptor&& descriptor); /** * @param render pass id of render pass data to return @@ -164,7 +155,7 @@ class RenderPassNode final : public PassNode } /** - * + * */ void resolve(FrameGraph* frameGraph) final; @@ -177,16 +168,12 @@ class RenderPassNode final : public PassNode class PresentPassNode final : public PassNode { public: - explicit PresentPassNode(FrameGraph* ownerFrameGraph, - std::string_view&& passName, - SwapChain* swapChainToPresent, - const FrameContext& frameContext); + explicit PresentPassNode(FrameGraph* ownerFrameGraph, std::string_view&& passName, SwapChain* swapChainToPresent, const FrameContext& frameContext); ~PresentPassNode() final; PresentPassNode(PresentPassNode&& passNode); PresentPassNode& operator=(PresentPassNode&& passNode); - void execute(const FrameGraphResources* resources, - CommandStream* cmdStream) final; + void execute(const FrameGraphResources* resources, CommandStream* cmdStream) final; void resolve(FrameGraph* frameGraph) final { diff --git a/Includes/VoxFlow/Core/FrameGraph/FrameGraphRenderPass.hpp b/Includes/VoxFlow/Core/FrameGraph/FrameGraphRenderPass.hpp index 377bbfc2..b67eaca8 100644 --- a/Includes/VoxFlow/Core/FrameGraph/FrameGraphRenderPass.hpp +++ b/Includes/VoxFlow/Core/FrameGraph/FrameGraphRenderPass.hpp @@ -20,10 +20,9 @@ struct FrameGraphRenderPass { struct Descriptor { - std::array - _attachments = { - INVALID_RESOURCE_HANDLE, - }; + std::array _attachments = { + INVALID_RESOURCE_HANDLE, + }; glm::uvec2 _viewportSize = glm::uvec2(0U, 0U); std::array _clearColors; float _clearDepth = 0.0f; diff --git a/Includes/VoxFlow/Core/FrameGraph/FrameGraphResources.hpp b/Includes/VoxFlow/Core/FrameGraph/FrameGraphResources.hpp index 811b65b2..8f40e3f3 100644 --- a/Includes/VoxFlow/Core/FrameGraph/FrameGraphResources.hpp +++ b/Includes/VoxFlow/Core/FrameGraph/FrameGraphResources.hpp @@ -18,8 +18,7 @@ namespace RenderGraph class FrameGraphResources { public: - explicit FrameGraphResources(FrameGraph* frameGraph, PassNode* passNode) - : _frameGraph(frameGraph), _passNode(passNode) + explicit FrameGraphResources(FrameGraph* frameGraph, PassNode* passNode) : _frameGraph(frameGraph), _passNode(passNode) { } @@ -38,12 +37,10 @@ class FrameGraphResources } template - [[nodiscard]] inline const Resource& getResource( - ResourceHandle handle) const; + [[nodiscard]] inline const Resource& getResource(ResourceHandle handle) const; template - [[nodiscard]] inline const typename ResourceDataType::Descriptor - getResourceDescriptor(ResourceHandle handle) const; + [[nodiscard]] inline const typename ResourceDataType::Descriptor getResourceDescriptor(ResourceHandle handle) const; [[nodiscard]] TextureView* getTextureView(ResourceHandle handle) const; diff --git a/Includes/VoxFlow/Core/FrameGraph/FrameGraphTexture.hpp b/Includes/VoxFlow/Core/FrameGraph/FrameGraphTexture.hpp index 4bc19074..54cf5f62 100644 --- a/Includes/VoxFlow/Core/FrameGraph/FrameGraphTexture.hpp +++ b/Includes/VoxFlow/Core/FrameGraph/FrameGraphTexture.hpp @@ -29,8 +29,7 @@ struct FrameGraphTexture using Usage = TextureUsage; - bool create(RenderResourceAllocator* resourceAllocator, - std::string&& debugName, Descriptor descriptor, Usage usage); + bool create(RenderResourceAllocator* resourceAllocator, std::string&& debugName, Descriptor descriptor, Usage usage); void destroy(RenderResourceAllocator* resourceAllocator); diff --git a/Includes/VoxFlow/Core/FrameGraph/Resource-Impl.hpp b/Includes/VoxFlow/Core/FrameGraph/Resource-Impl.hpp index e2c01159..15570b90 100644 --- a/Includes/VoxFlow/Core/FrameGraph/Resource-Impl.hpp +++ b/Includes/VoxFlow/Core/FrameGraph/Resource-Impl.hpp @@ -10,38 +10,24 @@ namespace VoxFlow namespace RenderGraph { template -Resource::Resource( - std::string&& name, typename ResourceDataType::Descriptor&& resourceArgs) - : VirtualResource(std::move(name)), - _descriptor(resourceArgs), - _usage(static_cast(0)) +Resource::Resource(std::string&& name, typename ResourceDataType::Descriptor&& resourceArgs) + : VirtualResource(std::move(name)), _descriptor(resourceArgs), _usage(static_cast(0)) { } template -Resource::Resource( - std::string&& name, typename ResourceDataType::Descriptor&& resourceArgs, - const ResourceDataType& resource) - : VirtualResource(std::move(name)), - _descriptor(resourceArgs), - _resource(resource), - _usage(static_cast(0)) +Resource::Resource(std::string&& name, typename ResourceDataType::Descriptor&& resourceArgs, const ResourceDataType& resource) + : VirtualResource(std::move(name)), _descriptor(resourceArgs), _resource(resource), _usage(static_cast(0)) { } template -Resource::Resource( - std::string&& name, typename ResourceDataType::Descriptor&& resourceArgs, - typename ResourceDataType::Usage usage) +Resource::Resource(std::string&& name, typename ResourceDataType::Descriptor&& resourceArgs, typename ResourceDataType::Usage usage) : VirtualResource(std::move(name)), _descriptor(resourceArgs), _usage(usage) { } template -Resource::Resource( - std::string&& name, typename ResourceDataType::Descriptor&& resourceArgs, - typename ResourceDataType::Usage usage, const ResourceDataType& resource) - : VirtualResource(std::move(name)), - _descriptor(resourceArgs), - _resource(resource), - _usage(usage) +Resource::Resource(std::string&& name, typename ResourceDataType::Descriptor&& resourceArgs, typename ResourceDataType::Usage usage, + const ResourceDataType& resource) + : VirtualResource(std::move(name)), _descriptor(resourceArgs), _resource(resource), _usage(usage) { } } // namespace RenderGraph diff --git a/Includes/VoxFlow/Core/FrameGraph/Resource.hpp b/Includes/VoxFlow/Core/FrameGraph/Resource.hpp index 5d8ca110..b5734731 100644 --- a/Includes/VoxFlow/Core/FrameGraph/Resource.hpp +++ b/Includes/VoxFlow/Core/FrameGraph/Resource.hpp @@ -4,10 +4,10 @@ #define VOXEL_FLOW_FRAME_GRAPH_RESOURCE_HPP #include -#include -#include #include +#include #include +#include #include #include #include @@ -24,10 +24,7 @@ class FrameGraph; class ResourceEdgeBase : public DependencyGraph::Edge { public: - explicit ResourceEdgeBase(DependencyGraph* ownerGraph, - DependencyGraph::Node* from, - DependencyGraph::Node* to) - : DependencyGraph::Edge(ownerGraph, from, to) + explicit ResourceEdgeBase(DependencyGraph* ownerGraph, DependencyGraph::Node* from, DependencyGraph::Node* to) : DependencyGraph::Edge(ownerGraph, from, to) { } }; @@ -35,8 +32,7 @@ class ResourceEdgeBase : public DependencyGraph::Edge class ResourceNode : public DependencyGraph::Node { public: - explicit ResourceNode(DependencyGraph* dependencyGraph, - ResourceHandle resourceHandle); + explicit ResourceNode(DependencyGraph* dependencyGraph, ResourceHandle resourceHandle); inline ResourceHandle getResourceHandle() const { @@ -93,9 +89,7 @@ class VirtualResource : private NonCopyable virtual void destroy(RenderResourceAllocator*) = 0; - virtual void resolveUsage(DependencyGraph* dependencyGraph, - const DependencyGraph::EdgeContainer& edges, - DependencyGraph::Edge* writerEdge) = 0; + virtual void resolveUsage(DependencyGraph* dependencyGraph, const DependencyGraph::EdgeContainer& edges, DependencyGraph::Edge* writerEdge) = 0; protected: std::string _resourceName; @@ -108,17 +102,10 @@ template class Resource : public VirtualResource { public: - explicit Resource(std::string&& name, - typename ResourceDataType::Descriptor&& resourceArgs); - explicit Resource(std::string&& name, - typename ResourceDataType::Descriptor&& resourceArgs, - const ResourceDataType& resource); - explicit Resource(std::string&& name, - typename ResourceDataType::Descriptor&& resourceArgs, - typename ResourceDataType::Usage usage); - explicit Resource(std::string&& name, - typename ResourceDataType::Descriptor&& resourceArgs, - typename ResourceDataType::Usage usage, + explicit Resource(std::string&& name, typename ResourceDataType::Descriptor&& resourceArgs); + explicit Resource(std::string&& name, typename ResourceDataType::Descriptor&& resourceArgs, const ResourceDataType& resource); + explicit Resource(std::string&& name, typename ResourceDataType::Descriptor&& resourceArgs, typename ResourceDataType::Usage usage); + explicit Resource(std::string&& name, typename ResourceDataType::Descriptor&& resourceArgs, typename ResourceDataType::Usage usage, const ResourceDataType& resource); ~Resource() = default; @@ -152,10 +139,7 @@ class Resource : public VirtualResource class ResourceEdge : public ResourceEdgeBase { public: - explicit ResourceEdge(DependencyGraph* ownerGraph, - DependencyGraph::Node* from, - DependencyGraph::Node* to, - typename ResourceDataType::Usage usage) + explicit ResourceEdge(DependencyGraph* ownerGraph, DependencyGraph::Node* from, DependencyGraph::Node* to, typename ResourceDataType::Usage usage) : ResourceEdgeBase(ownerGraph, from, to), _usage(usage) { } @@ -176,15 +160,11 @@ class Resource : public VirtualResource }; // Make connection to given pass node from resource node with specific usage - bool connect(DependencyGraph* dependencyGraph, ResourceNode* node, - PassNode* passNode, typename ResourceDataType::Usage usage); + bool connect(DependencyGraph* dependencyGraph, ResourceNode* node, PassNode* passNode, typename ResourceDataType::Usage usage); // Make connection to given resource node from pass node with specific usage - bool connect(DependencyGraph* dependencyGraph, PassNode* passNode, - ResourceNode* node, typename ResourceDataType::Usage usage); + bool connect(DependencyGraph* dependencyGraph, PassNode* passNode, ResourceNode* node, typename ResourceDataType::Usage usage); - void resolveUsage(DependencyGraph* dependencyGraph, - const DependencyGraph::EdgeContainer& edges, - DependencyGraph::Edge* writerEdge) override final; + void resolveUsage(DependencyGraph* dependencyGraph, const DependencyGraph::EdgeContainer& edges, DependencyGraph::Edge* writerEdge) override final; protected: typename ResourceDataType::Descriptor _descriptor; @@ -197,12 +177,9 @@ template class ImportedResource : public Resource { public: - ImportedResource(std::string&& name, - typename ResourceDataType::Descriptor&& resourceArgs, - typename ResourceDataType::Usage usage, + ImportedResource(std::string&& name, typename ResourceDataType::Descriptor&& resourceArgs, typename ResourceDataType::Usage usage, const ResourceDataType& resource) - : Resource(std::move(name), - std::move(resourceArgs), usage, resource) + : Resource(std::move(name), std::move(resourceArgs), usage, resource) { } ~ImportedResource() @@ -215,19 +192,16 @@ class ImportedResource : public Resource return true; } - void devirtualize(RenderResourceAllocator*) final {}; + void devirtualize(RenderResourceAllocator*) final{}; - void destroy(RenderResourceAllocator*) final {}; + void destroy(RenderResourceAllocator*) final{}; }; class ImportedRenderTarget : public ImportedResource { public: - ImportedRenderTarget(std::string&& name, - FrameGraphTexture::Descriptor&& resourceArgs, - FrameGraphRenderPass::ImportedDescriptor&& importedDesc, - const FrameGraphTexture& resource, - TextureView* textureView); + ImportedRenderTarget(std::string&& name, FrameGraphTexture::Descriptor&& resourceArgs, FrameGraphRenderPass::ImportedDescriptor&& importedDesc, + const FrameGraphTexture& resource, TextureView* textureView); ~ImportedRenderTarget(); inline TextureView* getTextureView() diff --git a/Includes/VoxFlow/Core/FrameGraph/ResourceHandle.hpp b/Includes/VoxFlow/Core/FrameGraph/ResourceHandle.hpp index 4079806d..aa64a043 100644 --- a/Includes/VoxFlow/Core/FrameGraph/ResourceHandle.hpp +++ b/Includes/VoxFlow/Core/FrameGraph/ResourceHandle.hpp @@ -16,12 +16,13 @@ constexpr const uint32_t INVALID_HANDLE_ID = UINT32_MAX; class ResourceHandle { public: - ResourceHandle() : _handleID(INVALID_HANDLE_ID){} + ResourceHandle() : _handleID(INVALID_HANDLE_ID) + { + } constexpr ResourceHandle(const uint32_t id) noexcept : _handleID(id) { } - constexpr ResourceHandle(const std::size_t id) noexcept - : _handleID(static_cast(id)) + constexpr ResourceHandle(const std::size_t id) noexcept : _handleID(static_cast(id)) { } @@ -72,8 +73,7 @@ constexpr const ResourceHandle INVALID_RESOURCE_HANDLE(INVALID_HANDLE_ID); template <> struct std::hash { - std::size_t operator()( - VoxFlow::RenderGraph::ResourceHandle const& handle) const noexcept; + std::size_t operator()(VoxFlow::RenderGraph::ResourceHandle const& handle) const noexcept; }; #endif \ No newline at end of file diff --git a/Includes/VoxFlow/Core/FrameGraph/TypeTraits.hpp b/Includes/VoxFlow/Core/FrameGraph/TypeTraits.hpp index 7172c7cd..1423d0b9 100644 --- a/Includes/VoxFlow/Core/FrameGraph/TypeTraits.hpp +++ b/Includes/VoxFlow/Core/FrameGraph/TypeTraits.hpp @@ -4,8 +4,8 @@ #define VOXEL_FLOW_FRAME_GRAPH_CONCEPT_HPP #include -#include #include +#include namespace VoxFlow { @@ -20,12 +20,10 @@ concept ResourceConcept = requires(Type resource) typename Type::Descriptor; typename Type::Usage; - requires std::is_default_constructible_v and - std::is_move_constructible_v; + requires std::is_default_constructible_v and std::is_move_constructible_v; { - resource.create((RenderResourceAllocator *)nullptr, std::string{}, - typename Type::Descriptor{}, typename Type::Usage{}) + resource.create((RenderResourceAllocator *)nullptr, std::string{}, typename Type::Descriptor{}, typename Type::Usage{}) } -> std::same_as; { resource.destroy((RenderResourceAllocator *)nullptr) @@ -36,8 +34,7 @@ template concept RenderPassConcept = requires(Type resource) { typename Type::Descriptor; - requires std::is_default_constructible_v and - std::is_move_constructible_v; + requires std::is_default_constructible_v and std::is_move_constructible_v; }; } // namespace RenderGraph diff --git a/Includes/VoxFlow/Core/Graphics/Commands/CommandBuffer.hpp b/Includes/VoxFlow/Core/Graphics/Commands/CommandBuffer.hpp index 2529b411..2223bee1 100644 --- a/Includes/VoxFlow/Core/Graphics/Commands/CommandBuffer.hpp +++ b/Includes/VoxFlow/Core/Graphics/Commands/CommandBuffer.hpp @@ -4,17 +4,17 @@ #define VOXEL_FLOW_COMMAND_BUFFER_HPP #include -#include -#include -#include #include #include +#include +#include #include #include -#include -#include -#include +#include +#include +#include #include +#include namespace VoxFlow { @@ -43,15 +43,13 @@ class CommandBuffer : private NonCopyable } // Begin command buffer to record new commands - void beginCommandBuffer(const FenceObject& fenceToSignal, - const std::string& debugName); - + void beginCommandBuffer(const FenceObject& fenceToSignal, const std::string& debugName); + // End command buffer recording void endCommandBuffer(); // Begin RenderPass scope - void beginRenderPass(const AttachmentGroup& attachmentGroup, - const RenderPassParams& passParams); + void beginRenderPass(const AttachmentGroup& attachmentGroup, const RenderPassParams& passParams); // End RenderPass scope void endRenderPass(); @@ -77,13 +75,11 @@ class CommandBuffer : private NonCopyable // Make final preparation to present recorded result to swapChain back // buffer. - void makeSwapChainFinalLayout(SwapChain* swapChain, - const uint32_t backBufferIndex); + void makeSwapChainFinalLayout(SwapChain* swapChain, const uint32_t backBufferIndex); // Bind given resource group to command buffer according to descriptor set // layout informations - void bindResourceGroup(SetSlotCategory setSlotCategory, - std::vector&& bindGroup); + void bindResourceGroup(SetSlotCategory setSlotCategory, std::vector&& bindGroup); // Commit pending resource bindings to command buffer void commitPendingResourceBindings(); @@ -93,30 +89,19 @@ class CommandBuffer : private NonCopyable return _fenceToSignal; } - void uploadBuffer(Buffer* dstBuffer, StagingBuffer* srcBuffer, - const uint32_t dstOffset, const uint32_t srcOffset, - const uint32_t size); + void uploadBuffer(Buffer* dstBuffer, StagingBuffer* srcBuffer, const uint32_t dstOffset, const uint32_t srcOffset, const uint32_t size); - void uploadTexture(Texture* dstTexture, StagingBuffer* srcBuffer, - const uint32_t dstOffset, const uint32_t srcOffset, - const uint32_t size); + void uploadTexture(Texture* dstTexture, StagingBuffer* srcBuffer, const uint32_t dstOffset, const uint32_t srcOffset, const uint32_t size); - void draw(uint32_t vertexCount, uint32_t instanceCount, - uint32_t firstVertex, uint32_t firstInstance); + void draw(uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance); - void drawIndexed(uint32_t indexCount, uint32_t instanceCount, - uint32_t firstIndex, int32_t vertexOffset, - uint32_t firstInstance); + void drawIndexed(uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance); - void addGlobalMemoryBarrier(ResourceAccessMask prevAccessMasks, - ResourceAccessMask nextAccessMasks); + void addGlobalMemoryBarrier(ResourceAccessMask prevAccessMasks, ResourceAccessMask nextAccessMasks); - void addMemoryBarrier( - ResourceView* view, ResourceAccessMask accessMask, - VkPipelineStageFlags nextStages = VK_PIPELINE_STAGE_NONE); + void addMemoryBarrier(ResourceView* view, ResourceAccessMask accessMask, VkPipelineStageFlags nextStages = VK_PIPELINE_STAGE_NONE); - void addExecutionBarrier(VkPipelineStageFlags prevStages, - VkPipelineStageFlags nextStages); + void addExecutionBarrier(VkPipelineStageFlags prevStages, VkPipelineStageFlags nextStages); private: LogicalDevice* _logicalDevice = nullptr; @@ -125,8 +110,7 @@ class CommandBuffer : private NonCopyable RenderTargetsInfo _boundRenderTargetsInfo; FenceObject _fenceToSignal = FenceObject::Default(); VkCommandBuffer _vkCommandBuffer = VK_NULL_HANDLE; - std::array, MAX_NUM_SET_SLOTS> - _pendingResourceBindings; + std::array, MAX_NUM_SET_SLOTS> _pendingResourceBindings; std::string _debugName; bool _hasBegun = false; diff --git a/Includes/VoxFlow/Core/Graphics/Commands/CommandConfig.hpp b/Includes/VoxFlow/Core/Graphics/Commands/CommandConfig.hpp index 95914806..c77bca46 100644 --- a/Includes/VoxFlow/Core/Graphics/Commands/CommandConfig.hpp +++ b/Includes/VoxFlow/Core/Graphics/Commands/CommandConfig.hpp @@ -8,18 +8,18 @@ namespace VoxFlow { -constexpr const char* MAIN_GRAPHICS_STREAM_NAME = "MainGraphicsStream"; -constexpr const char* ASYNC_UPLOAD_STREAM_NAME = "AsyncUploadStream"; -constexpr const char* ASYNC_COMPUTE_STREAM_NAME = "AsyncComputeStream"; -constexpr const char* IMMEDIATE_UPLOAD_STREAM_NAME = "ImmediateUploadStream"; +constexpr const char* MAIN_GRAPHICS_STREAM_NAME = "MainGraphicsStream"; +constexpr const char* ASYNC_UPLOAD_STREAM_NAME = "AsyncUploadStream"; +constexpr const char* ASYNC_COMPUTE_STREAM_NAME = "AsyncComputeStream"; +constexpr const char* IMMEDIATE_UPLOAD_STREAM_NAME = "ImmediateUploadStream"; -enum class CommandStreamUsage : uint8_t +enum class CommandStreamUsage : uint8_t { - Graphics = 0, - Compute = 1, - Transfer = 2, - Count = 4, - Undefined = 5, + Graphics = 0, + Compute = 1, + Transfer = 2, + Count = 4, + Undefined = 5, }; struct CommandStreamKey @@ -30,8 +30,7 @@ struct CommandStreamKey inline bool operator==(const CommandStreamKey& lhs, const CommandStreamKey& rhs) { - return (lhs._cmdStreamName == rhs._cmdStreamName) && - (lhs._cmdStreamUsage == rhs._cmdStreamUsage); + return (lhs._cmdStreamName == rhs._cmdStreamName) && (lhs._cmdStreamUsage == rhs._cmdStreamUsage); } } // namespace VoxFlow @@ -39,8 +38,7 @@ inline bool operator==(const CommandStreamKey& lhs, const CommandStreamKey& rhs) template <> struct std::hash { - std::size_t operator()( - VoxFlow::CommandStreamKey const& streamKey) const noexcept; + std::size_t operator()(VoxFlow::CommandStreamKey const& streamKey) const noexcept; }; #endif \ No newline at end of file diff --git a/Includes/VoxFlow/Core/Graphics/Commands/CommandJobSystem-Impl.hpp b/Includes/VoxFlow/Core/Graphics/Commands/CommandJobSystem-Impl.hpp index de315052..d988faef 100644 --- a/Includes/VoxFlow/Core/Graphics/Commands/CommandJobSystem-Impl.hpp +++ b/Includes/VoxFlow/Core/Graphics/Commands/CommandJobSystem-Impl.hpp @@ -3,9 +3,8 @@ #ifndef VOXEL_FLOW_COMMAND_JOB_SYSTEM_IMPL_HPP #define VOXEL_FLOW_COMMAND_JOB_SYSTEM_IMPL_HPP -#include -#include #include +#include #include #include @@ -21,8 +20,7 @@ struct CommandParameterIndex : std::integral_constant }; template -struct CommandParameterIndex - : std::integral_constant::value> +struct CommandParameterIndex : std::integral_constant::value> { }; @@ -30,18 +28,17 @@ class CommandParameterPacker { public: template - CommandParameterPacker(ParamTypes&&... params) - : _params{ static_cast(¶ms)... } + CommandParameterPacker(ParamTypes&&... params) : _params{ static_cast(¶ms)... } { } - template - ParamType getParam( const uint32_t index ) + template + ParamType getParam(const uint32_t index) { - return *(static_cast(_params[index])); + return *(static_cast(_params[index])); } -private: + private: std::vector _params; }; @@ -55,8 +52,7 @@ void CommandStream::addJob(CommandJobType jobType, CommandJobArgs&&... args) switch (jobType) { case CommandJobType::BeginRenderPass: - cmdBuffer->beginRenderPass(params.getParam(0), - params.getParam(1)); + cmdBuffer->beginRenderPass(params.getParam(0), params.getParam(1)); break; case CommandJobType::EndRenderPass: cmdBuffer->endRenderPass(); @@ -70,44 +66,30 @@ void CommandStream::addJob(CommandJobType jobType, CommandJobArgs&&... args) break; case CommandJobType::BindResourceGroup: - cmdBuffer->bindResourceGroup( - params.getParam(0), - params.getParam>(1)); + cmdBuffer->bindResourceGroup(params.getParam(0), params.getParam>(1)); break; case CommandJobType::UploadBuffer: - cmdBuffer->uploadBuffer(params.getParam(0), - params.getParam(1), - params.getParam(2), - params.getParam(3), + cmdBuffer->uploadBuffer(params.getParam(0), params.getParam(1), params.getParam(2), params.getParam(3), params.getParam(4)); break; case CommandJobType::UploadTexture: - cmdBuffer->uploadTexture(params.getParam(0), - params.getParam(1), - params.getParam(2), - params.getParam(3), - params.getParam(4)); + cmdBuffer->uploadTexture(params.getParam(0), params.getParam(1), params.getParam(2), + params.getParam(3), params.getParam(4)); break; case CommandJobType::Draw: - cmdBuffer->draw(params.getParam(0), - params.getParam(1), - params.getParam(2), - params.getParam(3)); + cmdBuffer->draw(params.getParam(0), params.getParam(1), params.getParam(2), params.getParam(3)); break; case CommandJobType::DrawIndexed: - cmdBuffer->drawIndexed( - params.getParam(0), params.getParam(1), - params.getParam(2), params.getParam(3), - params.getParam(4)); + cmdBuffer->drawIndexed(params.getParam(0), params.getParam(1), params.getParam(2), params.getParam(3), + params.getParam(4)); break; case CommandJobType::MakeSwapChainFinalLayout: - cmdBuffer->makeSwapChainFinalLayout(params.getParam(0), - params.getParam(1)); + cmdBuffer->makeSwapChainFinalLayout(params.getParam(0), params.getParam(1)); break; case CommandJobType::BindVertexBuffer: diff --git a/Includes/VoxFlow/Core/Graphics/Commands/CommandJobSystem.hpp b/Includes/VoxFlow/Core/Graphics/Commands/CommandJobSystem.hpp index 45a02fa9..8b7d474d 100644 --- a/Includes/VoxFlow/Core/Graphics/Commands/CommandJobSystem.hpp +++ b/Includes/VoxFlow/Core/Graphics/Commands/CommandJobSystem.hpp @@ -42,22 +42,19 @@ enum class CommandJobType class CommandStream final : private NonCopyable { public: - using CommandPoolStorage = - std::unordered_map>; - using CommandBufferStorage = - std::unordered_map>; + using CommandPoolStorage = std::unordered_map>; + using CommandBufferStorage = std::unordered_map>; public: explicit CommandStream(LogicalDevice* logicalDevice, Queue* queue); ~CommandStream(); - FenceObject flush(SwapChain* swapChain, const FrameContext* frameContext, - const bool waitAllCompletion); + FenceObject flush(SwapChain* swapChain, const FrameContext* frameContext, const bool waitAllCompletion); template void addJob(CommandJobType jobType, CommandJobArgs&&... args); -private: + private: CommandBuffer* getOrAllocateCommandBuffer(); CommandPool* getOrAllocateCommandPool(); diff --git a/Includes/VoxFlow/Core/Graphics/Commands/CommandPool.hpp b/Includes/VoxFlow/Core/Graphics/Commands/CommandPool.hpp index b9efff8f..8b50126e 100644 --- a/Includes/VoxFlow/Core/Graphics/Commands/CommandPool.hpp +++ b/Includes/VoxFlow/Core/Graphics/Commands/CommandPool.hpp @@ -35,11 +35,9 @@ class CommandPool : private NonCopyable private: struct CommandBufferComparator { - bool operator()(const std::shared_ptr& lhs, - const std::shared_ptr& rhs) + bool operator()(const std::shared_ptr& lhs, const std::shared_ptr& rhs) { - return lhs->getFenceToSignal().getFenceValue() > - rhs->getFenceToSignal().getFenceValue(); + return lhs->getFenceToSignal().getFenceValue() > rhs->getFenceToSignal().getFenceValue(); } }; @@ -47,10 +45,7 @@ class CommandPool : private NonCopyable LogicalDevice* _logicalDevice = nullptr; Queue* _ownerQueue = nullptr; VkCommandPool _commandPool = VK_NULL_HANDLE; - std::priority_queue, - std::vector>, - CommandBufferComparator> - _freedCommandBuffers; + std::priority_queue, std::vector>, CommandBufferComparator> _freedCommandBuffers; }; } // namespace VoxFlow diff --git a/Includes/VoxFlow/Core/Graphics/Commands/ResourceBarrierManager.hpp b/Includes/VoxFlow/Core/Graphics/Commands/ResourceBarrierManager.hpp index cdd649c2..88789ea5 100644 --- a/Includes/VoxFlow/Core/Graphics/Commands/ResourceBarrierManager.hpp +++ b/Includes/VoxFlow/Core/Graphics/Commands/ResourceBarrierManager.hpp @@ -17,30 +17,21 @@ class BufferView; class ResourceBarrierManager : private NonCopyable { public: - ResourceBarrierManager(CommandBuffer* commandBuffer) - : _commandBuffer(commandBuffer) + ResourceBarrierManager(CommandBuffer* commandBuffer) : _commandBuffer(commandBuffer) { } ~ResourceBarrierManager() = default; public: - void addGlobalMemoryBarrier(ResourceAccessMask prevAccessMasks, - ResourceAccessMask nextAccessMasks); + void addGlobalMemoryBarrier(ResourceAccessMask prevAccessMasks, ResourceAccessMask nextAccessMasks); - void addTextureMemoryBarrier(TextureView* textureView, - ResourceAccessMask accessMask, - VkPipelineStageFlags nextStageFlags); + void addTextureMemoryBarrier(TextureView* textureView, ResourceAccessMask accessMask, VkPipelineStageFlags nextStageFlags); - void addBufferMemoryBarrier(BufferView* bufferView, - ResourceAccessMask accessMask, - VkPipelineStageFlags nextStageFlags); + void addBufferMemoryBarrier(BufferView* bufferView, ResourceAccessMask accessMask, VkPipelineStageFlags nextStageFlags); - void addStagingBufferMemoryBarrier(StagingBufferView* stagingBufferView, - ResourceAccessMask accessMask, - VkPipelineStageFlags nextStageFlags); + void addStagingBufferMemoryBarrier(StagingBufferView* stagingBufferView, ResourceAccessMask accessMask, VkPipelineStageFlags nextStageFlags); - void addExecutionBarrier(VkPipelineStageFlags prevStageFlags, - VkPipelineStageFlags nextStageFlags); + void addExecutionBarrier(VkPipelineStageFlags prevStageFlags, VkPipelineStageFlags nextStageFlags); void commitPendingBarriers(const bool inRenderPassScope); @@ -52,8 +43,7 @@ class ResourceBarrierManager : private NonCopyable inline bool isValid() const { - return (_srcAccessFlags != VK_ACCESS_NONE) || - (_dstAccessFlags != VK_ACCESS_NONE); + return (_srcAccessFlags != VK_ACCESS_NONE) || (_dstAccessFlags != VK_ACCESS_NONE); } inline void reset() @@ -91,8 +81,7 @@ class ResourceBarrierManager : private NonCopyable inline bool isValid() const { - return (_srcStageFlags != VK_PIPELINE_STAGE_NONE) || - (_dstStageFlags != VK_PIPELINE_STAGE_NONE); + return (_srcStageFlags != VK_PIPELINE_STAGE_NONE) || (_dstStageFlags != VK_PIPELINE_STAGE_NONE); } inline void reset() diff --git a/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSet.hpp b/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSet.hpp index bdcc5380..fbc9d9a7 100644 --- a/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSet.hpp +++ b/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSet.hpp @@ -9,7 +9,7 @@ namespace VoxFlow { - + enum class SetSlotCategory : uint8_t { Bindless = 0, @@ -38,15 +38,13 @@ struct DescriptorInfo inline bool isValid() const { - return (_setCategory != SetSlotCategory::Undefined) && - (_descriptorCategory != DescriptorCategory::Undefined); + return (_setCategory != SetSlotCategory::Undefined) && (_descriptorCategory != DescriptorCategory::Undefined); } inline bool operator==(const DescriptorInfo& rhs) const { - return (_setCategory == rhs._setCategory) && - (_descriptorCategory == rhs._descriptorCategory) && - (_arraySize == rhs._arraySize) && (_binding == rhs._binding); + return (_setCategory == rhs._setCategory) && (_descriptorCategory == rhs._descriptorCategory) && (_arraySize == rhs._arraySize) && + (_binding == rhs._binding); } }; @@ -57,9 +55,7 @@ struct DescriptorSetLayoutDesc inline bool operator==(const DescriptorSetLayoutDesc& rhs) const { - return std::equal(_descriptorInfos.begin(), _descriptorInfos.end(), - rhs._descriptorInfos.begin(), - rhs._descriptorInfos.end()) && + return std::equal(_descriptorInfos.begin(), _descriptorInfos.end(), rhs._descriptorInfos.begin(), rhs._descriptorInfos.end()) && (_stageFlags == rhs._stageFlags); } }; @@ -69,15 +65,13 @@ struct DescriptorSetLayoutDesc template <> struct std::hash { - std::size_t operator()( - VoxFlow::DescriptorInfo const& info) const noexcept; + std::size_t operator()(VoxFlow::DescriptorInfo const& info) const noexcept; }; template <> struct std::hash { - std::size_t operator()( - VoxFlow::DescriptorSetLayoutDesc const& setLayout) const noexcept; + std::size_t operator()(VoxFlow::DescriptorSetLayoutDesc const& setLayout) const noexcept; }; #endif \ No newline at end of file diff --git a/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocator.hpp b/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocator.hpp index ea13426d..2fb13b87 100644 --- a/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocator.hpp +++ b/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocator.hpp @@ -19,8 +19,7 @@ class CommandBuffer; class DescriptorSetAllocator : private NonCopyable { protected: - explicit DescriptorSetAllocator(LogicalDevice* logicalDevice, - const bool isBindless); + explicit DescriptorSetAllocator(LogicalDevice* logicalDevice, const bool isBindless); public: ~DescriptorSetAllocator() override; @@ -33,14 +32,12 @@ class DescriptorSetAllocator : private NonCopyable } // Get descriptor set layout description for this allocator - [[nodiscard]] inline DescriptorSetLayoutDesc getDescriptorSetLayoutDesc() - const + [[nodiscard]] inline DescriptorSetLayoutDesc getDescriptorSetLayoutDesc() const { return _setLayoutDesc; } - bool initialize(const DescriptorSetLayoutDesc& setLayout, - const uint32_t numSets); + bool initialize(const DescriptorSetLayoutDesc& setLayout, const uint32_t numSets); private: void release(); @@ -67,14 +64,12 @@ class PooledDescriptorSetAllocator final : public DescriptorSetAllocator explicit PooledDescriptorSetAllocator(LogicalDevice* logicalDevice); ~PooledDescriptorSetAllocator() override; PooledDescriptorSetAllocator(PooledDescriptorSetAllocator&& other) noexcept; - PooledDescriptorSetAllocator& operator=( - PooledDescriptorSetAllocator&& other) noexcept; + PooledDescriptorSetAllocator& operator=(PooledDescriptorSetAllocator&& other) noexcept; // Get or create pooled descriptor set with predefined descriptor set layout // binding infos. Allocated descriptor set will be reused when the given // fence object is completed. - [[nodiscard]] VkDescriptorSet getOrCreatePooledDescriptorSet( - const FenceObject& fenceObject); + [[nodiscard]] VkDescriptorSet getOrCreatePooledDescriptorSet(const FenceObject& fenceObject); }; class BindlessDescriptorSetAllocator final : public DescriptorSetAllocator @@ -82,14 +77,11 @@ class BindlessDescriptorSetAllocator final : public DescriptorSetAllocator public: explicit BindlessDescriptorSetAllocator(LogicalDevice* logicalDevice); ~BindlessDescriptorSetAllocator() override; - BindlessDescriptorSetAllocator( - BindlessDescriptorSetAllocator&& other) noexcept; - BindlessDescriptorSetAllocator& operator=( - BindlessDescriptorSetAllocator&& other) noexcept; + BindlessDescriptorSetAllocator(BindlessDescriptorSetAllocator&& other) noexcept; + BindlessDescriptorSetAllocator& operator=(BindlessDescriptorSetAllocator&& other) noexcept; // Allocate bindless descriptor set which will be used forever. - [[nodiscard]] VkDescriptorSet getBindlessDescriptorSet( - const uint32_t setIndex, const FenceObject& fenceObject); + [[nodiscard]] VkDescriptorSet getBindlessDescriptorSet(const uint32_t setIndex, const FenceObject& fenceObject); }; } // namespace VoxFlow diff --git a/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocatorPool.hpp b/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocatorPool.hpp index 3abc2726..a8048f70 100644 --- a/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocatorPool.hpp +++ b/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocatorPool.hpp @@ -7,9 +7,9 @@ #include #include #include +#include #include #include -#include namespace VoxFlow { @@ -20,9 +20,7 @@ class ShaderModule; class DescriptorSetAllocatorPool : private NonCopyable { public: - using ContainerType = - std::unordered_map>; + using ContainerType = std::unordered_map>; public: explicit DescriptorSetAllocatorPool(LogicalDevice* logicalDevice); @@ -33,8 +31,7 @@ class DescriptorSetAllocatorPool : private NonCopyable public: // Get or create new descriptor set allocator for given descriptor set // layout description - std::shared_ptr getOrCreateDescriptorSetAllocator( - const DescriptorSetLayoutDesc& descSetLayout); + std::shared_ptr getOrCreateDescriptorSetAllocator(const DescriptorSetLayoutDesc& descSetLayout); // Get bindless descriptor set allocator std::shared_ptr getBindlessDescriptorSetAllocator(); diff --git a/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSetConfig.hpp b/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSetConfig.hpp index 40af1e2c..0080dcfd 100644 --- a/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSetConfig.hpp +++ b/Includes/VoxFlow/Core/Graphics/Descriptors/DescriptorSetConfig.hpp @@ -8,15 +8,13 @@ namespace VoxFlow { -constexpr uint32_t MAX_NUM_SET_SLOTS = - static_cast(SetSlotCategory::Count); +constexpr uint32_t MAX_NUM_SET_SLOTS = static_cast(SetSlotCategory::Count); -constexpr std::array(DescriptorCategory::Count)> - NUM_BINDLESS_DESCRIPTORS = { - 100000, - 100000, - 100000, - }; +constexpr std::array(DescriptorCategory::Count)> NUM_BINDLESS_DESCRIPTORS = { + 100000, + 100000, + 100000, +}; } // namespace VoxFlow diff --git a/Includes/VoxFlow/Core/Graphics/Pipelines/BasePipeline.hpp b/Includes/VoxFlow/Core/Graphics/Pipelines/BasePipeline.hpp index aea0d1f0..2699b2eb 100644 --- a/Includes/VoxFlow/Core/Graphics/Pipelines/BasePipeline.hpp +++ b/Includes/VoxFlow/Core/Graphics/Pipelines/BasePipeline.hpp @@ -21,8 +21,7 @@ class PipelineCache; class BasePipeline : NonCopyable { public: - explicit BasePipeline(PipelineStreamingContext* pipelineStreamingContext, - std::vector&& shaderFilePaths); + explicit BasePipeline(PipelineStreamingContext* pipelineStreamingContext, std::vector&& shaderFilePaths); ~BasePipeline() override; BasePipeline(BasePipeline&& other) noexcept; BasePipeline& operator=(BasePipeline&& other) noexcept; diff --git a/Includes/VoxFlow/Core/Graphics/Pipelines/ComputePipeline.hpp b/Includes/VoxFlow/Core/Graphics/Pipelines/ComputePipeline.hpp index 9066e791..8bc0234d 100644 --- a/Includes/VoxFlow/Core/Graphics/Pipelines/ComputePipeline.hpp +++ b/Includes/VoxFlow/Core/Graphics/Pipelines/ComputePipeline.hpp @@ -14,8 +14,7 @@ class ShaderModule; class ComputePipeline : public BasePipeline { public: - explicit ComputePipeline(PipelineStreamingContext* pipelineStreamingContext, - const ShaderPathInfo& shaderPath); + explicit ComputePipeline(PipelineStreamingContext* pipelineStreamingContext, const ShaderPathInfo& shaderPath); ~ComputePipeline() override; ComputePipeline(ComputePipeline&& other) noexcept; ComputePipeline& operator=(ComputePipeline&& other) noexcept; @@ -24,10 +23,11 @@ class ComputePipeline : public BasePipeline { return VK_PIPELINE_BIND_POINT_COMPUTE; } -public: + + public: /** - * Create compute pipeline with owned shader modules - */ + * Create compute pipeline with owned shader modules + */ bool initialize(); }; } // namespace VoxFlow diff --git a/Includes/VoxFlow/Core/Graphics/Pipelines/GraphicsPipeline.hpp b/Includes/VoxFlow/Core/Graphics/Pipelines/GraphicsPipeline.hpp index a4b664b9..407a7298 100644 --- a/Includes/VoxFlow/Core/Graphics/Pipelines/GraphicsPipeline.hpp +++ b/Includes/VoxFlow/Core/Graphics/Pipelines/GraphicsPipeline.hpp @@ -5,8 +5,8 @@ #include #include -#include #include +#include #include #include @@ -19,9 +19,7 @@ class RenderPass; class GraphicsPipeline : public BasePipeline { public: - explicit GraphicsPipeline( - PipelineStreamingContext* pipelineStreamingContext, - std::vector&& shaderPaths); + explicit GraphicsPipeline(PipelineStreamingContext* pipelineStreamingContext, std::vector&& shaderPaths); ~GraphicsPipeline() override; GraphicsPipeline(GraphicsPipeline&& other) noexcept; GraphicsPipeline& operator=(GraphicsPipeline&& other) noexcept; @@ -46,14 +44,14 @@ class GraphicsPipeline : public BasePipeline return _pipelineState; } -public: + public: /** - * Create graphics pipeline with given renderpass and owned shader modules - */ - bool initialize(RenderPass* renderPass); + * Create graphics pipeline with given renderpass and owned shader modules + */ + bool initialize(RenderPass* renderPass); -private: - GraphicsPipelineState _pipelineState; + private: + GraphicsPipelineState _pipelineState; }; } // namespace VoxFlow diff --git a/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineCache.hpp b/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineCache.hpp index 8ebecdb2..f6a6d5e0 100644 --- a/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineCache.hpp +++ b/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineCache.hpp @@ -13,8 +13,7 @@ class PipelineStreamingContext; class PipelineCache : NonCopyable { public: - explicit PipelineCache(PipelineStreamingContext* pipelineStreamingContext, - const uint32_t pipelineHash); + explicit PipelineCache(PipelineStreamingContext* pipelineStreamingContext, const uint32_t pipelineHash); ~PipelineCache() override; PipelineCache(PipelineCache&& other) noexcept; PipelineCache& operator=(PipelineCache&& other) noexcept; diff --git a/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineLayout.hpp b/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineLayout.hpp index f8475fa8..7b8592c2 100644 --- a/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineLayout.hpp +++ b/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineLayout.hpp @@ -4,12 +4,12 @@ #define VOXEL_FLOW_PIPELINE_LAYOUT_HPP #include -#include -#include #include +#include +#include +#include #include #include -#include namespace VoxFlow { @@ -49,8 +49,7 @@ class PipelineLayout : NonCopyable /** * @return shader variables used from this pipeline layout */ - [[nodiscard]] const ShaderVariableMap& getShaderVariableMap() - const + [[nodiscard]] const ShaderVariableMap& getShaderVariableMap() const { return _shaderVariableMap; } @@ -59,8 +58,7 @@ class PipelineLayout : NonCopyable * @return pipeline layout descriptor combined with all shader modules * inserted */ - [[nodiscard]] const PipelineLayoutDescriptor& getPipelineLayoutDescriptor() - const + [[nodiscard]] const PipelineLayoutDescriptor& getPipelineLayoutDescriptor() const { return _combinedPipelineLayoutDesc; } @@ -70,12 +68,11 @@ class PipelineLayout : NonCopyable * Combine given shader layout bindings into descriptor set layouts with conflict resolved. * The shader resource binding declared in different shader module can be resolved by this process. * Get descriptor set allocator from the pool which match to each combined descriptor set layout - * + * * @param setLayoutBindings shader layout binding which match to reflections of each shader module * @return whether pipeline layout creation is success or not */ - bool initialize(const std::vector& - combinedReflectionDataGroups); + bool initialize(const std::vector& combinedReflectionDataGroups); protected: /** diff --git a/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineLayoutDescriptor.hpp b/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineLayoutDescriptor.hpp index 01163f26..44288599 100644 --- a/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineLayoutDescriptor.hpp +++ b/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineLayoutDescriptor.hpp @@ -56,22 +56,19 @@ struct PipelineLayoutDescriptor template <> struct std::hash { - std::size_t operator()( - VoxFlow::VertexInputLayout const& inputLayout) const noexcept; + std::size_t operator()(VoxFlow::VertexInputLayout const& inputLayout) const noexcept; }; template <> struct std::hash { - std::size_t operator()( - VoxFlow::FragmentOutputLayout const& outputLayout) const noexcept; + std::size_t operator()(VoxFlow::FragmentOutputLayout const& outputLayout) const noexcept; }; template <> struct std::hash { - std::size_t operator()( - VoxFlow::PipelineLayoutDescriptor const& shaderLayout) const noexcept; + std::size_t operator()(VoxFlow::PipelineLayoutDescriptor const& shaderLayout) const noexcept; }; #endif \ No newline at end of file diff --git a/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineStateObject.hpp b/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineStateObject.hpp index ed0f9053..41880a15 100644 --- a/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineStateObject.hpp +++ b/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineStateObject.hpp @@ -4,9 +4,9 @@ #define VOXEL_FLOW_PIPELINE_STATE_OBJECT_HPP #include -#include -#include #include +#include +#include #include namespace VoxFlow @@ -40,7 +40,6 @@ struct StencilOperationState uint32_t compareMask = 0xff; uint32_t writeMask = 0xff; uint32_t reference = 0xff; - }; struct DepthStencilCreation @@ -72,16 +71,12 @@ struct BlendState VkBlendFactor destinationAlpha = VK_BLEND_FACTOR_ONE; VkBlendOp alphaOperation = VK_BLEND_OP_ADD; - VkColorComponentFlags colorMasks = - VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | - VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; + VkColorComponentFlags colorMasks = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; bool blendEnabled = false; bool separateBlend = false; - BlendState& setColor(VkBlendFactor sourceColor_, - VkBlendFactor destinationColor_, - VkBlendOp colorOperation_) + BlendState& setColor(VkBlendFactor sourceColor_, VkBlendFactor destinationColor_, VkBlendOp colorOperation_) { sourceColor = sourceColor_; destinationColor = destinationColor_; @@ -90,9 +85,7 @@ struct BlendState return *this; } - BlendState& setAlpha(VkBlendFactor sourceAlpha_, - VkBlendFactor destinationAlpha_, - VkBlendOp alphaOperation_) + BlendState& setAlpha(VkBlendFactor sourceAlpha_, VkBlendFactor destinationAlpha_, VkBlendOp alphaOperation_) { sourceAlpha = sourceAlpha_; destinationAlpha = destinationAlpha_; @@ -105,7 +98,6 @@ struct BlendState colorMasks = value; return *this; } - }; struct BlendStateCreation @@ -114,7 +106,7 @@ struct BlendStateCreation uint32_t activeStates = 0; BlendStateCreation& reset() - { + { activeStates = 0; return *this; } diff --git a/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineStreamingContext.hpp b/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineStreamingContext.hpp index f46a95e6..ba4584a4 100644 --- a/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineStreamingContext.hpp +++ b/Includes/VoxFlow/Core/Graphics/Pipelines/PipelineStreamingContext.hpp @@ -20,26 +20,19 @@ class ComputePipeline; class PipelineStreamingContext : NonCopyable { public: - explicit PipelineStreamingContext(LogicalDevice* logicalDevice, - const std::string& shaderRootPath); + explicit PipelineStreamingContext(LogicalDevice* logicalDevice, const std::string& shaderRootPath); ~PipelineStreamingContext() override; PipelineStreamingContext(PipelineStreamingContext&& other) noexcept; - PipelineStreamingContext& operator=( - PipelineStreamingContext&& other) noexcept; + PipelineStreamingContext& operator=(PipelineStreamingContext&& other) noexcept; public: - std::shared_ptr createGraphicsPipeline( - std::vector&& shaderPaths); + std::shared_ptr createGraphicsPipeline(std::vector&& shaderPaths); - std::shared_ptr createComputePipeline( - std::string&& shaderPath); + std::shared_ptr createComputePipeline(std::string&& shaderPath); - bool loadSpirvBinary(std::vector& outSpirvBinary, - const ShaderPathInfo& pathInfo, - const bool skipShaderCacheExport = false); + bool loadSpirvBinary(std::vector& outSpirvBinary, const ShaderPathInfo& pathInfo, const bool skipShaderCacheExport = false); - void exportPipelineCache(const size_t pipelineHash, - std::vector&& pipelineCacheBinary); + void exportPipelineCache(const size_t pipelineHash, std::vector&& pipelineCacheBinary); [[nodiscard]] inline LogicalDevice* getLogicalDevice() { @@ -48,10 +41,8 @@ class PipelineStreamingContext : NonCopyable private: ShaderPathInfo getShaderPathInfo(const std::string& path); - void getPipelineCacheIfExist(const std::string& pipelineCachePath, - std::vector& outCacheData); - void exportShaderCache(const ShaderPathInfo& pathInfo, - const std::vector& spirvBinary); + void getPipelineCacheIfExist(const std::string& pipelineCachePath, std::vector& outCacheData); + void exportShaderCache(const ShaderPathInfo& pathInfo, const std::vector& spirvBinary); private: LogicalDevice* _logicalDevice; diff --git a/Includes/VoxFlow/Core/Graphics/Pipelines/ResourceBindingLayout.hpp b/Includes/VoxFlow/Core/Graphics/Pipelines/ResourceBindingLayout.hpp index 2c3d4196..d0d9a844 100644 --- a/Includes/VoxFlow/Core/Graphics/Pipelines/ResourceBindingLayout.hpp +++ b/Includes/VoxFlow/Core/Graphics/Pipelines/ResourceBindingLayout.hpp @@ -4,8 +4,8 @@ #define VOXEL_FLOW_RESOURCE_BINDING_LAYOUT_HPP #include -#include #include +#include namespace VoxFlow { diff --git a/Includes/VoxFlow/Core/Graphics/Pipelines/ShaderModule.hpp b/Includes/VoxFlow/Core/Graphics/Pipelines/ShaderModule.hpp index 649d8213..7e12aa94 100644 --- a/Includes/VoxFlow/Core/Graphics/Pipelines/ShaderModule.hpp +++ b/Includes/VoxFlow/Core/Graphics/Pipelines/ShaderModule.hpp @@ -10,8 +10,8 @@ #include #include #include -#include #include +#include namespace VoxFlow { @@ -20,8 +20,7 @@ class PipelineStreamingContext; class ShaderModule : private NonCopyable { public: - explicit ShaderModule(PipelineStreamingContext* pipelineStreamingContext, - const ShaderPathInfo& shaderPath); + explicit ShaderModule(PipelineStreamingContext* pipelineStreamingContext, const ShaderPathInfo& shaderPath); ~ShaderModule() override; ShaderModule(ShaderModule&& other) noexcept; ShaderModule& operator=(ShaderModule&& other) noexcept; @@ -42,8 +41,7 @@ class ShaderModule : private NonCopyable /** * @return reflected shader layout binding of thie module */ - [[nodiscard]] inline const ShaderReflectionDataGroup* - getShaderReflectionDataGroup() const + [[nodiscard]] inline const ShaderReflectionDataGroup* getShaderReflectionDataGroup() const { return &_reflectionDataGroup; } @@ -60,9 +58,8 @@ class ShaderModule : private NonCopyable * slot category will be reflected * @return whether reflection is successful or not */ - static bool reflectShaderLayoutBindings( - ShaderReflectionDataGroup* reflectionDataGroup, - std::vector&& spirvCodes, VkShaderStageFlagBits stageBits); + static bool reflectShaderLayoutBindings(ShaderReflectionDataGroup* reflectionDataGroup, std::vector&& spirvCodes, + VkShaderStageFlagBits stageBits); protected: PipelineStreamingContext* _pipelineStreamingContext = nullptr; diff --git a/Includes/VoxFlow/Core/Graphics/Pipelines/ShaderUtil.hpp b/Includes/VoxFlow/Core/Graphics/Pipelines/ShaderUtil.hpp index 0a94755d..4a3dfd00 100644 --- a/Includes/VoxFlow/Core/Graphics/Pipelines/ShaderUtil.hpp +++ b/Includes/VoxFlow/Core/Graphics/Pipelines/ShaderUtil.hpp @@ -3,8 +3,8 @@ #ifndef VOXEL_FLOW_SHADER_UTIL_HPP #define VOXEL_FLOW_SHADER_UTIL_HPP -#include #include +#include #include #include @@ -20,20 +20,17 @@ class GlslangUtil /** * @return glslang stage flag from given filename extension */ - [[nodiscard]] static glslang_stage_t GlslangStageFromFilename( - const std::string_view filename); + [[nodiscard]] static glslang_stage_t GlslangStageFromFilename(const std::string_view filename); /** * @return glslang stage flag that match to given vulkan stage flag */ - [[nodiscard]] static glslang_stage_t VulkanStageToGlslangStage( - VkShaderStageFlagBits vkStage); + [[nodiscard]] static glslang_stage_t VulkanStageToGlslangStage(VkShaderStageFlagBits vkStage); /** * @return vulkan stage flag that match to given glslang stage flag */ - [[nodiscard]] static VkShaderStageFlagBits GlslangStageToVulkanStage( - glslang_stage_t glslangStage); + [[nodiscard]] static VkShaderStageFlagBits GlslangStageToVulkanStage(glslang_stage_t glslangStage); /** * Read given filename as glsl shader file and return its texts to dst @@ -42,8 +39,7 @@ class GlslangUtil * @param dst destination of shader file text read operation * @return whether file open is successful or not */ - [[nodiscard]] static bool ReadShaderFile(const char* filename, - std::vector* dst); + [[nodiscard]] static bool ReadShaderFile(const char* filename, std::vector* dst); /** * Compile given shader text with glslangValidator into SPIR-V binary @@ -53,9 +49,7 @@ class GlslangUtil * pointer * @return whether spir-v compilation is successful or not */ - [[nodiscard]] static bool CompileShader( - glslang_stage_t stage, const char* shaderSource, - std::vector* pSpirvBinary); + [[nodiscard]] static bool CompileShader(glslang_stage_t stage, const char* shaderSource, std::vector* pSpirvBinary); }; enum class ShaderFileType : uint8_t @@ -89,14 +83,11 @@ struct ShaderPathInfo class ShaderUtil { public: - [[nodiscard]] static VkShaderStageFlagBits ConvertToShaderStageFlag( - const ShaderStage stage); + [[nodiscard]] static VkShaderStageFlagBits ConvertToShaderStageFlag(const ShaderStage stage); - [[nodiscard]] static std::string ConvertToShaderFileExtension( - const ShaderStage stage); + [[nodiscard]] static std::string ConvertToShaderFileExtension(const ShaderStage stage); - [[nodiscard]] static bool ReadSpirvBinary(const char* filename, - std::vector* dst); + [[nodiscard]] static bool ReadSpirvBinary(const char* filename, std::vector* dst); }; } // namespace VoxFlow diff --git a/Includes/VoxFlow/Core/Graphics/RenderPass/FrameBuffer.hpp b/Includes/VoxFlow/Core/Graphics/RenderPass/FrameBuffer.hpp index a7222df1..8dc9746a 100644 --- a/Includes/VoxFlow/Core/Graphics/RenderPass/FrameBuffer.hpp +++ b/Includes/VoxFlow/Core/Graphics/RenderPass/FrameBuffer.hpp @@ -4,9 +4,9 @@ #define VOXEL_FLOW_FRAME_BUFFER_HPP #include +#include #include #include -#include namespace VoxFlow { diff --git a/Includes/VoxFlow/Core/Graphics/RenderPass/RenderPass.hpp b/Includes/VoxFlow/Core/Graphics/RenderPass/RenderPass.hpp index 04786178..c2c60c67 100644 --- a/Includes/VoxFlow/Core/Graphics/RenderPass/RenderPass.hpp +++ b/Includes/VoxFlow/Core/Graphics/RenderPass/RenderPass.hpp @@ -4,9 +4,9 @@ #define VOXEL_FLOW_RENDER_PASS_HPP #include +#include #include #include -#include namespace VoxFlow { diff --git a/Includes/VoxFlow/Core/Graphics/RenderPass/RenderPassCollector.hpp b/Includes/VoxFlow/Core/Graphics/RenderPass/RenderPassCollector.hpp index b6060644..01b6fbdb 100644 --- a/Includes/VoxFlow/Core/Graphics/RenderPass/RenderPassCollector.hpp +++ b/Includes/VoxFlow/Core/Graphics/RenderPass/RenderPassCollector.hpp @@ -25,8 +25,7 @@ class RenderPassCollector : private NonCopyable RenderPassCollector& operator=(RenderPassCollector&& other) noexcept; public: - [[nodiscard]] RenderPass* getOrCreateRenderPass( - RenderTargetLayoutKey layoutKey); + [[nodiscard]] RenderPass* getOrCreateRenderPass(RenderTargetLayoutKey layoutKey); [[nodiscard]] FrameBuffer* getOrCreateFrameBuffer(RenderTargetsInfo rtInfo); @@ -34,10 +33,8 @@ class RenderPassCollector : private NonCopyable private: LogicalDevice* _logicalDevice = nullptr; - std::unordered_map> - _renderPassCollection; - std::unordered_map> - _frameBufferCollection; + std::unordered_map> _renderPassCollection; + std::unordered_map> _frameBufferCollection; }; } // namespace VoxFlow diff --git a/Includes/VoxFlow/Core/Graphics/RenderPass/RenderPassParams.hpp b/Includes/VoxFlow/Core/Graphics/RenderPass/RenderPassParams.hpp index 97d4694f..fb532bcb 100644 --- a/Includes/VoxFlow/Core/Graphics/RenderPass/RenderPassParams.hpp +++ b/Includes/VoxFlow/Core/Graphics/RenderPass/RenderPassParams.hpp @@ -4,10 +4,10 @@ #define VOXEL_FLOW_RENDER_PASS_PARAMS_HPP #include -#include #include -#include +#include #include +#include namespace VoxFlow { @@ -30,23 +30,19 @@ enum class AttachmentMaskFlags : uint32_t }; IMPL_BITWISE_OPERATORS(AttachmentMaskFlags, uint32_t); -inline bool hasColorAspect(const AttachmentMaskFlags& attachmentFlags, - const uint32_t index) +inline bool hasColorAspect(const AttachmentMaskFlags& attachmentFlags, const uint32_t index) { - return (static_cast(attachmentFlags) & - (static_cast(AttachmentMaskFlags::Color0) << index)) > 0; + return (static_cast(attachmentFlags) & (static_cast(AttachmentMaskFlags::Color0) << index)) > 0; } inline bool hasDepthAspect(const AttachmentMaskFlags& attachmentFlags) { - return (static_cast(attachmentFlags) & - static_cast(AttachmentMaskFlags::Depth)) > 0; + return (static_cast(attachmentFlags) & static_cast(AttachmentMaskFlags::Depth)) > 0; } inline bool hasStencilAspect(const AttachmentMaskFlags& attachmentFlags) { - return (static_cast(attachmentFlags) & - static_cast(AttachmentMaskFlags::Stencil)) > 0; + return (static_cast(attachmentFlags) & static_cast(AttachmentMaskFlags::Stencil)) > 0; } struct RenderPassFlags @@ -57,9 +53,7 @@ struct RenderPassFlags inline bool operator==(const RenderPassFlags& rhs) const { - return (_clearFlags == rhs._clearFlags) && - (_loadFlags == rhs._loadFlags) && - (_storeFlags == rhs._storeFlags); + return (_clearFlags == rhs._clearFlags) && (_loadFlags == rhs._loadFlags) && (_storeFlags == rhs._storeFlags); } }; @@ -78,8 +72,7 @@ struct RenderPassParams template <> struct std::hash { - std::size_t operator()( - VoxFlow::RenderPassFlags const& passFlags) const noexcept; + std::size_t operator()(VoxFlow::RenderPassFlags const& passFlags) const noexcept; }; #endif \ No newline at end of file diff --git a/Includes/VoxFlow/Core/Graphics/RenderPass/RenderTargetGroup.hpp b/Includes/VoxFlow/Core/Graphics/RenderPass/RenderTargetGroup.hpp index 96529ea1..18976e6c 100644 --- a/Includes/VoxFlow/Core/Graphics/RenderPass/RenderTargetGroup.hpp +++ b/Includes/VoxFlow/Core/Graphics/RenderPass/RenderTargetGroup.hpp @@ -87,9 +87,7 @@ class AttachmentGroup { public: AttachmentGroup() = default; - explicit AttachmentGroup(std::vector&& colorAttachments, - Attachment&& depthStencilAttachment, - const uint32_t numSamples); + explicit AttachmentGroup(std::vector&& colorAttachments, Attachment&& depthStencilAttachment, const uint32_t numSamples); ~AttachmentGroup() = default; AttachmentGroup(const AttachmentGroup& rhs) { @@ -159,15 +157,13 @@ class AttachmentGroup template <> struct std::hash { - std::size_t operator()( - VoxFlow::RenderTargetLayoutKey const& layoutKey) const noexcept; + std::size_t operator()(VoxFlow::RenderTargetLayoutKey const& layoutKey) const noexcept; }; template <> struct std::hash { - std::size_t operator()( - VoxFlow::RenderTargetsInfo const& rtInfo) const noexcept; + std::size_t operator()(VoxFlow::RenderTargetsInfo const& rtInfo) const noexcept; }; #endif \ No newline at end of file diff --git a/Includes/VoxFlow/Core/Renderer/SceneRenderPass.hpp b/Includes/VoxFlow/Core/Renderer/SceneRenderPass.hpp index fd1b1811..9b7113f1 100644 --- a/Includes/VoxFlow/Core/Renderer/SceneRenderPass.hpp +++ b/Includes/VoxFlow/Core/Renderer/SceneRenderPass.hpp @@ -29,7 +29,7 @@ class SceneRenderPass : NonCopyable * @return self */ SceneRenderPass* addDependency(const std::string& passName); - + /** * @return get added dependency pass names */ diff --git a/Includes/VoxFlow/Core/Renderer/SceneRenderer.hpp b/Includes/VoxFlow/Core/Renderer/SceneRenderer.hpp index e702ad7d..fde008dc 100644 --- a/Includes/VoxFlow/Core/Renderer/SceneRenderer.hpp +++ b/Includes/VoxFlow/Core/Renderer/SceneRenderer.hpp @@ -4,8 +4,8 @@ #define VOXEL_FLOW_SCENE_RENDERER_HPP #include -#include #include +#include #include #include #include @@ -22,8 +22,7 @@ class SwapChain; class SceneRenderer final : NonCopyable { public: - SceneRenderer(LogicalDevice* mainLogicalDevice, - RenderGraph::FrameGraph* frameGraph); + SceneRenderer(LogicalDevice* mainLogicalDevice, RenderGraph::FrameGraph* frameGraph); ~SceneRenderer() override; public: @@ -34,13 +33,10 @@ class SceneRenderer final : NonCopyable void submitFrameGraph(); template ::value>> - SceneRenderPassType* getOrCreateSceneRenderPass(const std::string& passName, - Args... args) + typename = typename std::enable_if_t::value>> + SceneRenderPassType* getOrCreateSceneRenderPass(const std::string& passName, Args... args) { - SceneRenderPassType* newPassPtr = - new SceneRenderPassType(args...); + SceneRenderPassType* newPassPtr = new SceneRenderPassType(args...); std::unique_ptr newPass(newPassPtr); @@ -57,8 +53,7 @@ class SceneRenderer final : NonCopyable std::unique_ptr _renderResourceAllocator; CommandStreamKey _renderCmdStreamKey; - std::unordered_map> - _sceneRenderPasses; + std::unordered_map> _sceneRenderPasses; }; } // namespace VoxFlow diff --git a/Includes/VoxFlow/Core/Resources/Buffer.hpp b/Includes/VoxFlow/Core/Resources/Buffer.hpp index 51d37d14..2d824caa 100644 --- a/Includes/VoxFlow/Core/Resources/Buffer.hpp +++ b/Includes/VoxFlow/Core/Resources/Buffer.hpp @@ -23,8 +23,7 @@ class BufferView; class Buffer final : public RenderResource { public: - explicit Buffer(std::string_view&& debugName, LogicalDevice* logicalDevice, - RenderResourceMemoryPool* renderResourceMemoryPool); + explicit Buffer(std::string_view&& debugName, LogicalDevice* logicalDevice, RenderResourceMemoryPool* renderResourceMemoryPool); ~Buffer() override; public: @@ -33,12 +32,9 @@ class Buffer final : public RenderResource return _vkBuffer; } - [[nodiscard]] inline std::shared_ptr getView( - const uint32_t viewIndex) const + [[nodiscard]] inline std::shared_ptr getView(const uint32_t viewIndex) const { - VOX_ASSERT(viewIndex < static_cast(_ownedBufferViews.size()), - "Given Index ({}), Num Buffer Views ({})", viewIndex, - _ownedBufferViews.size()); + VOX_ASSERT(viewIndex < static_cast(_ownedBufferViews.size()), "Given Index ({}), Num Buffer Views ({})", viewIndex, _ownedBufferViews.size()); return _ownedBufferViews[viewIndex]; } @@ -88,8 +84,7 @@ class Buffer final : public RenderResource class BufferView : public ResourceView { public: - explicit BufferView(std::string&& debugName, LogicalDevice* logicalDevice, - RenderResource* ownerResource); + explicit BufferView(std::string&& debugName, LogicalDevice* logicalDevice, RenderResource* ownerResource); ~BufferView(); public: diff --git a/Includes/VoxFlow/Core/Resources/HandleAllocator.hpp b/Includes/VoxFlow/Core/Resources/HandleAllocator.hpp index 0dcc3365..e7e5a327 100644 --- a/Includes/VoxFlow/Core/Resources/HandleAllocator.hpp +++ b/Includes/VoxFlow/Core/Resources/HandleAllocator.hpp @@ -5,8 +5,8 @@ #include #include -#include #include +#include namespace VoxFlow { @@ -17,7 +17,6 @@ class HandleAllocator : private NonCopyable HandleAllocator(); ~HandleAllocator(); - private: std::unordered_map _handleArena; }; diff --git a/Includes/VoxFlow/Core/Resources/RenderResource.hpp b/Includes/VoxFlow/Core/Resources/RenderResource.hpp index 4643f985..1b6771eb 100644 --- a/Includes/VoxFlow/Core/Resources/RenderResource.hpp +++ b/Includes/VoxFlow/Core/Resources/RenderResource.hpp @@ -4,9 +4,9 @@ #define VOXEL_FLOW_RENDER_RESOURCE_HPP #include +#include #include #include -#include #include #include #include @@ -29,8 +29,7 @@ enum class RenderResourceType : uint8_t class RenderResource : private NonCopyable { public: - RenderResource(std::string_view&& debugName, LogicalDevice* logicalDevice, - RenderResourceMemoryPool* renderResourceMemoryPool); + RenderResource(std::string_view&& debugName, LogicalDevice* logicalDevice, RenderResourceMemoryPool* renderResourceMemoryPool); virtual ~RenderResource(){}; RenderResource(RenderResource&&) = default; RenderResource& operator=(RenderResource&&) = default; diff --git a/Includes/VoxFlow/Core/Resources/RenderResourceAllocator.hpp b/Includes/VoxFlow/Core/Resources/RenderResourceAllocator.hpp index aae2bb82..605f0a3c 100644 --- a/Includes/VoxFlow/Core/Resources/RenderResourceAllocator.hpp +++ b/Includes/VoxFlow/Core/Resources/RenderResourceAllocator.hpp @@ -18,17 +18,13 @@ class Buffer; class RenderResourceAllocator : private NonCopyable { public: - explicit RenderResourceAllocator( - LogicalDevice* logicalDevice, - RenderResourceMemoryPool* renderResourceMemoryPool); + explicit RenderResourceAllocator(LogicalDevice* logicalDevice, RenderResourceMemoryPool* renderResourceMemoryPool); ~RenderResourceAllocator(); public: - std::shared_ptr allocateTexture(const TextureInfo& textureInfo, - std::string&& debugName); + std::shared_ptr allocateTexture(const TextureInfo& textureInfo, std::string&& debugName); - std::shared_ptr allocateBuffer(const BufferInfo& bufferInfo, - std::string&& debugName); + std::shared_ptr allocateBuffer(const BufferInfo& bufferInfo, std::string&& debugName); protected: private: diff --git a/Includes/VoxFlow/Core/Resources/RenderResourceGarbageCollector.hpp b/Includes/VoxFlow/Core/Resources/RenderResourceGarbageCollector.hpp index 81b3308a..660453c7 100644 --- a/Includes/VoxFlow/Core/Resources/RenderResourceGarbageCollector.hpp +++ b/Includes/VoxFlow/Core/Resources/RenderResourceGarbageCollector.hpp @@ -17,10 +17,8 @@ struct RenderResourceGarbage std::function _deletionDelegate; RenderResourceGarbage() = default; - RenderResourceGarbage(std::vector&& accessedFences, - std::function&& deletionDelegate) - : _accessedFences(std::move(accessedFences)), - _deletionDelegate(std::move(deletionDelegate)) + RenderResourceGarbage(std::vector&& accessedFences, std::function&& deletionDelegate) + : _accessedFences(std::move(accessedFences)), _deletionDelegate(std::move(deletionDelegate)) { } ~RenderResourceGarbage() = default; @@ -52,7 +50,6 @@ struct RenderResourceGarbage } }; - class RenderResourceGarbageCollector : private Thread { public: diff --git a/Includes/VoxFlow/Core/Resources/RenderResourceMemoryPool.hpp b/Includes/VoxFlow/Core/Resources/RenderResourceMemoryPool.hpp index 2134d6f8..98c4751d 100644 --- a/Includes/VoxFlow/Core/Resources/RenderResourceMemoryPool.hpp +++ b/Includes/VoxFlow/Core/Resources/RenderResourceMemoryPool.hpp @@ -16,9 +16,7 @@ class Instance; class RenderResourceMemoryPool : private NonCopyable { public: - explicit RenderResourceMemoryPool(LogicalDevice* logicalDevice, - PhysicalDevice* physicalDevice, - Instance* instance); + explicit RenderResourceMemoryPool(LogicalDevice* logicalDevice, PhysicalDevice* physicalDevice, Instance* instance); ~RenderResourceMemoryPool(); public: diff --git a/Includes/VoxFlow/Core/Resources/ResourceTracker.hpp b/Includes/VoxFlow/Core/Resources/ResourceTracker.hpp index e511f529..686e8aaa 100644 --- a/Includes/VoxFlow/Core/Resources/ResourceTracker.hpp +++ b/Includes/VoxFlow/Core/Resources/ResourceTracker.hpp @@ -3,8 +3,8 @@ #ifndef VOXEL_FLOW_RESOURCE_TRACKER_HPP #define VOXEL_FLOW_RESOURCE_TRACKER_HPP -#include #include +#include #include #include #include @@ -31,16 +31,11 @@ class ResourceTracker : private NonCopyable public: template - Handle allocate(std::string_view&& debugName, - LogicalDevice* logicalDevice, - RenderResourceMemoryPool* memoryPool) + Handle allocate(std::string_view&& debugName, LogicalDevice* logicalDevice, RenderResourceMemoryPool* memoryPool) { - std::unique_ptr renderResource = - std::make_unique(std::move(debugName), - logicalDevice, memoryPool); + std::unique_ptr renderResource = std::make_unique(std::move(debugName), logicalDevice, memoryPool); - const HandleBase::HandleID handleID = - static_cast(_nextHandleID++); + const HandleBase::HandleID handleID = static_cast(_nextHandleID++); Handle resourceHandle(handleID); auto iter = _renderResources.find(handleID); @@ -78,8 +73,7 @@ class ResourceTracker : private NonCopyable } private: - std::unordered_map> - _renderResources; + std::unordered_map> _renderResources; HandleBase::HandleID _nextHandleID = 0; private: diff --git a/Includes/VoxFlow/Core/Resources/ResourceUploadContext.hpp b/Includes/VoxFlow/Core/Resources/ResourceUploadContext.hpp index 0a28d14c..fe94d087 100644 --- a/Includes/VoxFlow/Core/Resources/ResourceUploadContext.hpp +++ b/Includes/VoxFlow/Core/Resources/ResourceUploadContext.hpp @@ -4,8 +4,8 @@ #define VOXEL_FLOW_RESOURCE_UPLOAD_CONTEXT_HPP #include -#include #include +#include #include namespace VoxFlow @@ -40,11 +40,9 @@ class ResourceUploadContext : private NonCopyable ~ResourceUploadContext(); public: - void addPendingUpload(UploadPhase uploadPhase, RenderResource* uploadDst, - UploadData&& uploadData); + void addPendingUpload(UploadPhase uploadPhase, RenderResource* uploadDst, UploadData&& uploadData); - void processPendingUploads(UploadPhase uploadPhase, - CommandStream* cmdStream); + void processPendingUploads(UploadPhase uploadPhase, CommandStream* cmdStream); private: struct PendingUploadInfo @@ -55,17 +53,14 @@ class ResourceUploadContext : private NonCopyable UploadData _uploadData = {}; }; - void uploadResource(PendingUploadInfo&& uploadInfo, - CommandStream* cmdStream); + void uploadResource(PendingUploadInfo&& uploadInfo, CommandStream* cmdStream); void release(); -private: + private: RenderDevice* _renderDevice = nullptr; std::vector> _stagingBufferContexts; - std::array, - static_cast(UploadPhase::Count)> - _pendingUploadDatas; + std::array, static_cast(UploadPhase::Count)> _pendingUploadDatas; }; } // namespace VoxFlow diff --git a/Includes/VoxFlow/Core/Resources/ResourceView.hpp b/Includes/VoxFlow/Core/Resources/ResourceView.hpp index 5f9bc733..4691a9ac 100644 --- a/Includes/VoxFlow/Core/Resources/ResourceView.hpp +++ b/Includes/VoxFlow/Core/Resources/ResourceView.hpp @@ -3,11 +3,11 @@ #ifndef VOXEL_FLOW_BINDABLE_RESOURCE_VIEW_HPP #define VOXEL_FLOW_BINDABLE_RESOURCE_VIEW_HPP +#include #include #include -#include -#include #include +#include namespace VoxFlow { @@ -26,9 +26,7 @@ enum class ResourceViewType : uint8_t class ResourceView : private NonCopyable { public: - explicit ResourceView( - std::string&& debugName, LogicalDevice* logicalDevice, - RenderResource* ownerResource); + explicit ResourceView(std::string&& debugName, LogicalDevice* logicalDevice, RenderResource* ownerResource); virtual ~ResourceView(); virtual ResourceViewType getResourceViewType() const = 0; @@ -43,8 +41,7 @@ class ResourceView : private NonCopyable _lastAccessMask = accessMask; } - inline void setLastusedShaderStageFlags( - VkPipelineStageFlags stageFlags) + inline void setLastusedShaderStageFlags(VkPipelineStageFlags stageFlags) { _lastUsedStageFlags = stageFlags; diff --git a/Includes/VoxFlow/Core/Resources/StagingBuffer.hpp b/Includes/VoxFlow/Core/Resources/StagingBuffer.hpp index 6798b800..23f90e36 100644 --- a/Includes/VoxFlow/Core/Resources/StagingBuffer.hpp +++ b/Includes/VoxFlow/Core/Resources/StagingBuffer.hpp @@ -3,8 +3,8 @@ #ifndef VOXEL_FLOW_STAGING_BUFFER_HPP #define VOXEL_FLOW_STAGING_BUFFER_HPP -#include #include +#include #include #include #include @@ -22,9 +22,7 @@ class StagingBufferView; class StagingBuffer : public RenderResource { public: - explicit StagingBuffer(std::string_view&& debugName, - LogicalDevice* logicalDevice, - RenderResourceMemoryPool* renderResourceMemoryPool); + explicit StagingBuffer(std::string_view&& debugName, LogicalDevice* logicalDevice, RenderResourceMemoryPool* renderResourceMemoryPool); ~StagingBuffer() override; public: @@ -38,12 +36,9 @@ class StagingBuffer : public RenderResource return _size; } - [[nodiscard]] inline std::shared_ptr getView( - const uint32_t viewIndex) const + [[nodiscard]] inline std::shared_ptr getView(const uint32_t viewIndex) const { - VOX_ASSERT(viewIndex < static_cast(_ownedBufferViews.size()), - "Given Index ({}), Num Buffer Views ({})", viewIndex, - _ownedBufferViews.size()); + VOX_ASSERT(viewIndex < static_cast(_ownedBufferViews.size()), "Given Index ({}), Num Buffer Views ({})", viewIndex, _ownedBufferViews.size()); return _ownedBufferViews[viewIndex]; } @@ -59,8 +54,7 @@ class StagingBuffer : public RenderResource void release(); // Create buffer view and return its index for given buffer view info - std::optional createStagingBufferView( - const BufferViewInfo& viewInfo); + std::optional createStagingBufferView(const BufferViewInfo& viewInfo); // Get default created view that is pointing whole buffer [[nodiscard]] inline StagingBufferView* getDefaultView() const @@ -90,8 +84,7 @@ class StagingBuffer : public RenderResource class StagingBufferView : public ResourceView { public: - explicit StagingBufferView(std::string&& debugName, LogicalDevice* logicalDevice, - RenderResource* ownerResource); + explicit StagingBufferView(std::string&& debugName, LogicalDevice* logicalDevice, RenderResource* ownerResource); ~StagingBufferView(); public: diff --git a/Includes/VoxFlow/Core/Resources/StagingBufferContext.hpp b/Includes/VoxFlow/Core/Resources/StagingBufferContext.hpp index 96ab28b7..a5a2562c 100644 --- a/Includes/VoxFlow/Core/Resources/StagingBufferContext.hpp +++ b/Includes/VoxFlow/Core/Resources/StagingBufferContext.hpp @@ -17,14 +17,11 @@ class StagingBuffer; class StagingBufferContext : private NonCopyable { public: - explicit StagingBufferContext( - LogicalDevice* logicalDevice, - RenderResourceMemoryPool* renderResourceMemoryPool); + explicit StagingBufferContext(LogicalDevice* logicalDevice, RenderResourceMemoryPool* renderResourceMemoryPool); ~StagingBufferContext(); public: - std::tuple getOrCreateStagingBuffer( - const uint64_t size); + std::tuple getOrCreateStagingBuffer(const uint64_t size); void release(); diff --git a/Includes/VoxFlow/Core/Resources/Texture.hpp b/Includes/VoxFlow/Core/Resources/Texture.hpp index bcf5619d..f97aabcf 100644 --- a/Includes/VoxFlow/Core/Resources/Texture.hpp +++ b/Includes/VoxFlow/Core/Resources/Texture.hpp @@ -3,8 +3,8 @@ #ifndef VOXEL_FLOW_TEXTURE_HPP #define VOXEL_FLOW_TEXTURE_HPP -#include #include +#include #include #include #include @@ -23,14 +23,12 @@ extern bool hasDepthAspect(VkFormat vkFormat); extern bool hasStencilAspect(VkFormat vkFormat); extern VkImageAspectFlags convertToImageAspectFlags(VkFormat vkFormat); extern VkImageType convertToImageType(glm::uvec3 imageType); -extern VkImageViewType convertToImageViewType(VkImageType vkImageType, - glm::uvec3 extent); +extern VkImageViewType convertToImageViewType(VkImageType vkImageType, glm::uvec3 extent); class Texture final : public RenderResource { public: - explicit Texture(std::string_view&& debugName, LogicalDevice* logicalDevice, - RenderResourceMemoryPool* renderResourceMemoryPool); + explicit Texture(std::string_view&& debugName, LogicalDevice* logicalDevice, RenderResourceMemoryPool* renderResourceMemoryPool); ~Texture(); public: @@ -39,11 +37,9 @@ class Texture final : public RenderResource return _vkImage; } - [[nodiscard]] inline std::shared_ptr getView( - const uint32_t viewIndex) const + [[nodiscard]] inline std::shared_ptr getView(const uint32_t viewIndex) const { - VOX_ASSERT(viewIndex < static_cast(_ownedTextureViews.size()), - "Given Index ({}), Num Image Views ({})", viewIndex, + VOX_ASSERT(viewIndex < static_cast(_ownedTextureViews.size()), "Given Index ({}), Num Image Views ({})", viewIndex, _ownedTextureViews.size()); return _ownedTextureViews[viewIndex]; } @@ -69,8 +65,7 @@ class Texture final : public RenderResource // Create texture instance from swapchain image which should be separated // from others - bool initializeFromSwapChain(const TextureInfo& swapChainSurfaceInfo, - VkImage swapChainImage); + bool initializeFromSwapChain(const TextureInfo& swapChainSurfaceInfo, VkImage swapChainImage); // Create image view and return its index for given image view info std::optional createTextureView(const TextureViewInfo& viewInfo); @@ -90,8 +85,7 @@ class Texture final : public RenderResource class TextureView : public ResourceView { public: - explicit TextureView(std::string&& debugName, LogicalDevice* logicalDevice, - RenderResource* ownerResource); + explicit TextureView(std::string&& debugName, LogicalDevice* logicalDevice, RenderResource* ownerResource); ~TextureView(); public: diff --git a/Includes/VoxFlow/Core/Utils/ChromeTracer.hpp b/Includes/VoxFlow/Core/Utils/ChromeTracer.hpp index 6869b158..0104629e 100644 --- a/Includes/VoxFlow/Core/Utils/ChromeTracer.hpp +++ b/Includes/VoxFlow/Core/Utils/ChromeTracer.hpp @@ -10,7 +10,7 @@ #include #include #include -#endif // ENABLE_CHROME_TRACING +#endif // ENABLE_CHROME_TRACING namespace VoxFlow { @@ -71,7 +71,7 @@ class ChromeTracer private: ChromeTracer() = default; -private: + private: struct EventDescriptor { std::string _name; @@ -80,7 +80,7 @@ class ChromeTracer std::thread::id _threadId; }; -private: + private: std::mutex _mutex; nlohmann::json _json; std::chrono::system_clock::time_point _traceStartTime; @@ -90,11 +90,8 @@ class ChromeTracer #define HAS_TRACING_BEGIN() ChromeTracer::Get().hasBegun() #define BEGIN_CHROME_TRACING() ChromeTracer::Get().beginTrace() -#define END_CHROME_TRACING(traceFilePath) \ - ChromeTracer::Get().endTrace(traceFilePath) -#define SCOPED_CHROME_TRACING(eventName) \ - auto scopdChromeTracing##__LINE__ = \ - ChromeTracer::Get().createScopedTracingHandle(eventName); +#define END_CHROME_TRACING(traceFilePath) ChromeTracer::Get().endTrace(traceFilePath) +#define SCOPED_CHROME_TRACING(eventName) auto scopdChromeTracing##__LINE__ = ChromeTracer::Get().createScopedTracingHandle(eventName); #else #define HAS_TRACING_BEGIN() false #define BEGIN_CHROME_TRACING() diff --git a/Includes/VoxFlow/Core/Utils/DebugUtil.hpp b/Includes/VoxFlow/Core/Utils/DebugUtil.hpp index 09832baa..0a9f9fdf 100644 --- a/Includes/VoxFlow/Core/Utils/DebugUtil.hpp +++ b/Includes/VoxFlow/Core/Utils/DebugUtil.hpp @@ -13,25 +13,18 @@ class LogicalDevice; class DebugUtil { public: - static VKAPI_ATTR VkBool32 VKAPI_CALL - DebugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT severity, - VkDebugUtilsMessageTypeFlagsEXT flags, - const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, - void* userData); + static VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT severity, VkDebugUtilsMessageTypeFlagsEXT flags, + const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* userData); static void GlfwDebugCallback(int errorCode, const char* description); static void DebugBreak(); public: struct ScopedCmdLabel { - ScopedCmdLabel(VkCommandBuffer cmdBuffer, const char* label) - : _cmdBuffer(cmdBuffer) + ScopedCmdLabel(VkCommandBuffer cmdBuffer, const char* label) : _cmdBuffer(cmdBuffer) { const VkDebugUtilsLabelEXT labelInfo = { - .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, - .pNext = nullptr, - .pLabelName = label, - .color = { 1.0f, 1.0f, 1.0f, 1.0f } + .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, .pNext = nullptr, .pLabelName = label, .color = { 1.0f, 1.0f, 1.0f, 1.0f } }; vkCmdBeginDebugUtilsLabelEXT(_cmdBuffer, &labelInfo); } @@ -47,10 +40,7 @@ class DebugUtil void insertLabel(const char* label) const { const VkDebugUtilsLabelEXT labelInfo = { - .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, - .pNext = nullptr, - .pLabelName = label, - .color = { 1.0f, 1.0f, 1.0f, 1.0f } + .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, .pNext = nullptr, .pLabelName = label, .color = { 1.0f, 1.0f, 1.0f, 1.0f } }; vkCmdInsertDebugUtilsLabelEXT(_cmdBuffer, &labelInfo); } @@ -59,113 +49,80 @@ class DebugUtil VkCommandBuffer _cmdBuffer{ VK_NULL_HANDLE }; }; - static ScopedCmdLabel scopeLabel(VkCommandBuffer cmdBuffer, - const char* label) + static ScopedCmdLabel scopeLabel(VkCommandBuffer cmdBuffer, const char* label) { return { cmdBuffer, label }; } #if defined(VK_DEBUG_NAME_ENABLED) - static void setObjectName(LogicalDevice* logicalDevice, - VkCommandBuffer commandBuffer, const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkCommandBuffer commandBuffer, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(commandBuffer), - name, VK_OBJECT_TYPE_COMMAND_BUFFER); + setObjectName(logicalDevice, reinterpret_cast(commandBuffer), name, VK_OBJECT_TYPE_COMMAND_BUFFER); } - static void setObjectName(LogicalDevice* logicalDevice, - VkCommandPool commandPool, const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkCommandPool commandPool, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(commandPool), - name, VK_OBJECT_TYPE_COMMAND_POOL); + setObjectName(logicalDevice, reinterpret_cast(commandPool), name, VK_OBJECT_TYPE_COMMAND_POOL); } - static void setObjectName(LogicalDevice* logicalDevice, VkBuffer buffer, - const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkBuffer buffer, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(buffer), name, - VK_OBJECT_TYPE_BUFFER); + setObjectName(logicalDevice, reinterpret_cast(buffer), name, VK_OBJECT_TYPE_BUFFER); } - static void setObjectName(LogicalDevice* logicalDevice, VkImage image, - const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkImage image, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(image), name, - VK_OBJECT_TYPE_IMAGE); + setObjectName(logicalDevice, reinterpret_cast(image), name, VK_OBJECT_TYPE_IMAGE); } - static void setObjectName(LogicalDevice* logicalDevice, - VkImageView imageView, const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkImageView imageView, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(imageView), - name, VK_OBJECT_TYPE_IMAGE_VIEW); + setObjectName(logicalDevice, reinterpret_cast(imageView), name, VK_OBJECT_TYPE_IMAGE_VIEW); } - static void setObjectName(LogicalDevice* logicalDevice, - VkQueryPool queryPool, const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkQueryPool queryPool, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(queryPool), - name, VK_OBJECT_TYPE_QUERY_POOL); + setObjectName(logicalDevice, reinterpret_cast(queryPool), name, VK_OBJECT_TYPE_QUERY_POOL); } - static void setObjectName(LogicalDevice* logicalDevice, VkSampler sampler, - const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkSampler sampler, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(sampler), name, - VK_OBJECT_TYPE_SAMPLER); + setObjectName(logicalDevice, reinterpret_cast(sampler), name, VK_OBJECT_TYPE_SAMPLER); } - static void setObjectName(LogicalDevice* logicalDevice, VkPipeline pipeline, - const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkPipeline pipeline, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(pipeline), name, - VK_OBJECT_TYPE_PIPELINE); + setObjectName(logicalDevice, reinterpret_cast(pipeline), name, VK_OBJECT_TYPE_PIPELINE); } - static void setObjectName(LogicalDevice* logicalDevice, - VkRenderPass renderPass, const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkRenderPass renderPass, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(renderPass), - name, VK_OBJECT_TYPE_RENDER_PASS); + setObjectName(logicalDevice, reinterpret_cast(renderPass), name, VK_OBJECT_TYPE_RENDER_PASS); } - static void setObjectName(LogicalDevice* logicalDevice, VkFence fence, - const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkFence fence, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(fence), name, - VK_OBJECT_TYPE_FENCE); + setObjectName(logicalDevice, reinterpret_cast(fence), name, VK_OBJECT_TYPE_FENCE); } - static void setObjectName(LogicalDevice* logicalDevice, VkFramebuffer frameBuffer, - const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkFramebuffer frameBuffer, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(frameBuffer), - name, VK_OBJECT_TYPE_FRAMEBUFFER); + setObjectName(logicalDevice, reinterpret_cast(frameBuffer), name, VK_OBJECT_TYPE_FRAMEBUFFER); } - static void setObjectName(LogicalDevice* logicalDevice, - VkSemaphore semaphore, const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkSemaphore semaphore, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(semaphore), - name, VK_OBJECT_TYPE_SEMAPHORE); + setObjectName(logicalDevice, reinterpret_cast(semaphore), name, VK_OBJECT_TYPE_SEMAPHORE); } - static void setObjectName(LogicalDevice* logicalDevice, - VkDescriptorSet descSet, const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkDescriptorSet descSet, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(descSet), name, - VK_OBJECT_TYPE_DESCRIPTOR_SET); + setObjectName(logicalDevice, reinterpret_cast(descSet), name, VK_OBJECT_TYPE_DESCRIPTOR_SET); } - static void setObjectName(LogicalDevice* logicalDevice, - VkBufferView bufferView, const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkBufferView bufferView, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(bufferView), - name, VK_OBJECT_TYPE_BUFFER_VIEW); + setObjectName(logicalDevice, reinterpret_cast(bufferView), name, VK_OBJECT_TYPE_BUFFER_VIEW); } - static void setObjectName(LogicalDevice* logicalDevice, VkQueue queue, - const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkQueue queue, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(queue), name, - VK_OBJECT_TYPE_QUEUE); + setObjectName(logicalDevice, reinterpret_cast(queue), name, VK_OBJECT_TYPE_QUEUE); } - static void setObjectName(LogicalDevice* logicalDevice, - VkSwapchainKHR swapChain, const char* name) + static void setObjectName(LogicalDevice* logicalDevice, VkSwapchainKHR swapChain, const char* name) { - setObjectName(logicalDevice, reinterpret_cast(swapChain), - name, VK_OBJECT_TYPE_SWAPCHAIN_KHR); + setObjectName(logicalDevice, reinterpret_cast(swapChain), name, VK_OBJECT_TYPE_SWAPCHAIN_KHR); } private: - static void setObjectName(LogicalDevice* logicalDevice, uint64_t object, - const char* name, VkObjectType type); + static void setObjectName(LogicalDevice* logicalDevice, uint64_t object, const char* name, VkObjectType type); + public: #endif diff --git a/Includes/VoxFlow/Core/Utils/DecisionMaker.hpp b/Includes/VoxFlow/Core/Utils/DecisionMaker.hpp index 8e17f944..be1a89eb 100644 --- a/Includes/VoxFlow/Core/Utils/DecisionMaker.hpp +++ b/Includes/VoxFlow/Core/Utils/DecisionMaker.hpp @@ -15,16 +15,11 @@ class DecisionMaker public: DecisionMaker() = delete; - [[nodiscard]] static VkResult pickLayers( - std::vector& used, - const std::vector& properties, - const std::vector& requested); + [[nodiscard]] static VkResult pickLayers(std::vector& used, const std::vector& properties, + const std::vector& requested); - [[nodiscard]] static VkResult pickExtensions( - std::vector& used, - const std::vector& properties, - const std::vector& requested, - std::vector& featureStructs); + [[nodiscard]] static VkResult pickExtensions(std::vector& used, const std::vector& properties, + const std::vector& requested, std::vector& featureStructs); }; } // namespace VoxFlow diff --git a/Includes/VoxFlow/Core/Utils/DeviceInputSubscriber.hpp b/Includes/VoxFlow/Core/Utils/DeviceInputSubscriber.hpp index d291884c..e5d4eeff 100644 --- a/Includes/VoxFlow/Core/Utils/DeviceInputSubscriber.hpp +++ b/Includes/VoxFlow/Core/Utils/DeviceInputSubscriber.hpp @@ -4,8 +4,8 @@ #define VOXEL_FLOW_DEVICE_INPUT_REGISTRATOR_HPP #include -#include #include +#include struct GLFWwindow; @@ -29,8 +29,7 @@ enum class DeviceKeyInputType : uint32_t Count = Undefined }; -using DeviceKeyInputCallback = - std::function; +using DeviceKeyInputCallback = std::function; class DeviceInputSubscriber : NonCopyable { @@ -41,23 +40,19 @@ class DeviceInputSubscriber : NonCopyable static constexpr uint32_t sMaxAvailableNumWindows = 32U; template - using DeviceInputRegistration = - std::pair, InputType>; + using DeviceInputRegistration = std::pair, InputType>; public: void addObserveTargetWindow(GLFWwindow* window); void removeObserveTargetWindow(GLFWwindow* window); - void registerDeviceKeyCallback(const uint32_t targetWindowBits, - DeviceKeyInputCallback&& callback); + void registerDeviceKeyCallback(const uint32_t targetWindowBits, DeviceKeyInputCallback&& callback); -public: - void broadcastKeyInput(uint32_t windowIndex, DeviceKeyInputType key, - bool isReleased); + public: + void broadcastKeyInput(uint32_t windowIndex, DeviceKeyInputType key, bool isReleased); private: - std::vector> - _deviceKeyInputCallbacks; + std::vector> _deviceKeyInputCallbacks; }; } // namespace VoxFlow diff --git a/Includes/VoxFlow/Core/Utils/FenceObject.hpp b/Includes/VoxFlow/Core/Utils/FenceObject.hpp index 544b5bc5..521366d5 100644 --- a/Includes/VoxFlow/Core/Utils/FenceObject.hpp +++ b/Includes/VoxFlow/Core/Utils/FenceObject.hpp @@ -12,8 +12,7 @@ class Queue; class FenceObject { public: - explicit FenceObject(Queue* queue, const uint64_t initialTimelineValue) - : _queue(queue), _timelineValue(initialTimelineValue) + explicit FenceObject(Queue* queue, const uint64_t initialTimelineValue) : _queue(queue), _timelineValue(initialTimelineValue) { } ~FenceObject() = default; @@ -55,7 +54,7 @@ class FenceObject // Returns whether queue's current fence value reach to expected one (synced) bool isCompleted() const; - // Returns whether queue's current fence value reach to expected one. + // Returns whether queue's current fence value reach to expected one. // This could returns false even current fence value of queue reached to expected one. bool isCompletedCached() const; diff --git a/Includes/VoxFlow/Core/Utils/HashUtil.hpp b/Includes/VoxFlow/Core/Utils/HashUtil.hpp index 9034d003..1041512b 100644 --- a/Includes/VoxFlow/Core/Utils/HashUtil.hpp +++ b/Includes/VoxFlow/Core/Utils/HashUtil.hpp @@ -3,8 +3,8 @@ #ifndef VOXEL_FLOW_HASH_UTIL_HPP #define VOXEL_FLOW_HASH_UTIL_HPP -#include #include +#include namespace VoxFlow { @@ -13,8 +13,7 @@ template inline void hash_combine(uint32_t& seed, const Type& v) { std::hash hasher; - seed ^= static_cast(hasher(v)) + 0x9e3779b9 + (seed << 6) + - (seed >> 2); + seed ^= static_cast(hasher(v)) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } } // namespace VoxFlow diff --git a/Includes/VoxFlow/Core/Utils/Logger.hpp b/Includes/VoxFlow/Core/Utils/Logger.hpp index 52e4c5e0..d39baf44 100644 --- a/Includes/VoxFlow/Core/Utils/Logger.hpp +++ b/Includes/VoxFlow/Core/Utils/Logger.hpp @@ -10,17 +10,16 @@ namespace VoxFlow { // #ifdef VOXFLOW_DEBUG -#define VK_ASSERT(returnCode) \ - do \ - { \ - if (!static_cast(returnCode == VK_SUCCESS)) \ - { \ - spdlog::error("Vulkan Error ({}) at {}:{}.", \ - getVkResultString(returnCode), __FILE__, __LINE__); \ - if (returnCode == VK_ERROR_DEVICE_LOST) \ - DeviceRemoveTracker::get()->onDeviceRemoved(); \ - std::abort(); \ - } \ +#define VK_ASSERT(returnCode) \ + do \ + { \ + if (!static_cast(returnCode == VK_SUCCESS)) \ + { \ + spdlog::error("Vulkan Error ({}) at {}:{}.", getVkResultString(returnCode), __FILE__, __LINE__); \ + if (returnCode == VK_ERROR_DEVICE_LOST) \ + DeviceRemoveTracker::get()->onDeviceRemoved(); \ + std::abort(); \ + } \ } while (false) template diff --git a/Includes/VoxFlow/Core/Utils/MemoryAllocator.hpp b/Includes/VoxFlow/Core/Utils/MemoryAllocator.hpp index 30080e36..13ae2dec 100644 --- a/Includes/VoxFlow/Core/Utils/MemoryAllocator.hpp +++ b/Includes/VoxFlow/Core/Utils/MemoryAllocator.hpp @@ -5,10 +5,10 @@ #include #include +#include #include #include #include -#include namespace VoxFlow { @@ -28,8 +28,7 @@ class BlockAllocator : private NonCopyable protected: virtual uint64_t allocateInner(const uint64_t size) = 0; - virtual void deallocateInner(const uint64_t offset, - const uint64_t size) = 0; + virtual void deallocateInner(const uint64_t offset, const uint64_t size) = 0; virtual void defragmentInner() = 0; private: @@ -42,8 +41,7 @@ class FixedBlockAllocator : public BlockAllocator { public: FixedBlockAllocator() = default; - FixedBlockAllocator(const uint64_t blockSize, const uint64_t numBlocks, - const bool isThreadSafe); + FixedBlockAllocator(const uint64_t blockSize, const uint64_t numBlocks, const bool isThreadSafe); ~FixedBlockAllocator(); uint64_t allocateInner(const uint64_t size) override; diff --git a/Includes/VoxFlow/Core/Utils/RendererCommon.hpp b/Includes/VoxFlow/Core/Utils/RendererCommon.hpp index c4033a6f..4a6d5f6d 100644 --- a/Includes/VoxFlow/Core/Utils/RendererCommon.hpp +++ b/Includes/VoxFlow/Core/Utils/RendererCommon.hpp @@ -4,16 +4,16 @@ #define VOXEL_FLOW_RENDERER_COMMON_HPP #include -#include -#include -#include +#include #include -#include -#include -#include #include -#include +#include +#include +#include #include +#include +#include +#include namespace VoxFlow { @@ -41,37 +41,37 @@ struct FrameContext enum class BufferUsage : uint32_t { - ConstantBuffer = 0x00000001, - RwStructuredBuffer = 0x00000002, - VertexBuffer = 0x00000004, - IndexBuffer = 0x00000008, - IndirectCommand = 0x00000010, - CopyDst = 0x00000020, - CopySrc = 0x00000040, - Readback = 0x00000080, - Upload = 0x00000100, - Unknown = 0, + ConstantBuffer = 0x00000001, + RwStructuredBuffer = 0x00000002, + VertexBuffer = 0x00000004, + IndexBuffer = 0x00000008, + IndirectCommand = 0x00000010, + CopyDst = 0x00000020, + CopySrc = 0x00000040, + Readback = 0x00000080, + Upload = 0x00000100, + Unknown = 0, }; IMPL_BITWISE_OPERATORS(BufferUsage, uint32_t); -enum class ResourceAccessMask : uint32_t +enum class ResourceAccessMask : uint32_t { - Undefined = 0x00000001, - TransferSource = 0x00000002, - TransferDest = 0x00000004, - VertexBuffer = 0x00000008, - IndexBuffer = 0x00000010, - ColorAttachment = 0x00000020, - DepthAttachment = 0x00000040, - StencilAttachment = 0x00000080, - DepthReadOnly = 0x00000100, - StencilReadOnly = 0x00000200, - ShaderReadOnly = 0x00000400, - General = 0x00000800, - StorageBuffer = 0x00001000, - UniformBuffer = 0x00002000, - Present = 0x00004000, - IndirectBuffer = 0x00008000, + Undefined = 0x00000001, + TransferSource = 0x00000002, + TransferDest = 0x00000004, + VertexBuffer = 0x00000008, + IndexBuffer = 0x00000010, + ColorAttachment = 0x00000020, + DepthAttachment = 0x00000040, + StencilAttachment = 0x00000080, + DepthReadOnly = 0x00000100, + StencilReadOnly = 0x00000200, + ShaderReadOnly = 0x00000400, + General = 0x00000800, + StorageBuffer = 0x00001000, + UniformBuffer = 0x00002000, + Present = 0x00004000, + IndirectBuffer = 0x00008000, }; IMPL_BITWISE_OPERATORS(ResourceAccessMask, uint32_t); @@ -89,14 +89,14 @@ struct BufferViewInfo enum class TextureUsage : uint32_t { - RenderTarget = 0x00000001, - DepthStencil = 0x00000010, - Sampled = 0x00000100, - Storage = 0x00001000, - CopySrc = 0x00010000, - CopyDst = 0x00100000, - BackBuffer = 0x01000000, - Unknown = 0, + RenderTarget = 0x00000001, + DepthStencil = 0x00000010, + Sampled = 0x00000100, + Storage = 0x00001000, + CopySrc = 0x00010000, + CopyDst = 0x00100000, + BackBuffer = 0x01000000, + Unknown = 0, }; IMPL_BITWISE_OPERATORS(TextureUsage, uint32_t); diff --git a/Includes/VoxFlow/Core/Utils/VertexFormat.hpp b/Includes/VoxFlow/Core/Utils/VertexFormat.hpp index 0e397657..95038fe9 100644 --- a/Includes/VoxFlow/Core/Utils/VertexFormat.hpp +++ b/Includes/VoxFlow/Core/Utils/VertexFormat.hpp @@ -3,8 +3,8 @@ #ifndef VOXEL_FLOW_VERTEX_FORMAT_HPP #define VOXEL_FLOW_VERTEX_FORMAT_HPP -#include #include +#include namespace VoxFlow { @@ -88,8 +88,7 @@ enum class VertexFormat : uint32_t //! Position (3D), normal (3D), texture coordinates (2D), color in RGBA //! (4D), and tangent coordinates (4D). - Position3Normal3TexCoord2Color4Tangent4 = - Position3Normal3TexCoord2Color4 | Tangent4, + Position3Normal3TexCoord2Color4Tangent4 = Position3Normal3TexCoord2Color4 | Tangent4, }; //! Bit-wise operator for two vertex formats diff --git a/Includes/VoxFlow/Editor/RenderPass/PostProcessPass.hpp b/Includes/VoxFlow/Editor/RenderPass/PostProcessPass.hpp index 3b45ce94..9634d4d8 100644 --- a/Includes/VoxFlow/Editor/RenderPass/PostProcessPass.hpp +++ b/Includes/VoxFlow/Editor/RenderPass/PostProcessPass.hpp @@ -3,9 +3,9 @@ #ifndef VOXEL_FLOW_POST_PROCESS_PASS_HPP #define VOXEL_FLOW_POST_PROCESS_PASS_HPP +#include #include #include -#include #include namespace VoxFlow diff --git a/Includes/VoxFlow/Editor/RenderPass/SceneObjectPass.hpp b/Includes/VoxFlow/Editor/RenderPass/SceneObjectPass.hpp index e511fb8b..c7f4b052 100644 --- a/Includes/VoxFlow/Editor/RenderPass/SceneObjectPass.hpp +++ b/Includes/VoxFlow/Editor/RenderPass/SceneObjectPass.hpp @@ -3,9 +3,9 @@ #ifndef VOXEL_FLOW_SCENE_OBJECT_PASS_HPP #define VOXEL_FLOW_SCENE_OBJECT_PASS_HPP +#include #include #include -#include #include namespace VoxFlow diff --git a/Includes/VoxFlow/Editor/VoxEditor.hpp b/Includes/VoxFlow/Editor/VoxEditor.hpp index ef6261ac..fbfc74c1 100644 --- a/Includes/VoxFlow/Editor/VoxEditor.hpp +++ b/Includes/VoxFlow/Editor/VoxEditor.hpp @@ -21,7 +21,7 @@ class VoxEditor public: void runEditorLoop(); -private: + private: void processKeyInput(DeviceKeyInputType key, const bool isReleased); protected: diff --git a/Includes/VoxFlow/VoxFlow.hpp b/Includes/VoxFlow/VoxFlow.hpp index 9c2c18c1..3f7e3fe4 100644 --- a/Includes/VoxFlow/VoxFlow.hpp +++ b/Includes/VoxFlow/VoxFlow.hpp @@ -2,21 +2,82 @@ #define VOXEL_FLOW_HPP #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #endif \ No newline at end of file diff --git a/Sources/VoxFlow/Core/Devices/Context.cpp b/Sources/VoxFlow/Core/Devices/Context.cpp index 17c06a51..4cdc1972 100644 --- a/Sources/VoxFlow/Core/Devices/Context.cpp +++ b/Sources/VoxFlow/Core/Devices/Context.cpp @@ -4,8 +4,7 @@ namespace VoxFlow { -Context::Context(bool useValidation /* true */) - : useValidationLayer(useValidation) +Context::Context(bool useValidation /* true */) : useValidationLayer(useValidation) { if (useValidationLayer) { @@ -27,24 +26,18 @@ void Context::addInstanceLayer(const char* name, bool isOptional /* false */) instanceLayers.emplace_back(name, isOptional); } -void Context::addInstanceExtension(const char* name, - bool isOptional /* false */) +void Context::addInstanceExtension(const char* name, bool isOptional /* false */) { instanceExtensions.emplace_back(name, isOptional); } -void Context::addDeviceExtension(const char* name, bool isOptional /* false */, - void* pFeatureStruct /* nullptr */, - uint32_t version /* 0 */) +void Context::addDeviceExtension(const char* name, bool isOptional /* false */, void* pFeatureStruct /* nullptr */, uint32_t version /* 0 */) { deviceExtensions.emplace_back(name, isOptional, pFeatureStruct, version); } -void Context::addRequiredQueue(std::string&& queueName, VkQueueFlags queueFlag, - uint32_t queueCount, float queuePriority, - bool isMainQueue) +void Context::addRequiredQueue(std::string&& queueName, VkQueueFlags queueFlag, uint32_t queueCount, float queuePriority, bool isMainQueue) { - requiredQueues.emplace_back(std::move(queueName), queueFlag, queueCount, - queuePriority, isMainQueue); + requiredQueues.emplace_back(std::move(queueName), queueFlag, queueCount, queuePriority, isMainQueue); } } // namespace VoxFlow \ No newline at end of file diff --git a/Sources/VoxFlow/Core/Devices/DeviceQueryContext.cpp b/Sources/VoxFlow/Core/Devices/DeviceQueryContext.cpp index 0c8664dd..8375b5e8 100644 --- a/Sources/VoxFlow/Core/Devices/DeviceQueryContext.cpp +++ b/Sources/VoxFlow/Core/Devices/DeviceQueryContext.cpp @@ -7,8 +7,7 @@ namespace VoxFlow { -DeviceQueryContext::DeviceQueryContext(LogicalDevice* logicalDevice) - : _logicalDevice(logicalDevice) +DeviceQueryContext::DeviceQueryContext(LogicalDevice* logicalDevice) : _logicalDevice(logicalDevice) { } @@ -22,8 +21,7 @@ DeviceQueryContext::DeviceQueryContext(DeviceQueryContext&& context) noexcept operator=(std::move(context)); } -DeviceQueryContext& DeviceQueryContext::operator=( - DeviceQueryContext&& context) noexcept +DeviceQueryContext& DeviceQueryContext::operator=(DeviceQueryContext&& context) noexcept { if (this != &context) { @@ -47,8 +45,7 @@ bool DeviceQueryContext::initialize(DeviceQueryMode queryMode) queryType = VK_QUERY_TYPE_TIMESTAMP; break; default: - VOX_ASSERT(false, "Unknown query mode is given : {}", - static_cast(_queryMode)); + VOX_ASSERT(false, "Unknown query mode is given : {}", static_cast(_queryMode)); return false; } @@ -61,30 +58,23 @@ bool DeviceQueryContext::initialize(DeviceQueryMode queryMode) .pipelineStatistics = 0, }; - VK_ASSERT(vkCreateQueryPool(_logicalDevice->get(), &createInfo, nullptr, - &_vkQueryPool)); + VK_ASSERT(vkCreateQueryPool(_logicalDevice->get(), &createInfo, nullptr, &_vkQueryPool)); if (_vkQueryPool == VK_NULL_HANDLE) { return false; } #if defined(VK_DEBUG_NAME_ENABLED) - std::string queryPoolDebugName = fmt::format( - "QueryPool_QueryMode({})", static_cast(_queryMode)); - DebugUtil::setObjectName(_logicalDevice, _vkQueryPool, - queryPoolDebugName.c_str()); + std::string queryPoolDebugName = fmt::format("QueryPool_QueryMode({})", static_cast(_queryMode)); + DebugUtil::setObjectName(_logicalDevice, _vkQueryPool, queryPoolDebugName.c_str()); #endif const PhysicalDevice* physicalDevice = _logicalDevice->getPhysicalDevice(); - _timestampPeriod = - physicalDevice->getPhysicalDeviceProperties().limits.timestampPeriod; - - _queryDataBuffer = - new Buffer("QueryResultBuffer", _logicalDevice, - _logicalDevice->getDeviceDefaultResourceMemoryPool()); - if (_queryDataBuffer->makeAllocationResident(BufferInfo{ - ._size = sizeof(uint64_t) * kMaxQueryCount, - ._usage = BufferUsage::CopyDst | BufferUsage::Readback }) == false) + _timestampPeriod = physicalDevice->getPhysicalDeviceProperties().limits.timestampPeriod; + + _queryDataBuffer = new Buffer("QueryResultBuffer", _logicalDevice, _logicalDevice->getDeviceDefaultResourceMemoryPool()); + if (_queryDataBuffer->makeAllocationResident( + BufferInfo{ ._size = sizeof(uint64_t) * kMaxQueryCount, ._usage = BufferUsage::CopyDst | BufferUsage::Readback }) == false) { return false; } @@ -113,8 +103,7 @@ void DeviceQueryContext::beginTimestampQuery(VkCommandBuffer vkCommandBuffer) VOX_ASSERT((_numTimestamps % 2) == 0, "begin and end call must be in pair"); - vkCmdWriteTimestamp(vkCommandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - _vkQueryPool, _numTimestamps); + vkCmdWriteTimestamp(vkCommandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, _vkQueryPool, _numTimestamps); _numTimestamps++; } @@ -127,8 +116,7 @@ void DeviceQueryContext::endTimestampQuery(VkCommandBuffer vkCommandBuffer) VOX_ASSERT((_numTimestamps % 2) == 1, "begin and end call must be in pair"); - vkCmdWriteTimestamp(vkCommandBuffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - _vkQueryPool, _numTimestamps); + vkCmdWriteTimestamp(vkCommandBuffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, _vkQueryPool, _numTimestamps); _numTimestamps++; } diff --git a/Sources/VoxFlow/Core/Devices/Instance.cpp b/Sources/VoxFlow/Core/Devices/Instance.cpp index 1d7ecbeb..fc8035bf 100644 --- a/Sources/VoxFlow/Core/Devices/Instance.cpp +++ b/Sources/VoxFlow/Core/Devices/Instance.cpp @@ -1,10 +1,10 @@ // Author : snowapril +#include #include #include #include #include -#include namespace VoxFlow { @@ -13,27 +13,22 @@ Instance::Instance(const Context& ctx) glslang_initialize_process(); VK_ASSERT(volkInitialize()); - VkApplicationInfo appInfo = { - .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, - .pNext = nullptr, - .pApplicationName = ctx.appTitle.c_str(), - .applicationVersion = VK_MAKE_VERSION(0, 0, 0), - .pEngineName = ctx.appEngine.c_str(), - .engineVersion = 0, - .apiVersion = VK_MAKE_VERSION(ctx.majorVersion, ctx.minorVersion, 0) - }; + VkApplicationInfo appInfo = { .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, + .pNext = nullptr, + .pApplicationName = ctx.appTitle.c_str(), + .applicationVersion = VK_MAKE_VERSION(0, 0, 0), + .pEngineName = ctx.appEngine.c_str(), + .engineVersion = 0, + .apiVersion = VK_MAKE_VERSION(ctx.majorVersion, ctx.minorVersion, 0) }; uint32_t extensionCount; vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr); std::vector extensionProperties(extensionCount); - vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, - extensionProperties.data()); + vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, extensionProperties.data()); std::vector usedExtensions; std::vector featureStructs; - VK_ASSERT(DecisionMaker::pickExtensions(usedExtensions, extensionProperties, - ctx.instanceExtensions, - featureStructs)); + VK_ASSERT(DecisionMaker::pickExtensions(usedExtensions, extensionProperties, ctx.instanceExtensions, featureStructs)); uint32_t layerCount; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); @@ -41,19 +36,16 @@ Instance::Instance(const Context& ctx) vkEnumerateInstanceLayerProperties(&layerCount, layerProperties.data()); std::vector usedLayers; - VK_ASSERT(DecisionMaker::pickLayers(usedLayers, layerProperties, - ctx.instanceLayers)); - - [[maybe_unused]] VkInstanceCreateInfo instanceInfo = { - .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .pApplicationInfo = &appInfo, - .enabledLayerCount = static_cast(usedLayers.size()), - .ppEnabledLayerNames = usedLayers.data(), - .enabledExtensionCount = static_cast(usedExtensions.size()), - .ppEnabledExtensionNames = usedExtensions.data() - }; + VK_ASSERT(DecisionMaker::pickLayers(usedLayers, layerProperties, ctx.instanceLayers)); + + [[maybe_unused]] VkInstanceCreateInfo instanceInfo = { .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .pApplicationInfo = &appInfo, + .enabledLayerCount = static_cast(usedLayers.size()), + .ppEnabledLayerNames = usedLayers.data(), + .enabledExtensionCount = static_cast(usedExtensions.size()), + .ppEnabledExtensionNames = usedExtensions.data() }; // TODO(snowapril) : enable below features [[maybe_unused]] VkDebugUtilsMessengerCreateInfoEXT debugInfo; @@ -67,28 +59,27 @@ Instance::Instance(const Context& ctx) .pNext = nullptr, .flags = 0, .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT, - .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | - VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | - VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT, + .messageType = + VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT, .pfnUserCallback = DebugUtil::DebugCallback, .pUserData = nullptr, }; instanceInfo.pNext = &debugInfo; - // - // validationFeatures.sType = VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT; - // enabledValidationFeatures.push_back( - // VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT); - // enabledValidationFeatures.push_back( - // VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT); - // enabledValidationFeatures.push_back( - // VK_VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT); - // enabledValidationFeatures.push_back( - // VK_VALIDATION_FEATURE_ENABLE_DEBUG_PRINTF_EXT); - // enabledValidationFeatures.push_back( - // VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT); - // validationFeatures.enabledValidationFeatureCount = static_cast(enabledValidationFeatures.size()); - // validationFeatures.pEnabledValidationFeatures = enabledValidationFeatures.data(); - // debugInfo.pNext = &validationFeatures; + // + // validationFeatures.sType = VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT; + // enabledValidationFeatures.push_back( + // VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT); + // enabledValidationFeatures.push_back( + // VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT); + // enabledValidationFeatures.push_back( + // VK_VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT); + // enabledValidationFeatures.push_back( + // VK_VALIDATION_FEATURE_ENABLE_DEBUG_PRINTF_EXT); + // enabledValidationFeatures.push_back( + // VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT); + // validationFeatures.enabledValidationFeatureCount = static_cast(enabledValidationFeatures.size()); + // validationFeatures.pEnabledValidationFeatures = enabledValidationFeatures.data(); + // debugInfo.pNext = &validationFeatures; } VK_ASSERT(vkCreateInstance(&instanceInfo, nullptr, &_instance)); @@ -96,8 +87,7 @@ Instance::Instance(const Context& ctx) if (ctx.useValidationLayer) { - VK_ASSERT(vkCreateDebugUtilsMessengerEXT(_instance, &debugInfo, nullptr, - &_debugMessenger)); + VK_ASSERT(vkCreateDebugUtilsMessengerEXT(_instance, &debugInfo, nullptr, &_debugMessenger)); } } diff --git a/Sources/VoxFlow/Core/Devices/LogicalDevice.cpp b/Sources/VoxFlow/Core/Devices/LogicalDevice.cpp index fb404d2d..e57f83e0 100644 --- a/Sources/VoxFlow/Core/Devices/LogicalDevice.cpp +++ b/Sources/VoxFlow/Core/Devices/LogicalDevice.cpp @@ -5,10 +5,10 @@ #include #include #include -#include -#include -#include #include +#include +#include +#include #include #include #include @@ -19,29 +19,20 @@ namespace VoxFlow { -LogicalDevice::LogicalDevice(const Context& ctx, PhysicalDevice* physicalDevice, - Instance* instance, - const LogicalDeviceType deviceType) - : _physicalDevice(physicalDevice), - _instance(instance), - _deviceType(deviceType) +LogicalDevice::LogicalDevice(const Context& ctx, PhysicalDevice* physicalDevice, Instance* instance, const LogicalDeviceType deviceType) + : _physicalDevice(physicalDevice), _instance(instance), _deviceType(deviceType) { - const std::vector layerProperties = - physicalDevice->getPossibleLayers(); + const std::vector layerProperties = physicalDevice->getPossibleLayers(); std::vector usedLayers; // As instance layers are same with device layers, we can use it again - VK_ASSERT(DecisionMaker::pickLayers(usedLayers, layerProperties, - ctx.instanceLayers)); + VK_ASSERT(DecisionMaker::pickLayers(usedLayers, layerProperties, ctx.instanceLayers)); - const std::vector extensionProperties = - physicalDevice->getPossibleExtensions(); + const std::vector extensionProperties = physicalDevice->getPossibleExtensions(); std::vector usedExtensions; std::vector featureStructs; - VK_ASSERT(DecisionMaker::pickExtensions(usedExtensions, extensionProperties, - ctx.deviceExtensions, - featureStructs)); + VK_ASSERT(DecisionMaker::pickExtensions(usedExtensions, extensionProperties, ctx.deviceExtensions, featureStructs)); const auto queueFamilies = physicalDevice->getQueueFamilyProperties(); @@ -61,18 +52,14 @@ LogicalDevice::LogicalDevice(const Context& ctx, PhysicalDevice* physicalDevice, for (const auto& queueFamily : queueFamilies) { - if ((queueFamily.queueCount >= requiredQueue.queueCount) && - (queueFamily.queueFlags && requiredQueue.flag)) + if ((queueFamily.queueCount >= requiredQueue.queueCount) && (queueFamily.queueFlags && requiredQueue.flag)) { familyIndex = index; queueFlags = queueFamily.queueFlags; } if (familyIndex.has_value() && - std::find(requiredQueueFamilyIndices.begin(), - requiredQueueFamilyIndices.end(), - familyIndex.value()) == - requiredQueueFamilyIndices.end()) + std::find(requiredQueueFamilyIndices.begin(), requiredQueueFamilyIndices.end(), familyIndex.value()) == requiredQueueFamilyIndices.end()) { break; } @@ -81,21 +68,19 @@ LogicalDevice::LogicalDevice(const Context& ctx, PhysicalDevice* physicalDevice, if (familyIndex.has_value() == false) { - spdlog::error("Failed to find required queue [{}] in this device.", - requiredQueue.queueName); + spdlog::error("Failed to find required queue [{}] in this device.", requiredQueue.queueName); std::abort(); } else { requiredQueueFlags.push_back(queueFlags.value()); requiredQueueFamilyIndices.push_back(familyIndex.value()); - queueInfos.push_back( - { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .queueFamilyIndex = familyIndex.value(), - .queueCount = requiredQueue.queueCount, - .pQueuePriorities = &requiredQueue.priority }); + queueInfos.push_back({ .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .queueFamilyIndex = familyIndex.value(), + .queueCount = requiredQueue.queueCount, + .pQueuePriorities = &requiredQueue.priority }); } } @@ -119,35 +104,30 @@ LogicalDevice::LogicalDevice(const Context& ctx, PhysicalDevice* physicalDevice, features12.descriptorBindingStorageBufferUpdateAfterBind = VK_TRUE; pNextChain = &features12; - [[maybe_unused]] const VkDeviceCreateInfo deviceInfo = { - .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, - .pNext = pNextChain, - .flags = 0, - .queueCreateInfoCount = static_cast(queueInfos.size()), - .pQueueCreateInfos = queueInfos.data(), - .enabledLayerCount = static_cast(usedLayers.size()), - .ppEnabledLayerNames = usedLayers.data(), - .enabledExtensionCount = static_cast(usedExtensions.size()), - .ppEnabledExtensionNames = usedExtensions.data(), - .pEnabledFeatures = nullptr - }; - - VK_ASSERT( - vkCreateDevice(physicalDevice->get(), &deviceInfo, nullptr, &_device)); + [[maybe_unused]] const VkDeviceCreateInfo deviceInfo = { .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, + .pNext = pNextChain, + .flags = 0, + .queueCreateInfoCount = static_cast(queueInfos.size()), + .pQueueCreateInfos = queueInfos.data(), + .enabledLayerCount = static_cast(usedLayers.size()), + .ppEnabledLayerNames = usedLayers.data(), + .enabledExtensionCount = static_cast(usedExtensions.size()), + .ppEnabledExtensionNames = usedExtensions.data(), + .pEnabledFeatures = nullptr }; + + VK_ASSERT(vkCreateDevice(physicalDevice->get(), &deviceInfo, nullptr, &_device)); std::unordered_map queueIndicesPerFamily; for (size_t i = 0; i < ctx.requiredQueues.size(); ++i) { VkQueue queueHandle; - vkGetDeviceQueue(_device, requiredQueueFamilyIndices[i], 0, - &queueHandle); + vkGetDeviceQueue(_device, requiredQueueFamilyIndices[i], 0, &queueHandle); VOX_ASSERT(queueHandle != VK_NULL_HANDLE, "Failed to get device queue"); if (queueHandle != VK_NULL_HANDLE) { - std::unordered_map::iterator findIt = - queueIndicesPerFamily.find(requiredQueueFamilyIndices[i]); + std::unordered_map::iterator findIt = queueIndicesPerFamily.find(requiredQueueFamilyIndices[i]); uint32_t queueIndex = 0U; if (findIt != queueIndicesPerFamily.end()) @@ -156,13 +136,10 @@ LogicalDevice::LogicalDevice(const Context& ctx, PhysicalDevice* physicalDevice, } else { - queueIndicesPerFamily.insert( - std::make_pair(requiredQueueFamilyIndices[i], queueIndex)); + queueIndicesPerFamily.insert(std::make_pair(requiredQueueFamilyIndices[i], queueIndex)); } - Queue* queue = new Queue(ctx.requiredQueues[i].queueName, this, - requiredQueueFlags[i], queueHandle, - requiredQueueFamilyIndices[i], queueIndex); + Queue* queue = new Queue(ctx.requiredQueues[i].queueName, this, requiredQueueFlags[i], queueHandle, requiredQueueFamilyIndices[i], queueIndex); VOX_ASSERT(queue != nullptr, "Failed to allocate queue"); @@ -179,20 +156,16 @@ LogicalDevice::LogicalDevice(const Context& ctx, PhysicalDevice* physicalDevice, volkLoadDevice(_device); DeviceRemoveTracker::get()->addLogicalDeviceToTrack(this); - _deviceDefaultResourceMemoryPool = - new RenderResourceMemoryPool(this, _physicalDevice, _instance); + _deviceDefaultResourceMemoryPool = new RenderResourceMemoryPool(this, _physicalDevice, _instance); - VOX_ASSERT( - _deviceDefaultResourceMemoryPool->initialize(), - "Failed to initialize device-default render resource memory pool"); + VOX_ASSERT(_deviceDefaultResourceMemoryPool->initialize(), "Failed to initialize device-default render resource memory pool"); _renderPassCollector = new RenderPassCollector(this); _descriptorSetAllocatorPool = new DescriptorSetAllocatorPool(this); initializeCommandStreams(); - _pipelineStreamingContext = std::make_unique( - this, RESOURCES_DIR "Shaders/"); + _pipelineStreamingContext = std::make_unique(this, RESOURCES_DIR "Shaders/"); } LogicalDevice::~LogicalDevice() @@ -201,8 +174,7 @@ LogicalDevice::~LogicalDevice() release(); } -LogicalDevice::LogicalDevice(LogicalDevice&& other) noexcept - : _device(other._device), _queueMap(std::move(other._queueMap)) +LogicalDevice::LogicalDevice(LogicalDevice&& other) noexcept : _device(other._device), _queueMap(std::move(other._queueMap)) { // Do nothing } @@ -224,14 +196,11 @@ Queue* LogicalDevice::getQueuePtr(const std::string& queueName) return iter->second; } -std::shared_ptr LogicalDevice::addSwapChain( - const char* title, const glm::ivec2 resolution) +std::shared_ptr LogicalDevice::addSwapChain(const char* title, const glm::ivec2 resolution) { - std::shared_ptr swapChain = std::make_shared( - _instance, _physicalDevice, this, _mainQueue, title, resolution); + std::shared_ptr swapChain = std::make_shared(_instance, _physicalDevice, this, _mainQueue, title, resolution); - VOX_ASSERT(swapChain->create(), "Failed to create swapchain (name : {})", - title); + VOX_ASSERT(swapChain->create(), "Failed to create swapchain (name : {})", title); _swapChains.push_back(swapChain); @@ -242,25 +211,17 @@ void LogicalDevice::initializeCommandStreams() { _commandJobSystem = std::make_unique(this); - _commandJobSystem->createCommandStream( - CommandStreamKey{ ._cmdStreamName = MAIN_GRAPHICS_STREAM_NAME, - ._cmdStreamUsage = CommandStreamUsage::Graphics }, - getQueuePtr("MainGraphics")); - - _commandJobSystem->createCommandStream( - CommandStreamKey{ ._cmdStreamName = ASYNC_COMPUTE_STREAM_NAME, - ._cmdStreamUsage = CommandStreamUsage::Compute }, - getQueuePtr("AsyncCompute")); - - _commandJobSystem->createCommandStream( - CommandStreamKey{ ._cmdStreamName = ASYNC_UPLOAD_STREAM_NAME, - ._cmdStreamUsage = CommandStreamUsage::Transfer }, - getQueuePtr("AsyncUpload")); - - _commandJobSystem->createCommandStream( - CommandStreamKey{ ._cmdStreamName = IMMEDIATE_UPLOAD_STREAM_NAME, - ._cmdStreamUsage = CommandStreamUsage::Transfer }, - getQueuePtr("ImmediateUpload")); + _commandJobSystem->createCommandStream(CommandStreamKey{ ._cmdStreamName = MAIN_GRAPHICS_STREAM_NAME, ._cmdStreamUsage = CommandStreamUsage::Graphics }, + getQueuePtr("MainGraphics")); + + _commandJobSystem->createCommandStream(CommandStreamKey{ ._cmdStreamName = ASYNC_COMPUTE_STREAM_NAME, ._cmdStreamUsage = CommandStreamUsage::Compute }, + getQueuePtr("AsyncCompute")); + + _commandJobSystem->createCommandStream(CommandStreamKey{ ._cmdStreamName = ASYNC_UPLOAD_STREAM_NAME, ._cmdStreamUsage = CommandStreamUsage::Transfer }, + getQueuePtr("AsyncUpload")); + + _commandJobSystem->createCommandStream(CommandStreamKey{ ._cmdStreamName = IMMEDIATE_UPLOAD_STREAM_NAME, ._cmdStreamUsage = CommandStreamUsage::Transfer }, + getQueuePtr("ImmediateUpload")); } void LogicalDevice::releaseDedicatedResources() @@ -284,14 +245,12 @@ void LogicalDevice::releaseDedicatedResources() delete _descriptorSetAllocatorPool; } - std::for_each( - _queueMap.begin(), _queueMap.end(), - [](std::unordered_map::value_type& queue) { - if (queue.second != nullptr) - { - delete queue.second; - } - }); + std::for_each(_queueMap.begin(), _queueMap.end(), [](std::unordered_map::value_type& queue) { + if (queue.second != nullptr) + { + delete queue.second; + } + }); } void LogicalDevice::release() diff --git a/Sources/VoxFlow/Core/Devices/PhysicalDevice.cpp b/Sources/VoxFlow/Core/Devices/PhysicalDevice.cpp index 7e36683a..c3d67505 100644 --- a/Sources/VoxFlow/Core/Devices/PhysicalDevice.cpp +++ b/Sources/VoxFlow/Core/Devices/PhysicalDevice.cpp @@ -1,7 +1,7 @@ // Author : snowapril -#include #include +#include #include namespace VoxFlow @@ -11,8 +11,7 @@ PhysicalDevice::PhysicalDevice(Instance* instance) uint32_t numPhysicalDevices; vkEnumeratePhysicalDevices(instance->get(), &numPhysicalDevices, nullptr); std::vector deviceCandidates(numPhysicalDevices); - vkEnumeratePhysicalDevices(instance->get(), &numPhysicalDevices, - deviceCandidates.data()); + vkEnumeratePhysicalDevices(instance->get(), &numPhysicalDevices, deviceCandidates.data()); // TODO(snowapril) : enable physical device selection between external gpu // and internal gpu @@ -24,19 +23,16 @@ std::vector PhysicalDevice::getPossibleLayers() const uint32_t layerCount; vkEnumerateDeviceLayerProperties(_physicalDevice, &layerCount, nullptr); std::vector layerProperties(layerCount); - vkEnumerateDeviceLayerProperties(_physicalDevice, &layerCount, - layerProperties.data()); + vkEnumerateDeviceLayerProperties(_physicalDevice, &layerCount, layerProperties.data()); return layerProperties; } std::vector PhysicalDevice::getPossibleExtensions() const { uint32_t extensionCount; - vkEnumerateDeviceExtensionProperties(_physicalDevice, nullptr, - &extensionCount, nullptr); + vkEnumerateDeviceExtensionProperties(_physicalDevice, nullptr, &extensionCount, nullptr); std::vector extensionProperties(extensionCount); - vkEnumerateDeviceExtensionProperties( - _physicalDevice, nullptr, &extensionCount, extensionProperties.data()); + vkEnumerateDeviceExtensionProperties(_physicalDevice, nullptr, &extensionCount, extensionProperties.data()); return extensionProperties; } @@ -47,21 +43,18 @@ VkPhysicalDeviceMemoryProperties PhysicalDevice::getMemoryProperty() const return memoryProperties; } -std::vector PhysicalDevice::getQueueFamilyProperties() - const +std::vector PhysicalDevice::getQueueFamilyProperties() const { uint32_t familyCount; - vkGetPhysicalDeviceQueueFamilyProperties(_physicalDevice, &familyCount, - nullptr); + vkGetPhysicalDeviceQueueFamilyProperties(_physicalDevice, &familyCount, nullptr); std::vector queueFamilyProperties(familyCount); - vkGetPhysicalDeviceQueueFamilyProperties(_physicalDevice, &familyCount, - queueFamilyProperties.data()); + vkGetPhysicalDeviceQueueFamilyProperties(_physicalDevice, &familyCount, queueFamilyProperties.data()); return queueFamilyProperties; } VkPhysicalDeviceProperties PhysicalDevice::getPhysicalDeviceProperties() const { - VkPhysicalDeviceProperties physicalDeviceProperties; + VkPhysicalDeviceProperties physicalDeviceProperties; vkGetPhysicalDeviceProperties(_physicalDevice, &physicalDeviceProperties); return physicalDeviceProperties; diff --git a/Sources/VoxFlow/Core/Devices/Queue.cpp b/Sources/VoxFlow/Core/Devices/Queue.cpp index 70dd9718..869a06dc 100644 --- a/Sources/VoxFlow/Core/Devices/Queue.cpp +++ b/Sources/VoxFlow/Core/Devices/Queue.cpp @@ -11,9 +11,8 @@ namespace VoxFlow { -Queue::Queue(const std::string& debugName, LogicalDevice* logicalDevice, - VkQueueFlags queueTypeFlags, VkQueue queueHandle, - uint32_t familyIndex, uint32_t queueIndex) noexcept +Queue::Queue(const std::string& debugName, LogicalDevice* logicalDevice, VkQueueFlags queueTypeFlags, VkQueue queueHandle, uint32_t familyIndex, + uint32_t queueIndex) noexcept : _debugName(debugName), _logicalDevice(logicalDevice), _queueTypeFlags(queueTypeFlags), @@ -39,22 +38,18 @@ Queue::Queue(const std::string& debugName, LogicalDevice* logicalDevice, createInfo.pNext = &timelineCreateInfo; createInfo.flags = 0; - vkCreateSemaphore(_logicalDevice->get(), &createInfo, NULL, - &_submitTimelineSemaphore); + vkCreateSemaphore(_logicalDevice->get(), &createInfo, NULL, &_submitTimelineSemaphore); #if defined(VK_DEBUG_NAME_ENABLED) - std::string timelineSemaphoreDebugName = - fmt::format("{}_TimelineSemaphore", _debugName); - DebugUtil::setObjectName(_logicalDevice, _submitTimelineSemaphore, - timelineSemaphoreDebugName.c_str()); + std::string timelineSemaphoreDebugName = fmt::format("{}_TimelineSemaphore", _debugName); + DebugUtil::setObjectName(_logicalDevice, _submitTimelineSemaphore, timelineSemaphoreDebugName.c_str()); #endif } Queue::~Queue() { vkQueueWaitIdle(_queue); - vkDestroySemaphore(_logicalDevice->get(), _submitTimelineSemaphore, - nullptr); + vkDestroySemaphore(_logicalDevice->get(), _submitTimelineSemaphore, nullptr); } Queue::Queue(Queue&& other) noexcept @@ -78,19 +73,15 @@ Queue& Queue::operator=(Queue&& other) noexcept return *this; } -FenceObject Queue::submitCommandBuffer( - const std::shared_ptr& commandBuffer, SwapChain* swapChain, - const FrameContext* frameContext, const bool waitCompletion) +FenceObject Queue::submitCommandBuffer(const std::shared_ptr& commandBuffer, SwapChain* swapChain, const FrameContext* frameContext, + const bool waitCompletion) { - VOX_ASSERT((swapChain == nullptr) || (frameContext == nullptr) || - (frameContext->_frameIndex < FRAME_BUFFER_COUNT), + VOX_ASSERT((swapChain == nullptr) || (frameContext == nullptr) || (frameContext->_frameIndex < FRAME_BUFFER_COUNT), "Must provide valid frame index when swapChain is not nullptr"); VkCommandBuffer cmdBufferToSubmit = commandBuffer->get(); - uint64_t signalingValues[2] = { - commandBuffer->getFenceToSignal().getFenceValue(), 0ULL - }; + uint64_t signalingValues[2] = { commandBuffer->getFenceToSignal().getFenceValue(), 0ULL }; uint64_t waitingValues[2] = { signalingValues[0] - 1, 0ULL }; VkTimelineSemaphoreSubmitInfo timelineInfo{ @@ -102,35 +93,22 @@ FenceObject Queue::submitCommandBuffer( .pSignalSemaphoreValues = signalingValues, }; - VkSemaphore waitingSemaphores[2] = { - _submitTimelineSemaphore, - swapChain == nullptr ? VK_NULL_HANDLE - : swapChain->getCurrentBackBufferReadySemaphore() - }; + VkSemaphore waitingSemaphores[2] = { _submitTimelineSemaphore, swapChain == nullptr ? VK_NULL_HANDLE : swapChain->getCurrentBackBufferReadySemaphore() }; - VkSemaphore signalingSemaphores[2] = { - _submitTimelineSemaphore, - swapChain == nullptr ? VK_NULL_HANDLE - : swapChain->getCurrentPresentReadySemaphore() - }; + VkSemaphore signalingSemaphores[2] = { _submitTimelineSemaphore, swapChain == nullptr ? VK_NULL_HANDLE : swapChain->getCurrentPresentReadySemaphore() }; // TODO(snowapril) : modify stage masks - VkPipelineStageFlags waitDstStageMasks[2] = { - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT - }; + VkPipelineStageFlags waitDstStageMasks[2] = { VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT }; // Add wait semaphore for waiting acquire back buffer image VkSubmitInfo submitInfo = { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .pNext = &timelineInfo, - .waitSemaphoreCount = - swapChain != nullptr ? 2U : 1U, + .waitSemaphoreCount = swapChain != nullptr ? 2U : 1U, .pWaitSemaphores = &waitingSemaphores[0], .pWaitDstStageMask = waitDstStageMasks, .commandBufferCount = 1, .pCommandBuffers = &cmdBufferToSubmit, - .signalSemaphoreCount = - swapChain != nullptr ? 2U : 1U, + .signalSemaphoreCount = swapChain != nullptr ? 2U : 1U, .pSignalSemaphores = &signalingSemaphores[0] }; _lastExecutedFence = FenceObject(this, waitingValues[0]); @@ -155,46 +133,34 @@ FenceObject Queue::submitCommandBuffer( } else if (swapChain != nullptr && frameContext != nullptr) { - swapChain->addWaitSemaphores(frameContext->_frameIndex, - _submitTimelineSemaphore, - signalingValues[0]); + swapChain->addWaitSemaphores(frameContext->_frameIndex, _submitTimelineSemaphore, signalingValues[0]); } return _lastExecutedFence; } -FenceObject Queue::submitCommandBufferBatch( - std::vector>&& batchedCommandBuffers, - SwapChain* swapChain, const FrameContext* frameContext, - const bool waitAllCompletion) +FenceObject Queue::submitCommandBufferBatch(std::vector>&& batchedCommandBuffers, SwapChain* swapChain, + const FrameContext* frameContext, const bool waitAllCompletion) { - VOX_ASSERT((swapChain == nullptr) || (frameContext == nullptr) || - (frameContext->_frameIndex < FRAME_BUFFER_COUNT), + VOX_ASSERT((swapChain == nullptr) || (frameContext == nullptr) || (frameContext->_frameIndex < FRAME_BUFFER_COUNT), "Must provide valid frame index when swapChain is not nullptr"); - std::vector>&& commandBuffersToSubmit = - std::move(batchedCommandBuffers); + std::vector>&& commandBuffersToSubmit = std::move(batchedCommandBuffers); // Must sort given command buffers with fence value allocated to // guarantee sequential execution. std::sort(commandBuffersToSubmit.begin(), commandBuffersToSubmit.end(), - [](const std::shared_ptr& lhs, - const std::shared_ptr& rhs) { - return lhs->getFenceToSignal().getFenceValue() < - rhs->getFenceToSignal().getFenceValue(); + [](const std::shared_ptr& lhs, const std::shared_ptr& rhs) { + return lhs->getFenceToSignal().getFenceValue() < rhs->getFenceToSignal().getFenceValue(); }); std::vector cmdBuffersToSubmit; cmdBuffersToSubmit.reserve(batchedCommandBuffers.size()); uint64_t maxFenceSignalValue = 0; - std::transform(batchedCommandBuffers.begin(), batchedCommandBuffers.end(), - std::back_inserter(cmdBuffersToSubmit), - [&maxFenceSignalValue]( - const std::shared_ptr& cmdBuffer) { - maxFenceSignalValue = glm::max( - maxFenceSignalValue, - cmdBuffer->getFenceToSignal().getFenceValue()); + std::transform(batchedCommandBuffers.begin(), batchedCommandBuffers.end(), std::back_inserter(cmdBuffersToSubmit), + [&maxFenceSignalValue](const std::shared_ptr& cmdBuffer) { + maxFenceSignalValue = glm::max(maxFenceSignalValue, cmdBuffer->getFenceToSignal().getFenceValue()); return cmdBuffer->get(); }); @@ -210,36 +176,23 @@ FenceObject Queue::submitCommandBufferBatch( .pSignalSemaphoreValues = signalingValues, }; - VkSemaphore waitingSemaphores[2] = { - _submitTimelineSemaphore, - swapChain == nullptr ? VK_NULL_HANDLE - : swapChain->getCurrentBackBufferReadySemaphore() - }; + VkSemaphore waitingSemaphores[2] = { _submitTimelineSemaphore, swapChain == nullptr ? VK_NULL_HANDLE : swapChain->getCurrentBackBufferReadySemaphore() }; - VkSemaphore signalingSemaphores[2] = { - _submitTimelineSemaphore, - swapChain == nullptr ? VK_NULL_HANDLE - : swapChain->getCurrentPresentReadySemaphore() - }; + VkSemaphore signalingSemaphores[2] = { _submitTimelineSemaphore, swapChain == nullptr ? VK_NULL_HANDLE : swapChain->getCurrentPresentReadySemaphore() }; // TODO(snowapril) : modify stage masks - VkPipelineStageFlags waitDstStageMasks[2] = { - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT - }; + VkPipelineStageFlags waitDstStageMasks[2] = { VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT }; // Add wait semaphore for waiting acquire back buffer image - VkSubmitInfo submitInfo = { - .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, - .pNext = &timelineInfo, - .waitSemaphoreCount = swapChain != nullptr ? 2U : 1U, - .pWaitSemaphores = &waitingSemaphores[0], - .pWaitDstStageMask = waitDstStageMasks, - .commandBufferCount = static_cast(cmdBuffersToSubmit.size()), - .pCommandBuffers = cmdBuffersToSubmit.data(), - .signalSemaphoreCount = swapChain != nullptr ? 2U : 1U, - .pSignalSemaphores = &signalingSemaphores[0] - }; + VkSubmitInfo submitInfo = { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, + .pNext = &timelineInfo, + .waitSemaphoreCount = swapChain != nullptr ? 2U : 1U, + .pWaitSemaphores = &waitingSemaphores[0], + .pWaitDstStageMask = waitDstStageMasks, + .commandBufferCount = static_cast(cmdBuffersToSubmit.size()), + .pCommandBuffers = cmdBuffersToSubmit.data(), + .signalSemaphoreCount = swapChain != nullptr ? 2U : 1U, + .pSignalSemaphores = &signalingSemaphores[0] }; _lastExecutedFence = FenceObject(this, waitingValues[0]); @@ -263,9 +216,7 @@ FenceObject Queue::submitCommandBufferBatch( } else if (swapChain != nullptr && frameContext != nullptr) { - swapChain->addWaitSemaphores(frameContext->_frameIndex, - _submitTimelineSemaphore, - maxFenceSignalValue); + swapChain->addWaitSemaphores(frameContext->_frameIndex, _submitTimelineSemaphore, maxFenceSignalValue); } return _lastExecutedFence; @@ -274,8 +225,7 @@ FenceObject Queue::submitCommandBufferBatch( uint64_t Queue::querySemaphoreValue() { uint64_t value = 0; - VK_ASSERT(vkGetSemaphoreCounterValueKHR(_logicalDevice->get(), - _submitTimelineSemaphore, &value)); + VK_ASSERT(vkGetSemaphoreCounterValueKHR(_logicalDevice->get(), _submitTimelineSemaphore, &value)); if (value == UINT64_MAX) { diff --git a/Sources/VoxFlow/Core/Devices/RenderDevice.cpp b/Sources/VoxFlow/Core/Devices/RenderDevice.cpp index 5f70b80f..a7b1cfab 100644 --- a/Sources/VoxFlow/Core/Devices/RenderDevice.cpp +++ b/Sources/VoxFlow/Core/Devices/RenderDevice.cpp @@ -3,53 +3,41 @@ #include #include #include +#include #include #include #include #include -#include -#include #include #include +#include #include namespace VoxFlow { RenderDevice::RenderDevice(Context deviceSetupCtx) { - deviceSetupCtx.addRequiredQueue("MainGraphics", VK_QUEUE_GRAPHICS_BIT, 1, - 1.0F, true); - deviceSetupCtx.addRequiredQueue("AsyncUpload", VK_QUEUE_TRANSFER_BIT, 1, - 1.0F, false); - deviceSetupCtx.addRequiredQueue("AsyncCompute", VK_QUEUE_COMPUTE_BIT, 1, - 1.0F, false); - deviceSetupCtx.addRequiredQueue("ImmediateUpload", VK_QUEUE_TRANSFER_BIT, 1, - 1.0F, false); - - deviceSetupCtx.addInstanceExtension(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, - false); + deviceSetupCtx.addRequiredQueue("MainGraphics", VK_QUEUE_GRAPHICS_BIT, 1, 1.0F, true); + deviceSetupCtx.addRequiredQueue("AsyncUpload", VK_QUEUE_TRANSFER_BIT, 1, 1.0F, false); + deviceSetupCtx.addRequiredQueue("AsyncCompute", VK_QUEUE_COMPUTE_BIT, 1, 1.0F, false); + deviceSetupCtx.addRequiredQueue("ImmediateUpload", VK_QUEUE_TRANSFER_BIT, 1, 1.0F, false); + + deviceSetupCtx.addInstanceExtension(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, false); deviceSetupCtx.addDeviceExtension(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME); - deviceSetupCtx.addDeviceExtension( - VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME); + deviceSetupCtx.addDeviceExtension(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME); _deviceSetupCtx = new Context(deviceSetupCtx); _instance = new Instance(deviceSetupCtx); _physicalDevice = new PhysicalDevice(_instance); - _logicalDevices.emplace_back(std::make_unique( - deviceSetupCtx, _physicalDevice, _instance, - LogicalDeviceType::MainDevice)); + _logicalDevices.emplace_back(std::make_unique(deviceSetupCtx, _physicalDevice, _instance, LogicalDeviceType::MainDevice)); - RenderResourceGarbageCollector::Get().threadConstruct(); - LogicalDevice* mainLogicalDevice = - getLogicalDevice(LogicalDeviceType::MainDevice); - _mainSwapChain = mainLogicalDevice->addSwapChain("VoxFlow Editor", - glm::ivec2(1280, 920)); + LogicalDevice* mainLogicalDevice = getLogicalDevice(LogicalDeviceType::MainDevice); + _mainSwapChain = mainLogicalDevice->addSwapChain("VoxFlow Editor", glm::ivec2(1280, 920)); - _sceneRenderer = - std::make_unique(mainLogicalDevice, &_frameGraph); + _sceneRenderer = std::make_unique(mainLogicalDevice, &_frameGraph); _mainCmdJobSystem = mainLogicalDevice->getCommandJobSystem(); @@ -73,18 +61,13 @@ void RenderDevice::updateRender(const double deltaTime) SCOPED_CHROME_TRACING("RenderDevice::updateRender"); (void)deltaTime; - const CommandStreamKey cmdStreamKey = { ._cmdStreamName = - ASYNC_UPLOAD_STREAM_NAME, - ._cmdStreamUsage = - CommandStreamUsage::Transfer }; + const CommandStreamKey cmdStreamKey = { ._cmdStreamName = ASYNC_UPLOAD_STREAM_NAME, ._cmdStreamUsage = CommandStreamUsage::Transfer }; - CommandStream* asyncUploadStream = - _mainCmdJobSystem->getCommandStream(cmdStreamKey); + CommandStream* asyncUploadStream = _mainCmdJobSystem->getCommandStream(cmdStreamKey); _sceneRenderer->updateRender(_uploadContext); - _uploadContext->processPendingUploads(UploadPhase::PreUpdate, - asyncUploadStream); + _uploadContext->processPendingUploads(UploadPhase::PreUpdate, asyncUploadStream); asyncUploadStream->flush(nullptr, nullptr, false); } @@ -93,23 +76,17 @@ void RenderDevice::renderScene() { SCOPED_CHROME_TRACING("RenderDevice::renderScene"); - const CommandStreamKey cmdStreamKey = { ._cmdStreamName = - ASYNC_UPLOAD_STREAM_NAME, - ._cmdStreamUsage = - CommandStreamUsage::Transfer }; + const CommandStreamKey cmdStreamKey = { ._cmdStreamName = ASYNC_UPLOAD_STREAM_NAME, ._cmdStreamUsage = CommandStreamUsage::Transfer }; - CommandStream* asyncUploadStream = - _mainCmdJobSystem->getCommandStream(cmdStreamKey); + CommandStream* asyncUploadStream = _mainCmdJobSystem->getCommandStream(cmdStreamKey); - _uploadContext->processPendingUploads(UploadPhase::PreRender, - asyncUploadStream); + _uploadContext->processPendingUploads(UploadPhase::PreRender, asyncUploadStream); asyncUploadStream->flush(nullptr, nullptr, false); _mainSwapChain->prepareForNextFrame(); - std::optional backBufferIndex = - _mainSwapChain->acquireNextImageIndex(); + std::optional backBufferIndex = _mainSwapChain->acquireNextImageIndex(); if (backBufferIndex.has_value()) { @@ -123,8 +100,7 @@ void RenderDevice::renderScene() _sceneRenderer->beginFrameGraph(tempFrameContext); - tf::Future resolveFence = - _sceneRenderer->resolveSceneRenderPasses(_mainSwapChain.get()); + tf::Future resolveFence = _sceneRenderer->resolveSceneRenderPasses(_mainSwapChain.get()); resolveFence.wait(); _sceneRenderer->submitFrameGraph(); diff --git a/Sources/VoxFlow/Core/Devices/SwapChain.cpp b/Sources/VoxFlow/Core/Devices/SwapChain.cpp index 42682d76..e579c14d 100644 --- a/Sources/VoxFlow/Core/Devices/SwapChain.cpp +++ b/Sources/VoxFlow/Core/Devices/SwapChain.cpp @@ -13,9 +13,8 @@ namespace VoxFlow { -SwapChain::SwapChain(Instance* instance, PhysicalDevice* physicalDevice, - LogicalDevice* logicalDevice, Queue* presentSupportQueue, - std::string&& titleName, const glm::uvec2 resolution) noexcept +SwapChain::SwapChain(Instance* instance, PhysicalDevice* physicalDevice, LogicalDevice* logicalDevice, Queue* presentSupportQueue, std::string&& titleName, + const glm::uvec2 resolution) noexcept : _instance(instance), _physicalDevice(physicalDevice), _queue(presentSupportQueue), @@ -25,44 +24,32 @@ SwapChain::SwapChain(Instance* instance, PhysicalDevice* physicalDevice, { // TODO(snowapril) : check glfwGetPhysicalDevicePresentationSupport glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - _window = glfwCreateWindow(resolution.x, resolution.y, titleName.c_str(), - nullptr, - nullptr); + _window = glfwCreateWindow(resolution.x, resolution.y, titleName.c_str(), nullptr, nullptr); // TODO(snowapril) : move callback registration other place - glfwSetKeyCallback(_window, [](GLFWwindow* window, int key, int scancode, - int action, int mods) { + glfwSetKeyCallback(_window, [](GLFWwindow* window, int key, int scancode, int action, int mods) { (void)scancode; (void)mods; if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GLFW_TRUE); }); - VK_ASSERT( - glfwCreateWindowSurface(_instance->get(), _window, nullptr, &_surface)); + VK_ASSERT(glfwCreateWindowSurface(_instance->get(), _window, nullptr, &_surface)); - const std::vector surfaceFormatList = { - { VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR }, - { VK_FORMAT_B8G8R8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR } - }; + const std::vector surfaceFormatList = { { VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR }, + { VK_FORMAT_B8G8R8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR } }; uint32_t numFormats{ 0 }; - VK_ASSERT(vkGetPhysicalDeviceSurfaceFormatsKHR( - _physicalDevice->get(), _surface, &numFormats, nullptr)); + VK_ASSERT(vkGetPhysicalDeviceSurfaceFormatsKHR(_physicalDevice->get(), _surface, &numFormats, nullptr)); std::vector deviceSurfaceFormats(numFormats); - VK_ASSERT(vkGetPhysicalDeviceSurfaceFormatsKHR( - _physicalDevice->get(), _surface, &numFormats, - deviceSurfaceFormats.data())); + VK_ASSERT(vkGetPhysicalDeviceSurfaceFormatsKHR(_physicalDevice->get(), _surface, &numFormats, deviceSurfaceFormats.data())); for (const VkSurfaceFormatKHR& deviceSurfaceFormat : deviceSurfaceFormats) { - for (const VkSurfaceFormatKHR& preferredSurfaceFormat : - surfaceFormatList) + for (const VkSurfaceFormatKHR& preferredSurfaceFormat : surfaceFormatList) { - if ((deviceSurfaceFormat.format == preferredSurfaceFormat.format) && - (deviceSurfaceFormat.colorSpace == - preferredSurfaceFormat.colorSpace)) + if ((deviceSurfaceFormat.format == preferredSurfaceFormat.format) && (deviceSurfaceFormat.colorSpace == preferredSurfaceFormat.colorSpace)) { _surfaceFormat = deviceSurfaceFormat.format; _colorSpace = deviceSurfaceFormat.colorSpace; @@ -103,10 +90,7 @@ SwapChain& SwapChain::operator=(SwapChain&& other) noexcept std::optional SwapChain::acquireNextImageIndex() { - VK_ASSERT(vkAcquireNextImageKHR(_logicalDevice->get(), _swapChain, - UINT64_MAX, - _backBufferReadySemaphores[_frameIndex], - VK_NULL_HANDLE, &_backBufferIndex)); + VK_ASSERT(vkAcquireNextImageKHR(_logicalDevice->get(), _swapChain, UINT64_MAX, _backBufferReadySemaphores[_frameIndex], VK_NULL_HANDLE, &_backBufferIndex)); // TODO(snowapril) : need handling out-of-date or not-ready situation. return { _backBufferIndex }; @@ -120,8 +104,7 @@ bool SwapChain::create(const bool vsync) querySwapChainCapability(swapChainCreateInfo, vsync); swapChainCreateInfo.oldSwapchain = oldSwapChain; - VK_ASSERT(vkCreateSwapchainKHR(_logicalDevice->get(), &swapChainCreateInfo, - nullptr, &_swapChain)); + VK_ASSERT(vkCreateSwapchainKHR(_logicalDevice->get(), &swapChainCreateInfo, nullptr, &_swapChain)); if (_swapChain == VK_NULL_HANDLE) { @@ -131,7 +114,7 @@ bool SwapChain::create(const bool vsync) #if defined(VK_DEBUG_NAME_ENABLED) DebugUtil::setObjectName(_logicalDevice, _swapChain, _titleName.c_str()); -#endif // VK_DEBUG_NAME_ENABLED +#endif // VK_DEBUG_NAME_ENABLED if (oldSwapChain != VK_NULL_HANDLE) { @@ -140,33 +123,26 @@ bool SwapChain::create(const bool vsync) } uint32_t numSwapChainImages; - vkGetSwapchainImagesKHR(_logicalDevice->get(), _swapChain, - &numSwapChainImages, nullptr); - + vkGetSwapchainImagesKHR(_logicalDevice->get(), _swapChain, &numSwapChainImages, nullptr); + std::vector vkSwapChainImages(numSwapChainImages); - vkGetSwapchainImagesKHR(_logicalDevice->get(), _swapChain, - &numSwapChainImages, vkSwapChainImages.data()); + vkGetSwapchainImagesKHR(_logicalDevice->get(), _swapChain, &numSwapChainImages, vkSwapChainImages.data()); // Create Textures from queried swapChain images _swapChainImages.reserve(numSwapChainImages); for (uint32_t i = 0; i < numSwapChainImages; ++i) { - auto swapChainImage = std::make_shared( - fmt::format("{}_Image({})", _titleName, i), _logicalDevice, - nullptr); + auto swapChainImage = std::make_shared(fmt::format("{}_Image({})", _titleName, i), _logicalDevice, nullptr); - TextureInfo surfaceInfo = { ._extent = glm::uvec3(_resolution, 1), - ._format = _surfaceFormat, - ._imageType = VK_IMAGE_TYPE_2D, - ._usage = TextureUsage::RenderTarget }; + TextureInfo surfaceInfo = { + ._extent = glm::uvec3(_resolution, 1), ._format = _surfaceFormat, ._imageType = VK_IMAGE_TYPE_2D, ._usage = TextureUsage::RenderTarget + }; - swapChainImage->initializeFromSwapChain(surfaceInfo, - vkSwapChainImages[i]); + swapChainImage->initializeFromSwapChain(surfaceInfo, vkSwapChainImages[i]); TextureViewInfo surfaceViewInfo = { ._viewType = VK_IMAGE_VIEW_TYPE_2D, ._format = _surfaceFormat, - ._aspectFlags = - VK_IMAGE_ASPECT_COLOR_BIT, + ._aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT, ._baseMipLevel = 0, ._levelCount = 1, ._baseArrayLayer = 0, @@ -181,38 +157,25 @@ bool SwapChain::create(const bool vsync) if (numSwapChainImages != _presentSemaphores.size()) { LogicalDevice* logicalDevice = _logicalDevice; - auto recreateSemaphores = - [logicalDevice, this](const uint32_t numSwapChainImages, - std::vector& targetSemaphores) { - for (uint32_t i = numSwapChainImages; - i < targetSemaphores.size(); ++i) - { - vkDestroySemaphore(logicalDevice->get(), - targetSemaphores[i], nullptr); - } - - const uint32_t oldNumSemaphores = - static_cast(targetSemaphores.size()); - targetSemaphores.resize(numSwapChainImages); - for (uint32_t i = oldNumSemaphores; i < numSwapChainImages; ++i) - { - const VkSemaphoreCreateInfo semaphoreInfo = { - .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, - .pNext = nullptr, - .flags = 0 - }; - vkCreateSemaphore(logicalDevice->get(), &semaphoreInfo, - nullptr, &targetSemaphores[i]); + auto recreateSemaphores = [logicalDevice, this](const uint32_t numSwapChainImages, std::vector& targetSemaphores) { + for (uint32_t i = numSwapChainImages; i < targetSemaphores.size(); ++i) + { + vkDestroySemaphore(logicalDevice->get(), targetSemaphores[i], nullptr); + } + + const uint32_t oldNumSemaphores = static_cast(targetSemaphores.size()); + targetSemaphores.resize(numSwapChainImages); + for (uint32_t i = oldNumSemaphores; i < numSwapChainImages; ++i) + { + const VkSemaphoreCreateInfo semaphoreInfo = { .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, .pNext = nullptr, .flags = 0 }; + vkCreateSemaphore(logicalDevice->get(), &semaphoreInfo, nullptr, &targetSemaphores[i]); #if defined(VK_DEBUG_NAME_ENABLED) - std::string swapChainSemaphoreDebugName = - fmt::format("{}_SwapChain_Semaphore_{}", _titleName, i); - DebugUtil::setObjectName( - _logicalDevice, targetSemaphores[i], - swapChainSemaphoreDebugName.c_str()); + std::string swapChainSemaphoreDebugName = fmt::format("{}_SwapChain_Semaphore_{}", _titleName, i); + DebugUtil::setObjectName(_logicalDevice, targetSemaphores[i], swapChainSemaphoreDebugName.c_str()); #endif - } - }; + } + }; recreateSemaphores(numSwapChainImages, _backBufferReadySemaphores); recreateSemaphores(numSwapChainImages, _presentSemaphores); @@ -221,24 +184,18 @@ bool SwapChain::create(const bool vsync) return true; } -void SwapChain::querySwapChainCapability( - VkSwapchainCreateInfoKHR& swapChainCreateInfo, const bool vsync) +void SwapChain::querySwapChainCapability(VkSwapchainCreateInfoKHR& swapChainCreateInfo, const bool vsync) { VkSurfaceCapabilitiesKHR surfaceCaps = {}; - VK_ASSERT(vkGetPhysicalDeviceSurfaceCapabilitiesKHR( - _physicalDevice->get(), _surface, &surfaceCaps)); + VK_ASSERT(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(_physicalDevice->get(), _surface, &surfaceCaps)); uint32_t numPresentModes = 0; - vkGetPhysicalDeviceSurfacePresentModesKHR(_physicalDevice->get(), _surface, - &numPresentModes, nullptr); + vkGetPhysicalDeviceSurfacePresentModesKHR(_physicalDevice->get(), _surface, &numPresentModes, nullptr); std::vector supportedPresentModes(numPresentModes); - vkGetPhysicalDeviceSurfacePresentModesKHR(_physicalDevice->get(), _surface, - &numPresentModes, - supportedPresentModes.data()); + vkGetPhysicalDeviceSurfacePresentModesKHR(_physicalDevice->get(), _surface, &numPresentModes, supportedPresentModes.data()); - if (surfaceCaps.currentExtent.width == UINT32_MAX || - surfaceCaps.currentExtent.height == UINT32_MAX) + if (surfaceCaps.currentExtent.width == UINT32_MAX || surfaceCaps.currentExtent.height == UINT32_MAX) { surfaceCaps.currentExtent.width = _resolution.x; surfaceCaps.currentExtent.height = _resolution.y; @@ -249,10 +206,7 @@ void SwapChain::querySwapChainCapability( _resolution.y = surfaceCaps.currentExtent.height; } - const VkExtent2D swapchainExtent{ - .width = static_cast(_resolution.x), - .height = static_cast(_resolution.y) - }; + const VkExtent2D swapchainExtent{ .width = static_cast(_resolution.x), .height = static_cast(_resolution.y) }; VkPresentModeKHR resultPresentMode = VK_PRESENT_MODE_FIFO_KHR; if (vsync == false) @@ -280,13 +234,11 @@ void SwapChain::querySwapChainCapability( uint32_t numDesiredSwapChainImages = surfaceCaps.minImageCount + 1; if ((surfaceCaps.maxImageCount > 0)) { - numDesiredSwapChainImages = - glm::min(numDesiredSwapChainImages, surfaceCaps.maxImageCount); + numDesiredSwapChainImages = glm::min(numDesiredSwapChainImages, surfaceCaps.maxImageCount); } VkSurfaceTransformFlagBitsKHR preTransform; - if (surfaceCaps.supportedTransforms == - VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) + if (surfaceCaps.supportedTransforms == VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) { preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; } @@ -295,8 +247,7 @@ void SwapChain::querySwapChainCapability( preTransform = surfaceCaps.currentTransform; } - VkCompositeAlphaFlagBitsKHR compositeAlpha = - VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; VkCompositeAlphaFlagBitsKHR compositeAlphaList[] = { VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, @@ -314,27 +265,25 @@ void SwapChain::querySwapChainCapability( } } - swapChainCreateInfo = { - .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, - .pNext = nullptr, - .flags = 0, - .surface = _surface, - .minImageCount = numDesiredSwapChainImages, - .imageFormat = _surfaceFormat, - .imageColorSpace = _colorSpace, - .imageExtent = swapchainExtent, - .imageArrayLayers = 1, - .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, - .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE, - .queueFamilyIndexCount = 0, - .pQueueFamilyIndices = nullptr, - .preTransform = preTransform, - .compositeAlpha = compositeAlpha, - .presentMode = resultPresentMode, - .clipped = VK_TRUE, // Allow presentation engine discard rendering - // outside of the surface, - .oldSwapchain = VK_NULL_HANDLE - }; + swapChainCreateInfo = { .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, + .pNext = nullptr, + .flags = 0, + .surface = _surface, + .minImageCount = numDesiredSwapChainImages, + .imageFormat = _surfaceFormat, + .imageColorSpace = _colorSpace, + .imageExtent = swapchainExtent, + .imageArrayLayers = 1, + .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, + .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE, + .queueFamilyIndexCount = 0, + .pQueueFamilyIndices = nullptr, + .preTransform = preTransform, + .compositeAlpha = compositeAlpha, + .presentMode = resultPresentMode, + .clipped = VK_TRUE, // Allow presentation engine discard rendering + // outside of the surface, + .oldSwapchain = VK_NULL_HANDLE }; if (surfaceCaps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) { @@ -351,8 +300,7 @@ void SwapChain::release() { for (VkSemaphore& backBufferReadySemaphore : _backBufferReadySemaphores) { - vkDestroySemaphore(_logicalDevice->get(), backBufferReadySemaphore, - nullptr); + vkDestroySemaphore(_logicalDevice->get(), backBufferReadySemaphore, nullptr); } _backBufferReadySemaphores.clear(); @@ -401,18 +349,14 @@ void SwapChain::prepareForNextFrame() _frameIndex = (_frameIndex + 1) % FRAME_BUFFER_COUNT; } -void SwapChain::addWaitSemaphores(const uint32_t frameIndex, - VkSemaphore timelineSemaphore, - const uint64_t waitingValue) +void SwapChain::addWaitSemaphores(const uint32_t frameIndex, VkSemaphore timelineSemaphore, const uint64_t waitingValue) { - SemaphoreWaitInfo& waitInfo = - _waitSemaphoreInfos[frameIndex]; + SemaphoreWaitInfo& waitInfo = _waitSemaphoreInfos[frameIndex]; std::lock_guard scopeLockGuard(waitInfo._waitInfoMutex); waitInfo._waitSemaphores.push_back(timelineSemaphore); - waitInfo._waitingSemaphoreValues.push_back( - waitingValue); + waitInfo._waitingSemaphoreValues.push_back(waitingValue); } void SwapChain::waitForGpuComplete(const uint32_t frameIndex) @@ -423,17 +367,13 @@ void SwapChain::waitForGpuComplete(const uint32_t frameIndex) if (waitInfo._waitSemaphores.empty() == false) { - VkSemaphoreWaitInfo vkWaitInfo = { - .sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO_KHR, - .pNext = nullptr, - .flags = 0, - .semaphoreCount = - static_cast(waitInfo._waitSemaphores.size()), - .pSemaphores = waitInfo._waitSemaphores.data(), - .pValues = waitInfo._waitingSemaphoreValues.data() - }; - VK_ASSERT(vkWaitSemaphoresKHR(_logicalDevice->get(), &vkWaitInfo, - UINT64_MAX)); + VkSemaphoreWaitInfo vkWaitInfo = { .sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO_KHR, + .pNext = nullptr, + .flags = 0, + .semaphoreCount = static_cast(waitInfo._waitSemaphores.size()), + .pSemaphores = waitInfo._waitSemaphores.data(), + .pValues = waitInfo._waitingSemaphoreValues.data() }; + VK_ASSERT(vkWaitSemaphoresKHR(_logicalDevice->get(), &vkWaitInfo, UINT64_MAX)); waitInfo._waitSemaphores.clear(); waitInfo._waitingSemaphoreValues.clear(); diff --git a/Sources/VoxFlow/Core/FrameGraph/DependencyGraph.cpp b/Sources/VoxFlow/Core/FrameGraph/DependencyGraph.cpp index 372333f4..ce548cce 100644 --- a/Sources/VoxFlow/Core/FrameGraph/DependencyGraph.cpp +++ b/Sources/VoxFlow/Core/FrameGraph/DependencyGraph.cpp @@ -6,16 +6,13 @@ namespace VoxFlow { -DependencyGraph::Node::Node(DependencyGraph* ownerGraph) - : _ownerGraph(ownerGraph), _nodeId(ownerGraph->getNextNodeID()) +DependencyGraph::Node::Node(DependencyGraph* ownerGraph) : _ownerGraph(ownerGraph), _nodeId(ownerGraph->getNextNodeID()) { _ownerGraph->registerNode(this, _nodeId); } DependencyGraph::Edge::Edge(DependencyGraph* ownerGraph, Node* from, Node* to) - : _ownerGraph(ownerGraph), - _fromNodeID(from->getNodeID()), - _toNodeID(to->getNodeID()) + : _ownerGraph(ownerGraph), _fromNodeID(from->getNodeID()), _toNodeID(to->getNodeID()) { } @@ -34,27 +31,22 @@ DependencyGraph::NodeID DependencyGraph::getNextNodeID() DependencyGraph::EdgeContainer DependencyGraph::getIncomingEdges(NodeID id) { EdgeContainer incomingEdges; - std::copy_if(_edges.begin(), _edges.end(), - std::back_inserter(incomingEdges), - [id](Edge* edge) { return edge->_toNodeID == id; }); - + std::copy_if(_edges.begin(), _edges.end(), std::back_inserter(incomingEdges), [id](Edge* edge) { return edge->_toNodeID == id; }); + return incomingEdges; } DependencyGraph::EdgeContainer DependencyGraph::getOutgoingEdges(NodeID id) { EdgeContainer outgoingEdges; - std::copy_if(_edges.begin(), _edges.end(), - std::back_inserter(outgoingEdges), - [id](Edge* edge) { return edge->_fromNodeID == id; }); + std::copy_if(_edges.begin(), _edges.end(), std::back_inserter(outgoingEdges), [id](Edge* edge) { return edge->_fromNodeID == id; }); return outgoingEdges; } void DependencyGraph::registerNode(Node* node, NodeID id) -{ - VOX_ASSERT(id == static_cast(_nodes.size()), - "Invalid Node ID {} was given", id); +{ + VOX_ASSERT(id == static_cast(_nodes.size()), "Invalid Node ID {} was given", id); _nodes.push_back(node); } @@ -87,8 +79,7 @@ void DependencyGraph::cullUnreferencedNodes() for (Edge* incomingEdge : incomingEdges) { Node* linkedNode = getNode(incomingEdge->_fromNodeID); - VOX_ASSERT(linkedNode->_refCount > 0, - "Reference count must not be zero"); + VOX_ASSERT(linkedNode->_refCount > 0, "Reference count must not be zero"); if ((--linkedNode->_refCount) == 0) { unreferencedNodes.push(linkedNode); @@ -105,8 +96,7 @@ void DependencyGraph::insertNode(Node* node, NodeID id) bool DependencyGraph::isEdgeValid(const Edge* edge) const { - return (_nodes[edge->_fromNodeID]->isCulled() == false) && - (_nodes[edge->_toNodeID]->isCulled() == false); + return (_nodes[edge->_fromNodeID]->isCulled() == false) && (_nodes[edge->_toNodeID]->isCulled() == false); } } // namespace VoxFlow \ No newline at end of file diff --git a/Sources/VoxFlow/Core/FrameGraph/FrameGraph.cpp b/Sources/VoxFlow/Core/FrameGraph/FrameGraph.cpp index 12d5e7b1..1a008286 100644 --- a/Sources/VoxFlow/Core/FrameGraph/FrameGraph.cpp +++ b/Sources/VoxFlow/Core/FrameGraph/FrameGraph.cpp @@ -4,21 +4,17 @@ #include #include #include -#include #include +#include namespace VoxFlow { namespace RenderGraph { -uint32_t FrameGraphBuilder::declareRenderPass( - std::string_view&& passName, - typename FrameGraphRenderPass::Descriptor&& initArgs) +uint32_t FrameGraphBuilder::declareRenderPass(std::string_view&& passName, typename FrameGraphRenderPass::Descriptor&& initArgs) { - return static_cast(_currentPassNode) - ->declareRenderPass(_frameGraph, this, std::move(passName), - std::move(initArgs)); + return static_cast(_currentPassNode)->declareRenderPass(_frameGraph, this, std::move(passName), std::move(initArgs)); } FrameGraph::FrameGraph() @@ -29,8 +25,7 @@ FrameGraph::~FrameGraph() { } -void FrameGraph::reset(CommandStream* cmdStream, - RenderResourceAllocator* renderResourceAllocator) +void FrameGraph::reset(CommandStream* cmdStream, RenderResourceAllocator* renderResourceAllocator) { clear(); @@ -38,26 +33,19 @@ void FrameGraph::reset(CommandStream* cmdStream, _renderResourceAllocator = renderResourceAllocator; } -ResourceHandle FrameGraph::importRenderTarget( - std::string&& resourceName, - FrameGraphTexture::Descriptor&& resourceDescArgs, - typename FrameGraphRenderPass::ImportedDescriptor&& importedDesc, - TextureView* textureView) +ResourceHandle FrameGraph::importRenderTarget(std::string&& resourceName, FrameGraphTexture::Descriptor&& resourceDescArgs, + typename FrameGraphRenderPass::ImportedDescriptor&& importedDesc, TextureView* textureView) { - VirtualResource* virtualResource = new ImportedRenderTarget( - std::move(resourceName), std::move(resourceDescArgs), std::move(importedDesc), {}, textureView); + VirtualResource* virtualResource = new ImportedRenderTarget(std::move(resourceName), std::move(resourceDescArgs), std::move(importedDesc), {}, textureView); ResourceHandle resourceHandle(_resources.size()); - _resourceSlots.push_back( - { ._resourceIndex = - static_cast(_resourceNodes.size()), - ._nodeIndex = static_cast(_resources.size()), - ._version = static_cast(0) }); + _resourceSlots.push_back({ ._resourceIndex = static_cast(_resourceNodes.size()), + ._nodeIndex = static_cast(_resources.size()), + ._version = static_cast(0) }); _resources.push_back(virtualResource); - ResourceNode* resourceNode = new ResourceNode( - &_dependencyGraph, resourceHandle); + ResourceNode* resourceNode = new ResourceNode(&_dependencyGraph, resourceHandle); resourceNode->_refCount = UINT32_MAX; _resourceNodes.push_back(resourceNode); @@ -78,7 +66,7 @@ bool FrameGraph::compile() // #define FRAMEGRAPH_FULL_OPTIMIZE #define FRAMEGRAPH_CULLING_ONLY #if defined(FRAMEGRAPH_FULL_OPTIMIZE) - + buildAdjacencyLists(numPassNodes); if (bool isCycleExist = topologicalSortPassNodes(numPassNodes)) @@ -95,35 +83,26 @@ bool FrameGraph::compile() _dependencyGraph.cullUnreferencedNodes(); - _passNodeLast = std::stable_partition( - _passNodes.begin(), _passNodes.end(), - [](PassNode* node) { return node->isCulled() == false; }); + _passNodeLast = std::stable_partition(_passNodes.begin(), _passNodes.end(), [](PassNode* node) { return node->isCulled() == false; }); for (auto it = _passNodes.begin(); it != _passNodeLast; ++it) { PassNode* passNode = *it; - VOX_ASSERT(passNode->isCulled() == false, - "There must not be culled nodes after culling"); + VOX_ASSERT(passNode->isCulled() == false, "There must not be culled nodes after culling"); - DependencyGraph::EdgeContainer reads = - _dependencyGraph.getIncomingEdges(passNode->getNodeID()); + DependencyGraph::EdgeContainer reads = _dependencyGraph.getIncomingEdges(passNode->getNodeID()); for (const DependencyGraph::Edge* edge : reads) { - DependencyGraph::Node* node = - _dependencyGraph.getNode(edge->_fromNodeID); - passNode->registerResource( - this, static_cast(node)->getResourceHandle()); + DependencyGraph::Node* node = _dependencyGraph.getNode(edge->_fromNodeID); + passNode->registerResource(this, static_cast(node)->getResourceHandle()); } - DependencyGraph::EdgeContainer writes = - _dependencyGraph.getOutgoingEdges(passNode->getNodeID()); + DependencyGraph::EdgeContainer writes = _dependencyGraph.getOutgoingEdges(passNode->getNodeID()); for (const DependencyGraph::Edge* edge : writes) { - DependencyGraph::Node* node = - _dependencyGraph.getNode(edge->_toNodeID); - passNode->registerResource( - this, static_cast(node)->getResourceHandle()); + DependencyGraph::Node* node = _dependencyGraph.getNode(edge->_toNodeID); + passNode->registerResource(this, static_cast(node)->getResourceHandle()); } passNode->resolve(this); @@ -153,29 +132,24 @@ bool FrameGraph::compile() return true; } -ResourceHandle FrameGraph::readInternal( - ResourceHandle id, [[maybe_unused]] PassNode* passNode, - std::function&& connect) +ResourceHandle FrameGraph::readInternal(ResourceHandle id, [[maybe_unused]] PassNode* passNode, std::function&& connect) { - VOX_ASSERT(id < static_cast(_resourceSlots.size()), - "Invalid ResourceHandle({}) is given", id.get()); + VOX_ASSERT(id < static_cast(_resourceSlots.size()), "Invalid ResourceHandle({}) is given", id.get()); const ResourceSlot& resourceSlot = getResourceSlot(id); ResourceNode* resourceNode = _resourceNodes[resourceSlot._nodeIndex]; VirtualResource* vResource = _resources[resourceSlot._resourceIndex]; - + #if defined(VOXFLOW_DEBUG) - DependencyGraph::EdgeContainer incomingEdges = - _dependencyGraph.getIncomingEdges(resourceNode->getNodeID()); + DependencyGraph::EdgeContainer incomingEdges = _dependencyGraph.getIncomingEdges(resourceNode->getNodeID()); for (const DependencyGraph::Edge* edge : incomingEdges) { if (edge->_fromNodeID == passNode->getNodeID()) { - VOX_ASSERT(false, - "This resource is already written by same pass node"); + VOX_ASSERT(false, "This resource is already written by same pass node"); } } -#endif // VOXFLOW_DEBUG +#endif // VOXFLOW_DEBUG if (connect(resourceNode, vResource)) { @@ -187,39 +161,35 @@ ResourceHandle FrameGraph::readInternal( return id; } -ResourceHandle FrameGraph::writeInternal( - ResourceHandle id, PassNode* passNode, - std::function&& connect) +ResourceHandle FrameGraph::writeInternal(ResourceHandle id, PassNode* passNode, std::function&& connect) { - VOX_ASSERT(id < static_cast(_resourceSlots.size()), - "Invalid ResourceHandle({}) is given", id.get()); + VOX_ASSERT(id < static_cast(_resourceSlots.size()), "Invalid ResourceHandle({}) is given", id.get()); const ResourceSlot& resourceSlot = getResourceSlot(id); VirtualResource* vResource = _resources[resourceSlot._resourceIndex]; ResourceNode* resourceNode = _resourceNodes[resourceSlot._nodeIndex]; - //const DependencyGraph::NodeID resourceNodeID = resourceNode->getNodeID(); + // const DependencyGraph::NodeID resourceNodeID = resourceNode->getNodeID(); - DependencyGraph::EdgeContainer outgoingEdges = - _dependencyGraph.getOutgoingEdges(passNode->getNodeID()); + DependencyGraph::EdgeContainer outgoingEdges = _dependencyGraph.getOutgoingEdges(passNode->getNodeID()); - //bool alreadyWritten = false; - //for (const DependencyGraph::Edge* edge : outgoingEdges) + // bool alreadyWritten = false; + // for (const DependencyGraph::Edge* edge : outgoingEdges) //{ - // if (edge->_toNodeID == resourceNodeID) - // { - // alreadyWritten = true; - // break; - // } - //} + // if (edge->_toNodeID == resourceNodeID) + // { + // alreadyWritten = true; + // break; + // } + // } // - //if (alreadyWritten) + // if (alreadyWritten) //{ - // // TODO(snowapril) : update resource usage or something else - //} - //else + // // TODO(snowapril) : update resource usage or something else + // } + // else //{ - // _dependencyGraph.link(passNode->getNodeID(), resourceNode->getNodeID()); - //} + // _dependencyGraph.link(passNode->getNodeID(), resourceNode->getNodeID()); + // } if (connect(resourceNode, vResource)) { @@ -251,12 +221,9 @@ void FrameGraph::buildAdjacencyLists(const uint32_t numPassNodes) if (i == j) continue; - for (const DependencyGraph::Edge* writeEdge : - _dependencyGraph.getOutgoingEdges(_passNodes[i]->getNodeID())) + for (const DependencyGraph::Edge* writeEdge : _dependencyGraph.getOutgoingEdges(_passNodes[i]->getNodeID())) { - for (const DependencyGraph::Edge* readEdge : - _dependencyGraph.getIncomingEdges( - _passNodes[j]->getNodeID())) + for (const DependencyGraph::Edge* readEdge : _dependencyGraph.getIncomingEdges(_passNodes[j]->getNodeID())) { if (writeEdge->_toNodeID == readEdge->_fromNodeID) { @@ -339,8 +306,7 @@ void FrameGraph::calcDependencyLevels(const uint32_t numPassNodes) if (sDistances[connectedNodeIndex] < sDistances[nodeIndex] + 1) { sDistances[connectedNodeIndex] = sDistances[nodeIndex] + 1; - maxDistances = - std::max(maxDistances, sDistances[connectedNodeIndex]); + maxDistances = std::max(maxDistances, sDistances[connectedNodeIndex]); } } } @@ -384,8 +350,7 @@ void FrameGraph::execute() { SCOPED_CHROME_TRACING("FrameGraph::execute"); - for (std::vector::iterator iter = _passNodes.begin(); - iter != _passNodeLast; ++iter) + for (std::vector::iterator iter = _passNodes.begin(); iter != _passNodeLast; ++iter) { PassNode* passNode = *iter; @@ -451,7 +416,7 @@ class AlphabetPermutator { permutationIndex++; needToIncrementAlphabet = false; - } + } } } return alphabetPermutation; @@ -467,8 +432,7 @@ void FrameGraph::dumpGraphViz(std::ostringstream& osstr) "[style=dashed];\n"; std::map nodeLabelMap; - const uint32_t numTotalNodes = - static_cast(_passNodes.size() + _resourceNodes.size()); + const uint32_t numTotalNodes = static_cast(_passNodes.size() + _resourceNodes.size()); AlphabetPermutator permutator(numTotalNodes); @@ -476,31 +440,25 @@ void FrameGraph::dumpGraphViz(std::ostringstream& osstr) { const std::string& nodeLabel = permutator.getNextAlphabetPermutation(); nodeLabelMap[passNode->getNodeID()] = nodeLabel; - osstr << "\t" << nodeLabel << "[ label=\"" << passNode->getPassName() - << "\" shape=record bgcolor=\"grey\" " - << "style=\"filled" << (passNode->isCulled() ? ",dashed\"" : "\"") - << "];\n"; + osstr << "\t" << nodeLabel << "[ label=\"" << passNode->getPassName() << "\" shape=record bgcolor=\"grey\" " + << "style=\"filled" << (passNode->isCulled() ? ",dashed\"" : "\"") << "];\n"; } osstr << '\n'; for (ResourceNode* resourceNode : _resourceNodes) { - VirtualResource* vresource = - _resources[getResourceSlot(resourceNode->getResourceHandle()) - ._resourceIndex]; + VirtualResource* vresource = _resources[getResourceSlot(resourceNode->getResourceHandle())._resourceIndex]; const std::string& nodeLabel = permutator.getNextAlphabetPermutation(); nodeLabelMap[resourceNode->getNodeID()] = nodeLabel; - osstr << "\t" << nodeLabel << "[ label=\"" - << vresource->getResourceName() << "\" shape=label " - << (resourceNode->isCulled() ? "style=dashed" : "") << "];\n"; + osstr << "\t" << nodeLabel << "[ label=\"" << vresource->getResourceName() << "\" shape=label " << (resourceNode->isCulled() ? "style=dashed" : "") + << "];\n"; } osstr << '\n'; for (const DependencyGraph::Edge* edge : _dependencyGraph.getLinkedEdges()) { - osstr << '\t' << nodeLabelMap[edge->_fromNodeID] << " -> " - << nodeLabelMap[edge->_toNodeID] << '\n'; + osstr << '\t' << nodeLabelMap[edge->_fromNodeID] << " -> " << nodeLabelMap[edge->_toNodeID] << '\n'; } osstr << '}'; } diff --git a/Sources/VoxFlow/Core/FrameGraph/FrameGraphPass.cpp b/Sources/VoxFlow/Core/FrameGraph/FrameGraphPass.cpp index cccd64bf..66caecc6 100644 --- a/Sources/VoxFlow/Core/FrameGraph/FrameGraphPass.cpp +++ b/Sources/VoxFlow/Core/FrameGraph/FrameGraphPass.cpp @@ -1,8 +1,8 @@ // Author : snowapril #include -#include #include +#include #include #include #include @@ -21,9 +21,7 @@ FrameGraphPassBase::~FrameGraphPassBase() { } -PassNode::PassNode(FrameGraph* ownerFrameGraph, std::string_view&& passName) - : DependencyGraph::Node(ownerFrameGraph->getDependencyGraph()), - _passName(passName) +PassNode::PassNode(FrameGraph* ownerFrameGraph, std::string_view&& passName) : DependencyGraph::Node(ownerFrameGraph->getDependencyGraph()), _passName(passName) { } @@ -31,8 +29,7 @@ PassNode ::~PassNode() { } -PassNode::PassNode(PassNode&& passNode) - : DependencyGraph::Node(std::move(passNode)) +PassNode::PassNode(PassNode&& passNode) : DependencyGraph::Node(std::move(passNode)) { operator=(std::move(passNode)); } @@ -66,8 +63,7 @@ void PassNode::addDestroy(VirtualResource* resource) _destroyes.push_back(resource); } -void RenderPassData::devirtualize(FrameGraph* frameGraph, - RenderResourceAllocator* allocator) +void RenderPassData::devirtualize(FrameGraph* frameGraph, RenderResourceAllocator* allocator) { (void)allocator; @@ -79,15 +75,12 @@ void RenderPassData::devirtualize(FrameGraph* frameGraph, ResourceHandle colorHandle = _descriptor._attachments[i]; if (colorHandle) { - Resource* resource = - static_cast*>( - frameGraph->getVirtualResource(colorHandle)); + Resource* resource = static_cast*>(frameGraph->getVirtualResource(colorHandle)); TextureView* attachmentView = nullptr; if (resource->isImported()) { - attachmentView = static_cast(resource) - ->getTextureView(); + attachmentView = static_cast(resource)->getTextureView(); } else { @@ -101,15 +94,12 @@ void RenderPassData::devirtualize(FrameGraph* frameGraph, if (_descriptor._attachments[MAX_RENDER_TARGET_COUNTS]) { Resource* resource = - static_cast*>( - frameGraph->getVirtualResource( - _descriptor._attachments[MAX_RENDER_TARGET_COUNTS])); + static_cast*>(frameGraph->getVirtualResource(_descriptor._attachments[MAX_RENDER_TARGET_COUNTS])); TextureView* attachmentView = nullptr; if (resource->isImported()) { - attachmentView = - static_cast(resource)->getTextureView(); + attachmentView = static_cast(resource)->getTextureView(); } else { @@ -119,9 +109,7 @@ void RenderPassData::devirtualize(FrameGraph* frameGraph, depthStencilAttachment = Attachment(attachmentView); } - _attachmentGroup = AttachmentGroup(std::move(colorAttachments), - std::move(depthStencilAttachment), - _descriptor._numSamples); + _attachmentGroup = AttachmentGroup(std::move(colorAttachments), std::move(depthStencilAttachment), _descriptor._numSamples); } void RenderPassData::destroy(RenderResourceAllocator* allocator) @@ -129,8 +117,7 @@ void RenderPassData::destroy(RenderResourceAllocator* allocator) (void)allocator; } -RenderPassNode::RenderPassNode(FrameGraph* ownerFrameGraph, std::string_view&& passName, - std::unique_ptr&& pass) +RenderPassNode::RenderPassNode(FrameGraph* ownerFrameGraph, std::string_view&& passName, std::unique_ptr&& pass) : PassNode(ownerFrameGraph, std::move(passName)), _passImpl(std::move(pass)) { } @@ -140,8 +127,7 @@ RenderPassNode::~RenderPassNode() _passImpl.reset(); } -RenderPassNode::RenderPassNode(RenderPassNode&& passNode) - : PassNode(std::move(passNode)) +RenderPassNode::RenderPassNode(RenderPassNode&& passNode) : PassNode(std::move(passNode)) { operator=(std::move(passNode)); } @@ -158,12 +144,10 @@ RenderPassNode& RenderPassNode::operator=(RenderPassNode&& passNode) return *this; } -void RenderPassNode::execute(const FrameGraphResources* resources, - CommandStream* cmdStream) +void RenderPassNode::execute(const FrameGraphResources* resources, CommandStream* cmdStream) { FrameGraph* frameGraph = resources->getFrameGraph(); - RenderResourceAllocator* allocator = - frameGraph->getRenderResourceAllocator(); + RenderResourceAllocator* allocator = frameGraph->getRenderResourceAllocator(); for (RenderPassData& passData : _renderPassDatas) { @@ -172,26 +156,22 @@ void RenderPassNode::execute(const FrameGraphResources* resources, _passImpl->execute(resources, cmdStream); - for (RenderPassData& passData : _renderPassDatas) { passData.destroy(allocator); } } -uint32_t RenderPassNode::declareRenderPass( - FrameGraph* frameGraph, FrameGraphBuilder* builder, std::string_view&& name, - typename FrameGraphRenderPass::Descriptor&& descriptor) +uint32_t RenderPassNode::declareRenderPass(FrameGraph* frameGraph, FrameGraphBuilder* builder, std::string_view&& name, + typename FrameGraphRenderPass::Descriptor&& descriptor) { // TODO(snowapril) : implement (void)frameGraph; (void)builder; - const uint32_t rpID = - static_cast(_renderPassDatas.size()); + const uint32_t rpID = static_cast(_renderPassDatas.size()); - RenderPassData renderPassData = { ._renderPassName = std::move(name), - ._descriptor = std::move(descriptor) }; + RenderPassData renderPassData = { ._renderPassName = std::move(name), ._descriptor = std::move(descriptor) }; _renderPassDatas.emplace_back(renderPassData); return rpID; @@ -208,20 +188,16 @@ void RenderPassNode::resolve(FrameGraph* frameGraph) { if (attachmentHandle) { - Resource* resource = - static_cast*>( - frameGraph->getVirtualResource(attachmentHandle)); + Resource* resource = static_cast*>(frameGraph->getVirtualResource(attachmentHandle)); - const FrameGraphTexture::Descriptor descriptor = - resource->getDescriptor(); + const FrameGraphTexture::Descriptor descriptor = resource->getDescriptor(); maxWidth = glm::max(descriptor._width, maxWidth); maxHeight = glm::max(descriptor._height, maxHeight); } } - if ((rpData._descriptor._viewportSize.x != 0U) && - (rpData._descriptor._viewportSize.y != 0U)) + if ((rpData._descriptor._viewportSize.x != 0U) && (rpData._descriptor._viewportSize.y != 0U)) { maxWidth = rpData._descriptor._viewportSize.x; maxHeight = rpData._descriptor._viewportSize.y; @@ -232,18 +208,12 @@ void RenderPassNode::resolve(FrameGraph* frameGraph) rpData._passParams._clearColors = rpData._descriptor._clearColors; rpData._passParams._clearDepth = rpData._descriptor._clearDepth; rpData._passParams._clearStencil = rpData._descriptor._clearStencil; - rpData._passParams._writableAttachment = - rpData._descriptor._writableAttachment; + rpData._passParams._writableAttachment = rpData._descriptor._writableAttachment; } } -PresentPassNode::PresentPassNode(FrameGraph* ownerFrameGraph, - std::string_view&& passName, - SwapChain* swapChainToPresent, - const FrameContext& frameContext) - : PassNode(ownerFrameGraph, std::move(passName)), - _swapChainToPresent(swapChainToPresent), - _frameContext(frameContext) +PresentPassNode::PresentPassNode(FrameGraph* ownerFrameGraph, std::string_view&& passName, SwapChain* swapChainToPresent, const FrameContext& frameContext) + : PassNode(ownerFrameGraph, std::move(passName)), _swapChainToPresent(swapChainToPresent), _frameContext(frameContext) { } @@ -251,8 +221,7 @@ PresentPassNode ::~PresentPassNode() { } -PresentPassNode::PresentPassNode(PresentPassNode&& passNode) - : PassNode(std::move(passNode)) +PresentPassNode::PresentPassNode(PresentPassNode&& passNode) : PassNode(std::move(passNode)) { operator=(std::move(passNode)); } @@ -263,15 +232,12 @@ PresentPassNode& PresentPassNode::operator=(PresentPassNode&& passNode) return *this; } -void PresentPassNode::execute(const FrameGraphResources* resources, - CommandStream* cmdStream) +void PresentPassNode::execute(const FrameGraphResources* resources, CommandStream* cmdStream) { - cmdStream->addJob(CommandJobType::MakeSwapChainFinalLayout, - _swapChainToPresent, _frameContext._backBufferIndex); + cmdStream->addJob(CommandJobType::MakeSwapChainFinalLayout, _swapChainToPresent, _frameContext._backBufferIndex); + + FenceObject executedFence = cmdStream->flush(_swapChainToPresent, &_frameContext, false); - FenceObject executedFence = - cmdStream->flush(_swapChainToPresent, &_frameContext, false); - resources->getFrameGraph()->setLastSubmitFence(executedFence); } diff --git a/Sources/VoxFlow/Core/FrameGraph/FrameGraphResources.cpp b/Sources/VoxFlow/Core/FrameGraph/FrameGraphResources.cpp index ff15b13a..98b9ab99 100644 --- a/Sources/VoxFlow/Core/FrameGraph/FrameGraphResources.cpp +++ b/Sources/VoxFlow/Core/FrameGraph/FrameGraphResources.cpp @@ -13,15 +13,12 @@ namespace RenderGraph TextureView* FrameGraphResources::getTextureView(ResourceHandle handle) const { - Resource* resource = - static_cast*>( - _frameGraph->getVirtualResource(handle)); + Resource* resource = static_cast*>(_frameGraph->getVirtualResource(handle)); TextureView* attachmentView = nullptr; if (resource->isImported()) { - attachmentView = - static_cast(resource)->getTextureView(); + attachmentView = static_cast(resource)->getTextureView(); } else { diff --git a/Sources/VoxFlow/Core/FrameGraph/FrameGraphTexture.cpp b/Sources/VoxFlow/Core/FrameGraph/FrameGraphTexture.cpp index e65a8129..63e98585 100644 --- a/Sources/VoxFlow/Core/FrameGraph/FrameGraphTexture.cpp +++ b/Sources/VoxFlow/Core/FrameGraph/FrameGraphTexture.cpp @@ -9,38 +9,29 @@ namespace VoxFlow namespace RenderGraph { -bool FrameGraphTexture::create(RenderResourceAllocator* resourceAllocator, - std::string&& debugName, Descriptor descriptor, - Usage usage) +bool FrameGraphTexture::create(RenderResourceAllocator* resourceAllocator, std::string&& debugName, Descriptor descriptor, Usage usage) { // TODO(snowapril) : - const glm::uvec3 extent(descriptor._width, descriptor._height, - descriptor._depth); + const glm::uvec3 extent(descriptor._width, descriptor._height, descriptor._depth); const VkImageType imageType = convertToImageType(extent); - const VkImageViewType imageViewType = - convertToImageViewType(imageType, extent); - - _texture = resourceAllocator->allocateTexture( - TextureInfo{ ._extent = - glm::uvec3(descriptor._width, descriptor._height, - descriptor._depth), - ._format = descriptor._format, - ._imageType = imageType, - ._usage = usage }, - std::move(debugName)); - - uint32_t viewIndex = - _texture - ->createTextureView(TextureViewInfo{ - ._viewType = imageViewType, - ._format = descriptor._format, - ._aspectFlags = convertToImageAspectFlags(descriptor._format), - ._baseMipLevel = descriptor._level, - ._levelCount = 1, - ._baseArrayLayer = 0, - ._layerCount = 1 }) - .value(); + const VkImageViewType imageViewType = convertToImageViewType(imageType, extent); + + _texture = resourceAllocator->allocateTexture(TextureInfo{ ._extent = glm::uvec3(descriptor._width, descriptor._height, descriptor._depth), + ._format = descriptor._format, + ._imageType = imageType, + ._usage = usage }, + std::move(debugName)); + + uint32_t viewIndex = _texture + ->createTextureView(TextureViewInfo{ ._viewType = imageViewType, + ._format = descriptor._format, + ._aspectFlags = convertToImageAspectFlags(descriptor._format), + ._baseMipLevel = descriptor._level, + ._levelCount = 1, + ._baseArrayLayer = 0, + ._layerCount = 1 }) + .value(); _textureView = _texture->getView(viewIndex).get(); diff --git a/Sources/VoxFlow/Core/FrameGraph/Resource.cpp b/Sources/VoxFlow/Core/FrameGraph/Resource.cpp index 389314d6..f2ffc6f1 100644 --- a/Sources/VoxFlow/Core/FrameGraph/Resource.cpp +++ b/Sources/VoxFlow/Core/FrameGraph/Resource.cpp @@ -1,9 +1,9 @@ // Author : snowapril +#include +#include #include #include -#include -#include #include #include @@ -11,8 +11,7 @@ namespace VoxFlow { namespace RenderGraph { -static FrameGraphTexture::Usage convertAttachmentFlagsToUsage( - FrameGraphRenderPass::ImportedDescriptor&& importedDesc) +static FrameGraphTexture::Usage convertAttachmentFlagsToUsage(FrameGraphRenderPass::ImportedDescriptor&& importedDesc) { (void)importedDesc; // TODO(snowapril) @@ -21,34 +20,24 @@ static FrameGraphTexture::Usage convertAttachmentFlagsToUsage( ResourceEdgeBase* ResourceNode::getReaderEdgeForPassNode(const PassNode* passNode) { - DependencyGraph::EdgeContainer outgoings = - _ownerGraph->getOutgoingEdges(passNode->getNodeID()); - - auto iter = - std::find_if(outgoings.begin(), outgoings.end(), - [passNode, this](const DependencyGraph::Edge* edge) { - return edge->_fromNodeID == passNode->getNodeID() && - edge->_toNodeID == _nodeId; - }); - - return iter == outgoings.end() ? nullptr - : static_cast(*iter); + DependencyGraph::EdgeContainer outgoings = _ownerGraph->getOutgoingEdges(passNode->getNodeID()); + + auto iter = std::find_if(outgoings.begin(), outgoings.end(), [passNode, this](const DependencyGraph::Edge* edge) { + return edge->_fromNodeID == passNode->getNodeID() && edge->_toNodeID == _nodeId; + }); + + return iter == outgoings.end() ? nullptr : static_cast(*iter); } ResourceEdgeBase* ResourceNode::getWriterEdgeForPassNode(const PassNode* passNode) { - DependencyGraph::EdgeContainer incomings = - _ownerGraph->getIncomingEdges(passNode->getNodeID()); - - auto iter = - std::find_if(incomings.begin(), incomings.end(), - [passNode, this](const DependencyGraph::Edge* edge) { - return edge->_fromNodeID == passNode->getNodeID() && - edge->_toNodeID == _nodeId; - }); - - return iter == incomings.end() ? nullptr - : static_cast(*iter); + DependencyGraph::EdgeContainer incomings = _ownerGraph->getIncomingEdges(passNode->getNodeID()); + + auto iter = std::find_if(incomings.begin(), incomings.end(), [passNode, this](const DependencyGraph::Edge* edge) { + return edge->_fromNodeID == passNode->getNodeID() && edge->_toNodeID == _nodeId; + }); + + return iter == incomings.end() ? nullptr : static_cast(*iter); } void ResourceNode::addOutgoingEdge(DependencyGraph::Edge* edge) @@ -58,8 +47,7 @@ void ResourceNode::addOutgoingEdge(DependencyGraph::Edge* edge) void ResourceNode::setIncomingEdge(DependencyGraph::Edge* edge) { - VOX_ASSERT(_incomingEdge == nullptr, - "There must not be multiple writer edges"); + VOX_ASSERT(_incomingEdge == nullptr, "There must not be multiple writer edges"); _incomingEdge = edge; } @@ -69,8 +57,7 @@ void ResourceNode::resolveResourceUsage(FrameGraph* frameGraph) resource->resolveUsage(_ownerGraph, _outgoingEdges, _incomingEdge); } -VirtualResource::VirtualResource(std::string&& name) - : _resourceName(std::move(name)) +VirtualResource::VirtualResource(std::string&& name) : _resourceName(std::move(name)) { } VirtualResource ::~VirtualResource() @@ -84,13 +71,10 @@ void VirtualResource::isReferencedByPass(PassNode* passNode) _lastPass = passNode; } -ImportedRenderTarget::ImportedRenderTarget( - std::string&& name, FrameGraphTexture::Descriptor&& resourceArgs, - typename FrameGraphRenderPass::ImportedDescriptor&& importedDesc, - const FrameGraphTexture& resource, TextureView* textureView) - : ImportedResource( - std::move(name), std::move(resourceArgs), - convertAttachmentFlagsToUsage(std::move(importedDesc)), resource), +ImportedRenderTarget::ImportedRenderTarget(std::string&& name, FrameGraphTexture::Descriptor&& resourceArgs, + typename FrameGraphRenderPass::ImportedDescriptor&& importedDesc, const FrameGraphTexture& resource, + TextureView* textureView) + : ImportedResource(std::move(name), std::move(resourceArgs), convertAttachmentFlagsToUsage(std::move(importedDesc)), resource), _textureViewHandle(textureView) { } @@ -99,8 +83,7 @@ ImportedRenderTarget::~ImportedRenderTarget() { } -ResourceNode::ResourceNode(DependencyGraph* dependencyGraph, - ResourceHandle resourceHandle) +ResourceNode::ResourceNode(DependencyGraph* dependencyGraph, ResourceHandle resourceHandle) : DependencyGraph::Node(dependencyGraph), _resourceHandle(resourceHandle) { } diff --git a/Sources/VoxFlow/Core/FrameGraph/ResourceHandle.cpp b/Sources/VoxFlow/Core/FrameGraph/ResourceHandle.cpp index 03c53364..b6d88297 100644 --- a/Sources/VoxFlow/Core/FrameGraph/ResourceHandle.cpp +++ b/Sources/VoxFlow/Core/FrameGraph/ResourceHandle.cpp @@ -11,8 +11,7 @@ namespace RenderGraph } // namespace VoxFlow -std::size_t std::hash::operator()( - VoxFlow::RenderGraph::ResourceHandle const& handle) const noexcept +std::size_t std::hash::operator()(VoxFlow::RenderGraph::ResourceHandle const& handle) const noexcept { uint32_t seed = 0; VoxFlow::hash_combine(seed, handle.get()); diff --git a/Sources/VoxFlow/Core/Graphics/Commands/CommandBuffer.cpp b/Sources/VoxFlow/Core/Graphics/Commands/CommandBuffer.cpp index 14ccf70e..fa38879e 100644 --- a/Sources/VoxFlow/Core/Graphics/Commands/CommandBuffer.cpp +++ b/Sources/VoxFlow/Core/Graphics/Commands/CommandBuffer.cpp @@ -9,27 +9,24 @@ #include #include #include -#include #include +#include #include #include #include #include -#include #include -#include #include -#include +#include #include +#include +#include #include namespace VoxFlow { -CommandBuffer::CommandBuffer(LogicalDevice* logicalDevice, - VkCommandBuffer vkCommandBuffer) - : _logicalDevice(logicalDevice), - _vkCommandBuffer(vkCommandBuffer), - _resourceBarrierManager(this) +CommandBuffer::CommandBuffer(LogicalDevice* logicalDevice, VkCommandBuffer vkCommandBuffer) + : _logicalDevice(logicalDevice), _vkCommandBuffer(vkCommandBuffer), _resourceBarrierManager(this) { // TODO(snowapril) : temporal sampler _sampler = new Sampler("TempSampler", logicalDevice); @@ -45,8 +42,7 @@ CommandBuffer::~CommandBuffer() } } -void CommandBuffer::beginCommandBuffer(const FenceObject& fenceToSignal, - const std::string& debugName) +void CommandBuffer::beginCommandBuffer(const FenceObject& fenceToSignal, const std::string& debugName) { _debugName = debugName; @@ -54,9 +50,7 @@ void CommandBuffer::beginCommandBuffer(const FenceObject& fenceToSignal, // will use below new allocated fence. _fenceToSignal = fenceToSignal; - VOX_ASSERT(_hasBegun == false, - "Duplicated beginning on the same CommandBuffer({})", - _debugName); + VOX_ASSERT(_hasBegun == false, "Duplicated beginning on the same CommandBuffer({})", _debugName); VkCommandBufferBeginInfo beginInfo = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, @@ -68,8 +62,7 @@ void CommandBuffer::beginCommandBuffer(const FenceObject& fenceToSignal, _hasBegun = true; #if defined(VK_DEBUG_NAME_ENABLED) - DebugUtil::setObjectName(_logicalDevice, _vkCommandBuffer, - _debugName.c_str()); + DebugUtil::setObjectName(_logicalDevice, _vkCommandBuffer, _debugName.c_str()); #endif } @@ -79,14 +72,11 @@ void CommandBuffer::endCommandBuffer() _hasBegun = false; } -void CommandBuffer::beginRenderPass(const AttachmentGroup& attachmentGroup, - const RenderPassParams& passParams) +void CommandBuffer::beginRenderPass(const AttachmentGroup& attachmentGroup, const RenderPassParams& passParams) { - RenderPassCollector* renderPassCollector = - _logicalDevice->getRenderPassCollector(); + RenderPassCollector* renderPassCollector = _logicalDevice->getRenderPassCollector(); - const uint32_t numColorAttachments = - attachmentGroup.getNumColorAttachments(); + const uint32_t numColorAttachments = attachmentGroup.getNumColorAttachments(); const bool hasDepthStencil = attachmentGroup.hasDepthStencil(); RenderTargetLayoutKey rtLayoutKey = {}; @@ -103,8 +93,7 @@ void CommandBuffer::beginRenderPass(const AttachmentGroup& attachmentGroup, rtInfo._colorRenderTarget.emplace_back(textureView); - addMemoryBarrier(textureView, ResourceAccessMask::ColorAttachment, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); + addMemoryBarrier(textureView, ResourceAccessMask::ColorAttachment, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); } if (hasDepthStencil) @@ -116,8 +105,7 @@ void CommandBuffer::beginRenderPass(const AttachmentGroup& attachmentGroup, rtInfo._depthStencilImage = textureView; addMemoryBarrier(textureView, ResourceAccessMask::DepthAttachment, - VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | - VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT); + VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT); } _resourceBarrierManager.commitPendingBarriers(false); @@ -139,35 +127,23 @@ void CommandBuffer::beginRenderPass(const AttachmentGroup& attachmentGroup, { const glm::vec4& clearColorValue = passParams._clearColors[i]; clearValues.push_back( - VkClearValue{ .color = VkClearColorValue{ - .float32 = { clearColorValue.x, - clearColorValue.y, - clearColorValue.z, - clearColorValue.w } } }); + VkClearValue{ .color = VkClearColorValue{ .float32 = { clearColorValue.x, clearColorValue.y, clearColorValue.z, clearColorValue.w } } }); } if (hasDepthStencil) { - clearValues.push_back( - VkClearValue{ .depthStencil = VkClearDepthStencilValue{ - .depth = passParams._clearDepth, - .stencil = passParams._clearStencil } }); + clearValues.push_back(VkClearValue{ .depthStencil = VkClearDepthStencilValue{ .depth = passParams._clearDepth, .stencil = passParams._clearStencil } }); } - VkRenderPassBeginInfo renderPassInfo = { - .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, - .pNext = nullptr, - .renderPass = _boundRenderPass->get(), - .framebuffer = frameBuffer->get(), - .renderArea = { .offset = { 0U, 0U }, - .extent = { rtInfo._resolution.x, - rtInfo._resolution.y } }, - .clearValueCount = static_cast(clearValues.size()), - .pClearValues = clearValues.data() - }; + VkRenderPassBeginInfo renderPassInfo = { .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, + .pNext = nullptr, + .renderPass = _boundRenderPass->get(), + .framebuffer = frameBuffer->get(), + .renderArea = { .offset = { 0U, 0U }, .extent = { rtInfo._resolution.x, rtInfo._resolution.y } }, + .clearValueCount = static_cast(clearValues.size()), + .pClearValues = clearValues.data() }; - vkCmdBeginRenderPass(_vkCommandBuffer, &renderPassInfo, - VK_SUBPASS_CONTENTS_INLINE); + vkCmdBeginRenderPass(_vkCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); _isInRenderPassScope = true; } @@ -191,8 +167,7 @@ void CommandBuffer::bindIndexBuffer(Buffer* indexBuffer) { // TODO(snowapril) : must implement details VkBuffer vkIndexBuffer = indexBuffer->get(); - vkCmdBindIndexBuffer(_vkCommandBuffer, vkIndexBuffer, 0, - VK_INDEX_TYPE_UINT32); + vkCmdBindIndexBuffer(_vkCommandBuffer, vkIndexBuffer, 0, VK_INDEX_TYPE_UINT32); } void CommandBuffer::bindPipeline(BasePipeline* pipeline) @@ -217,8 +192,7 @@ void CommandBuffer::bindPipeline(BasePipeline* pipeline) } } - vkCmdBindPipeline(_vkCommandBuffer, _boundPipeline->getBindPoint(), - _boundPipeline->get()); + vkCmdBindPipeline(_vkCommandBuffer, _boundPipeline->getBindPoint(), _boundPipeline->get()); } void CommandBuffer::unbindPipeline() @@ -228,36 +202,27 @@ void CommandBuffer::unbindPipeline() void CommandBuffer::setViewport(const glm::uvec2& viewportSize) { - VkViewport viewport = { .x = 0, - .y = 0, - .width = static_cast(viewportSize.x), - .height = static_cast(viewportSize.y), - .minDepth = 0.0f, - .maxDepth = 1.0f }; + VkViewport viewport = { + .x = 0, .y = 0, .width = static_cast(viewportSize.x), .height = static_cast(viewportSize.y), .minDepth = 0.0f, .maxDepth = 1.0f + }; vkCmdSetViewport(_vkCommandBuffer, 0, 1, &viewport); - VkRect2D scissor = { .offset = { .x = 0, .y = 0 }, - .extent = { .width = viewportSize.x, - .height = viewportSize.y } }; + VkRect2D scissor = { .offset = { .x = 0, .y = 0 }, .extent = { .width = viewportSize.x, .height = viewportSize.y } }; vkCmdSetScissor(_vkCommandBuffer, 0, 1, &scissor); } void CommandBuffer::makeSwapChainFinalLayout(SwapChain* swapChain, const uint32_t backBufferIndex) { const std::shared_ptr& backBuffer = swapChain->getSwapChainImage(backBufferIndex); - - addMemoryBarrier(backBuffer->getDefaultView(), ResourceAccessMask::Present, - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); + + addMemoryBarrier(backBuffer->getDefaultView(), ResourceAccessMask::Present, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); _resourceBarrierManager.commitPendingBarriers(_isInRenderPassScope); } -void CommandBuffer::bindResourceGroup( - SetSlotCategory setSlotCategory, - std::vector&& shaderVariables) +void CommandBuffer::bindResourceGroup(SetSlotCategory setSlotCategory, std::vector&& shaderVariables) { - std::vector& dstBindingResources = - _pendingResourceBindings[static_cast(setSlotCategory)]; + std::vector& dstBindingResources = _pendingResourceBindings[static_cast(setSlotCategory)]; if (dstBindingResources.empty()) { @@ -265,11 +230,8 @@ void CommandBuffer::bindResourceGroup( } else { - dstBindingResources.reserve(dstBindingResources.size() + - shaderVariables.size()); - std::move(std::make_move_iterator(shaderVariables.begin()), - std::make_move_iterator(shaderVariables.end()), - std::back_inserter(dstBindingResources)); + dstBindingResources.reserve(dstBindingResources.size() + shaderVariables.size()); + std::move(std::make_move_iterator(shaderVariables.begin()), std::make_move_iterator(shaderVariables.end()), std::back_inserter(dstBindingResources)); } } @@ -281,8 +243,7 @@ static VkPipelineStageFlags evaluatePipelineStageFlags(ResourceView* view, Resou if (uint32_t(usedStages & VK_SHADER_STAGE_VERTEX_BIT) > 0) { - if ((uint32_t(accessMask & ResourceAccessMask::VertexBuffer) > 0) || - (uint32_t(accessMask & ResourceAccessMask::IndexBuffer) > 0)) + if ((uint32_t(accessMask & ResourceAccessMask::VertexBuffer) > 0) || (uint32_t(accessMask & ResourceAccessMask::IndexBuffer) > 0)) { pipelineStageFlags |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT; } @@ -296,10 +257,8 @@ static VkPipelineStageFlags evaluatePipelineStageFlags(ResourceView* view, Resou } } - if ((uint32_t(accessMask & ResourceAccessMask::ShaderReadOnly) > 0) || - (uint32_t(accessMask & ResourceAccessMask::General) > 0) || - (uint32_t(accessMask & ResourceAccessMask::StorageBuffer) > 0) || - (uint32_t(accessMask & ResourceAccessMask::UniformBuffer) > 0)) + if ((uint32_t(accessMask & ResourceAccessMask::ShaderReadOnly) > 0) || (uint32_t(accessMask & ResourceAccessMask::General) > 0) || + (uint32_t(accessMask & ResourceAccessMask::StorageBuffer) > 0) || (uint32_t(accessMask & ResourceAccessMask::UniformBuffer) > 0)) { if (uint32_t(usedStages & VK_SHADER_STAGE_VERTEX_BIT) > 0) { @@ -307,14 +266,11 @@ static VkPipelineStageFlags evaluatePipelineStageFlags(ResourceView* view, Resou } if (uint32_t(usedStages & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT) > 0) { - pipelineStageFlags |= - VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT; + pipelineStageFlags |= VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT; } - if (uint32_t(usedStages & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) > - 0) + if (uint32_t(usedStages & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) > 0) { - pipelineStageFlags |= - VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT; + pipelineStageFlags |= VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT; } if (uint32_t(usedStages & VK_SHADER_STAGE_GEOMETRY_BIT) > 0) { @@ -330,8 +286,7 @@ static VkPipelineStageFlags evaluatePipelineStageFlags(ResourceView* view, Resou } } - if ((uint32_t(accessMask & ResourceAccessMask::TransferSource) > 0) || - uint32_t(accessMask & ResourceAccessMask::TransferDest) > 0) + if ((uint32_t(accessMask & ResourceAccessMask::TransferSource) > 0) || uint32_t(accessMask & ResourceAccessMask::TransferDest) > 0) { pipelineStageFlags |= VK_PIPELINE_STAGE_TRANSFER_BIT; } @@ -344,13 +299,11 @@ static VkPipelineStageFlags evaluatePipelineStageFlags(ResourceView* view, Resou } if (uint32_t(accessMask & ResourceAccessMask::DepthAttachment) > 0) { - pipelineStageFlags |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | - VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; + pipelineStageFlags |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; } if (uint32_t(accessMask & ResourceAccessMask::StencilAttachment) > 0) { - pipelineStageFlags |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | - VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; + pipelineStageFlags |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; } if (uint32_t(accessMask & ResourceAccessMask::DepthReadOnly) > 0) { @@ -369,24 +322,18 @@ void CommandBuffer::commitPendingResourceBindings() { // TODO(snowapril) : split update descriptor sets according to set frequency const PipelineLayout* pipelineLayout = _boundPipeline->getPipelineLayout(); - - const PipelineLayout::ShaderVariableMap& shaderVariableMap = - pipelineLayout->getShaderVariableMap(); - const PipelineLayoutDescriptor& pipelineLayoutDesc = - pipelineLayout->getPipelineLayoutDescriptor(); + + const PipelineLayout::ShaderVariableMap& shaderVariableMap = pipelineLayout->getShaderVariableMap(); + const PipelineLayoutDescriptor& pipelineLayoutDesc = pipelineLayout->getPipelineLayoutDescriptor(); for (uint32_t setIndex = 1; setIndex < MAX_NUM_SET_SLOTS; ++setIndex) { - const SetSlotCategory setSlotCategory = - static_cast(setIndex); + const SetSlotCategory setSlotCategory = static_cast(setIndex); - std::vector& bindGroup = - _pendingResourceBindings[setIndex]; + std::vector& bindGroup = _pendingResourceBindings[setIndex]; - DescriptorSetAllocator* setAllocator = - pipelineLayout->getDescSetAllocator(setSlotCategory); - const DescriptorSetLayoutDesc& setLayoutDesc = - setAllocator->getDescriptorSetLayoutDesc(); + DescriptorSetAllocator* setAllocator = pipelineLayout->getDescSetAllocator(setSlotCategory); + const DescriptorSetLayoutDesc& setLayoutDesc = setAllocator->getDescriptorSetLayoutDesc(); const size_t numDescriptors = setLayoutDesc._descriptorInfos.size(); if (numDescriptors == 0ULL) @@ -394,9 +341,7 @@ void CommandBuffer::commitPendingResourceBindings() continue; } - VkDescriptorSet pooledDescriptorSet = - static_cast(setAllocator) - ->getOrCreatePooledDescriptorSet(_fenceToSignal); + VkDescriptorSet pooledDescriptorSet = static_cast(setAllocator)->getOrCreatePooledDescriptorSet(_fenceToSignal); std::vector vkWrites; vkWrites.reserve(bindGroup.size()); @@ -411,11 +356,9 @@ void CommandBuffer::commitPendingResourceBindings() for (const ShaderVariableBinding& resourceBinding : bindGroup) { - const std::string& resourceBindingName = - resourceBinding._variableName; + const std::string& resourceBindingName = resourceBinding._variableName; - auto shaderVariableIter = - shaderVariableMap.find(resourceBindingName); + auto shaderVariableIter = shaderVariableMap.find(resourceBindingName); if (shaderVariableIter == shaderVariableMap.end()) { VOX_ASSERT(false, @@ -429,11 +372,9 @@ void CommandBuffer::commitPendingResourceBindings() ResourceView* bindingResourceView = resourceBinding._view; - const VkPipelineStageFlags stageFlags = evaluatePipelineStageFlags( - bindingResourceView, resourceBinding._usage, - pipelineLayoutDesc._sets[setIndex]._stageFlags); - addMemoryBarrier(bindingResourceView, resourceBinding._usage, - stageFlags); + const VkPipelineStageFlags stageFlags = + evaluatePipelineStageFlags(bindingResourceView, resourceBinding._usage, pipelineLayoutDesc._sets[setIndex]._stageFlags); + addMemoryBarrier(bindingResourceView, resourceBinding._usage, stageFlags); const VkDescriptorImageInfo* imageInfo = nullptr; const VkDescriptorBufferInfo* bufferInfo = nullptr; @@ -444,8 +385,7 @@ void CommandBuffer::commitPendingResourceBindings() switch (descriptorInfo._descriptorCategory) { case DescriptorCategory::CombinedImage: - vkDescriptorType = - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + vkDescriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; break; case DescriptorCategory::UniformBuffer: vkDescriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; @@ -454,55 +394,44 @@ void CommandBuffer::commitPendingResourceBindings() vkDescriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; break; default: - VOX_ASSERT(false, - "Unknown descriptor category must not be exist"); + VOX_ASSERT(false, "Unknown descriptor category must not be exist"); break; } switch (bindingResourceView->getResourceViewType()) { case ResourceViewType::BufferView: - sTmpBufferInfos[currentDescriptorInfoIndex] = - static_cast(bindingResourceView) - ->getDescriptorBufferInfo(); + sTmpBufferInfos[currentDescriptorInfoIndex] = static_cast(bindingResourceView)->getDescriptorBufferInfo(); bufferInfo = &sTmpBufferInfos[currentDescriptorInfoIndex++]; break; case ResourceViewType::ImageView: - sTmpImageInfos[currentDescriptorInfoIndex] = - static_cast(bindingResourceView) - ->getDescriptorImageInfo(); + sTmpImageInfos[currentDescriptorInfoIndex] = static_cast(bindingResourceView)->getDescriptorImageInfo(); - sTmpImageInfos[currentDescriptorInfoIndex].imageLayout = - static_cast(bindingResourceView) - ->getCurrentVkImageLayout(); + sTmpImageInfos[currentDescriptorInfoIndex].imageLayout = static_cast(bindingResourceView)->getCurrentVkImageLayout(); - if (descriptorInfo._descriptorCategory == - DescriptorCategory::CombinedImage) + if (descriptorInfo._descriptorCategory == DescriptorCategory::CombinedImage) { - sTmpImageInfos[currentDescriptorInfoIndex].sampler = - _sampler->get(); + sTmpImageInfos[currentDescriptorInfoIndex].sampler = _sampler->get(); } imageInfo = &sTmpImageInfos[currentDescriptorInfoIndex++]; break; case ResourceViewType::StagingBufferView: default: - VOX_ASSERT(false, - "Unhandled resource view type"); + VOX_ASSERT(false, "Unhandled resource view type"); break; } - vkWrites.push_back(VkWriteDescriptorSet{ - .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, - .pNext = nullptr, - .dstSet = pooledDescriptorSet, - .dstBinding = static_cast(binding), - .dstArrayElement = 0, - .descriptorCount = arraySize, - .descriptorType = vkDescriptorType, - .pImageInfo = imageInfo, - .pBufferInfo = bufferInfo, - .pTexelBufferView = nullptr }); + vkWrites.push_back(VkWriteDescriptorSet{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, + .pNext = nullptr, + .dstSet = pooledDescriptorSet, + .dstBinding = static_cast(binding), + .dstArrayElement = 0, + .descriptorCount = arraySize, + .descriptorType = vkDescriptorType, + .pImageInfo = imageInfo, + .pBufferInfo = bufferInfo, + .pTexelBufferView = nullptr }); } // Note(snowapril) : As vulkan validation layer require that resource @@ -510,44 +439,30 @@ void CommandBuffer::commitPendingResourceBindings() // before issuing draw/dispatch), commit barrier first. _resourceBarrierManager.commitPendingBarriers(_isInRenderPassScope); - vkUpdateDescriptorSets(_logicalDevice->get(), - static_cast(vkWrites.size()), - vkWrites.data(), 0, nullptr); + vkUpdateDescriptorSets(_logicalDevice->get(), static_cast(vkWrites.size()), vkWrites.data(), 0, nullptr); - vkCmdBindDescriptorSets( - _vkCommandBuffer, _boundPipeline->getBindPoint(), - pipelineLayout->get(), static_cast(setSlotCategory), 1, - &pooledDescriptorSet, 0, nullptr); + vkCmdBindDescriptorSets(_vkCommandBuffer, _boundPipeline->getBindPoint(), pipelineLayout->get(), static_cast(setSlotCategory), 1, + &pooledDescriptorSet, 0, nullptr); bindGroup.clear(); } } -void CommandBuffer::uploadBuffer(Buffer* dstBuffer, StagingBuffer* srcBuffer, - const uint32_t dstOffset, const uint32_t srcOffset, - const uint32_t size) +void CommandBuffer::uploadBuffer(Buffer* dstBuffer, StagingBuffer* srcBuffer, const uint32_t dstOffset, const uint32_t srcOffset, const uint32_t size) { - const VkBufferCopy bufferCopy = { .srcOffset = srcOffset, - .dstOffset = dstOffset, - .size = size }; + const VkBufferCopy bufferCopy = { .srcOffset = srcOffset, .dstOffset = dstOffset, .size = size }; VkBuffer srcVkBuffer = srcBuffer->get(); VkBuffer dstVkBuffer = dstBuffer->get(); - addMemoryBarrier(dstBuffer->getDefaultView(), - ResourceAccessMask::TransferDest, - VK_PIPELINE_STAGE_TRANSFER_BIT); - addMemoryBarrier(srcBuffer->getDefaultView(), - ResourceAccessMask::TransferSource, - VK_PIPELINE_STAGE_TRANSFER_BIT); + addMemoryBarrier(dstBuffer->getDefaultView(), ResourceAccessMask::TransferDest, VK_PIPELINE_STAGE_TRANSFER_BIT); + addMemoryBarrier(srcBuffer->getDefaultView(), ResourceAccessMask::TransferSource, VK_PIPELINE_STAGE_TRANSFER_BIT); _resourceBarrierManager.commitPendingBarriers(_isInRenderPassScope); vkCmdCopyBuffer(_vkCommandBuffer, srcVkBuffer, dstVkBuffer, 1, &bufferCopy); } -void CommandBuffer::uploadTexture(Texture* dstTexture, StagingBuffer* srcBuffer, - const uint32_t dstOffset, const uint32_t srcOffset, - const uint32_t size) +void CommandBuffer::uploadTexture(Texture* dstTexture, StagingBuffer* srcBuffer, const uint32_t dstOffset, const uint32_t srcOffset, const uint32_t size) { (void)dstTexture; (void)srcBuffer; @@ -556,59 +471,45 @@ void CommandBuffer::uploadTexture(Texture* dstTexture, StagingBuffer* srcBuffer, (void)size; } -void CommandBuffer::draw(uint32_t vertexCount, uint32_t instanceCount, - uint32_t firstVertex, uint32_t firstInstance) +void CommandBuffer::draw(uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance) { commitPendingResourceBindings(); - vkCmdDraw(_vkCommandBuffer, vertexCount, instanceCount, firstVertex, - firstInstance); + vkCmdDraw(_vkCommandBuffer, vertexCount, instanceCount, firstVertex, firstInstance); } -void CommandBuffer::drawIndexed(uint32_t indexCount, uint32_t instanceCount, - uint32_t firstIndex, int32_t vertexOffset, - uint32_t firstInstance) +void CommandBuffer::drawIndexed(uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) { commitPendingResourceBindings(); - vkCmdDrawIndexed(_vkCommandBuffer, indexCount, instanceCount, firstIndex, - vertexOffset, firstInstance); + vkCmdDrawIndexed(_vkCommandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance); } -void CommandBuffer::addGlobalMemoryBarrier(ResourceAccessMask prevAccessMasks, - ResourceAccessMask nextAccessMasks) +void CommandBuffer::addGlobalMemoryBarrier(ResourceAccessMask prevAccessMasks, ResourceAccessMask nextAccessMasks) { - _resourceBarrierManager.addGlobalMemoryBarrier(prevAccessMasks, - nextAccessMasks); + _resourceBarrierManager.addGlobalMemoryBarrier(prevAccessMasks, nextAccessMasks); } -void CommandBuffer::addMemoryBarrier(ResourceView* view, - ResourceAccessMask accessMask, - VkPipelineStageFlags nextStageFlags) +void CommandBuffer::addMemoryBarrier(ResourceView* view, ResourceAccessMask accessMask, VkPipelineStageFlags nextStageFlags) { const ResourceViewType viewType = view->getResourceViewType(); switch (viewType) { case ResourceViewType::BufferView: - _resourceBarrierManager.addBufferMemoryBarrier( - static_cast(view), accessMask, nextStageFlags); + _resourceBarrierManager.addBufferMemoryBarrier(static_cast(view), accessMask, nextStageFlags); break; case ResourceViewType::ImageView: - _resourceBarrierManager.addTextureMemoryBarrier( - static_cast(view), accessMask, nextStageFlags); + _resourceBarrierManager.addTextureMemoryBarrier(static_cast(view), accessMask, nextStageFlags); break; case ResourceViewType::StagingBufferView: - _resourceBarrierManager.addStagingBufferMemoryBarrier( - static_cast(view), accessMask, - nextStageFlags); + _resourceBarrierManager.addStagingBufferMemoryBarrier(static_cast(view), accessMask, nextStageFlags); break; default: break; } } -void CommandBuffer::addExecutionBarrier(VkPipelineStageFlags prevStageFlags, - VkPipelineStageFlags nextStageFlags) +void CommandBuffer::addExecutionBarrier(VkPipelineStageFlags prevStageFlags, VkPipelineStageFlags nextStageFlags) { _resourceBarrierManager.addExecutionBarrier(prevStageFlags, nextStageFlags); } diff --git a/Sources/VoxFlow/Core/Graphics/Commands/CommandConfig.cpp b/Sources/VoxFlow/Core/Graphics/Commands/CommandConfig.cpp index 68615220..66222324 100644 --- a/Sources/VoxFlow/Core/Graphics/Commands/CommandConfig.cpp +++ b/Sources/VoxFlow/Core/Graphics/Commands/CommandConfig.cpp @@ -7,8 +7,7 @@ namespace VoxFlow { } // namespace VoxFlow -std::size_t std::hash::operator()( - VoxFlow::CommandStreamKey const& streamKey) const noexcept +std::size_t std::hash::operator()(VoxFlow::CommandStreamKey const& streamKey) const noexcept { uint32_t seed = 0; diff --git a/Sources/VoxFlow/Core/Graphics/Commands/CommandJobSystem.cpp b/Sources/VoxFlow/Core/Graphics/Commands/CommandJobSystem.cpp index 633d192d..3b7a6bf3 100644 --- a/Sources/VoxFlow/Core/Graphics/Commands/CommandJobSystem.cpp +++ b/Sources/VoxFlow/Core/Graphics/Commands/CommandJobSystem.cpp @@ -7,8 +7,7 @@ namespace VoxFlow { -CommandStream::CommandStream(LogicalDevice* logicalDevice, Queue* queue) - : _logicalDevice(logicalDevice), _queue(queue) +CommandStream::CommandStream(LogicalDevice* logicalDevice, Queue* queue) : _logicalDevice(logicalDevice), _queue(queue) { } @@ -16,9 +15,7 @@ CommandStream::~CommandStream() { } -FenceObject CommandStream::flush(SwapChain* swapChain, - const FrameContext* frameContext, - const bool waitAllCompletion) +FenceObject CommandStream::flush(SwapChain* swapChain, const FrameContext* frameContext, const bool waitAllCompletion) { std::vector> cmdBufs; { @@ -37,8 +34,7 @@ FenceObject CommandStream::flush(SwapChain* swapChain, } // TODO(snowapril) : sort command buffer according and set dependency - FenceObject fenceToSignal = _queue->submitCommandBufferBatch( - std::move(cmdBufs), swapChain, frameContext, waitAllCompletion); + FenceObject fenceToSignal = _queue->submitCommandBufferBatch(std::move(cmdBufs), swapChain, frameContext, waitAllCompletion); return fenceToSignal; } @@ -55,11 +51,9 @@ CommandBuffer* CommandStream::getOrAllocateCommandBuffer() if (cmdIter == _cmdBufferStorage.end()) { CommandPool* cmdPool = getOrAllocateCommandPool(); - std::shared_ptr cmdBufferPtr = - cmdPool->getOrCreateCommandBuffer(); + std::shared_ptr cmdBufferPtr = cmdPool->getOrCreateCommandBuffer(); // TODO(snowapril) : add thread_id to command buffer begin name - cmdBufferPtr->beginCommandBuffer(_queue->allocateFenceToSignal(), - fmt::format("CommandStream")); + cmdBufferPtr->beginCommandBuffer(_queue->allocateFenceToSignal(), fmt::format("CommandStream")); cmdBuffer = cmdBufferPtr.get(); _cmdBufferStorage.emplace(threadId, std::move(cmdBufferPtr)); @@ -69,7 +63,7 @@ CommandBuffer* CommandStream::getOrAllocateCommandBuffer() cmdBuffer = cmdIter->second.get(); } } - + return cmdBuffer; } @@ -83,8 +77,7 @@ CommandPool* CommandStream::getOrAllocateCommandPool() auto cmdPoolIter = _cmdPoolStorage.find(threadId); if (cmdPoolIter == _cmdPoolStorage.end()) { - auto cmdPoolPtr = - std::make_unique(_logicalDevice, _queue); + auto cmdPoolPtr = std::make_unique(_logicalDevice, _queue); cmdPool = cmdPoolPtr.get(); _cmdPoolStorage.emplace(threadId, std::move(cmdPoolPtr)); } @@ -97,8 +90,7 @@ CommandPool* CommandStream::getOrAllocateCommandPool() return cmdPool; } -CommandJobSystem::CommandJobSystem(LogicalDevice* logicalDevice) - : _logicalDevice(logicalDevice) +CommandJobSystem::CommandJobSystem(LogicalDevice* logicalDevice) : _logicalDevice(logicalDevice) { } @@ -106,19 +98,15 @@ CommandJobSystem::~CommandJobSystem() { } -void CommandJobSystem::createCommandStream(const CommandStreamKey& streamKey, - Queue* queue) +void CommandJobSystem::createCommandStream(const CommandStreamKey& streamKey, Queue* queue) { - _cmdStreams.emplace(streamKey, - std::make_unique(_logicalDevice, queue)); + _cmdStreams.emplace(streamKey, std::make_unique(_logicalDevice, queue)); } -CommandStream* CommandJobSystem::getCommandStream( - const CommandStreamKey& streamKey) +CommandStream* CommandJobSystem::getCommandStream(const CommandStreamKey& streamKey) { CommandStream* cmdStream = nullptr; - if (auto cmdStreamIter = _cmdStreams.find(streamKey); - cmdStreamIter != _cmdStreams.end()) + if (auto cmdStreamIter = _cmdStreams.find(streamKey); cmdStreamIter != _cmdStreams.end()) { cmdStream = cmdStreamIter->second.get(); } diff --git a/Sources/VoxFlow/Core/Graphics/Commands/CommandPool.cpp b/Sources/VoxFlow/Core/Graphics/Commands/CommandPool.cpp index 1690c5fe..de98afe5 100644 --- a/Sources/VoxFlow/Core/Graphics/Commands/CommandPool.cpp +++ b/Sources/VoxFlow/Core/Graphics/Commands/CommandPool.cpp @@ -8,9 +8,7 @@ namespace VoxFlow { CommandPool::CommandPool(LogicalDevice* logicalDevice, Queue* ownerQueue) - : _creationThreadId(std::this_thread::get_id()), - _logicalDevice(logicalDevice), - _ownerQueue(ownerQueue) + : _creationThreadId(std::this_thread::get_id()), _logicalDevice(logicalDevice), _ownerQueue(ownerQueue) { VkCommandPoolCreateInfo poolInfo{ @@ -19,18 +17,14 @@ CommandPool::CommandPool(LogicalDevice* logicalDevice, Queue* ownerQueue) .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, .queueFamilyIndex = _ownerQueue->getFamilyIndex(), }; - VK_ASSERT(vkCreateCommandPool(_logicalDevice->get(), &poolInfo, nullptr, - &_commandPool)); + VK_ASSERT(vkCreateCommandPool(_logicalDevice->get(), &poolInfo, nullptr, &_commandPool)); #if defined(VK_DEBUG_NAME_ENABLED) - const std::string debugName = - _ownerQueue->getDebugName() + "_" + - std::to_string(reinterpret_cast(_commandPool)); + const std::string debugName = _ownerQueue->getDebugName() + "_" + std::to_string(reinterpret_cast(_commandPool)); if (_commandPool != VK_NULL_HANDLE) { - DebugUtil::setObjectName(_logicalDevice, _commandPool, - debugName.c_str()); + DebugUtil::setObjectName(_logicalDevice, _commandPool, debugName.c_str()); } else #endif @@ -90,17 +84,14 @@ std::shared_ptr CommandPool::getOrCreateCommandBuffer() }; VkCommandBuffer vkCommandBuffer = VK_NULL_HANDLE; - VK_ASSERT(vkAllocateCommandBuffers(_logicalDevice->get(), &allocInfo, - &vkCommandBuffer)); - outCommandBuffer = - std::make_shared(_logicalDevice, vkCommandBuffer); + VK_ASSERT(vkAllocateCommandBuffers(_logicalDevice->get(), &allocInfo, &vkCommandBuffer)); + outCommandBuffer = std::make_shared(_logicalDevice, vkCommandBuffer); } return outCommandBuffer; } -void CommandPool::releaseCommandBuffer( - std::shared_ptr&& commandBuffer) +void CommandPool::releaseCommandBuffer(std::shared_ptr&& commandBuffer) { VOX_ASSERT(std::this_thread::get_id() == _creationThreadId, ""); _freedCommandBuffers.push(std::move(commandBuffer)); diff --git a/Sources/VoxFlow/Core/Graphics/Commands/ResourceBarrierManager.cpp b/Sources/VoxFlow/Core/Graphics/Commands/ResourceBarrierManager.cpp index 660be299..d7251853 100644 --- a/Sources/VoxFlow/Core/Graphics/Commands/ResourceBarrierManager.cpp +++ b/Sources/VoxFlow/Core/Graphics/Commands/ResourceBarrierManager.cpp @@ -1,10 +1,10 @@ // Author : snowapril -#include #include +#include #include -#include #include +#include namespace VoxFlow { @@ -22,28 +22,21 @@ VkAccessFlags estimateAccessFlags(ResourceAccessMask accessMask) if (uint32_t(accessMask & ResourceAccessMask::IndexBuffer) > 0) finalAccessFlags |= VK_ACCESS_INDEX_READ_BIT; if (uint32_t(accessMask & ResourceAccessMask::ColorAttachment) > 0) - finalAccessFlags |= VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - if ((uint32_t(accessMask & ResourceAccessMask::DepthAttachment) > 0) || - (uint32_t(accessMask & ResourceAccessMask::StencilAttachment) > 0)) - finalAccessFlags |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - if ((uint32_t(accessMask & ResourceAccessMask::DepthReadOnly) > 0) || - (uint32_t(accessMask & ResourceAccessMask::StencilReadOnly) > 0)) + finalAccessFlags |= VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + if ((uint32_t(accessMask & ResourceAccessMask::DepthAttachment) > 0) || (uint32_t(accessMask & ResourceAccessMask::StencilAttachment) > 0)) + finalAccessFlags |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + if ((uint32_t(accessMask & ResourceAccessMask::DepthReadOnly) > 0) || (uint32_t(accessMask & ResourceAccessMask::StencilReadOnly) > 0)) finalAccessFlags |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT; if (uint32_t(accessMask & ResourceAccessMask::ShaderReadOnly) > 0) finalAccessFlags |= VK_ACCESS_SHADER_READ_BIT; if (uint32_t(accessMask & ResourceAccessMask::General) > 0) - finalAccessFlags |= - VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + finalAccessFlags |= VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; if (uint32_t(accessMask & ResourceAccessMask::StorageBuffer) > 0) - finalAccessFlags |= - VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + finalAccessFlags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; if (uint32_t(accessMask & ResourceAccessMask::UniformBuffer) > 0) finalAccessFlags |= VK_ACCESS_SHADER_READ_BIT; if (uint32_t(accessMask & ResourceAccessMask::Present) > 0) - finalAccessFlags |= VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + finalAccessFlags |= VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; if (uint32_t(accessMask & ResourceAccessMask::IndirectBuffer) > 0) finalAccessFlags |= VK_ACCESS_INDIRECT_COMMAND_READ_BIT; @@ -58,11 +51,9 @@ VkImageLayout estimateImageLayout(ResourceAccessMask accessMask) imageLayout = VK_IMAGE_LAYOUT_GENERAL; else if (uint32_t(accessMask & ResourceAccessMask::ColorAttachment) > 0) imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - else if ((uint32_t(accessMask & ResourceAccessMask::DepthAttachment) > 0) || - (uint32_t(accessMask & ResourceAccessMask::StencilAttachment) > 0)) + else if ((uint32_t(accessMask & ResourceAccessMask::DepthAttachment) > 0) || (uint32_t(accessMask & ResourceAccessMask::StencilAttachment) > 0)) imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - else if ((uint32_t(accessMask & ResourceAccessMask::DepthReadOnly) > 0) || - (uint32_t(accessMask & ResourceAccessMask::StencilReadOnly) > 0)) + else if ((uint32_t(accessMask & ResourceAccessMask::DepthReadOnly) > 0) || (uint32_t(accessMask & ResourceAccessMask::StencilReadOnly) > 0)) imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; else if (uint32_t(accessMask & ResourceAccessMask::TransferSource) > 0) imageLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; @@ -76,16 +67,13 @@ VkImageLayout estimateImageLayout(ResourceAccessMask accessMask) return imageLayout; } -void ResourceBarrierManager::addGlobalMemoryBarrier( - ResourceAccessMask prevAccessMasks, ResourceAccessMask nextAccessMasks) +void ResourceBarrierManager::addGlobalMemoryBarrier(ResourceAccessMask prevAccessMasks, ResourceAccessMask nextAccessMasks) { _globalMemoryBarrier._srcAccessFlags = estimateAccessFlags(prevAccessMasks); _globalMemoryBarrier._dstAccessFlags = estimateAccessFlags(nextAccessMasks); } -void ResourceBarrierManager::addTextureMemoryBarrier( - TextureView* textureView, ResourceAccessMask accessMask, - VkPipelineStageFlags nextStageFlags) +void ResourceBarrierManager::addTextureMemoryBarrier(TextureView* textureView, ResourceAccessMask accessMask, VkPipelineStageFlags nextStageFlags) { Texture* texture = static_cast(textureView->getOwnerResource()); // TODO(snowapril) : get dstQueueFamilyIndex from command buffer @@ -93,8 +81,7 @@ void ResourceBarrierManager::addTextureMemoryBarrier( const TextureViewInfo& textureViewInfo = textureView->getViewInfo(); const VkImageLayout nextImageLayout = estimateImageLayout(accessMask); - _memoryBarrierGroup._srcStageFlags |= - textureView->getLastusedShaderStageFlags(); + _memoryBarrierGroup._srcStageFlags |= textureView->getLastusedShaderStageFlags(); _memoryBarrierGroup._dstStageFlags |= nextStageFlags; _memoryBarrierGroup._imageBarriers.push_back(VkImageMemoryBarrier{ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, @@ -106,13 +93,11 @@ void ResourceBarrierManager::addTextureMemoryBarrier( .srcQueueFamilyIndex = texture->getCurrentQueueFamilyIndex(), .dstQueueFamilyIndex = texture->getCurrentQueueFamilyIndex(), .image = texture->get(), - .subresourceRange = - VkImageSubresourceRange{ - .aspectMask = textureViewInfo._aspectFlags, - .baseMipLevel = textureViewInfo._baseMipLevel, - .levelCount = textureViewInfo._levelCount, - .baseArrayLayer = textureViewInfo._baseMipLevel, - .layerCount = textureViewInfo._layerCount }, + .subresourceRange = VkImageSubresourceRange{ .aspectMask = textureViewInfo._aspectFlags, + .baseMipLevel = textureViewInfo._baseMipLevel, + .levelCount = textureViewInfo._levelCount, + .baseArrayLayer = textureViewInfo._baseMipLevel, + .layerCount = textureViewInfo._layerCount }, }); textureView->setLastusedShaderStageFlags(nextStageFlags); @@ -120,17 +105,14 @@ void ResourceBarrierManager::addTextureMemoryBarrier( textureView->setCurrentVkImageLayout(nextImageLayout); } -void ResourceBarrierManager::addBufferMemoryBarrier( - BufferView* bufferView, ResourceAccessMask accessMask, - VkPipelineStageFlags nextStageFlags) +void ResourceBarrierManager::addBufferMemoryBarrier(BufferView* bufferView, ResourceAccessMask accessMask, VkPipelineStageFlags nextStageFlags) { Buffer* buffer = static_cast(bufferView->getOwnerResource()); // TODO(snowapril) : get dstQueueFamilyIndex from command buffer const BufferViewInfo& bufferViewInfo = bufferView->getViewInfo(); - _memoryBarrierGroup._srcStageFlags |= - bufferView->getLastusedShaderStageFlags(); + _memoryBarrierGroup._srcStageFlags |= bufferView->getLastusedShaderStageFlags(); _memoryBarrierGroup._dstStageFlags |= nextStageFlags; _memoryBarrierGroup._bufferBarriers.push_back(VkBufferMemoryBarrier{ .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, @@ -148,25 +130,20 @@ void ResourceBarrierManager::addBufferMemoryBarrier( bufferView->setLastAccessMask(accessMask); } -void ResourceBarrierManager::addStagingBufferMemoryBarrier( - StagingBufferView* stagingBufferView, ResourceAccessMask accessMask, - VkPipelineStageFlags nextStageFlags) +void ResourceBarrierManager::addStagingBufferMemoryBarrier(StagingBufferView* stagingBufferView, ResourceAccessMask accessMask, + VkPipelineStageFlags nextStageFlags) { - StagingBuffer* stagingBuffer = - static_cast(stagingBufferView->getOwnerResource()); + StagingBuffer* stagingBuffer = static_cast(stagingBufferView->getOwnerResource()); // TODO(snowapril) : get dstQueueFamilyIndex from command buffer - const BufferViewInfo& stagingBufferViewInfo = - stagingBufferView->getViewInfo(); + const BufferViewInfo& stagingBufferViewInfo = stagingBufferView->getViewInfo(); - _memoryBarrierGroup._srcStageFlags |= - stagingBufferView->getLastusedShaderStageFlags(); + _memoryBarrierGroup._srcStageFlags |= stagingBufferView->getLastusedShaderStageFlags(); _memoryBarrierGroup._dstStageFlags |= nextStageFlags; _memoryBarrierGroup._bufferBarriers.push_back(VkBufferMemoryBarrier{ .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, .pNext = nullptr, - .srcAccessMask = - estimateAccessFlags(stagingBufferView->getLastAccessMask()), + .srcAccessMask = estimateAccessFlags(stagingBufferView->getLastAccessMask()), .dstAccessMask = estimateAccessFlags(accessMask), .srcQueueFamilyIndex = stagingBuffer->getCurrentQueueFamilyIndex(), .dstQueueFamilyIndex = stagingBuffer->getCurrentQueueFamilyIndex(), @@ -179,8 +156,7 @@ void ResourceBarrierManager::addStagingBufferMemoryBarrier( stagingBufferView->setLastAccessMask(accessMask); } -void ResourceBarrierManager::addExecutionBarrier( - VkPipelineStageFlags prevStageFlags, VkPipelineStageFlags nextStageFlags) +void ResourceBarrierManager::addExecutionBarrier(VkPipelineStageFlags prevStageFlags, VkPipelineStageFlags nextStageFlags) { _executionBarrier._srcStageFlags = prevStageFlags; _executionBarrier._dstStageFlags = nextStageFlags; @@ -188,21 +164,17 @@ void ResourceBarrierManager::addExecutionBarrier( void ResourceBarrierManager::commitPendingBarriers(const bool inRenderPassScope) { - const VkDependencyFlags dependencyFlag = - inRenderPassScope ? VK_DEPENDENCY_BY_REGION_BIT : 0; + const VkDependencyFlags dependencyFlag = inRenderPassScope ? VK_DEPENDENCY_BY_REGION_BIT : 0; const VkCommandBuffer vkCommandBuffer = _commandBuffer->get(); if (_globalMemoryBarrier.isValid() || _executionBarrier.isValid()) { - const VkMemoryBarrier memoryBarrier = { - .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER, - .pNext = nullptr, - .srcAccessMask = _globalMemoryBarrier._srcAccessFlags, - .dstAccessMask = _globalMemoryBarrier._dstAccessFlags - }; - vkCmdPipelineBarrier(vkCommandBuffer, _executionBarrier._srcStageFlags, - _executionBarrier._dstStageFlags, dependencyFlag, - 1, &memoryBarrier, 0, nullptr, 0, nullptr); + const VkMemoryBarrier memoryBarrier = { .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = _globalMemoryBarrier._srcAccessFlags, + .dstAccessMask = _globalMemoryBarrier._dstAccessFlags }; + vkCmdPipelineBarrier(vkCommandBuffer, _executionBarrier._srcStageFlags, _executionBarrier._dstStageFlags, dependencyFlag, 1, &memoryBarrier, 0, nullptr, + 0, nullptr); _globalMemoryBarrier.reset(); _executionBarrier.reset(); @@ -210,13 +182,9 @@ void ResourceBarrierManager::commitPendingBarriers(const bool inRenderPassScope) if (_memoryBarrierGroup.isValid()) { - vkCmdPipelineBarrier( - vkCommandBuffer, _memoryBarrierGroup._srcStageFlags, - _memoryBarrierGroup._dstStageFlags, dependencyFlag, 0, nullptr, - static_cast(_memoryBarrierGroup._bufferBarriers.size()), - _memoryBarrierGroup._bufferBarriers.data(), - static_cast(_memoryBarrierGroup._imageBarriers.size()), - _memoryBarrierGroup._imageBarriers.data()); + vkCmdPipelineBarrier(vkCommandBuffer, _memoryBarrierGroup._srcStageFlags, _memoryBarrierGroup._dstStageFlags, dependencyFlag, 0, nullptr, + static_cast(_memoryBarrierGroup._bufferBarriers.size()), _memoryBarrierGroup._bufferBarriers.data(), + static_cast(_memoryBarrierGroup._imageBarriers.size()), _memoryBarrierGroup._imageBarriers.data()); _memoryBarrierGroup.reset(); } diff --git a/Sources/VoxFlow/Core/Graphics/Descriptors/DescriptorSet.cpp b/Sources/VoxFlow/Core/Graphics/Descriptors/DescriptorSet.cpp index a95a7aa9..724e08e3 100644 --- a/Sources/VoxFlow/Core/Graphics/Descriptors/DescriptorSet.cpp +++ b/Sources/VoxFlow/Core/Graphics/Descriptors/DescriptorSet.cpp @@ -8,8 +8,7 @@ namespace VoxFlow } // namespace VoxFlow -std::size_t std::hash::operator()( - VoxFlow::DescriptorInfo const& info) const noexcept +std::size_t std::hash::operator()(VoxFlow::DescriptorInfo const& info) const noexcept { uint32_t seed = 0; @@ -21,8 +20,7 @@ std::size_t std::hash::operator()( return seed; } -std::size_t std::hash::operator()( - VoxFlow::DescriptorSetLayoutDesc const& setLayout) const noexcept +std::size_t std::hash::operator()(VoxFlow::DescriptorSetLayoutDesc const& setLayout) const noexcept { uint32_t seed = 0; diff --git a/Sources/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocator.cpp b/Sources/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocator.cpp index f2fd3a23..2d3a673c 100644 --- a/Sources/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocator.cpp +++ b/Sources/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocator.cpp @@ -9,8 +9,7 @@ namespace VoxFlow { -DescriptorSetAllocator::DescriptorSetAllocator(LogicalDevice* logicalDevice, const bool isBindless) - : _logicalDevice(logicalDevice), _isBindless(isBindless) +DescriptorSetAllocator::DescriptorSetAllocator(LogicalDevice* logicalDevice, const bool isBindless) : _logicalDevice(logicalDevice), _isBindless(isBindless) { } @@ -19,14 +18,12 @@ DescriptorSetAllocator::~DescriptorSetAllocator() release(); } -DescriptorSetAllocator::DescriptorSetAllocator( - DescriptorSetAllocator&& other) noexcept +DescriptorSetAllocator::DescriptorSetAllocator(DescriptorSetAllocator&& other) noexcept { operator=(std::move(other)); } -DescriptorSetAllocator& DescriptorSetAllocator::operator=( - DescriptorSetAllocator&& other) noexcept +DescriptorSetAllocator& DescriptorSetAllocator::operator=(DescriptorSetAllocator&& other) noexcept { if (&other != this) { @@ -37,13 +34,11 @@ DescriptorSetAllocator& DescriptorSetAllocator::operator=( return *this; } -bool DescriptorSetAllocator::initialize( - const DescriptorSetLayoutDesc& setLayout, const uint32_t numSets) +bool DescriptorSetAllocator::initialize(const DescriptorSetLayoutDesc& setLayout, const uint32_t numSets) { _setLayoutDesc = setLayout; - const uint32_t numBindings = - static_cast(_setLayoutDesc._descriptorInfos.size()); + const uint32_t numBindings = static_cast(_setLayoutDesc._descriptorInfos.size()); std::vector descSetLayoutBindings; std::vector poolSizes; @@ -51,9 +46,7 @@ bool DescriptorSetAllocator::initialize( descSetLayoutBindings.reserve(numBindings); poolSizes.reserve(numBindings); - for (std::vector::const_iterator it = - _setLayoutDesc._descriptorInfos.begin(); - it != _setLayoutDesc._descriptorInfos.end(); ++it) + for (std::vector::const_iterator it = _setLayoutDesc._descriptorInfos.begin(); it != _setLayoutDesc._descriptorInfos.end(); ++it) { VkDescriptorType descriptorType = VK_DESCRIPTOR_TYPE_MAX_ENUM; switch (it->_descriptorCategory) @@ -72,81 +65,58 @@ bool DescriptorSetAllocator::initialize( continue; } - descSetLayoutBindings.push_back( - { .binding = it->_binding, - .descriptorType = descriptorType, - .descriptorCount = it->_arraySize, - .stageFlags = _setLayoutDesc._stageFlags, - .pImmutableSamplers = nullptr }); - poolSizes.push_back( - { .type = descriptorType, .descriptorCount = it->_arraySize }); + descSetLayoutBindings.push_back({ .binding = it->_binding, + .descriptorType = descriptorType, + .descriptorCount = it->_arraySize, + .stageFlags = _setLayoutDesc._stageFlags, + .pImmutableSamplers = nullptr }); + poolSizes.push_back({ .type = descriptorType, .descriptorCount = it->_arraySize }); } // TODO(snowapril) : sort setLayout descriptorBindings according to binding // id - const VkDescriptorBindingFlags bindingFlag = - (_isBindless) ? (VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT | - VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT) - : 0; - std::vector bindingFlags(numBindings, - bindingFlag); + const VkDescriptorBindingFlags bindingFlag = (_isBindless) ? (VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT | VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT) : 0; + std::vector bindingFlags(numBindings, bindingFlag); - VkDescriptorSetLayoutBindingFlagsCreateInfo bindingFlagsCreateInfo = { - .sType = - VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO, - .pNext = nullptr, - .bindingCount = numBindings, - .pBindingFlags = bindingFlags.data() - }; + VkDescriptorSetLayoutBindingFlagsCreateInfo bindingFlagsCreateInfo = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO, + .pNext = nullptr, + .bindingCount = numBindings, + .pBindingFlags = bindingFlags.data() }; - VkDescriptorSetLayoutCreateInfo createInfo = { - .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, - .pNext = &bindingFlagsCreateInfo, - .flags = - _isBindless - ? VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT - : 0U, - .bindingCount = static_cast(numBindings), - .pBindings = descSetLayoutBindings.data() - }; + VkDescriptorSetLayoutCreateInfo createInfo = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + .pNext = &bindingFlagsCreateInfo, + .flags = _isBindless ? VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT : 0U, + .bindingCount = static_cast(numBindings), + .pBindings = descSetLayoutBindings.data() }; - VK_ASSERT(vkCreateDescriptorSetLayout(_logicalDevice->get(), &createInfo, - nullptr, &_vkSetLayout)); + VK_ASSERT(vkCreateDescriptorSetLayout(_logicalDevice->get(), &createInfo, nullptr, &_vkSetLayout)); VkDescriptorPoolCreateInfo poolCreateInfo = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, .pNext = nullptr, - .flags = - _isBindless ? VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT : 0U, + .flags = _isBindless ? VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT : 0U, .maxSets = numSets, .poolSizeCount = numBindings, .pPoolSizes = poolSizes.data(), }; - VK_ASSERT(vkCreateDescriptorPool(_logicalDevice->get(), &poolCreateInfo, - nullptr, &_vkDescPool)); + VK_ASSERT(vkCreateDescriptorPool(_logicalDevice->get(), &poolCreateInfo, nullptr, &_vkDescPool)); // Prepare VkDescriptorSets early if bindless if (_isBindless) { std::vector vkDescSets(numSets); - std::vector vkDescSetLayouts(numSets, - _vkSetLayout); - VkDescriptorSetAllocateInfo allocInfo = { - .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, - .pNext = nullptr, - .descriptorPool = _vkDescPool, - .descriptorSetCount = numSets, - .pSetLayouts = vkDescSetLayouts.data() - }; - vkAllocateDescriptorSets(_logicalDevice->get(), &allocInfo, - vkDescSets.data()); + std::vector vkDescSetLayouts(numSets, _vkSetLayout); + VkDescriptorSetAllocateInfo allocInfo = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, + .pNext = nullptr, + .descriptorPool = _vkDescPool, + .descriptorSetCount = numSets, + .pSetLayouts = vkDescSetLayouts.data() }; + vkAllocateDescriptorSets(_logicalDevice->get(), &allocInfo, vkDescSets.data()); for (VkDescriptorSet set : vkDescSets) { - _descriptorSetNodes.push_back( - { ._vkDescriptorSet = set, - ._lastAccessedFenceObject = FenceObject::Default() }); + _descriptorSetNodes.push_back({ ._vkDescriptorSet = set, ._lastAccessedFenceObject = FenceObject::Default() }); } } @@ -162,14 +132,11 @@ void DescriptorSetAllocator::release() if (_vkSetLayout) { - vkDestroyDescriptorSetLayout(_logicalDevice->get(), _vkSetLayout, - nullptr); + vkDestroyDescriptorSetLayout(_logicalDevice->get(), _vkSetLayout, nullptr); } } -PooledDescriptorSetAllocator::PooledDescriptorSetAllocator( - LogicalDevice* logicalDevice) - : DescriptorSetAllocator(logicalDevice, false) +PooledDescriptorSetAllocator::PooledDescriptorSetAllocator(LogicalDevice* logicalDevice) : DescriptorSetAllocator(logicalDevice, false) { } @@ -177,22 +144,18 @@ PooledDescriptorSetAllocator::~PooledDescriptorSetAllocator() { } -PooledDescriptorSetAllocator::PooledDescriptorSetAllocator( - PooledDescriptorSetAllocator&& other) noexcept - : DescriptorSetAllocator(std::move(other)) +PooledDescriptorSetAllocator::PooledDescriptorSetAllocator(PooledDescriptorSetAllocator&& other) noexcept : DescriptorSetAllocator(std::move(other)) { operator=(std::move(other)); } -PooledDescriptorSetAllocator& PooledDescriptorSetAllocator::operator=( - PooledDescriptorSetAllocator&& other) noexcept +PooledDescriptorSetAllocator& PooledDescriptorSetAllocator::operator=(PooledDescriptorSetAllocator&& other) noexcept { DescriptorSetAllocator::operator=(std::move(other)); return *this; } -VkDescriptorSet PooledDescriptorSetAllocator::getOrCreatePooledDescriptorSet( - const FenceObject& fenceObject) +VkDescriptorSet PooledDescriptorSetAllocator::getOrCreatePooledDescriptorSet(const FenceObject& fenceObject) { VkDescriptorSet vkPooledDescriptorSet = VK_NULL_HANDLE; for (DescriptorSetNode& node : _descriptorSetNodes) @@ -213,20 +176,15 @@ VkDescriptorSet PooledDescriptorSetAllocator::getOrCreatePooledDescriptorSet( .descriptorSetCount = 1, .pSetLayouts = &_vkSetLayout, }; - VK_ASSERT(vkAllocateDescriptorSets(_logicalDevice->get(), &allocInfo, - &vkPooledDescriptorSet)); + VK_ASSERT(vkAllocateDescriptorSets(_logicalDevice->get(), &allocInfo, &vkPooledDescriptorSet)); - _descriptorSetNodes.push_back( - { ._vkDescriptorSet = vkPooledDescriptorSet, - ._lastAccessedFenceObject = fenceObject }); + _descriptorSetNodes.push_back({ ._vkDescriptorSet = vkPooledDescriptorSet, ._lastAccessedFenceObject = fenceObject }); } return vkPooledDescriptorSet; } -BindlessDescriptorSetAllocator::BindlessDescriptorSetAllocator( - LogicalDevice* logicalDevice) - : DescriptorSetAllocator(logicalDevice, true) +BindlessDescriptorSetAllocator::BindlessDescriptorSetAllocator(LogicalDevice* logicalDevice) : DescriptorSetAllocator(logicalDevice, true) { } @@ -234,27 +192,22 @@ BindlessDescriptorSetAllocator::~BindlessDescriptorSetAllocator() { } -BindlessDescriptorSetAllocator::BindlessDescriptorSetAllocator( - BindlessDescriptorSetAllocator&& other) noexcept - : DescriptorSetAllocator(std::move(other)) +BindlessDescriptorSetAllocator::BindlessDescriptorSetAllocator(BindlessDescriptorSetAllocator&& other) noexcept : DescriptorSetAllocator(std::move(other)) { operator=(std::move(other)); } -BindlessDescriptorSetAllocator& BindlessDescriptorSetAllocator::operator=( - BindlessDescriptorSetAllocator&& other) noexcept +BindlessDescriptorSetAllocator& BindlessDescriptorSetAllocator::operator=(BindlessDescriptorSetAllocator&& other) noexcept { DescriptorSetAllocator::operator=(std::move(other)); return *this; } -VkDescriptorSet BindlessDescriptorSetAllocator::getBindlessDescriptorSet( - const uint32_t setIndex, const FenceObject& fenceObject) +VkDescriptorSet BindlessDescriptorSetAllocator::getBindlessDescriptorSet(const uint32_t setIndex, const FenceObject& fenceObject) { if (setIndex >= static_cast(_descriptorSetNodes.size())) { - VOX_ASSERT(false, "setIndex must be under {}", - _descriptorSetNodes.size()); + VOX_ASSERT(false, "setIndex must be under {}", _descriptorSetNodes.size()); return VK_NULL_HANDLE; } DescriptorSetNode& setNode = _descriptorSetNodes[setIndex]; diff --git a/Sources/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocatorPool.cpp b/Sources/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocatorPool.cpp index 64f482dd..15361457 100644 --- a/Sources/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocatorPool.cpp +++ b/Sources/VoxFlow/Core/Graphics/Descriptors/DescriptorSetAllocatorPool.cpp @@ -10,12 +10,9 @@ namespace VoxFlow { -DescriptorSetAllocatorPool::DescriptorSetAllocatorPool( - LogicalDevice* logicalDevice) - : _logicalDevice(logicalDevice) +DescriptorSetAllocatorPool::DescriptorSetAllocatorPool(LogicalDevice* logicalDevice) : _logicalDevice(logicalDevice) { - _bindlessSetAllocator = - std::make_shared(_logicalDevice); + _bindlessSetAllocator = std::make_shared(_logicalDevice); const bool result = _bindlessSetAllocator->initialize( DescriptorSetLayoutDesc { @@ -33,22 +30,19 @@ DescriptorSetAllocatorPool::DescriptorSetAllocatorPool( ._stageFlags = VK_SHADER_STAGE_ALL }, FRAME_BUFFER_COUNT); - VOX_ASSERT(result, - "Failed to initialize bindless descriptor set allocator"); + VOX_ASSERT(result, "Failed to initialize bindless descriptor set allocator"); } DescriptorSetAllocatorPool::~DescriptorSetAllocatorPool() { } -DescriptorSetAllocatorPool::DescriptorSetAllocatorPool( - DescriptorSetAllocatorPool&& rhs) +DescriptorSetAllocatorPool::DescriptorSetAllocatorPool(DescriptorSetAllocatorPool&& rhs) { operator=(std::move(rhs)); } -DescriptorSetAllocatorPool& DescriptorSetAllocatorPool::operator=( - DescriptorSetAllocatorPool&& rhs) +DescriptorSetAllocatorPool& DescriptorSetAllocatorPool::operator=(DescriptorSetAllocatorPool&& rhs) { if (this != &rhs) { @@ -57,23 +51,18 @@ DescriptorSetAllocatorPool& DescriptorSetAllocatorPool::operator=( return *this; } -std::shared_ptr -DescriptorSetAllocatorPool::getOrCreateDescriptorSetAllocator( - const DescriptorSetLayoutDesc& descSetLayout) +std::shared_ptr DescriptorSetAllocatorPool::getOrCreateDescriptorSetAllocator(const DescriptorSetLayoutDesc& descSetLayout) { std::lock_guard scopedLock(_mutex); ContainerType::iterator iter = _descriptorSetAllocators.find(descSetLayout); if (iter == _descriptorSetAllocators.end()) { - std::shared_ptr setAllocator = - std::make_shared(_logicalDevice); - - const bool initResult = setAllocator->initialize( - descSetLayout, 16); // TODO(snowapril) : replace this magic number + std::shared_ptr setAllocator = std::make_shared(_logicalDevice); - VOX_ASSERT(initResult == true, - "Failed to initialize DescriptorSetAllocator"); + const bool initResult = setAllocator->initialize(descSetLayout, 16); // TODO(snowapril) : replace this magic number + + VOX_ASSERT(initResult == true, "Failed to initialize DescriptorSetAllocator"); _descriptorSetAllocators.emplace(descSetLayout, setAllocator); return setAllocator; @@ -81,8 +70,7 @@ DescriptorSetAllocatorPool::getOrCreateDescriptorSetAllocator( return iter->second; } -std::shared_ptr -DescriptorSetAllocatorPool::getBindlessDescriptorSetAllocator() +std::shared_ptr DescriptorSetAllocatorPool::getBindlessDescriptorSetAllocator() { return _bindlessSetAllocator; } diff --git a/Sources/VoxFlow/Core/Graphics/Pipelines/BasePipeline.cpp b/Sources/VoxFlow/Core/Graphics/Pipelines/BasePipeline.cpp index d7916b27..66d156f7 100644 --- a/Sources/VoxFlow/Core/Graphics/Pipelines/BasePipeline.cpp +++ b/Sources/VoxFlow/Core/Graphics/Pipelines/BasePipeline.cpp @@ -4,24 +4,21 @@ #include #include -#include +#include #include -#include #include -#include +#include +#include #include namespace VoxFlow { -BasePipeline::BasePipeline(PipelineStreamingContext* pipelineStreamingContext, - std::vector&& shaderFilePaths) - : _pipelineStreamingContext(pipelineStreamingContext), - _logicalDevice(pipelineStreamingContext->getLogicalDevice()) +BasePipeline::BasePipeline(PipelineStreamingContext* pipelineStreamingContext, std::vector&& shaderFilePaths) + : _pipelineStreamingContext(pipelineStreamingContext), _logicalDevice(pipelineStreamingContext->getLogicalDevice()) { for (const ShaderPathInfo& shaderPath : shaderFilePaths) { - _shaderModules.push_back( - std::make_unique(_pipelineStreamingContext, shaderPath)); + _shaderModules.push_back(std::make_unique(_pipelineStreamingContext, shaderPath)); } } @@ -48,8 +45,7 @@ BasePipeline& BasePipeline::operator=(BasePipeline&& other) noexcept return *this; } -void BasePipeline::setPipelineCache( - std::unique_ptr&& pipelineCache) +void BasePipeline::setPipelineCache(std::unique_ptr&& pipelineCache) { _pipelineCache = std::move(pipelineCache); } @@ -67,7 +63,6 @@ void BasePipeline::release() void BasePipeline::exportPipelineCache() { - } } // namespace VoxFlow \ No newline at end of file diff --git a/Sources/VoxFlow/Core/Graphics/Pipelines/ComputePipeline.cpp b/Sources/VoxFlow/Core/Graphics/Pipelines/ComputePipeline.cpp index c9210454..484fcc82 100644 --- a/Sources/VoxFlow/Core/Graphics/Pipelines/ComputePipeline.cpp +++ b/Sources/VoxFlow/Core/Graphics/Pipelines/ComputePipeline.cpp @@ -2,16 +2,14 @@ #include #include -#include #include +#include #include #include namespace VoxFlow { -ComputePipeline::ComputePipeline( - PipelineStreamingContext* pipelineStreamingContext, - const ShaderPathInfo& shaderPath) +ComputePipeline::ComputePipeline(PipelineStreamingContext* pipelineStreamingContext, const ShaderPathInfo& shaderPath) : BasePipeline(pipelineStreamingContext, { shaderPath }) { } @@ -21,8 +19,7 @@ ComputePipeline::~ComputePipeline() // Do nothing } -ComputePipeline::ComputePipeline(ComputePipeline&& other) noexcept - : BasePipeline(std::move(other)) +ComputePipeline::ComputePipeline(ComputePipeline&& other) noexcept : BasePipeline(std::move(other)) { // Do nothing } @@ -47,8 +44,7 @@ bool ComputePipeline::initialize() for (size_t i = 0; i < numShaderModules; ++i) { - combinedReflectionDataGroups.push_back( - _shaderModules[i]->getShaderReflectionDataGroup()); + combinedReflectionDataGroups.push_back(_shaderModules[i]->getShaderReflectionDataGroup()); } if (_pipelineLayout->initialize(combinedReflectionDataGroups) == false) @@ -68,20 +64,16 @@ bool ComputePipeline::initialize() .pSpecializationInfo = 0, }; - [[maybe_unused]] const VkComputePipelineCreateInfo pipelineInfo = { - .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .stage = stageCreateInfo, - .layout = _pipelineLayout->get(), - .basePipelineHandle = VK_NULL_HANDLE, - .basePipelineIndex = -1 - }; + [[maybe_unused]] const VkComputePipelineCreateInfo pipelineInfo = { .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .stage = stageCreateInfo, + .layout = _pipelineLayout->get(), + .basePipelineHandle = VK_NULL_HANDLE, + .basePipelineIndex = -1 }; - VkPipelineCache pipelineCache = - _pipelineCache != nullptr ? _pipelineCache->get() : VK_NULL_HANDLE; - VK_ASSERT(vkCreateComputePipelines(_logicalDevice->get(), pipelineCache, 1, - &pipelineInfo, nullptr, &_pipeline)); + VkPipelineCache pipelineCache = _pipelineCache != nullptr ? _pipelineCache->get() : VK_NULL_HANDLE; + VK_ASSERT(vkCreateComputePipelines(_logicalDevice->get(), pipelineCache, 1, &pipelineInfo, nullptr, &_pipeline)); if (_pipeline == VK_NULL_HANDLE) { diff --git a/Sources/VoxFlow/Core/Graphics/Pipelines/GraphicsPipeline.cpp b/Sources/VoxFlow/Core/Graphics/Pipelines/GraphicsPipeline.cpp index b21ecabc..3ae24657 100644 --- a/Sources/VoxFlow/Core/Graphics/Pipelines/GraphicsPipeline.cpp +++ b/Sources/VoxFlow/Core/Graphics/Pipelines/GraphicsPipeline.cpp @@ -1,19 +1,17 @@ // Author : snowapril #include -#include -#include #include -#include #include +#include #include +#include +#include #include namespace VoxFlow { -GraphicsPipeline::GraphicsPipeline( - PipelineStreamingContext* pipelineStreamingContext, - std::vector&& shaderPaths) +GraphicsPipeline::GraphicsPipeline(PipelineStreamingContext* pipelineStreamingContext, std::vector&& shaderPaths) : BasePipeline(pipelineStreamingContext, std::move(shaderPaths)) { } @@ -23,8 +21,7 @@ GraphicsPipeline::~GraphicsPipeline() // Do nothing } -GraphicsPipeline::GraphicsPipeline(GraphicsPipeline&& other) noexcept - : BasePipeline(std::move(other)) +GraphicsPipeline::GraphicsPipeline(GraphicsPipeline&& other) noexcept : BasePipeline(std::move(other)) { // Do nothing } @@ -49,8 +46,7 @@ bool GraphicsPipeline::initialize(RenderPass* renderPass) for (size_t i = 0; i < numShaderModules; ++i) { - combinedReflectionDataGroups.push_back( - _shaderModules[i]->getShaderReflectionDataGroup()); + combinedReflectionDataGroups.push_back(_shaderModules[i]->getShaderReflectionDataGroup()); } if (_pipelineLayout->initialize(combinedReflectionDataGroups) == false) @@ -60,10 +56,10 @@ bool GraphicsPipeline::initialize(RenderPass* renderPass) } // TODO(snowapril) : need comparison between input layout and reflected one - //std::vector vertexInputLayouts; - //std::vector fragmentOutputLayouts; + // std::vector vertexInputLayouts; + // std::vector fragmentOutputLayouts; // - //for (const ShaderReflectionDataGroup* reflectionDataGroup : + // for (const ShaderReflectionDataGroup* reflectionDataGroup : // combinedReflectionDataGroups) //{ // if (vertexInputLayouts.empty() && @@ -86,20 +82,16 @@ bool GraphicsPipeline::initialize(RenderPass* renderPass) std::vector shaderStageInfos; shaderStageInfos.reserve(_shaderModules.size()); - std::for_each( - _shaderModules.begin(), _shaderModules.end(), - [&shaderStageInfos](const std::unique_ptr& module) { - const VkPipelineShaderStageCreateInfo stageCreateInfo = { - .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .stage = module->getStageFlagBits(), - .module = module->get(), - .pName = "main", - .pSpecializationInfo = nullptr - }; - shaderStageInfos.push_back(stageCreateInfo); - }); + std::for_each(_shaderModules.begin(), _shaderModules.end(), [&shaderStageInfos](const std::unique_ptr& module) { + const VkPipelineShaderStageCreateInfo stageCreateInfo = { .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .stage = module->getStageFlagBits(), + .module = module->get(), + .pName = "main", + .pSpecializationInfo = nullptr }; + shaderStageInfos.push_back(stageCreateInfo); + }); std::vector bindingDescriptions; std::vector attributeDescriptions; @@ -108,34 +100,23 @@ bool GraphicsPipeline::initialize(RenderPass* renderPass) vertexInputInfo.pNext = nullptr; // TODO(snowapril) : support instancing with given input layout - const std::vector& inputLayouts = - _pipelineState.inputLayout.inputLayouts; + const std::vector& inputLayouts = _pipelineState.inputLayout.inputLayouts; const bool hasStageInputs = inputLayouts.size() > 0; if (hasStageInputs) { uint32_t offset = 0; for (const VertexInputLayout& inputLayout : inputLayouts) { - bindingDescriptions.push_back( - { .binding = 0, - .stride = inputLayout._stride, - .inputRate = VK_VERTEX_INPUT_RATE_VERTEX }); - - attributeDescriptions.push_back( - { .location = inputLayout._location, - .binding = 0, - .format = inputLayout.getVkFormat(), - .offset = offset }); - + bindingDescriptions.push_back({ .binding = 0, .stride = inputLayout._stride, .inputRate = VK_VERTEX_INPUT_RATE_VERTEX }); + + attributeDescriptions.push_back({ .location = inputLayout._location, .binding = 0, .format = inputLayout.getVkFormat(), .offset = offset }); + offset += inputLayout._stride; } - vertexInputInfo.vertexAttributeDescriptionCount = - static_cast(attributeDescriptions.size()); - vertexInputInfo.pVertexAttributeDescriptions = - attributeDescriptions.data(); - vertexInputInfo.vertexBindingDescriptionCount = - static_cast(bindingDescriptions.size()); + vertexInputInfo.vertexAttributeDescriptionCount = static_cast(attributeDescriptions.size()); + vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data(); + vertexInputInfo.vertexBindingDescriptionCount = static_cast(bindingDescriptions.size()); vertexInputInfo.pVertexBindingDescriptions = bindingDescriptions.data(); } else @@ -146,18 +127,15 @@ bool GraphicsPipeline::initialize(RenderPass* renderPass) vertexInputInfo.pVertexBindingDescriptions = nullptr; } - VkPipelineInputAssemblyStateCreateInfo - inputAssemblyInfo = {}; - inputAssemblyInfo.sType = - VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + VkPipelineInputAssemblyStateCreateInfo inputAssemblyInfo = {}; + inputAssemblyInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssemblyInfo.pNext = nullptr; inputAssemblyInfo.topology = _pipelineState.topology; inputAssemblyInfo.flags = 0; inputAssemblyInfo.primitiveRestartEnable = VK_FALSE; VkPipelineTessellationStateCreateInfo tessellationInfo = {}; - tessellationInfo.sType = - VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO; + tessellationInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO; tessellationInfo.pNext = nullptr; tessellationInfo.flags = 0; tessellationInfo.patchControlPoints = 0; @@ -185,8 +163,7 @@ bool GraphicsPipeline::initialize(RenderPass* renderPass) rasterizationInfo.depthBiasSlopeFactor = 0.0f; // Optional VkPipelineMultisampleStateCreateInfo multiSampleInfo = {}; - multiSampleInfo.sType = - VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + multiSampleInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multiSampleInfo.sampleShadingEnable = VK_FALSE; multiSampleInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; multiSampleInfo.minSampleShading = 1.0f; // Optional @@ -198,29 +175,24 @@ bool GraphicsPipeline::initialize(RenderPass* renderPass) colorBlendAttachments.resize(_pipelineState.blendState.activeStates); for (uint32_t i = 0; i < _pipelineState.blendState.activeStates; ++i) { - const BlendState& blendState = - _pipelineState.blendState.blendStates - [i]; + const BlendState& blendState = _pipelineState.blendState.blendStates[i]; - VkPipelineColorBlendAttachmentState& colorBlendAttachmentState = - colorBlendAttachments[i]; + VkPipelineColorBlendAttachmentState& colorBlendAttachmentState = colorBlendAttachments[i]; colorBlendAttachmentState.colorWriteMask = blendState.colorMasks; colorBlendAttachmentState.blendEnable = blendState.blendEnabled ? VK_TRUE : VK_FALSE; - colorBlendAttachmentState.srcColorBlendFactor = blendState.sourceColor; // Optional + colorBlendAttachmentState.srcColorBlendFactor = blendState.sourceColor; // Optional colorBlendAttachmentState.dstColorBlendFactor = blendState.destinationColor; // Optional - colorBlendAttachmentState.colorBlendOp = blendState.colorOperation; // Optional - colorBlendAttachmentState.srcAlphaBlendFactor = blendState.sourceAlpha; // Optional + colorBlendAttachmentState.colorBlendOp = blendState.colorOperation; // Optional + colorBlendAttachmentState.srcAlphaBlendFactor = blendState.sourceAlpha; // Optional colorBlendAttachmentState.dstAlphaBlendFactor = blendState.destinationAlpha; // Optional - colorBlendAttachmentState.alphaBlendOp = blendState.alphaOperation; // Optional + colorBlendAttachmentState.alphaBlendOp = blendState.alphaOperation; // Optional } VkPipelineColorBlendStateCreateInfo colorBlendInfo = {}; - colorBlendInfo.sType = - VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + colorBlendInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlendInfo.logicOpEnable = VK_FALSE; colorBlendInfo.logicOp = VK_LOGIC_OP_COPY; // Optional - colorBlendInfo.attachmentCount = - static_cast(colorBlendAttachments.size()); + colorBlendInfo.attachmentCount = static_cast(colorBlendAttachments.size()); colorBlendInfo.pAttachments = colorBlendAttachments.data(); colorBlendInfo.blendConstants[0] = 0.0f; // Optional colorBlendInfo.blendConstants[1] = 0.0f; // Optional @@ -228,8 +200,7 @@ bool GraphicsPipeline::initialize(RenderPass* renderPass) colorBlendInfo.blendConstants[3] = 0.0f; // Optional VkPipelineDepthStencilStateCreateInfo depthStencilInfo = {}; - depthStencilInfo.sType = - VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; + depthStencilInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; depthStencilInfo.depthTestEnable = _pipelineState.depthStencil.depthEnable ? VK_TRUE : VK_FALSE; depthStencilInfo.depthWriteEnable = _pipelineState.depthStencil.depthWriteEnable ? VK_TRUE : VK_FALSE; depthStencilInfo.depthCompareOp = _pipelineState.depthStencil.depthComparison; @@ -256,42 +227,36 @@ bool GraphicsPipeline::initialize(RenderPass* renderPass) .reference = _pipelineState.depthStencil.back.reference, }; - VkDynamicState dynamicStates[] = { VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR }; + VkDynamicState dynamicStates[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicInfo = {}; dynamicInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; dynamicInfo.pDynamicStates = dynamicStates; - dynamicInfo.dynamicStateCount = - sizeof(dynamicStates) / sizeof(VkDynamicState); + dynamicInfo.dynamicStateCount = sizeof(dynamicStates) / sizeof(VkDynamicState); dynamicInfo.flags = 0; - const VkGraphicsPipelineCreateInfo pipelineInfo = { - .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, - .pNext = nullptr, - .flags = _pipelineState.flags, - .stageCount = static_cast(shaderStageInfos.size()), - .pStages = shaderStageInfos.data(), - .pVertexInputState = &vertexInputInfo, - .pInputAssemblyState = &inputAssemblyInfo, - .pTessellationState = &tessellationInfo, - .pViewportState = &viewportInfo, - .pRasterizationState = &rasterizationInfo, - .pMultisampleState = &multiSampleInfo, - .pDepthStencilState = &depthStencilInfo, - .pColorBlendState = &colorBlendInfo, - .pDynamicState = &dynamicInfo, - .layout = _pipelineLayout->get(), - .renderPass = renderPass->get(), - .subpass = 0, - .basePipelineHandle = VK_NULL_HANDLE, - .basePipelineIndex = -1 - }; - - VkPipelineCache pipelineCache = - _pipelineCache != nullptr ? _pipelineCache->get() : VK_NULL_HANDLE; - VK_ASSERT(vkCreateGraphicsPipelines(_logicalDevice->get(), pipelineCache, 1, - &pipelineInfo, nullptr, &_pipeline)); + const VkGraphicsPipelineCreateInfo pipelineInfo = { .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, + .pNext = nullptr, + .flags = _pipelineState.flags, + .stageCount = static_cast(shaderStageInfos.size()), + .pStages = shaderStageInfos.data(), + .pVertexInputState = &vertexInputInfo, + .pInputAssemblyState = &inputAssemblyInfo, + .pTessellationState = &tessellationInfo, + .pViewportState = &viewportInfo, + .pRasterizationState = &rasterizationInfo, + .pMultisampleState = &multiSampleInfo, + .pDepthStencilState = &depthStencilInfo, + .pColorBlendState = &colorBlendInfo, + .pDynamicState = &dynamicInfo, + .layout = _pipelineLayout->get(), + .renderPass = renderPass->get(), + .subpass = 0, + .basePipelineHandle = VK_NULL_HANDLE, + .basePipelineIndex = -1 }; + + VkPipelineCache pipelineCache = _pipelineCache != nullptr ? _pipelineCache->get() : VK_NULL_HANDLE; + VK_ASSERT(vkCreateGraphicsPipelines(_logicalDevice->get(), pipelineCache, 1, &pipelineInfo, nullptr, &_pipeline)); if (_pipeline == VK_NULL_HANDLE) { @@ -300,7 +265,7 @@ bool GraphicsPipeline::initialize(RenderPass* renderPass) } _pipelineCache.reset(); - + return true; } diff --git a/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineCache.cpp b/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineCache.cpp index c7390de0..ad0709c1 100644 --- a/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineCache.cpp +++ b/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineCache.cpp @@ -6,11 +6,8 @@ namespace VoxFlow { -PipelineCache::PipelineCache(PipelineStreamingContext* pipelineStreamingContext, - const uint32_t pipelineHash) - : _pipelineStreamingContext(pipelineStreamingContext), - _logicalDevice(pipelineStreamingContext->getLogicalDevice()), - _pipelineHash(pipelineHash) +PipelineCache::PipelineCache(PipelineStreamingContext* pipelineStreamingContext, const uint32_t pipelineHash) + : _pipelineStreamingContext(pipelineStreamingContext), _logicalDevice(pipelineStreamingContext->getLogicalDevice()), _pipelineHash(pipelineHash) { } @@ -39,20 +36,17 @@ PipelineCache& PipelineCache::operator=(PipelineCache&& other) noexcept return *this; } -bool PipelineCache::loadPipelineCache( - const std::vector& pipelineCacheBinary) +bool PipelineCache::loadPipelineCache(const std::vector& pipelineCacheBinary) { VkPipelineCacheCreateInfo cacheCreateInfo = { .sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, .pNext = nullptr, .flags = 0, - .initialDataSize = - static_cast(pipelineCacheBinary.size() * sizeof(uint8_t)), + .initialDataSize = static_cast(pipelineCacheBinary.size() * sizeof(uint8_t)), .pInitialData = pipelineCacheBinary.data(), }; - VkResult result = vkCreatePipelineCache( - _logicalDevice->get(), &cacheCreateInfo, nullptr, &_pipelineCache); + VkResult result = vkCreatePipelineCache(_logicalDevice->get(), &cacheCreateInfo, nullptr, &_pipelineCache); VK_ASSERT(result); @@ -64,15 +58,12 @@ void PipelineCache::exportPipelineCache() if (_pipelineCache != VK_NULL_HANDLE) { size_t size{}; - VK_ASSERT(vkGetPipelineCacheData(_logicalDevice->get(), _pipelineCache, - &size, nullptr)); + VK_ASSERT(vkGetPipelineCacheData(_logicalDevice->get(), _pipelineCache, &size, nullptr)); std::vector pipelineCacheBinary(size); - VK_ASSERT(vkGetPipelineCacheData(_logicalDevice->get(), _pipelineCache, - &size, pipelineCacheBinary.data())); + VK_ASSERT(vkGetPipelineCacheData(_logicalDevice->get(), _pipelineCache, &size, pipelineCacheBinary.data())); - _pipelineStreamingContext->exportPipelineCache( - _pipelineHash, std::move(pipelineCacheBinary)); + _pipelineStreamingContext->exportPipelineCache(_pipelineHash, std::move(pipelineCacheBinary)); vkDestroyPipelineCache(_logicalDevice->get(), _pipelineCache, nullptr); _pipelineCache = VK_NULL_HANDLE; diff --git a/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineLayout.cpp b/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineLayout.cpp index 458c68c7..0cea0f6d 100644 --- a/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineLayout.cpp +++ b/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineLayout.cpp @@ -12,9 +12,7 @@ namespace VoxFlow { -PipelineLayout::PipelineLayout( - LogicalDevice* logicalDevice) - : _logicalDevice(logicalDevice) +PipelineLayout::PipelineLayout(LogicalDevice* logicalDevice) : _logicalDevice(logicalDevice) { } @@ -35,48 +33,36 @@ PipelineLayout& PipelineLayout::operator=(PipelineLayout&& other) noexcept _logicalDevice = std::move(other._logicalDevice); _vkPipelineLayout = other._vkPipelineLayout; _setAllocators.swap(other._setAllocators); - _combinedPipelineLayoutDesc = - std::move(other._combinedPipelineLayoutDesc); - _shaderVariableMap = - std::move(other._shaderVariableMap); + _combinedPipelineLayoutDesc = std::move(other._combinedPipelineLayoutDesc); + _shaderVariableMap = std::move(other._shaderVariableMap); } return *this; } -static void organizeCombinedDescSetLayouts( - const std::vector& - combinedReflectionGroups, - PipelineLayoutDescriptor* combinedPipelineLayoutDesc, - PipelineLayout::ShaderVariableMap* combinedShaderVariables) +static void organizeCombinedDescSetLayouts(const std::vector& combinedReflectionGroups, + PipelineLayoutDescriptor* combinedPipelineLayoutDesc, PipelineLayout::ShaderVariableMap* combinedShaderVariables) { // TODO(snowapril) : As each descriptor set layout desc might have same // bindings, collision handling must be needed. std::unordered_set collisionCheckSet; - for (const ShaderReflectionDataGroup* reflectionDataGroup : - combinedReflectionGroups) + for (const ShaderReflectionDataGroup* reflectionDataGroup : combinedReflectionGroups) { for (uint32_t set = 0; set < MAX_NUM_SET_SLOTS; ++set) { - for (const auto& [descriptor, variableName] : - reflectionDataGroup->_descriptors) + for (const auto& [descriptor, variableName] : reflectionDataGroup->_descriptors) { if (set == static_cast(descriptor._setCategory)) { - const uint32_t key = - (static_cast(descriptor._descriptorCategory) - << 24) | - descriptor._binding; + const uint32_t key = (static_cast(descriptor._descriptorCategory) << 24) | descriptor._binding; if (collisionCheckSet.find(key) == collisionCheckSet.end()) { collisionCheckSet.emplace(key); - combinedPipelineLayoutDesc->_sets[set] - ._descriptorInfos.emplace_back(descriptor); + combinedPipelineLayoutDesc->_sets[set]._descriptorInfos.emplace_back(descriptor); - combinedShaderVariables->emplace(variableName, - descriptor); + combinedShaderVariables->emplace(variableName, descriptor); } else { @@ -85,39 +71,29 @@ static void organizeCombinedDescSetLayouts( } } - combinedPipelineLayoutDesc->_sets[set]._stageFlags |= - reflectionDataGroup->_stageFlagBit; + combinedPipelineLayoutDesc->_sets[set]._stageFlags |= reflectionDataGroup->_stageFlagBit; } } } -bool PipelineLayout::initialize( - const std::vector& - combinedReflectionDataGroups) +bool PipelineLayout::initialize(const std::vector& combinedReflectionDataGroups) { - organizeCombinedDescSetLayouts(combinedReflectionDataGroups, - &_combinedPipelineLayoutDesc, - &_shaderVariableMap); + organizeCombinedDescSetLayouts(combinedReflectionDataGroups, &_combinedPipelineLayoutDesc, &_shaderVariableMap); - DescriptorSetAllocatorPool* descriptorSetAllocatorPool = - _logicalDevice->getDescriptorSetAllocatorPool(); + DescriptorSetAllocatorPool* descriptorSetAllocatorPool = _logicalDevice->getDescriptorSetAllocatorPool(); std::vector vkSetLayouts; // Set index 0 is always bindless descriptor set. - _setAllocators[0] = - descriptorSetAllocatorPool->getBindlessDescriptorSetAllocator(); + _setAllocators[0] = descriptorSetAllocatorPool->getBindlessDescriptorSetAllocator(); vkSetLayouts.push_back(_setAllocators[0]->getVkDescriptorSetLayout()); for (uint32_t set = 1; set < MAX_NUM_SET_SLOTS; ++set) { if (_combinedPipelineLayoutDesc._sets[set]._stageFlags != 0) { - _setAllocators[set] = - descriptorSetAllocatorPool->getOrCreateDescriptorSetAllocator( - _combinedPipelineLayoutDesc._sets[set]); - vkSetLayouts.push_back( - _setAllocators[set]->getVkDescriptorSetLayout()); + _setAllocators[set] = descriptorSetAllocatorPool->getOrCreateDescriptorSetAllocator(_combinedPipelineLayoutDesc._sets[set]); + vkSetLayouts.push_back(_setAllocators[set]->getVkDescriptorSetLayout()); } } @@ -132,8 +108,7 @@ bool PipelineLayout::initialize( .pPushConstantRanges = nullptr, }; - VK_ASSERT(vkCreatePipelineLayout(_logicalDevice->get(), &createInfo, - nullptr, &_vkPipelineLayout)); + VK_ASSERT(vkCreatePipelineLayout(_logicalDevice->get(), &createInfo, nullptr, &_vkPipelineLayout)); return (_vkPipelineLayout != VK_NULL_HANDLE); } diff --git a/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineLayoutDescriptor.cpp b/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineLayoutDescriptor.cpp index 09d47b3d..1f4bb9db 100644 --- a/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineLayoutDescriptor.cpp +++ b/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineLayoutDescriptor.cpp @@ -9,24 +9,15 @@ namespace VoxFlow VkFormat VertexInputLayout::getVkFormat() const { constexpr VkFormat FORMAT_TABLE[] = { - VK_FORMAT_R16_SFLOAT, VK_FORMAT_R16G16_SFLOAT, - VK_FORMAT_R16G16B16_SFLOAT, VK_FORMAT_R16G16B16A16_SFLOAT, - VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32G32_SFLOAT, - VK_FORMAT_R32G32B32_SFLOAT, VK_FORMAT_R32G32B32A32_SFLOAT, - VK_FORMAT_R64_SFLOAT, VK_FORMAT_R64G64_SFLOAT, - VK_FORMAT_R64G64B64_SFLOAT, VK_FORMAT_R64G64B64A64_SFLOAT, - VK_FORMAT_R16_SINT, VK_FORMAT_R16G16_SINT, - VK_FORMAT_R16G16B16_SINT, VK_FORMAT_R16G16B16A16_SINT, - VK_FORMAT_R32_SINT, VK_FORMAT_R32G32_SINT, - VK_FORMAT_R32G32B32_SINT, VK_FORMAT_R32G32B32A32_SINT, - VK_FORMAT_R64_SINT, VK_FORMAT_R64G64_SINT, - VK_FORMAT_R64G64B64_SINT, VK_FORMAT_R64G64B64A64_SINT, - VK_FORMAT_R16_UINT, VK_FORMAT_R16G16_UINT, - VK_FORMAT_R16G16B16_UINT, VK_FORMAT_R16G16B16A16_UINT, - VK_FORMAT_R32_UINT, VK_FORMAT_R32G32_UINT, - VK_FORMAT_R32G32B32_UINT, VK_FORMAT_R32G32B32A32_UINT, - VK_FORMAT_R64_UINT, VK_FORMAT_R64G64_UINT, - VK_FORMAT_R64G64B64_UINT, VK_FORMAT_R64G64B64A64_UINT, + VK_FORMAT_R16_SFLOAT, VK_FORMAT_R16G16_SFLOAT, VK_FORMAT_R16G16B16_SFLOAT, VK_FORMAT_R16G16B16A16_SFLOAT, + VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32G32_SFLOAT, VK_FORMAT_R32G32B32_SFLOAT, VK_FORMAT_R32G32B32A32_SFLOAT, + VK_FORMAT_R64_SFLOAT, VK_FORMAT_R64G64_SFLOAT, VK_FORMAT_R64G64B64_SFLOAT, VK_FORMAT_R64G64B64A64_SFLOAT, + VK_FORMAT_R16_SINT, VK_FORMAT_R16G16_SINT, VK_FORMAT_R16G16B16_SINT, VK_FORMAT_R16G16B16A16_SINT, + VK_FORMAT_R32_SINT, VK_FORMAT_R32G32_SINT, VK_FORMAT_R32G32B32_SINT, VK_FORMAT_R32G32B32A32_SINT, + VK_FORMAT_R64_SINT, VK_FORMAT_R64G64_SINT, VK_FORMAT_R64G64B64_SINT, VK_FORMAT_R64G64B64A64_SINT, + VK_FORMAT_R16_UINT, VK_FORMAT_R16G16_UINT, VK_FORMAT_R16G16B16_UINT, VK_FORMAT_R16G16B16A16_UINT, + VK_FORMAT_R32_UINT, VK_FORMAT_R32G32_UINT, VK_FORMAT_R32G32B32_UINT, VK_FORMAT_R32G32B32A32_UINT, + VK_FORMAT_R64_UINT, VK_FORMAT_R64G64_UINT, VK_FORMAT_R64G64B64_UINT, VK_FORMAT_R64G64B64A64_UINT, }; static_assert((sizeof(FORMAT_TABLE) / sizeof(VkFormat)) == 36); @@ -76,20 +67,17 @@ VkFormat VertexInputLayout::getVkFormat() const return resultFormat; } -ShaderReflectionDataGroup::ShaderReflectionDataGroup( - const ShaderReflectionDataGroup& rhs) +ShaderReflectionDataGroup::ShaderReflectionDataGroup(const ShaderReflectionDataGroup& rhs) { operator=(rhs); } -ShaderReflectionDataGroup::ShaderReflectionDataGroup( - ShaderReflectionDataGroup&& rhs) +ShaderReflectionDataGroup::ShaderReflectionDataGroup(ShaderReflectionDataGroup&& rhs) { operator=(std::move(rhs)); } -ShaderReflectionDataGroup& ShaderReflectionDataGroup::operator=( - const ShaderReflectionDataGroup& rhs) +ShaderReflectionDataGroup& ShaderReflectionDataGroup::operator=(const ShaderReflectionDataGroup& rhs) { if (this != &rhs) { @@ -101,8 +89,7 @@ ShaderReflectionDataGroup& ShaderReflectionDataGroup::operator=( return *this; } -ShaderReflectionDataGroup& ShaderReflectionDataGroup::operator=( - ShaderReflectionDataGroup&& rhs) +ShaderReflectionDataGroup& ShaderReflectionDataGroup::operator=(ShaderReflectionDataGroup&& rhs) { if (this != &rhs) { @@ -116,8 +103,7 @@ ShaderReflectionDataGroup& ShaderReflectionDataGroup::operator=( } // namespace VoxFlow -std::size_t std::hash::operator()( - VoxFlow::VertexInputLayout const& inputLayout) const noexcept +std::size_t std::hash::operator()(VoxFlow::VertexInputLayout const& inputLayout) const noexcept { uint32_t seed = 0; @@ -128,8 +114,7 @@ std::size_t std::hash::operator()( return seed; } -std::size_t std::hash::operator()( - VoxFlow::FragmentOutputLayout const& outputLayout) const noexcept +std::size_t std::hash::operator()(VoxFlow::FragmentOutputLayout const& outputLayout) const noexcept { uint32_t seed = 0; @@ -139,8 +124,7 @@ std::size_t std::hash::operator()( return seed; } -std::size_t std::hash::operator()( - VoxFlow::PipelineLayoutDescriptor const& shaderLayout) const noexcept +std::size_t std::hash::operator()(VoxFlow::PipelineLayoutDescriptor const& shaderLayout) const noexcept { uint32_t seed = 0; diff --git a/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineStreamingContext.cpp b/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineStreamingContext.cpp index 8a7a2a62..e7981518 100644 --- a/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineStreamingContext.cpp +++ b/Sources/VoxFlow/Core/Graphics/Pipelines/PipelineStreamingContext.cpp @@ -1,20 +1,19 @@ // Author : snowapril -#include #include #include #include #include +#include #include #include -#include -#include #include +#include +#include namespace VoxFlow { -PipelineStreamingContext::PipelineStreamingContext( - LogicalDevice* logicalDevice, const std::string& shaderRootPath) +PipelineStreamingContext::PipelineStreamingContext(LogicalDevice* logicalDevice, const std::string& shaderRootPath) : _logicalDevice(logicalDevice), _shaderRootPath(shaderRootPath), _shaderCachePath(_shaderRootPath + "ShaderCache/"), @@ -28,14 +27,12 @@ PipelineStreamingContext::~PipelineStreamingContext() { } -PipelineStreamingContext::PipelineStreamingContext( - PipelineStreamingContext&& other) noexcept +PipelineStreamingContext::PipelineStreamingContext(PipelineStreamingContext&& other) noexcept { operator=(std::move(other)); } -PipelineStreamingContext& PipelineStreamingContext::operator=( - PipelineStreamingContext&& other) noexcept +PipelineStreamingContext& PipelineStreamingContext::operator=(PipelineStreamingContext&& other) noexcept { if (this != &other) { @@ -47,9 +44,7 @@ PipelineStreamingContext& PipelineStreamingContext::operator=( return *this; } -std::shared_ptr -PipelineStreamingContext::createGraphicsPipeline( - std::vector&& shaderPaths) +std::shared_ptr PipelineStreamingContext::createGraphicsPipeline(std::vector&& shaderPaths) { uint32_t pipelineHash = 0; @@ -61,14 +56,12 @@ PipelineStreamingContext::createGraphicsPipeline( hash_combine(pipelineHash, path); } - auto graphicsPipeline = - std::make_shared(this, std::move(pathInfos)); + auto graphicsPipeline = std::make_shared(this, std::move(pathInfos)); auto pipelineCache = std::make_unique(this, pipelineHash); std::vector pipelineCacheBinary; - const std::string pipelineCachePath = - _pipelineCachePath + std::to_string(pipelineHash) + ".vfpipeline"; + const std::string pipelineCachePath = _pipelineCachePath + std::to_string(pipelineHash) + ".vfpipeline"; getPipelineCacheIfExist(pipelineCachePath, pipelineCacheBinary); if (pipelineCacheBinary.size() > 0) @@ -83,20 +76,17 @@ PipelineStreamingContext::createGraphicsPipeline( return graphicsPipeline; } -std::shared_ptr -PipelineStreamingContext::createComputePipeline(std::string&& shaderPath) +std::shared_ptr PipelineStreamingContext::createComputePipeline(std::string&& shaderPath) { uint32_t pipelineHash = 0; hash_combine(pipelineHash, shaderPath); - auto computePipeline = - std::make_shared(this, getShaderPathInfo(shaderPath)); + auto computePipeline = std::make_shared(this, getShaderPathInfo(shaderPath)); auto pipelineCache = std::make_unique(this, pipelineHash); std::vector pipelineCacheBinary; - const std::string pipelineCachePath = - _pipelineCachePath + std::to_string(pipelineHash) + ".vfpipeline"; + const std::string pipelineCachePath = _pipelineCachePath + std::to_string(pipelineHash) + ".vfpipeline"; getPipelineCacheIfExist(pipelineCachePath, pipelineCacheBinary); if (pipelineCacheBinary.size() > 0) @@ -111,9 +101,7 @@ PipelineStreamingContext::createComputePipeline(std::string&& shaderPath) return computePipeline; } -bool PipelineStreamingContext::loadSpirvBinary( - std::vector& outSpirvBinary, const ShaderPathInfo& pathInfo, - const bool skipShaderCacheExport) +bool PipelineStreamingContext::loadSpirvBinary(std::vector& outSpirvBinary, const ShaderPathInfo& pathInfo, const bool skipShaderCacheExport) { bool compileResult = true; if (pathInfo.fileType == ShaderFileType::Glsl) @@ -121,15 +109,12 @@ bool PipelineStreamingContext::loadSpirvBinary( std::string shaderAbsPath = _shaderRootPath + pathInfo.path; std::vector shaderSource; - compileResult = - GlslangUtil::ReadShaderFile(shaderAbsPath.c_str(), &shaderSource); + compileResult = GlslangUtil::ReadShaderFile(shaderAbsPath.c_str(), &shaderSource); if (compileResult == false) return false; - compileResult = GlslangUtil::CompileShader( - GlslangUtil::GlslangStageFromFilename(shaderAbsPath), - shaderSource.data(), &outSpirvBinary); + compileResult = GlslangUtil::CompileShader(GlslangUtil::GlslangStageFromFilename(shaderAbsPath), shaderSource.data(), &outSpirvBinary); if (skipShaderCacheExport == false) { @@ -140,52 +125,42 @@ bool PipelineStreamingContext::loadSpirvBinary( { std::string shaderAbsPath = _shaderCachePath + pathInfo.path; - compileResult = - ShaderUtil::ReadSpirvBinary(shaderAbsPath.c_str(), &outSpirvBinary); - + compileResult = ShaderUtil::ReadSpirvBinary(shaderAbsPath.c_str(), &outSpirvBinary); + spdlog::info("shader cache loaded [ {} ]", shaderAbsPath); } return compileResult; } -void PipelineStreamingContext::exportShaderCache( - const ShaderPathInfo& pathInfo, const std::vector& spirvBinary) +void PipelineStreamingContext::exportShaderCache(const ShaderPathInfo& pathInfo, const std::vector& spirvBinary) { std::ofstream shaderCacheFile; - std::string shaderCachePath = - _shaderCachePath + - pathInfo.path.substr(0, pathInfo.path.find_last_of('.')) + ".vfcache_" + - ShaderUtil::ConvertToShaderFileExtension(pathInfo.shaderStage); + std::string shaderCachePath = _shaderCachePath + pathInfo.path.substr(0, pathInfo.path.find_last_of('.')) + ".vfcache_" + + ShaderUtil::ConvertToShaderFileExtension(pathInfo.shaderStage); shaderCacheFile.open(shaderCachePath, std::ios::app | std::ios::binary); - shaderCacheFile.write(reinterpret_cast(spirvBinary.data()), - spirvBinary.size() * 4); + shaderCacheFile.write(reinterpret_cast(spirvBinary.data()), spirvBinary.size() * 4); shaderCacheFile.close(); spdlog::info("shader cache exported [ {} ]", shaderCachePath); } -void PipelineStreamingContext::exportPipelineCache( - const size_t pipelineHash, std::vector&& pipelineCacheBinary) +void PipelineStreamingContext::exportPipelineCache(const size_t pipelineHash, std::vector&& pipelineCacheBinary) { std::ofstream pipelineCacheFile; - std::string pipelineCachePath = - _pipelineCachePath + std::to_string(pipelineHash) + ".vfpipeline"; + std::string pipelineCachePath = _pipelineCachePath + std::to_string(pipelineHash) + ".vfpipeline"; pipelineCacheFile.open(pipelineCachePath, std::ios::app | std::ios::binary); - pipelineCacheFile.write( - reinterpret_cast(pipelineCacheBinary.data()), - pipelineCacheBinary.size() * 4); + pipelineCacheFile.write(reinterpret_cast(pipelineCacheBinary.data()), pipelineCacheBinary.size() * 4); pipelineCacheFile.close(); spdlog::info("pipeline cache exported [ {} ]", pipelineCachePath); } -ShaderPathInfo PipelineStreamingContext::getShaderPathInfo( - const std::string& path) +ShaderPathInfo PipelineStreamingContext::getShaderPathInfo(const std::string& path) { ShaderPathInfo pathInfo; pathInfo.path = path; @@ -205,9 +180,7 @@ ShaderPathInfo PipelineStreamingContext::getShaderPathInfo( pathInfo.shaderStage = ShaderStage::Compute; } - const std::string shaderCacheName = - pathInfo.path.substr(0, pathInfo.path.find_last_of('.')) + ".vfcache_" + - extension; + const std::string shaderCacheName = pathInfo.path.substr(0, pathInfo.path.find_last_of('.')) + ".vfcache_" + extension; if (std::filesystem::exists(_shaderCachePath + shaderCacheName)) { @@ -218,11 +191,9 @@ ShaderPathInfo PipelineStreamingContext::getShaderPathInfo( return pathInfo; } -void PipelineStreamingContext::getPipelineCacheIfExist( - const std::string& pipelineCachePath, std::vector& outCacheData) +void PipelineStreamingContext::getPipelineCacheIfExist(const std::string& pipelineCachePath, std::vector& outCacheData) { - std::ifstream file(pipelineCachePath, - std::ios::in | std::ios::ate | std::ios::binary); + std::ifstream file(pipelineCachePath, std::ios::in | std::ios::ate | std::ios::binary); if (!file.is_open()) { return; diff --git a/Sources/VoxFlow/Core/Graphics/Pipelines/ShaderModule.cpp b/Sources/VoxFlow/Core/Graphics/Pipelines/ShaderModule.cpp index 84a99907..04a2ed6e 100644 --- a/Sources/VoxFlow/Core/Graphics/Pipelines/ShaderModule.cpp +++ b/Sources/VoxFlow/Core/Graphics/Pipelines/ShaderModule.cpp @@ -1,47 +1,37 @@ // Author : snowapril #include -#include -#include #include -#include +#include +#include #include +#include #include #include namespace VoxFlow { -ShaderModule::ShaderModule(PipelineStreamingContext* pipelineStreamingContext, - const ShaderPathInfo& shaderPath) - : _pipelineStreamingContext(pipelineStreamingContext), - _logicalDevice(_pipelineStreamingContext->getLogicalDevice()), - _shaderFilePath(shaderPath) +ShaderModule::ShaderModule(PipelineStreamingContext* pipelineStreamingContext, const ShaderPathInfo& shaderPath) + : _pipelineStreamingContext(pipelineStreamingContext), _logicalDevice(_pipelineStreamingContext->getLogicalDevice()), _shaderFilePath(shaderPath) { std::vector spirvBinary; const bool compileResult = _pipelineStreamingContext->loadSpirvBinary(spirvBinary, shaderPath); - VOX_ASSERT(compileResult, "Failed to load spirv binary for path : {}", - shaderPath.path); + VOX_ASSERT(compileResult, "Failed to load spirv binary for path : {}", shaderPath.path); if (compileResult == false) return; - const VkShaderModuleCreateInfo moduleInfo = { - .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .codeSize = spirvBinary.size() * sizeof(unsigned int), - .pCode = spirvBinary.data() - }; - VK_ASSERT(vkCreateShaderModule(_logicalDevice->get(), &moduleInfo, nullptr, - &_shaderModule)); - - _stageFlagBits = - ShaderUtil::ConvertToShaderStageFlag(_shaderFilePath.shaderStage); - - const bool reflectionResult = reflectShaderLayoutBindings( - &_reflectionDataGroup, std::move(spirvBinary), _stageFlagBits); - VOX_ASSERT(reflectionResult, "Failed to reflect shader module {}", - _shaderFilePath.path); + const VkShaderModuleCreateInfo moduleInfo = { .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .codeSize = spirvBinary.size() * sizeof(unsigned int), + .pCode = spirvBinary.data() }; + VK_ASSERT(vkCreateShaderModule(_logicalDevice->get(), &moduleInfo, nullptr, &_shaderModule)); + + _stageFlagBits = ShaderUtil::ConvertToShaderStageFlag(_shaderFilePath.shaderStage); + + const bool reflectionResult = reflectShaderLayoutBindings(&_reflectionDataGroup, std::move(spirvBinary), _stageFlagBits); + VOX_ASSERT(reflectionResult, "Failed to reflect shader module {}", _shaderFilePath.path); } ShaderModule::~ShaderModule() @@ -206,8 +196,7 @@ static VkFormat convertSpirvImageFormat(spv::ImageFormat imageFormat) } } -VertexFormatBaseType convertToBaseType( - const spirv_cross::SPIRType::BaseType& spirBaseType) +VertexFormatBaseType convertToBaseType(const spirv_cross::SPIRType::BaseType& spirBaseType) { using namespace spirv_cross; VertexFormatBaseType baseType = VertexFormatBaseType::Unknown; @@ -237,8 +226,8 @@ VertexFormatBaseType convertToBaseType( return baseType; } -bool ShaderModule::reflectShaderLayoutBindings(ShaderReflectionDataGroup* reflectionDataGroup, - std::vector&& spirvCodes, VkShaderStageFlagBits shaderStageBits) +bool ShaderModule::reflectShaderLayoutBindings(ShaderReflectionDataGroup* reflectionDataGroup, std::vector&& spirvCodes, + VkShaderStageFlagBits shaderStageBits) { // Note(snowapril) : sample codes from Khronos/SPIRV-Cross Wiki. // https://github.com/KhronosGroup/SPIRV-Cross/wiki/Reflection-API-user-guide @@ -247,37 +236,26 @@ bool ShaderModule::reflectShaderLayoutBindings(ShaderReflectionDataGroup* reflec spirv_cross::Compiler compiler(std::move(spirvCodes)); // Querying statically accessed resources - std::unordered_set activeVariableSet = - compiler.get_active_interface_variables(); - spirv_cross::ShaderResources shaderResources = - compiler.get_shader_resources(activeVariableSet); + std::unordered_set activeVariableSet = compiler.get_active_interface_variables(); + spirv_cross::ShaderResources shaderResources = compiler.get_shader_resources(activeVariableSet); compiler.set_enabled_interface_variables(std::move(activeVariableSet)); bool isBindless = false; for (const spirv_cross::Resource& resource : shaderResources.sampled_images) { - const uint32_t set = - compiler.get_decoration(resource.id, spv::DecorationDescriptorSet); - const uint32_t binding = - compiler.get_decoration(resource.id, spv::DecorationBinding); - VOX_ASSERT(set < MAX_NUM_SET_SLOTS, "Set number must be under {}", - MAX_NUM_SET_SLOTS); + const uint32_t set = compiler.get_decoration(resource.id, spv::DecorationDescriptorSet); + const uint32_t binding = compiler.get_decoration(resource.id, spv::DecorationBinding); + VOX_ASSERT(set < MAX_NUM_SET_SLOTS, "Set number must be under {}", MAX_NUM_SET_SLOTS); - const spirv_cross::SPIRType& resourceType = - compiler.get_type(resource.type_id); + const spirv_cross::SPIRType& resourceType = compiler.get_type(resource.type_id); - const uint32_t count = - getSpirTypeSize(resourceType, isBindless); - VOX_ASSERT( - (isBindless == false) || - (set == static_cast(SetSlotCategory::Bindless)), - "Bindless resource must use set = {}", - static_cast(SetSlotCategory::Bindless)); + const uint32_t count = getSpirTypeSize(resourceType, isBindless); + VOX_ASSERT((isBindless == false) || (set == static_cast(SetSlotCategory::Bindless)), "Bindless resource must use set = {}", + static_cast(SetSlotCategory::Bindless)); - //const std::string& blockName = compiler.get_name(resource.base_type_id); + // const std::string& blockName = compiler.get_name(resource.base_type_id); - spdlog::debug("\t {} (set : {}, binding : {}, count : {})", - resource.name, set, binding, count); + spdlog::debug("\t {} (set : {}, binding : {}, count : {})", resource.name, set, binding, count); if (resourceType.image.dim == spv::DimBuffer) { @@ -285,176 +263,119 @@ bool ShaderModule::reflectShaderLayoutBindings(ShaderReflectionDataGroup* reflec } else { - VkFormat imageFormat = - convertSpirvImageFormat(resourceType.image.format); + VkFormat imageFormat = convertSpirvImageFormat(resourceType.image.format); (void)imageFormat; - reflectionDataGroup->_descriptors.emplace( - DescriptorInfo{ static_cast(set), - DescriptorCategory::CombinedImage, count, - binding }, - resource.name); + reflectionDataGroup->_descriptors.emplace(DescriptorInfo{ static_cast(set), DescriptorCategory::CombinedImage, count, binding }, + resource.name); } } - for (const spirv_cross::Resource& resource : - shaderResources.uniform_buffers) + for (const spirv_cross::Resource& resource : shaderResources.uniform_buffers) { - const uint32_t set = - compiler.get_decoration(resource.id, spv::DecorationDescriptorSet); - const uint32_t binding = - compiler.get_decoration(resource.id, spv::DecorationBinding); - VOX_ASSERT(set < MAX_NUM_SET_SLOTS, "Set number must be under {}", - MAX_NUM_SET_SLOTS); - - const spirv_cross::SPIRType& resourceType = - compiler.get_type(resource.type_id); - - const uint32_t count = - getSpirTypeSize(resourceType, isBindless); - VOX_ASSERT( - (isBindless == false) || - (set == static_cast(SetSlotCategory::Bindless)), - "Bindless resource must use set = {}", - static_cast(SetSlotCategory::Bindless)); - - spdlog::debug("\t {} (set : {}, binding : {}, count : {})", - resource.name, set, binding, count); + const uint32_t set = compiler.get_decoration(resource.id, spv::DecorationDescriptorSet); + const uint32_t binding = compiler.get_decoration(resource.id, spv::DecorationBinding); + VOX_ASSERT(set < MAX_NUM_SET_SLOTS, "Set number must be under {}", MAX_NUM_SET_SLOTS); + + const spirv_cross::SPIRType& resourceType = compiler.get_type(resource.type_id); + + const uint32_t count = getSpirTypeSize(resourceType, isBindless); + VOX_ASSERT((isBindless == false) || (set == static_cast(SetSlotCategory::Bindless)), "Bindless resource must use set = {}", + static_cast(SetSlotCategory::Bindless)); + + spdlog::debug("\t {} (set : {}, binding : {}, count : {})", resource.name, set, binding, count); uint32_t totalSize = 0; for (uint32_t i = 0; i < resourceType.member_types.size(); ++i) { // auto& memberType = compiler.get_type(resourceType.member_types[i]); - size_t memberSize = - compiler.get_declared_struct_member_size(resourceType, i); + size_t memberSize = compiler.get_declared_struct_member_size(resourceType, i); size_t offset = compiler.type_struct_member_offset(resourceType, i); - const std::string& memberName = - compiler.get_member_name(resourceType.self, i); + const std::string& memberName = compiler.get_member_name(resourceType.self, i); - spdlog::debug("\t\t member({} : size({}), offset({})", memberName, - memberSize, offset); + spdlog::debug("\t\t member({} : size({}), offset({})", memberName, memberSize, offset); totalSize += static_cast(memberSize); } const std::string& blockName = compiler.get_name(resource.base_type_id); spdlog::debug("\t Block : {}, totalSize : {}", blockName, totalSize); - reflectionDataGroup->_descriptors.emplace( - DescriptorInfo{ static_cast(set), - DescriptorCategory::UniformBuffer, count, binding }, - resource.name); + reflectionDataGroup->_descriptors.emplace(DescriptorInfo{ static_cast(set), DescriptorCategory::UniformBuffer, count, binding }, + resource.name); } - for (const spirv_cross::Resource& resource : - shaderResources.storage_buffers) + for (const spirv_cross::Resource& resource : shaderResources.storage_buffers) { - const uint32_t set = - compiler.get_decoration(resource.id, spv::DecorationDescriptorSet); - const uint32_t binding = - compiler.get_decoration(resource.id, spv::DecorationBinding); - VOX_ASSERT(set < MAX_NUM_SET_SLOTS, "Set number must be under {}", - MAX_NUM_SET_SLOTS); - - const spirv_cross::SPIRType& resourceType = - compiler.get_type(resource.type_id); - - const uint32_t count = - getSpirTypeSize(resourceType, isBindless); - VOX_ASSERT( - (isBindless == false) || - (set == static_cast(SetSlotCategory::Bindless)), - "Bindless resource must use set = {}", - static_cast(SetSlotCategory::Bindless)); - - spdlog::debug("\t {} (set : {}, binding : {}, count : {})", - resource.name, set, binding, count); + const uint32_t set = compiler.get_decoration(resource.id, spv::DecorationDescriptorSet); + const uint32_t binding = compiler.get_decoration(resource.id, spv::DecorationBinding); + VOX_ASSERT(set < MAX_NUM_SET_SLOTS, "Set number must be under {}", MAX_NUM_SET_SLOTS); + + const spirv_cross::SPIRType& resourceType = compiler.get_type(resource.type_id); + + const uint32_t count = getSpirTypeSize(resourceType, isBindless); + VOX_ASSERT((isBindless == false) || (set == static_cast(SetSlotCategory::Bindless)), "Bindless resource must use set = {}", + static_cast(SetSlotCategory::Bindless)); + + spdlog::debug("\t {} (set : {}, binding : {}, count : {})", resource.name, set, binding, count); uint32_t totalSize = 0; for (uint32_t i = 0; i < resourceType.member_types.size(); ++i) { // auto& memberType = compiler.get_type(resourceType.member_types[i]); - size_t memberSize = - compiler.get_declared_struct_member_size(resourceType, i); + size_t memberSize = compiler.get_declared_struct_member_size(resourceType, i); size_t offset = compiler.type_struct_member_offset(resourceType, i); - const std::string& memberName = - compiler.get_member_name(resourceType.self, i); + const std::string& memberName = compiler.get_member_name(resourceType.self, i); - spdlog::debug("\t\t member({} : size({}), offset({})", memberName, - memberSize, offset); + spdlog::debug("\t\t member({} : size({}), offset({})", memberName, memberSize, offset); totalSize += static_cast(memberSize); } const std::string& blockName = compiler.get_name(resource.base_type_id); spdlog::debug("\t Block : {}, totalSize : {}", blockName, totalSize); - reflectionDataGroup->_descriptors.emplace( - DescriptorInfo{ static_cast(set), - DescriptorCategory::StorageBuffer, count, binding }, - resource.name); + reflectionDataGroup->_descriptors.emplace(DescriptorInfo{ static_cast(set), DescriptorCategory::StorageBuffer, count, binding }, + resource.name); } if (shaderStageBits == VK_SHADER_STAGE_VERTEX_BIT) { - for (const spirv_cross::Resource& attribute : - shaderResources.stage_inputs) + for (const spirv_cross::Resource& attribute : shaderResources.stage_inputs) { - auto location = - compiler.get_decoration(attribute.id, spv::DecorationLocation); + auto location = compiler.get_decoration(attribute.id, spv::DecorationLocation); - auto binding = - compiler.get_decoration(attribute.id, spv::DecorationBinding); + auto binding = compiler.get_decoration(attribute.id, spv::DecorationBinding); - const spirv_cross::SPIRType& resourceType = - compiler.get_type(attribute.type_id); + const spirv_cross::SPIRType& resourceType = compiler.get_type(attribute.type_id); - const uint32_t size = static_cast(resourceType.width * - resourceType.vecsize); - VOX_ASSERT(resourceType.columns == 1, - "Matrix should not be used in stage input/output"); + const uint32_t size = static_cast(resourceType.width * resourceType.vecsize); + VOX_ASSERT(resourceType.columns == 1, "Matrix should not be used in stage input/output"); - VertexFormatBaseType baseType = - convertToBaseType(resourceType.basetype); + VertexFormatBaseType baseType = convertToBaseType(resourceType.basetype); - reflectionDataGroup->_vertexInputLayouts.push_back( - { ._location = location, - ._binding = binding, - ._stride = (size >> 3), - ._baseType = baseType }); + reflectionDataGroup->_vertexInputLayouts.push_back({ ._location = location, ._binding = binding, ._stride = (size >> 3), ._baseType = baseType }); } - std::sort(reflectionDataGroup->_vertexInputLayouts.begin(), - reflectionDataGroup->_vertexInputLayouts.end(), - [](const auto& lhs, const auto& rhs) { - return lhs._location <= rhs._location; - }); + std::sort(reflectionDataGroup->_vertexInputLayouts.begin(), reflectionDataGroup->_vertexInputLayouts.end(), + [](const auto& lhs, const auto& rhs) { return lhs._location <= rhs._location; }); } - + if (shaderStageBits == VK_SHADER_STAGE_FRAGMENT_BIT) { - for (const spirv_cross::Resource& attribute : - shaderResources.stage_outputs) + for (const spirv_cross::Resource& attribute : shaderResources.stage_outputs) { - auto location = - compiler.get_decoration(attribute.id, spv::DecorationLocation); + auto location = compiler.get_decoration(attribute.id, spv::DecorationLocation); - const spirv_cross::SPIRType& resourceType = - compiler.get_type(attribute.type_id); + const spirv_cross::SPIRType& resourceType = compiler.get_type(attribute.type_id); - VkFormat imageFormat = - convertSpirvImageFormat(resourceType.image.format); + VkFormat imageFormat = convertSpirvImageFormat(resourceType.image.format); - reflectionDataGroup->_fragmentOutputLayouts.push_back( - { ._location = location, ._format = imageFormat }); + reflectionDataGroup->_fragmentOutputLayouts.push_back({ ._location = location, ._format = imageFormat }); } - std::sort(reflectionDataGroup->_fragmentOutputLayouts.begin(), - reflectionDataGroup->_fragmentOutputLayouts.end(), - [](const auto& lhs, const auto& rhs) { - return lhs._location <= rhs._location; - }); + std::sort(reflectionDataGroup->_fragmentOutputLayouts.begin(), reflectionDataGroup->_fragmentOutputLayouts.end(), + [](const auto& lhs, const auto& rhs) { return lhs._location <= rhs._location; }); } if (!shaderResources.push_constant_buffers.empty()) { - reflectionDataGroup->_pushConstantSize = static_cast( - compiler.get_declared_struct_size(compiler.get_type( - shaderResources.push_constant_buffers.front().base_type_id))); + reflectionDataGroup->_pushConstantSize = + static_cast(compiler.get_declared_struct_size(compiler.get_type(shaderResources.push_constant_buffers.front().base_type_id))); } reflectionDataGroup->_stageFlagBit = shaderStageBits; diff --git a/Sources/VoxFlow/Core/Graphics/Pipelines/ShaderUtil.cpp b/Sources/VoxFlow/Core/Graphics/Pipelines/ShaderUtil.cpp index f376d603..ebdfbc2e 100644 --- a/Sources/VoxFlow/Core/Graphics/Pipelines/ShaderUtil.cpp +++ b/Sources/VoxFlow/Core/Graphics/Pipelines/ShaderUtil.cpp @@ -117,8 +117,7 @@ constexpr TBuiltInResource GetDefaultGlslangResource() .limits = limits }; } -glslang_stage_t GlslangUtil::GlslangStageFromFilename( - const std::string_view filename) +glslang_stage_t GlslangUtil::GlslangStageFromFilename(const std::string_view filename) { if (filename.find(".vert") != std::string_view::npos) return GLSLANG_STAGE_VERTEX; @@ -137,8 +136,7 @@ glslang_stage_t GlslangUtil::GlslangStageFromFilename( return GLSLANG_STAGE_VERTEX; } -glslang_stage_t GlslangUtil::VulkanStageToGlslangStage( - VkShaderStageFlagBits vkStage) +glslang_stage_t GlslangUtil::VulkanStageToGlslangStage(VkShaderStageFlagBits vkStage) { switch (vkStage) { @@ -155,14 +153,12 @@ glslang_stage_t GlslangUtil::VulkanStageToGlslangStage( case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT: return GLSLANG_STAGE_TESSEVALUATION; default: - VOX_ASSERT(false, "Unknown shader stage flags bits : {}", - static_cast(vkStage)); + VOX_ASSERT(false, "Unknown shader stage flags bits : {}", static_cast(vkStage)); return GLSLANG_STAGE_VERTEX; } } -VkShaderStageFlagBits GlslangUtil::GlslangStageToVulkanStage( - glslang_stage_t glslangStage) +VkShaderStageFlagBits GlslangUtil::GlslangStageToVulkanStage(glslang_stage_t glslangStage) { switch (glslangStage) { @@ -179,8 +175,7 @@ VkShaderStageFlagBits GlslangUtil::GlslangStageToVulkanStage( case GLSLANG_STAGE_TESSEVALUATION: return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT; default: - VOX_ASSERT(false, "Unknown shader stage flags bits : {}", - static_cast(glslangStage)); + VOX_ASSERT(false, "Unknown shader stage flags bits : {}", static_cast(glslangStage)); return VK_SHADER_STAGE_VERTEX_BIT; } } @@ -204,8 +199,7 @@ bool GlslangUtil::ReadShaderFile(const char* filename, std::vector* dst) return true; } -bool GlslangUtil::CompileShader(glslang_stage_t stage, const char* shaderSource, - std::vector* pSpirvBinary) +bool GlslangUtil::CompileShader(glslang_stage_t stage, const char* shaderSource, std::vector* pSpirvBinary) { constexpr TBuiltInResource defaultResource = GetDefaultGlslangResource(); @@ -221,40 +215,31 @@ bool GlslangUtil::CompileShader(glslang_stage_t stage, const char* shaderSource, .default_profile = GLSLANG_NO_PROFILE, .force_default_version_and_profile = false, .forward_compatible = false, - .messages = - GLSLANG_MSG_DEBUG_INFO_BIT, // TODO(snowapril) : must expose this - // bits to command line arguments - .resource = - reinterpret_cast(&defaultResource), + .messages = GLSLANG_MSG_DEBUG_INFO_BIT, // TODO(snowapril) : must expose this + // bits to command line arguments + .resource = reinterpret_cast(&defaultResource), }; glslang_shader_t* shader = glslang_shader_create(&input); if (!glslang_shader_preprocess(shader, &input)) { - spdlog::error("[Glslang] GLSL preprocessing failed\n{}\n{}", - glslang_shader_get_info_log(shader), - glslang_shader_get_info_debug_log(shader)); + spdlog::error("[Glslang] GLSL preprocessing failed\n{}\n{}", glslang_shader_get_info_log(shader), glslang_shader_get_info_debug_log(shader)); return false; } if (!glslang_shader_parse(shader, &input)) { - spdlog::error("[Glslang] GLSL parsing failed\n{}\n{}", - glslang_shader_get_info_log(shader), - glslang_shader_get_info_debug_log(shader)); + spdlog::error("[Glslang] GLSL parsing failed\n{}\n{}", glslang_shader_get_info_log(shader), glslang_shader_get_info_debug_log(shader)); return false; } glslang_program_t* program = glslang_program_create(); glslang_program_add_shader(program, shader); - if (!glslang_program_link( - program, GLSLANG_MSG_SPV_RULES_BIT | GLSLANG_MSG_VULKAN_RULES_BIT)) + if (!glslang_program_link(program, GLSLANG_MSG_SPV_RULES_BIT | GLSLANG_MSG_VULKAN_RULES_BIT)) { - spdlog::error("[Glslang] GLSL linking failed\n{}\n{}", - glslang_shader_get_info_log(shader), - glslang_shader_get_info_debug_log(shader)); + spdlog::error("[Glslang] GLSL linking failed\n{}\n{}", glslang_shader_get_info_log(shader), glslang_shader_get_info_debug_log(shader)); return false; } @@ -264,8 +249,7 @@ bool GlslangUtil::CompileShader(glslang_stage_t stage, const char* shaderSource, glslang_program_SPIRV_get(program, pSpirvBinary->data()); { - if (const char* spirvMessages = - glslang_program_SPIRV_get_messages(program)) + if (const char* spirvMessages = glslang_program_SPIRV_get_messages(program)) { spdlog::error("[Glslang] {}", spirvMessages); } @@ -276,8 +260,7 @@ bool GlslangUtil::CompileShader(glslang_stage_t stage, const char* shaderSource, return true; } -VkShaderStageFlagBits ShaderUtil::ConvertToShaderStageFlag( - const ShaderStage stage) +VkShaderStageFlagBits ShaderUtil::ConvertToShaderStageFlag(const ShaderStage stage) { switch (stage) { @@ -327,11 +310,9 @@ std::string ShaderUtil::ConvertToShaderFileExtension(const ShaderStage stage) } } -bool ShaderUtil::ReadSpirvBinary(const char* filename, - std::vector* dst) +bool ShaderUtil::ReadSpirvBinary(const char* filename, std::vector* dst) { - std::ifstream file( - filename, std::ios::in | std::ios::ate | std::ios::binary); + std::ifstream file(filename, std::ios::in | std::ios::ate | std::ios::binary); if (!file.is_open()) { spdlog::error("Failed to find shader file {}", filename); diff --git a/Sources/VoxFlow/Core/Graphics/RenderPass/FrameBuffer.cpp b/Sources/VoxFlow/Core/Graphics/RenderPass/FrameBuffer.cpp index 8182673c..563426de 100644 --- a/Sources/VoxFlow/Core/Graphics/RenderPass/FrameBuffer.cpp +++ b/Sources/VoxFlow/Core/Graphics/RenderPass/FrameBuffer.cpp @@ -1,14 +1,13 @@ // Author : snowapril -#include #include +#include #include #include namespace VoxFlow { -FrameBuffer::FrameBuffer(LogicalDevice* logicalDevice) - : _logicalDevice(logicalDevice) +FrameBuffer::FrameBuffer(LogicalDevice* logicalDevice) : _logicalDevice(logicalDevice) { } @@ -39,10 +38,8 @@ bool FrameBuffer::initialize(const RenderTargetsInfo& rtInfo) _renderTargetsInfo = rtInfo; std::vector attachments; - attachments.reserve( - _renderTargetsInfo._colorRenderTarget.size() + - (_renderTargetsInfo._depthStencilImage.has_value() ? 1U : 0U)); - + attachments.reserve(_renderTargetsInfo._colorRenderTarget.size() + (_renderTargetsInfo._depthStencilImage.has_value() ? 1U : 0U)); + for (const auto& colorRT : rtInfo._colorRenderTarget) { attachments.push_back(colorRT->get()); @@ -69,8 +66,7 @@ bool FrameBuffer::initialize(const RenderTargetsInfo& rtInfo) frameBufferInfo.flags = VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT; } - VK_ASSERT(vkCreateFramebuffer(_logicalDevice->get(), &frameBufferInfo, nullptr, - &_vkFrameBuffer)); + VK_ASSERT(vkCreateFramebuffer(_logicalDevice->get(), &frameBufferInfo, nullptr, &_vkFrameBuffer)); if (_vkFrameBuffer == VK_NULL_HANDLE) { @@ -78,8 +74,7 @@ bool FrameBuffer::initialize(const RenderTargetsInfo& rtInfo) } #if defined(VK_DEBUG_NAME_ENABLED) - DebugUtil::setObjectName(_logicalDevice, _vkFrameBuffer, - _renderTargetsInfo._debugName.c_str()); + DebugUtil::setObjectName(_logicalDevice, _vkFrameBuffer, _renderTargetsInfo._debugName.c_str()); #endif return true; diff --git a/Sources/VoxFlow/Core/Graphics/RenderPass/RenderPass.cpp b/Sources/VoxFlow/Core/Graphics/RenderPass/RenderPass.cpp index 8a66647f..0a92d7f0 100644 --- a/Sources/VoxFlow/Core/Graphics/RenderPass/RenderPass.cpp +++ b/Sources/VoxFlow/Core/Graphics/RenderPass/RenderPass.cpp @@ -6,8 +6,7 @@ namespace VoxFlow { -RenderPass::RenderPass(LogicalDevice* logicalDevice) - : _logicalDevice(logicalDevice) +RenderPass::RenderPass(LogicalDevice* logicalDevice) : _logicalDevice(logicalDevice) { } @@ -35,10 +34,8 @@ bool RenderPass::initialize(const RenderTargetLayoutKey& rtLayoutKey) { _renderTargetLayout = rtLayoutKey; - const uint32_t numColorAttachments = - static_cast(rtLayoutKey._colorFormats.size()); - const bool hasDepthStencilAttachment = - rtLayoutKey._depthStencilFormat.has_value(); + const uint32_t numColorAttachments = static_cast(rtLayoutKey._colorFormats.size()); + const bool hasDepthStencilAttachment = rtLayoutKey._depthStencilFormat.has_value(); std::vector attachmentDescs; std::vector colorAttachments; VkAttachmentReference depthAttachment; @@ -47,23 +44,16 @@ bool RenderPass::initialize(const RenderTargetLayoutKey& rtLayoutKey) for (uint32_t i = 0; i < numColorAttachments; ++i) { const VkFormat vkColorFormat = rtLayoutKey._colorFormats[i]; - const bool loadColor = - hasColorAspect(rtLayoutKey._renderPassFlags._loadFlags, i); - const bool storeColor = - hasColorAspect(rtLayoutKey._renderPassFlags._storeFlags, i); - const bool clearColor = - hasColorAspect(rtLayoutKey._renderPassFlags._clearFlags, i); + const bool loadColor = hasColorAspect(rtLayoutKey._renderPassFlags._loadFlags, i); + const bool storeColor = hasColorAspect(rtLayoutKey._renderPassFlags._storeFlags, i); + const bool clearColor = hasColorAspect(rtLayoutKey._renderPassFlags._clearFlags, i); VkAttachmentDescription colorAttachmentDesc{ .flags = 0, .format = vkColorFormat, .samples = VK_SAMPLE_COUNT_1_BIT, - .loadOp = clearColor - ? VK_ATTACHMENT_LOAD_OP_CLEAR - : (loadColor ? VK_ATTACHMENT_LOAD_OP_LOAD - : VK_ATTACHMENT_LOAD_OP_DONT_CARE), - .storeOp = storeColor ? VK_ATTACHMENT_STORE_OP_STORE - : VK_ATTACHMENT_STORE_OP_DONT_CARE, + .loadOp = clearColor ? VK_ATTACHMENT_LOAD_OP_CLEAR : (loadColor ? VK_ATTACHMENT_LOAD_OP_LOAD : VK_ATTACHMENT_LOAD_OP_DONT_CARE), + .storeOp = storeColor ? VK_ATTACHMENT_STORE_OP_STORE : VK_ATTACHMENT_STORE_OP_DONT_CARE, .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, .initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, @@ -71,115 +61,85 @@ bool RenderPass::initialize(const RenderTargetLayoutKey& rtLayoutKey) }; attachmentDescs.push_back(colorAttachmentDesc); - VkAttachmentReference colorRef{ - .attachment = attachmentIndex++, - .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL - }; + VkAttachmentReference colorRef{ .attachment = attachmentIndex++, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL }; colorAttachments.push_back(colorRef); } if (hasDepthStencilAttachment) { - const VkFormat& vkDepthStencilFormat = - _renderTargetLayout._depthStencilFormat.value(); - - const bool loadDepth = - hasDepthAspect(rtLayoutKey._renderPassFlags._loadFlags); - const bool storeDepth = - hasDepthAspect(rtLayoutKey._renderPassFlags._storeFlags); - const bool clearDepth = - hasDepthAspect(rtLayoutKey._renderPassFlags._clearFlags); - - const bool loadStencil = - hasStencilAspect(rtLayoutKey._renderPassFlags._loadFlags); - const bool storeStencil = - hasStencilAspect(rtLayoutKey._renderPassFlags._storeFlags); - const bool clearStencil = - hasStencilAspect(rtLayoutKey._renderPassFlags._clearFlags); - - VkAttachmentDescription depthAttachmentDesc - { - .flags = 0, .format = vkDepthStencilFormat, + const VkFormat& vkDepthStencilFormat = _renderTargetLayout._depthStencilFormat.value(); + + const bool loadDepth = hasDepthAspect(rtLayoutKey._renderPassFlags._loadFlags); + const bool storeDepth = hasDepthAspect(rtLayoutKey._renderPassFlags._storeFlags); + const bool clearDepth = hasDepthAspect(rtLayoutKey._renderPassFlags._clearFlags); + + const bool loadStencil = hasStencilAspect(rtLayoutKey._renderPassFlags._loadFlags); + const bool storeStencil = hasStencilAspect(rtLayoutKey._renderPassFlags._storeFlags); + const bool clearStencil = hasStencilAspect(rtLayoutKey._renderPassFlags._clearFlags); + + VkAttachmentDescription depthAttachmentDesc{ + .flags = 0, + .format = vkDepthStencilFormat, .samples = VK_SAMPLE_COUNT_1_BIT, - .loadOp = clearDepth - ? VK_ATTACHMENT_LOAD_OP_CLEAR - : (loadDepth ? VK_ATTACHMENT_LOAD_OP_LOAD - : VK_ATTACHMENT_LOAD_OP_DONT_CARE), - .storeOp = storeDepth ? VK_ATTACHMENT_STORE_OP_STORE - : VK_ATTACHMENT_STORE_OP_DONT_CARE, - .stencilLoadOp = clearStencil - ? VK_ATTACHMENT_LOAD_OP_CLEAR - : (loadStencil ? VK_ATTACHMENT_LOAD_OP_LOAD : VK_ATTACHMENT_LOAD_OP_DONT_CARE), + .loadOp = clearDepth ? VK_ATTACHMENT_LOAD_OP_CLEAR : (loadDepth ? VK_ATTACHMENT_LOAD_OP_LOAD : VK_ATTACHMENT_LOAD_OP_DONT_CARE), + .storeOp = storeDepth ? VK_ATTACHMENT_STORE_OP_STORE : VK_ATTACHMENT_STORE_OP_DONT_CARE, + .stencilLoadOp = clearStencil ? VK_ATTACHMENT_LOAD_OP_CLEAR : (loadStencil ? VK_ATTACHMENT_LOAD_OP_LOAD : VK_ATTACHMENT_LOAD_OP_DONT_CARE), .stencilStoreOp = storeStencil ? VK_ATTACHMENT_STORE_OP_DONT_CARE : VK_ATTACHMENT_STORE_OP_DONT_CARE, .initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, .finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, }; attachmentDescs.push_back(depthAttachmentDesc); - depthAttachment = VkAttachmentReference{ - .attachment = attachmentIndex++, - .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL - }; + depthAttachment = VkAttachmentReference{ .attachment = attachmentIndex++, .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL }; } - VkSubpassDescription subPassDesc{ - .flags = 0, - .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, - .inputAttachmentCount = 0, - .pInputAttachments = nullptr, - .colorAttachmentCount = numColorAttachments, - .pColorAttachments = colorAttachments.data(), - .pResolveAttachments = nullptr, - .pDepthStencilAttachment = - hasDepthStencilAttachment ? &depthAttachment : nullptr, - .preserveAttachmentCount = 0, - .pPreserveAttachments = nullptr - }; + VkSubpassDescription subPassDesc{ .flags = 0, + .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, + .inputAttachmentCount = 0, + .pInputAttachments = nullptr, + .colorAttachmentCount = numColorAttachments, + .pColorAttachments = colorAttachments.data(), + .pResolveAttachments = nullptr, + .pDepthStencilAttachment = hasDepthStencilAttachment ? &depthAttachment : nullptr, + .preserveAttachmentCount = 0, + .pPreserveAttachments = nullptr }; // TODO(snowapril) : support multi-pass architecture. for now, use only // single pass and self-dependency std::vector dependencies = { - /* VkSubpassDependency */ { - .srcSubpass = VK_SUBPASS_EXTERNAL, - .dstSubpass = 0, - .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - .srcAccessMask = 0, - .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - .dependencyFlags = 0 }, + /* VkSubpassDependency */ { .srcSubpass = VK_SUBPASS_EXTERNAL, + .dstSubpass = 0, + .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .srcAccessMask = 0, + .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dependencyFlags = 0 }, }; - const VkRenderPassCreateInfo renderPassInfo = { - .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .attachmentCount = static_cast(attachmentDescs.size()), - .pAttachments = attachmentDescs.data(), - .subpassCount = 1, - .pSubpasses = &subPassDesc, - .dependencyCount = static_cast(dependencies.size()), - .pDependencies = dependencies.data() - }; + const VkRenderPassCreateInfo renderPassInfo = { .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .attachmentCount = static_cast(attachmentDescs.size()), + .pAttachments = attachmentDescs.data(), + .subpassCount = 1, + .pSubpasses = &subPassDesc, + .dependencyCount = static_cast(dependencies.size()), + .pDependencies = dependencies.data() }; - [[maybe_unused]] VkResult result = vkCreateRenderPass( - _logicalDevice->get(), &renderPassInfo, nullptr, &_renderPass); + [[maybe_unused]] VkResult result = vkCreateRenderPass(_logicalDevice->get(), &renderPassInfo, nullptr, &_renderPass); VK_ASSERT(result); if (_renderPass == VK_NULL_HANDLE) { - VOX_ASSERT(false, " Failed to create RenderPass({})", - _renderTargetLayout._debugName); + VOX_ASSERT(false, " Failed to create RenderPass({})", _renderTargetLayout._debugName); return false; } #if defined(VK_DEBUG_NAME_ENABLED) const std::string renderPassDebugName = - fmt::format("{}_Color(#{})_Depth(#{})", _renderTargetLayout._debugName, - numColorAttachments, hasDepthStencilAttachment ? 1U : 0U); - DebugUtil::setObjectName(_logicalDevice, _renderPass, - renderPassDebugName.c_str()); + fmt::format("{}_Color(#{})_Depth(#{})", _renderTargetLayout._debugName, numColorAttachments, hasDepthStencilAttachment ? 1U : 0U); + DebugUtil::setObjectName(_logicalDevice, _renderPass, renderPassDebugName.c_str()); #endif return true; diff --git a/Sources/VoxFlow/Core/Graphics/RenderPass/RenderPassCollector.cpp b/Sources/VoxFlow/Core/Graphics/RenderPass/RenderPassCollector.cpp index a0e6ae36..178e0252 100644 --- a/Sources/VoxFlow/Core/Graphics/RenderPass/RenderPassCollector.cpp +++ b/Sources/VoxFlow/Core/Graphics/RenderPass/RenderPassCollector.cpp @@ -1,16 +1,14 @@ // Author : snowapril -#include -#include #include +#include +#include namespace VoxFlow { -RenderPassCollector::RenderPassCollector(LogicalDevice* logicalDevice) - : _logicalDevice(logicalDevice) +RenderPassCollector::RenderPassCollector(LogicalDevice* logicalDevice) : _logicalDevice(logicalDevice) { - } RenderPassCollector::~RenderPassCollector() @@ -23,8 +21,7 @@ RenderPassCollector::RenderPassCollector(RenderPassCollector&& other) noexcept operator=(std::move(other)); } -RenderPassCollector& RenderPassCollector::operator=( - RenderPassCollector&& other) noexcept +RenderPassCollector& RenderPassCollector::operator=(RenderPassCollector&& other) noexcept { if (&other != this) { @@ -34,8 +31,7 @@ RenderPassCollector& RenderPassCollector::operator=( return *this; } -RenderPass* RenderPassCollector::getOrCreateRenderPass( - RenderTargetLayoutKey layoutKey) +RenderPass* RenderPassCollector::getOrCreateRenderPass(RenderTargetLayoutKey layoutKey) { auto it = _renderPassCollection.find(layoutKey); @@ -56,8 +52,7 @@ RenderPass* RenderPassCollector::getOrCreateRenderPass( return it->second.get(); } -FrameBuffer* RenderPassCollector::getOrCreateFrameBuffer( - RenderTargetsInfo rtInfo) +FrameBuffer* RenderPassCollector::getOrCreateFrameBuffer(RenderTargetsInfo rtInfo) { auto it = _frameBufferCollection.find(rtInfo); diff --git a/Sources/VoxFlow/Core/Graphics/RenderPass/RenderPassParams.cpp b/Sources/VoxFlow/Core/Graphics/RenderPass/RenderPassParams.cpp index f1242783..b133f167 100644 --- a/Sources/VoxFlow/Core/Graphics/RenderPass/RenderPassParams.cpp +++ b/Sources/VoxFlow/Core/Graphics/RenderPass/RenderPassParams.cpp @@ -6,8 +6,7 @@ namespace VoxFlow { } // namespace VoxFlow -std::size_t std::hash::operator()( - VoxFlow::RenderPassFlags const& passFlags) const noexcept +std::size_t std::hash::operator()(VoxFlow::RenderPassFlags const& passFlags) const noexcept { uint32_t seed = 0; diff --git a/Sources/VoxFlow/Core/Graphics/RenderPass/RenderTargetGroup.cpp b/Sources/VoxFlow/Core/Graphics/RenderPass/RenderTargetGroup.cpp index 9745e734..2107d7ef 100644 --- a/Sources/VoxFlow/Core/Graphics/RenderPass/RenderTargetGroup.cpp +++ b/Sources/VoxFlow/Core/Graphics/RenderPass/RenderTargetGroup.cpp @@ -8,28 +8,19 @@ namespace VoxFlow { bool RenderTargetLayoutKey::operator==(const RenderTargetLayoutKey& other) const { - return std::equal(_colorFormats.begin(), _colorFormats.end(), - other._colorFormats.begin(), other._colorFormats.end()) && - (_depthStencilFormat == other._depthStencilFormat) && - (_renderPassFlags == other._renderPassFlags) && - (_debugName == other._debugName); + return std::equal(_colorFormats.begin(), _colorFormats.end(), other._colorFormats.begin(), other._colorFormats.end()) && + (_depthStencilFormat == other._depthStencilFormat) && (_renderPassFlags == other._renderPassFlags) && (_debugName == other._debugName); } bool RenderTargetsInfo::operator==(const RenderTargetsInfo& other) const { return _vkRenderPass == other._vkRenderPass && - std::equal(_colorRenderTarget.begin(), _colorRenderTarget.end(), - other._colorRenderTarget.begin(), - other._colorRenderTarget.end()) && - (_depthStencilImage == other._depthStencilImage) && - (_resolution == other._resolution) && (_layers == other._layers) && - (_numSamples == other._numSamples) && - (_debugName == other._debugName); + std::equal(_colorRenderTarget.begin(), _colorRenderTarget.end(), other._colorRenderTarget.begin(), other._colorRenderTarget.end()) && + (_depthStencilImage == other._depthStencilImage) && (_resolution == other._resolution) && (_layers == other._layers) && + (_numSamples == other._numSamples) && (_debugName == other._debugName); } -AttachmentGroup::AttachmentGroup(std::vector&& colorAttachments, - Attachment&& depthStencilAttachment, - const uint32_t numSamples) +AttachmentGroup::AttachmentGroup(std::vector&& colorAttachments, Attachment&& depthStencilAttachment, const uint32_t numSamples) : _colorAttachments(std::move(colorAttachments)), _depthStencilAttachment(std::move(depthStencilAttachment)), _numColorAttachments(static_cast(_colorAttachments.size())), @@ -39,8 +30,7 @@ AttachmentGroup::AttachmentGroup(std::vector&& colorAttachments, }; // namespace VoxFlow -std::size_t std::hash::operator()( - VoxFlow::RenderTargetLayoutKey const& layoutKey) const noexcept +std::size_t std::hash::operator()(VoxFlow::RenderTargetLayoutKey const& layoutKey) const noexcept { uint32_t seed = 0; @@ -52,11 +42,9 @@ std::size_t std::hash::operator()( if (layoutKey._depthStencilFormat.has_value()) { - const VkFormat vkDepthStencilFormat = - layoutKey._depthStencilFormat.value(); + const VkFormat vkDepthStencilFormat = layoutKey._depthStencilFormat.value(); - VoxFlow::hash_combine(seed, - static_cast(vkDepthStencilFormat)); + VoxFlow::hash_combine(seed, static_cast(vkDepthStencilFormat)); } VoxFlow::hash_combine(seed, layoutKey._renderPassFlags); @@ -64,14 +52,12 @@ std::size_t std::hash::operator()( return seed; } -std::size_t std::hash::operator()( - VoxFlow::RenderTargetsInfo const& rtInfo) const noexcept +std::size_t std::hash::operator()(VoxFlow::RenderTargetsInfo const& rtInfo) const noexcept { uint32_t seed = 0; VoxFlow::hash_combine(seed, rtInfo._debugName); - VoxFlow::hash_combine(seed, - reinterpret_cast(rtInfo._vkRenderPass)); + VoxFlow::hash_combine(seed, reinterpret_cast(rtInfo._vkRenderPass)); for (VoxFlow::TextureView* colorRT : rtInfo._colorRenderTarget) { VoxFlow::hash_combine(seed, reinterpret_cast(colorRT->get())); @@ -79,11 +65,9 @@ std::size_t std::hash::operator()( if (rtInfo._depthStencilImage.has_value()) { - VoxFlow::TextureView* depthStencilImageView = - rtInfo._depthStencilImage.value(); + VoxFlow::TextureView* depthStencilImageView = rtInfo._depthStencilImage.value(); - VoxFlow::hash_combine( - seed, reinterpret_cast(depthStencilImageView->get())); + VoxFlow::hash_combine(seed, reinterpret_cast(depthStencilImageView->get())); } VoxFlow::hash_combine(seed, rtInfo._resolution.x); diff --git a/Sources/VoxFlow/Core/Renderer/SceneRenderer.cpp b/Sources/VoxFlow/Core/Renderer/SceneRenderer.cpp index 1f15bd97..4cd5a490 100644 --- a/Sources/VoxFlow/Core/Renderer/SceneRenderer.cpp +++ b/Sources/VoxFlow/Core/Renderer/SceneRenderer.cpp @@ -5,26 +5,20 @@ #include #include #include -#include #include +#include #include namespace VoxFlow { -SceneRenderer::SceneRenderer(LogicalDevice* mainLogicalDevice, - RenderGraph::FrameGraph* frameGraph) - : _mainLogicalDevice(mainLogicalDevice), - _frameGraph(frameGraph) +SceneRenderer::SceneRenderer(LogicalDevice* mainLogicalDevice, RenderGraph::FrameGraph* frameGraph) + : _mainLogicalDevice(mainLogicalDevice), _frameGraph(frameGraph) { _commandJobSystem = _mainLogicalDevice->getCommandJobSystem(); - _renderCmdStreamKey = - CommandStreamKey{ ._cmdStreamName = MAIN_GRAPHICS_STREAM_NAME, - ._cmdStreamUsage = CommandStreamUsage::Graphics }; + _renderCmdStreamKey = CommandStreamKey{ ._cmdStreamName = MAIN_GRAPHICS_STREAM_NAME, ._cmdStreamUsage = CommandStreamUsage::Graphics }; - _renderResourceAllocator = std::make_unique( - mainLogicalDevice, - mainLogicalDevice->getDeviceDefaultResourceMemoryPool()); + _renderResourceAllocator = std::make_unique(mainLogicalDevice, mainLogicalDevice->getDeviceDefaultResourceMemoryPool()); } SceneRenderer::~SceneRenderer() @@ -37,8 +31,7 @@ bool SceneRenderer::initializePasses() { if (pass->initialize() == false) { - VOX_ASSERT(false, "Failed to initialize scene render pass {}", - passName); + VOX_ASSERT(false, "Failed to initialize scene render pass {}", passName); return false; } } @@ -59,27 +52,19 @@ void SceneRenderer::beginFrameGraph(const FrameContext& frameContext) _currentFrameContext = frameContext; - _frameGraph->reset(_commandJobSystem->getCommandStream(_renderCmdStreamKey), - _renderResourceAllocator.get()); + _frameGraph->reset(_commandJobSystem->getCommandStream(_renderCmdStreamKey), _renderResourceAllocator.get()); - SwapChain* swapChain = - _mainLogicalDevice->getSwapChain(_currentFrameContext._swapChainIndex) - .get(); + SwapChain* swapChain = _mainLogicalDevice->getSwapChain(_currentFrameContext._swapChainIndex).get(); - Texture* currentBackBuffer = - swapChain->getSwapChainImage(_currentFrameContext._backBufferIndex) - .get(); + Texture* currentBackBuffer = swapChain->getSwapChainImage(_currentFrameContext._backBufferIndex).get(); const TextureInfo& backBufferInfo = currentBackBuffer->getTextureInfo(); // TODO(snowapril) : create back buffer view other place. std::optional backBufferViewIndex = - currentBackBuffer->createTextureView( - TextureViewInfo{ ._format = backBufferInfo._format, - ._aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT }); + currentBackBuffer->createTextureView(TextureViewInfo{ ._format = backBufferInfo._format, ._aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT }); - std::shared_ptr backBufferView = - currentBackBuffer->getView(backBufferViewIndex.value()); + std::shared_ptr backBufferView = currentBackBuffer->getView(backBufferViewIndex.value()); using namespace RenderGraph; auto backBufferDescriptor = FrameGraphTexture::Descriptor{ @@ -91,23 +76,19 @@ void SceneRenderer::beginFrameGraph(const FrameContext& frameContext) ._format = backBufferInfo._format, }; - auto backBufferRenderTargetDesc = - FrameGraphRenderPass::ImportedDescriptor{ - ._attachmentSlot = AttachmentMaskFlags::All, - ._viewportSize = - glm::uvec2(backBufferInfo._extent.x, backBufferInfo._extent.y), - ._clearColor = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f), - ._clearFlags = AttachmentMaskFlags::All, - ._writableAttachment = AttachmentMaskFlags::All, - ._numSamples = 1, - }; + auto backBufferRenderTargetDesc = FrameGraphRenderPass::ImportedDescriptor{ + ._attachmentSlot = AttachmentMaskFlags::All, + ._viewportSize = glm::uvec2(backBufferInfo._extent.x, backBufferInfo._extent.y), + ._clearColor = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f), + ._clearFlags = AttachmentMaskFlags::All, + ._writableAttachment = AttachmentMaskFlags::All, + ._numSamples = 1, + }; BlackBoard& blackBoard = _frameGraph->getBlackBoard(); ResourceHandle backBufferHandle = - _frameGraph->importRenderTarget( - "BackBuffer", std::move(backBufferDescriptor), - std::move(backBufferRenderTargetDesc), backBufferView.get()); + _frameGraph->importRenderTarget("BackBuffer", std::move(backBufferDescriptor), std::move(backBufferRenderTargetDesc), backBufferView.get()); blackBoard["BackBuffer"] = backBufferHandle; } @@ -121,13 +102,10 @@ tf::Future SceneRenderer::resolveSceneRenderPasses(SwapChain* swapChain) std::unordered_map tasks; // Prepare tasks from registered scene render passes - for (auto iter = _sceneRenderPasses.begin(); - iter != _sceneRenderPasses.end(); ++iter) + for (auto iter = _sceneRenderPasses.begin(); iter != _sceneRenderPasses.end(); ++iter) { SceneRenderPass* pass = iter->second.get(); - tf::Task fgTask = - taskflow.emplace([this, pass]() { pass->renderScene(_frameGraph); }) - .name(iter->first); + tf::Task fgTask = taskflow.emplace([this, pass]() { pass->renderScene(_frameGraph); }).name(iter->first); tasks.emplace(iter->first, std::move(fgTask)); } @@ -135,8 +113,7 @@ tf::Future SceneRenderer::resolveSceneRenderPasses(SwapChain* swapChain) // Resolve dependency between tasks for (const auto& [passName, pass] : _sceneRenderPasses) { - const std::vector* dependentPasses = - pass->getDepenentPasses(); + const std::vector* dependentPasses = pass->getDepenentPasses(); tf::Task& fgTask = tasks.find(passName)->second; for (const std::string& dependentPassName : *dependentPasses) @@ -146,18 +123,14 @@ tf::Future SceneRenderer::resolveSceneRenderPasses(SwapChain* swapChain) } // Add present pass which followed by all other passes - ResourceHandle backBufferHandle = - _frameGraph->getBlackBoard().getHandle("BackBuffer"); + ResourceHandle backBufferHandle = _frameGraph->getBlackBoard().getHandle("BackBuffer"); tf::Task presentTask = taskflow .emplace([&]() { _frameGraph->addPresentPass( - "PresentPass", - [&](FrameGraphBuilder& builder) { - builder.read(backBufferHandle, TextureUsage::BackBuffer); - }, - swapChain, _currentFrameContext); + "PresentPass", [&](FrameGraphBuilder& builder) { builder.read(backBufferHandle, TextureUsage::BackBuffer); }, swapChain, + _currentFrameContext); }) .name("PresentPass"); @@ -169,9 +142,7 @@ tf::Future SceneRenderer::resolveSceneRenderPasses(SwapChain* swapChain) } // Add frame graph compilation task - taskflow.emplace([&]() { _frameGraph->compile(); }) - .name("Compilation") - .succeed(presentTask); + taskflow.emplace([&]() { _frameGraph->compile(); }).name("Compilation").succeed(presentTask); tf::Executor executor; return executor.run(taskflow); diff --git a/Sources/VoxFlow/Core/Resources/Buffer.cpp b/Sources/VoxFlow/Core/Resources/Buffer.cpp index ea1b0428..648e1257 100644 --- a/Sources/VoxFlow/Core/Resources/Buffer.cpp +++ b/Sources/VoxFlow/Core/Resources/Buffer.cpp @@ -2,9 +2,9 @@ #include #include -#include #include #include +#include #include #include @@ -23,16 +23,14 @@ static VkBufferUsageFlags convertToVkBufferUsage(BufferUsage usage) resultUsage |= VK_BUFFER_USAGE_INDEX_BUFFER_BIT; if (static_cast(usage & BufferUsage::IndirectCommand) > 0) resultUsage |= VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; - if ((static_cast(usage & BufferUsage::Readback) > 0) || - (static_cast(usage & BufferUsage::CopyDst) > 0)) + if ((static_cast(usage & BufferUsage::Readback) > 0) || (static_cast(usage & BufferUsage::CopyDst) > 0)) resultUsage |= VK_BUFFER_USAGE_TRANSFER_DST_BIT; if (static_cast(usage & BufferUsage::CopySrc) > 0) resultUsage |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT; return resultUsage; } -Buffer::Buffer(std::string_view&& debugName, LogicalDevice* logicalDevice, - RenderResourceMemoryPool* renderResourceMemoryPool) +Buffer::Buffer(std::string_view&& debugName, LogicalDevice* logicalDevice, RenderResourceMemoryPool* renderResourceMemoryPool) : RenderResource(std::move(debugName), logicalDevice, renderResourceMemoryPool) { } @@ -44,36 +42,28 @@ Buffer::~Buffer() bool Buffer::makeAllocationResident(const BufferInfo& bufferInfo) { - VOX_ASSERT(bufferInfo._usage != BufferUsage::Unknown, - "BufferUsage must be specified"); + VOX_ASSERT(bufferInfo._usage != BufferUsage::Unknown, "BufferUsage must be specified"); _bufferInfo = bufferInfo; - VkBufferCreateInfo bufferCreateInfo = { - .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .size = bufferInfo._size, - .usage = convertToVkBufferUsage(bufferInfo._usage), - .sharingMode = VK_SHARING_MODE_EXCLUSIVE, - .queueFamilyIndexCount = 0, - .pQueueFamilyIndices = nullptr - }; - - VmaAllocationCreateInfo vmaCreateInfo = { - .flags = - VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT, // TODO(snowapril) : - // choose best one - .usage = VMA_MEMORY_USAGE_AUTO, - .requiredFlags = 0, - .preferredFlags = 0, - .memoryTypeBits = 0, - .pool = VK_NULL_HANDLE, - .pUserData = nullptr - }; - - VK_ASSERT(vmaCreateBuffer(_renderResourceMemoryPool->get(), - &bufferCreateInfo, &vmaCreateInfo, &_vkBuffer, - &_allocation, nullptr)); + VkBufferCreateInfo bufferCreateInfo = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .size = bufferInfo._size, + .usage = convertToVkBufferUsage(bufferInfo._usage), + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .queueFamilyIndexCount = 0, + .pQueueFamilyIndices = nullptr }; + + VmaAllocationCreateInfo vmaCreateInfo = { .flags = VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT, // TODO(snowapril) : + // choose best one + .usage = VMA_MEMORY_USAGE_AUTO, + .requiredFlags = 0, + .preferredFlags = 0, + .memoryTypeBits = 0, + .pool = VK_NULL_HANDLE, + .pUserData = nullptr }; + + VK_ASSERT(vmaCreateBuffer(_renderResourceMemoryPool->get(), &bufferCreateInfo, &vmaCreateInfo, &_vkBuffer, &_allocation, nullptr)); if (_vkBuffer == VK_NULL_HANDLE) { @@ -85,26 +75,21 @@ bool Buffer::makeAllocationResident(const BufferInfo& bufferInfo) DebugUtil::setObjectName(_logicalDevice, _vkBuffer, _debugName.c_str()); #endif - std::optional defaultViewIndex = createBufferView( - BufferViewInfo{ ._offset = 0, ._range = bufferInfo._size }); + std::optional defaultViewIndex = createBufferView(BufferViewInfo{ ._offset = 0, ._range = bufferInfo._size }); - VOX_ASSERT(defaultViewIndex.has_value(), - "Failed to create default buffer view for buffer({})", - _debugName); + VOX_ASSERT(defaultViewIndex.has_value(), "Failed to create default buffer view for buffer({})", _debugName); if (defaultViewIndex.has_value()) { _defaultView = getView(defaultViewIndex.value()).get(); } - + return true; } std::optional Buffer::createBufferView(const BufferViewInfo& viewInfo) { const uint32_t viewIndex = static_cast(_ownedBufferViews.size()); - std::shared_ptr bufferView = std::make_shared( - fmt::format("{}_View({})", _debugName, viewIndex), _logicalDevice, - this); + std::shared_ptr bufferView = std::make_shared(fmt::format("{}_View({})", _debugName, viewIndex), _logicalDevice, this); if (bufferView->initialize(viewInfo) == false) { @@ -127,17 +112,12 @@ void Buffer::release() if (_vkBuffer != VK_NULL_HANDLE) { - VmaAllocator vmaAllocator = - _renderResourceMemoryPool->get(); + VmaAllocator vmaAllocator = _renderResourceMemoryPool->get(); VkBuffer vkBuffer = _vkBuffer; VmaAllocation vmaAllocation = _allocation; - - RenderResourceGarbageCollector::Get().pushRenderResourceGarbage( - RenderResourceGarbage(std::move(_accessedFences), - [vmaAllocator, vkBuffer, vmaAllocation]() { - vmaDestroyBuffer(vmaAllocator, vkBuffer, - vmaAllocation); - })); + + RenderResourceGarbageCollector::Get().pushRenderResourceGarbage(RenderResourceGarbage( + std::move(_accessedFences), [vmaAllocator, vkBuffer, vmaAllocation]() { vmaDestroyBuffer(vmaAllocator, vkBuffer, vmaAllocation); })); _vkBuffer = VK_NULL_HANDLE; _allocation = VK_NULL_HANDLE; @@ -146,16 +126,13 @@ void Buffer::release() uint8_t* Buffer::map() { - VOX_ASSERT( - static_cast(_bufferInfo._usage & (BufferUsage::Readback | - BufferUsage::Upload)) > 0, - "Buffer without Readback flag must not be mapped"); + VOX_ASSERT(static_cast(_bufferInfo._usage & (BufferUsage::Readback | BufferUsage::Upload)) > 0, + "Buffer without Readback flag must not be mapped"); if (_permanentMappedAddress == nullptr) { void* memoryAddress = nullptr; - VK_ASSERT(vmaMapMemory(_renderResourceMemoryPool->get(), - _allocation, &memoryAddress)); + VK_ASSERT(vmaMapMemory(_renderResourceMemoryPool->get(), _allocation, &memoryAddress)); _permanentMappedAddress = memoryAddress; } @@ -167,8 +144,7 @@ void Buffer::unmap() // TODO(snowapril) : consider unmap or not } -BufferView::BufferView(std::string&& debugName, LogicalDevice* logicalDevice, - RenderResource* ownerResource) +BufferView::BufferView(std::string&& debugName, LogicalDevice* logicalDevice, RenderResource* ownerResource) : ResourceView(std::move(debugName), logicalDevice, ownerResource) { } diff --git a/Sources/VoxFlow/Core/Resources/RenderResource.cpp b/Sources/VoxFlow/Core/Resources/RenderResource.cpp index 6329fd7e..44f593a1 100644 --- a/Sources/VoxFlow/Core/Resources/RenderResource.cpp +++ b/Sources/VoxFlow/Core/Resources/RenderResource.cpp @@ -5,9 +5,7 @@ namespace VoxFlow { -RenderResource::RenderResource( - std::string_view&& debugName, LogicalDevice* logicalDevice, - RenderResourceMemoryPool* renderResourceMemoryPool) +RenderResource::RenderResource(std::string_view&& debugName, LogicalDevice* logicalDevice, RenderResourceMemoryPool* renderResourceMemoryPool) : _debugName(std::move(debugName)), _logicalDevice(logicalDevice), _renderResourceMemoryPool(renderResourceMemoryPool), diff --git a/Sources/VoxFlow/Core/Resources/RenderResourceAllocator.cpp b/Sources/VoxFlow/Core/Resources/RenderResourceAllocator.cpp index 6c01bc85..f51b8d81 100644 --- a/Sources/VoxFlow/Core/Resources/RenderResourceAllocator.cpp +++ b/Sources/VoxFlow/Core/Resources/RenderResourceAllocator.cpp @@ -7,11 +7,8 @@ namespace VoxFlow { -RenderResourceAllocator::RenderResourceAllocator( - LogicalDevice* logicalDevice, - RenderResourceMemoryPool* renderResourceMemoryPool) - : _logicalDevice(logicalDevice), - _renderResourceMemoryPool(renderResourceMemoryPool) +RenderResourceAllocator::RenderResourceAllocator(LogicalDevice* logicalDevice, RenderResourceMemoryPool* renderResourceMemoryPool) + : _logicalDevice(logicalDevice), _renderResourceMemoryPool(renderResourceMemoryPool) { } @@ -23,11 +20,9 @@ RenderResourceAllocator::~RenderResourceAllocator() } } -std::shared_ptr RenderResourceAllocator::allocateTexture( - const TextureInfo& textureInfo, std::string&& debugName) +std::shared_ptr RenderResourceAllocator::allocateTexture(const TextureInfo& textureInfo, std::string&& debugName) { - std::shared_ptr texture = std::make_shared( - std::move(debugName), _logicalDevice, _renderResourceMemoryPool); + std::shared_ptr texture = std::make_shared(std::move(debugName), _logicalDevice, _renderResourceMemoryPool); if (texture->makeAllocationResident(textureInfo) == false) { @@ -37,11 +32,9 @@ std::shared_ptr RenderResourceAllocator::allocateTexture( return texture; } -std::shared_ptr RenderResourceAllocator::allocateBuffer( - const BufferInfo& bufferInfo, std::string&& debugName) +std::shared_ptr RenderResourceAllocator::allocateBuffer(const BufferInfo& bufferInfo, std::string&& debugName) { - std::shared_ptr buffer = std::make_shared( - std::move(debugName), _logicalDevice, _renderResourceMemoryPool); + std::shared_ptr buffer = std::make_shared(std::move(debugName), _logicalDevice, _renderResourceMemoryPool); if (buffer->makeAllocationResident(bufferInfo) == false) { diff --git a/Sources/VoxFlow/Core/Resources/RenderResourceGarbageCollector.cpp b/Sources/VoxFlow/Core/Resources/RenderResourceGarbageCollector.cpp index 54ec7526..f562af9c 100644 --- a/Sources/VoxFlow/Core/Resources/RenderResourceGarbageCollector.cpp +++ b/Sources/VoxFlow/Core/Resources/RenderResourceGarbageCollector.cpp @@ -8,8 +8,7 @@ namespace VoxFlow { -void RenderResourceGarbageCollector::pushRenderResourceGarbage( - RenderResourceGarbage&& garbage) +void RenderResourceGarbageCollector::pushRenderResourceGarbage(RenderResourceGarbage&& garbage) { std::lock_guard scopedLock(_garbageCollectionLock); _garbageCollection.emplace_back(std::move(garbage)); @@ -29,12 +28,9 @@ void RenderResourceGarbageCollector::processRenderResourceGarbage() { std::lock_guard scopedLock(_garbageCollectionLock); - sTmpGarbageCollection.reserve(_garbageCollection.size() + - sTmpGarbageCollection.size()); - sTmpGarbageCollection.insert( - sTmpGarbageCollection.end(), - std::make_move_iterator(_garbageCollection.begin()), - std::make_move_iterator(_garbageCollection.end())); + sTmpGarbageCollection.reserve(_garbageCollection.size() + sTmpGarbageCollection.size()); + sTmpGarbageCollection.insert(sTmpGarbageCollection.end(), std::make_move_iterator(_garbageCollection.begin()), + std::make_move_iterator(_garbageCollection.end())); } uint32_t numGarbages = static_cast(sTmpGarbageCollection.size()); @@ -53,7 +49,7 @@ void RenderResourceGarbageCollector::processRenderResourceGarbage() } } - if (isUsingResource == false) + if (isUsingResource == false) { std::invoke(resourceGarbage._deletionDelegate); std::swap(resourceGarbage, sTmpGarbageCollection[numGarbages - 1]); @@ -66,8 +62,7 @@ void RenderResourceGarbageCollector::processRenderResourceGarbage() } } - sTmpGarbageCollection.resize(sTmpGarbageCollection.size() - - numDeletedResources); + sTmpGarbageCollection.resize(sTmpGarbageCollection.size() - numDeletedResources); } void RenderResourceGarbageCollector::threadConstruct() @@ -75,15 +70,14 @@ void RenderResourceGarbageCollector::threadConstruct() _isConstructed = true; _shouldTerminate = false; - _threadHandle = - std::thread(&RenderResourceGarbageCollector::threadProcess, this); + _threadHandle = std::thread(&RenderResourceGarbageCollector::threadProcess, this); } void RenderResourceGarbageCollector::threadProcess() { using namespace std::chrono_literals; - static bool sIsThreadNameInitialized = false; // TODO(snowapril) + static bool sIsThreadNameInitialized = false; // TODO(snowapril) if (sIsThreadNameInitialized == false) { Thread::SetThreadName("RenderResourceGarbageCollector"); diff --git a/Sources/VoxFlow/Core/Resources/RenderResourceMemoryPool.cpp b/Sources/VoxFlow/Core/Resources/RenderResourceMemoryPool.cpp index 0de7072e..7f5a7475 100644 --- a/Sources/VoxFlow/Core/Resources/RenderResourceMemoryPool.cpp +++ b/Sources/VoxFlow/Core/Resources/RenderResourceMemoryPool.cpp @@ -8,12 +8,8 @@ namespace VoxFlow { -RenderResourceMemoryPool::RenderResourceMemoryPool( - LogicalDevice* logicalDevice, PhysicalDevice* physicalDevice, - Instance* instance) - : _logicalDevice(logicalDevice), - _physicalDevice(physicalDevice), - _instance(instance) +RenderResourceMemoryPool::RenderResourceMemoryPool(LogicalDevice* logicalDevice, PhysicalDevice* physicalDevice, Instance* instance) + : _logicalDevice(logicalDevice), _physicalDevice(physicalDevice), _instance(instance) { } @@ -34,13 +30,13 @@ bool RenderResourceMemoryPool::initialize() .flags = 0, .physicalDevice = _physicalDevice->get(), .device = _logicalDevice->get(), - .preferredLargeHeapBlockSize = 0, // TODO(snowapril) : customize fields + .preferredLargeHeapBlockSize = 0, // TODO(snowapril) : customize fields .pAllocationCallbacks = nullptr, .pDeviceMemoryCallbacks = nullptr, - .pHeapSizeLimit = nullptr, // TODO(snowapril) : customize fields + .pHeapSizeLimit = nullptr, // TODO(snowapril) : customize fields .pVulkanFunctions = &vmaVulkanFunctions, .instance = _instance->get(), - .vulkanApiVersion = VK_API_VERSION_1_3, // TODO(snowapril) : customize fields + .vulkanApiVersion = VK_API_VERSION_1_3, // TODO(snowapril) : customize fields .pTypeExternalMemoryHandleTypes = nullptr, }; diff --git a/Sources/VoxFlow/Core/Resources/ResourceUploadContext.cpp b/Sources/VoxFlow/Core/Resources/ResourceUploadContext.cpp index 829342f6..4cdaada2 100644 --- a/Sources/VoxFlow/Core/Resources/ResourceUploadContext.cpp +++ b/Sources/VoxFlow/Core/Resources/ResourceUploadContext.cpp @@ -13,18 +13,12 @@ namespace VoxFlow { -ResourceUploadContext::ResourceUploadContext(RenderDevice* renderDevice) - : _renderDevice(renderDevice) +ResourceUploadContext::ResourceUploadContext(RenderDevice* renderDevice) : _renderDevice(renderDevice) { - for (uint32_t i = 0; i < static_cast(LogicalDeviceType::Count); - ++i) + for (uint32_t i = 0; i < static_cast(LogicalDeviceType::Count); ++i) { - LogicalDevice* logicalDevice = - _renderDevice->getLogicalDevice(static_cast(i)); - _stagingBufferContexts.emplace_back( - std::make_unique( - logicalDevice, - logicalDevice->getDeviceDefaultResourceMemoryPool())); + LogicalDevice* logicalDevice = _renderDevice->getLogicalDevice(static_cast(i)); + _stagingBufferContexts.emplace_back(std::make_unique(logicalDevice, logicalDevice->getDeviceDefaultResourceMemoryPool())); } } @@ -33,53 +27,37 @@ ResourceUploadContext ::~ResourceUploadContext() release(); } -void ResourceUploadContext::addPendingUpload(UploadPhase uploadPhase, - RenderResource* uploadDst, - UploadData&& uploadData) +void ResourceUploadContext::addPendingUpload(UploadPhase uploadPhase, RenderResource* uploadDst, UploadData&& uploadData) { const LogicalDeviceType deviceType = uploadDst->getDeviceType(); - auto [stagingBuffer, stagingBufferOffset] = - _stagingBufferContexts[static_cast(deviceType)] - ->getOrCreateStagingBuffer(uploadData._size); + auto [stagingBuffer, stagingBufferOffset] = _stagingBufferContexts[static_cast(deviceType)]->getOrCreateStagingBuffer(uploadData._size); uint8_t* mappedData = stagingBuffer->map(); - memcpy(mappedData + stagingBufferOffset, uploadData._data, - uploadData._size); + memcpy(mappedData + stagingBufferOffset, uploadData._data, uploadData._size); stagingBuffer->unmap(); - PendingUploadInfo uploadInfo = { ._srcBuffer = stagingBuffer, - ._dstResource = uploadDst, - ._stagingBufferOffset = - stagingBufferOffset, - ._uploadData = std::move(uploadData) }; + PendingUploadInfo uploadInfo = { + ._srcBuffer = stagingBuffer, ._dstResource = uploadDst, ._stagingBufferOffset = stagingBufferOffset, ._uploadData = std::move(uploadData) + }; if (uploadPhase == UploadPhase::Immediate) { - CommandStreamKey immediateStreamKey = { - ._cmdStreamName = IMMEDIATE_UPLOAD_STREAM_NAME, - ._cmdStreamUsage = CommandStreamUsage::Transfer - }; + CommandStreamKey immediateStreamKey = { ._cmdStreamName = IMMEDIATE_UPLOAD_STREAM_NAME, ._cmdStreamUsage = CommandStreamUsage::Transfer }; - CommandStream* cmdStream = _renderDevice->getLogicalDevice(deviceType) - ->getCommandJobSystem() - ->getCommandStream(immediateStreamKey); + CommandStream* cmdStream = _renderDevice->getLogicalDevice(deviceType)->getCommandJobSystem()->getCommandStream(immediateStreamKey); uploadResource(std::move(uploadInfo), cmdStream); cmdStream->flush(nullptr, nullptr, true); } else { - _pendingUploadDatas[static_cast(uploadPhase)].emplace_back( - std::move(uploadInfo) - ); + _pendingUploadDatas[static_cast(uploadPhase)].emplace_back(std::move(uploadInfo)); } } -void ResourceUploadContext::processPendingUploads( - UploadPhase uploadPhase, CommandStream* cmdStream) +void ResourceUploadContext::processPendingUploads(UploadPhase uploadPhase, CommandStream* cmdStream) { - std::vector& pendingUploadInfos = - _pendingUploadDatas[static_cast(uploadPhase)]; + std::vector& pendingUploadInfos = _pendingUploadDatas[static_cast(uploadPhase)]; for (PendingUploadInfo& uploadInfo : pendingUploadInfos) { uploadResource(std::move(uploadInfo), cmdStream); @@ -87,26 +65,18 @@ void ResourceUploadContext::processPendingUploads( pendingUploadInfos.clear(); } -void ResourceUploadContext::uploadResource(PendingUploadInfo&& uploadInfo, - CommandStream* cmdStream) +void ResourceUploadContext::uploadResource(PendingUploadInfo&& uploadInfo, CommandStream* cmdStream) { - const RenderResourceType resourceType = - uploadInfo._dstResource->getResourceType(); + const RenderResourceType resourceType = uploadInfo._dstResource->getResourceType(); switch (resourceType) { case RenderResourceType::Buffer: - cmdStream->addJob( - CommandJobType::UploadBuffer, - static_cast(uploadInfo._dstResource), - uploadInfo._srcBuffer, uploadInfo._uploadData._dstOffset, - uploadInfo._stagingBufferOffset, uploadInfo._uploadData._size); + cmdStream->addJob(CommandJobType::UploadBuffer, static_cast(uploadInfo._dstResource), uploadInfo._srcBuffer, + uploadInfo._uploadData._dstOffset, uploadInfo._stagingBufferOffset, uploadInfo._uploadData._size); break; case RenderResourceType::Texture: - cmdStream->addJob( - CommandJobType::UploadTexture, - static_cast(uploadInfo._dstResource), - uploadInfo._srcBuffer, uploadInfo._uploadData._dstOffset, - uploadInfo._stagingBufferOffset, uploadInfo._uploadData._size); + cmdStream->addJob(CommandJobType::UploadTexture, static_cast(uploadInfo._dstResource), uploadInfo._srcBuffer, + uploadInfo._uploadData._dstOffset, uploadInfo._stagingBufferOffset, uploadInfo._uploadData._size); break; default: break; diff --git a/Sources/VoxFlow/Core/Resources/ResourceView.cpp b/Sources/VoxFlow/Core/Resources/ResourceView.cpp index 50928e0e..d9705416 100644 --- a/Sources/VoxFlow/Core/Resources/ResourceView.cpp +++ b/Sources/VoxFlow/Core/Resources/ResourceView.cpp @@ -4,12 +4,8 @@ namespace VoxFlow { -ResourceView::ResourceView(std::string&& debugName, - LogicalDevice* logicalDevice, - RenderResource* ownerResource) - : _debugName(debugName), - _logicalDevice(logicalDevice), - _ownerResource(ownerResource) +ResourceView::ResourceView(std::string&& debugName, LogicalDevice* logicalDevice, RenderResource* ownerResource) + : _debugName(debugName), _logicalDevice(logicalDevice), _ownerResource(ownerResource) { } diff --git a/Sources/VoxFlow/Core/Resources/Sampler.cpp b/Sources/VoxFlow/Core/Resources/Sampler.cpp index ae30740f..0f3165b5 100644 --- a/Sources/VoxFlow/Core/Resources/Sampler.cpp +++ b/Sources/VoxFlow/Core/Resources/Sampler.cpp @@ -1,12 +1,11 @@ // Author : snowapril -#include #include +#include namespace VoxFlow { -Sampler::Sampler(std::string_view&& debugName, LogicalDevice* logicalDevice) - : RenderResource(std::move(debugName), logicalDevice, nullptr) +Sampler::Sampler(std::string_view&& debugName, LogicalDevice* logicalDevice) : RenderResource(std::move(debugName), logicalDevice, nullptr) { } @@ -16,7 +15,7 @@ Sampler::~Sampler() } bool Sampler::initialize() -{ +{ // TODO(snowapril) : implement various type of samplers VkSamplerCreateInfo samplerInfo{}; samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; @@ -27,8 +26,7 @@ bool Sampler::initialize() samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.anisotropyEnable = VK_FALSE; - VK_ASSERT(vkCreateSampler(_logicalDevice->get(), &samplerInfo, nullptr, - &_vkSampler)); + VK_ASSERT(vkCreateSampler(_logicalDevice->get(), &samplerInfo, nullptr, &_vkSampler)); #if defined(VK_DEBUG_NAME_ENABLED) DebugUtil::setObjectName(_logicalDevice, _vkSampler, _debugName.c_str()); diff --git a/Sources/VoxFlow/Core/Resources/StagingBuffer.cpp b/Sources/VoxFlow/Core/Resources/StagingBuffer.cpp index 17c83267..f8fade03 100644 --- a/Sources/VoxFlow/Core/Resources/StagingBuffer.cpp +++ b/Sources/VoxFlow/Core/Resources/StagingBuffer.cpp @@ -9,11 +9,8 @@ namespace VoxFlow { -StagingBuffer::StagingBuffer(std::string_view&& debugName, - LogicalDevice* logicalDevice, - RenderResourceMemoryPool* renderResourceMemoryPool) - : RenderResource(std::move(debugName), logicalDevice, - renderResourceMemoryPool) +StagingBuffer::StagingBuffer(std::string_view&& debugName, LogicalDevice* logicalDevice, RenderResourceMemoryPool* renderResourceMemoryPool) + : RenderResource(std::move(debugName), logicalDevice, renderResourceMemoryPool) { } @@ -26,33 +23,25 @@ bool StagingBuffer::makeAllocationResident(const uint32_t size) { _size = size; - VkBufferCreateInfo bufferCreateInfo = { - .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .size = size, - .usage = - VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - .sharingMode = VK_SHARING_MODE_EXCLUSIVE, - .queueFamilyIndexCount = 0, - .pQueueFamilyIndices = nullptr - }; - - VmaAllocationCreateInfo vmaCreateInfo = { - .flags = - VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT, // TODO(snowapril) : - // choose best one - .usage = VMA_MEMORY_USAGE_CPU_TO_GPU, - .requiredFlags = 0, - .preferredFlags = 0, - .memoryTypeBits = 0, - .pool = VK_NULL_HANDLE, - .pUserData = nullptr - }; - - VK_ASSERT(vmaCreateBuffer(_renderResourceMemoryPool->get(), - &bufferCreateInfo, &vmaCreateInfo, &_vkBuffer, - &_allocation, nullptr)); + VkBufferCreateInfo bufferCreateInfo = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .size = size, + .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .queueFamilyIndexCount = 0, + .pQueueFamilyIndices = nullptr }; + + VmaAllocationCreateInfo vmaCreateInfo = { .flags = VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT, // TODO(snowapril) : + // choose best one + .usage = VMA_MEMORY_USAGE_CPU_TO_GPU, + .requiredFlags = 0, + .preferredFlags = 0, + .memoryTypeBits = 0, + .pool = VK_NULL_HANDLE, + .pUserData = nullptr }; + + VK_ASSERT(vmaCreateBuffer(_renderResourceMemoryPool->get(), &bufferCreateInfo, &vmaCreateInfo, &_vkBuffer, &_allocation, nullptr)); if (_vkBuffer == VK_NULL_HANDLE) { @@ -64,13 +53,9 @@ bool StagingBuffer::makeAllocationResident(const uint32_t size) DebugUtil::setObjectName(_logicalDevice, _vkBuffer, _debugName.c_str()); #endif - std::optional defaultViewIndex = createStagingBufferView( - BufferViewInfo{ ._offset = 0, ._range = _size }); + std::optional defaultViewIndex = createStagingBufferView(BufferViewInfo{ ._offset = 0, ._range = _size }); - VOX_ASSERT( - defaultViewIndex.has_value(), - "Failed to create default staging buffer view for staging buffer({})", - _debugName); + VOX_ASSERT(defaultViewIndex.has_value(), "Failed to create default staging buffer view for staging buffer({})", _debugName); if (defaultViewIndex.has_value()) { _defaultView = getView(defaultViewIndex.value()).get(); @@ -93,12 +78,8 @@ void StagingBuffer::release() VkBuffer vkBuffer = _vkBuffer; VmaAllocation vmaAllocation = _allocation; - RenderResourceGarbageCollector::Get().pushRenderResourceGarbage( - RenderResourceGarbage(std::move(_accessedFences), - [vmaAllocator, vkBuffer, vmaAllocation]() { - vmaDestroyBuffer(vmaAllocator, vkBuffer, - vmaAllocation); - })); + RenderResourceGarbageCollector::Get().pushRenderResourceGarbage(RenderResourceGarbage( + std::move(_accessedFences), [vmaAllocator, vkBuffer, vmaAllocation]() { vmaDestroyBuffer(vmaAllocator, vkBuffer, vmaAllocation); })); _vkBuffer = VK_NULL_HANDLE; _allocation = VK_NULL_HANDLE; @@ -109,9 +90,7 @@ std::optional StagingBuffer::createStagingBufferView(const BufferViewI { const uint32_t viewIndex = static_cast(_ownedBufferViews.size()); std::shared_ptr stagingBufferView = - std::make_shared( - fmt::format("{}_View({})", _debugName, viewIndex), _logicalDevice, - this); + std::make_shared(fmt::format("{}_View({})", _debugName, viewIndex), _logicalDevice, this); if (stagingBufferView->initialize(viewInfo) == false) { @@ -127,8 +106,7 @@ uint8_t* StagingBuffer::map() if (_permanentMappedAddress == nullptr) { void* memoryAddress = nullptr; - VK_ASSERT(vmaMapMemory(_renderResourceMemoryPool->get(), _allocation, - &memoryAddress)); + VK_ASSERT(vmaMapMemory(_renderResourceMemoryPool->get(), _allocation, &memoryAddress)); _permanentMappedAddress = memoryAddress; } @@ -140,8 +118,7 @@ void StagingBuffer::unmap() // TODO(snowapril) : consider unmap or not } -StagingBufferView::StagingBufferView(std::string&& debugName, LogicalDevice* logicalDevice, - RenderResource* ownerResource) +StagingBufferView::StagingBufferView(std::string&& debugName, LogicalDevice* logicalDevice, RenderResource* ownerResource) : ResourceView(std::move(debugName), logicalDevice, ownerResource) { } diff --git a/Sources/VoxFlow/Core/Resources/StagingBufferContext.cpp b/Sources/VoxFlow/Core/Resources/StagingBufferContext.cpp index 82bf2abf..fa21d8a3 100644 --- a/Sources/VoxFlow/Core/Resources/StagingBufferContext.cpp +++ b/Sources/VoxFlow/Core/Resources/StagingBufferContext.cpp @@ -2,18 +2,15 @@ #include #include -#include #include +#include namespace VoxFlow { constexpr uint64_t STAGING_BUFFER_DEFAULT_SIZE = 1024U * 1024U; -StagingBufferContext::StagingBufferContext( - LogicalDevice* logicalDevice, - RenderResourceMemoryPool* renderResourceMemoryPool) - : _logicalDevice(logicalDevice), - _renderResourceMemoryPool(renderResourceMemoryPool) +StagingBufferContext::StagingBufferContext(LogicalDevice* logicalDevice, RenderResourceMemoryPool* renderResourceMemoryPool) + : _logicalDevice(logicalDevice), _renderResourceMemoryPool(renderResourceMemoryPool) { } @@ -22,8 +19,7 @@ StagingBufferContext ::~StagingBufferContext() release(); } -std::tuple -StagingBufferContext::getOrCreateStagingBuffer(const uint64_t size) +std::tuple StagingBufferContext::getOrCreateStagingBuffer(const uint64_t size) { StagingBuffer* stagingBuffer = nullptr; uint64_t stagingBufferOffset = UINT32_MAX; @@ -40,20 +36,16 @@ StagingBufferContext::getOrCreateStagingBuffer(const uint64_t size) if (stagingBuffer == nullptr) { - auto stagingBufferPtr = std::make_shared( - "StagingBuffer", _logicalDevice, _renderResourceMemoryPool); + auto stagingBufferPtr = std::make_shared("StagingBuffer", _logicalDevice, _renderResourceMemoryPool); stagingBufferPtr->makeAllocationResident(STAGING_BUFFER_DEFAULT_SIZE); stagingBuffer = stagingBufferPtr.get(); _stagingBufferPools.push_back( - StagingBufferPool{ std::move(stagingBufferPtr), - std::make_unique( - STAGING_BUFFER_DEFAULT_SIZE, false) }); + StagingBufferPool{ std::move(stagingBufferPtr), std::make_unique(STAGING_BUFFER_DEFAULT_SIZE, false) }); - stagingBufferOffset = - _stagingBufferPools.back()._blockAllocator->allocate(size); + stagingBufferOffset = _stagingBufferPools.back()._blockAllocator->allocate(size); } return { stagingBuffer, stagingBufferOffset }; diff --git a/Sources/VoxFlow/Core/Resources/Texture.cpp b/Sources/VoxFlow/Core/Resources/Texture.cpp index 399b30e3..9ff05365 100644 --- a/Sources/VoxFlow/Core/Resources/Texture.cpp +++ b/Sources/VoxFlow/Core/Resources/Texture.cpp @@ -73,12 +73,10 @@ VkImageViewType convertToImageViewType(VkImageType vkImageType, glm::uvec3 exten switch (vkImageType) { case VK_IMAGE_TYPE_1D: - imageViewType = extent.y > 1 ? VK_IMAGE_VIEW_TYPE_1D_ARRAY - : VK_IMAGE_VIEW_TYPE_1D; + imageViewType = extent.y > 1 ? VK_IMAGE_VIEW_TYPE_1D_ARRAY : VK_IMAGE_VIEW_TYPE_1D; break; case VK_IMAGE_TYPE_2D: - imageViewType = extent.z > 1 ? VK_IMAGE_VIEW_TYPE_2D_ARRAY - : VK_IMAGE_VIEW_TYPE_2D; + imageViewType = extent.z > 1 ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D; break; case VK_IMAGE_TYPE_3D: imageViewType = VK_IMAGE_VIEW_TYPE_3D; @@ -120,10 +118,8 @@ bool hasStencilAspect(VkFormat vkFormat) } } -Texture::Texture(std::string_view&& debugName, LogicalDevice* logicalDevice, - RenderResourceMemoryPool* renderResourceMemoryPool) - : RenderResource(std::move(debugName), logicalDevice, - renderResourceMemoryPool) +Texture::Texture(std::string_view&& debugName, LogicalDevice* logicalDevice, RenderResourceMemoryPool* renderResourceMemoryPool) + : RenderResource(std::move(debugName), logicalDevice, renderResourceMemoryPool) { } Texture::~Texture() @@ -135,8 +131,7 @@ bool Texture::makeAllocationResident(const TextureInfo& textureInfo) { release(); - VOX_ASSERT(textureInfo._usage != TextureUsage::Unknown, - "TextureUsage must be specified"); + VOX_ASSERT(textureInfo._usage != TextureUsage::Unknown, "TextureUsage must be specified"); // TODO(snowapril) : sample count, mipLevels, arrayLayers _textureInfo = textureInfo; @@ -146,8 +141,7 @@ bool Texture::makeAllocationResident(const TextureInfo& textureInfo) .flags = 0, .imageType = textureInfo._imageType, .format = textureInfo._format, - .extent = VkExtent3D{ textureInfo._extent.x, textureInfo._extent.y, - textureInfo._extent.z }, + .extent = VkExtent3D{ textureInfo._extent.x, textureInfo._extent.y, textureInfo._extent.z }, .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, @@ -159,21 +153,16 @@ bool Texture::makeAllocationResident(const TextureInfo& textureInfo) .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, }; - VmaAllocationCreateInfo vmaInfo = { - .flags = - VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT, // TODO(snowapril) : - // choose best one - .usage = VMA_MEMORY_USAGE_AUTO, - .requiredFlags = 0, - .preferredFlags = 0, - .memoryTypeBits = 0, - .pool = VK_NULL_HANDLE, - .pUserData = nullptr - }; + VmaAllocationCreateInfo vmaInfo = { .flags = VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT, // TODO(snowapril) : + // choose best one + .usage = VMA_MEMORY_USAGE_AUTO, + .requiredFlags = 0, + .preferredFlags = 0, + .memoryTypeBits = 0, + .pool = VK_NULL_HANDLE, + .pUserData = nullptr }; - VK_ASSERT(vmaCreateImage(_renderResourceMemoryPool->get(), &imageCreateInfo, - &vmaInfo, &_vkImage, &_allocation, - nullptr)); + VK_ASSERT(vmaCreateImage(_renderResourceMemoryPool->get(), &imageCreateInfo, &vmaInfo, &_vkImage, &_allocation, nullptr)); if (_vkImage == VK_NULL_HANDLE) { @@ -188,19 +177,15 @@ bool Texture::makeAllocationResident(const TextureInfo& textureInfo) #endif const std::optional defaultViewIndex = - createTextureView(TextureViewInfo{ - ._viewType = convertToImageViewType(_textureInfo._imageType, - _textureInfo._extent), - ._format = _textureInfo._format, - ._aspectFlags = convertToImageAspectFlags(_textureInfo._format), - ._baseMipLevel = 0, - ._levelCount = 1, - ._baseArrayLayer = 0, - ._layerCount = 1 }); - - VOX_ASSERT(defaultViewIndex.has_value(), - "Failed to create default texture view for texture({})", - _debugName); + createTextureView(TextureViewInfo{ ._viewType = convertToImageViewType(_textureInfo._imageType, _textureInfo._extent), + ._format = _textureInfo._format, + ._aspectFlags = convertToImageAspectFlags(_textureInfo._format), + ._baseMipLevel = 0, + ._levelCount = 1, + ._baseArrayLayer = 0, + ._layerCount = 1 }); + + VOX_ASSERT(defaultViewIndex.has_value(), "Failed to create default texture view for texture({})", _debugName); if (defaultViewIndex.has_value()) { @@ -210,8 +195,7 @@ bool Texture::makeAllocationResident(const TextureInfo& textureInfo) return true; } -bool Texture::initializeFromSwapChain(const TextureInfo& swapChainSurfaceInfo, - VkImage swapChainImage) +bool Texture::initializeFromSwapChain(const TextureInfo& swapChainSurfaceInfo, VkImage swapChainImage) { release(); @@ -225,19 +209,15 @@ bool Texture::initializeFromSwapChain(const TextureInfo& swapChainSurfaceInfo, #endif const std::optional defaultViewIndex = - createTextureView(TextureViewInfo{ - ._viewType = convertToImageViewType(_textureInfo._imageType, - _textureInfo._extent), - ._format = _textureInfo._format, - ._aspectFlags = convertToImageAspectFlags(_textureInfo._format), - ._baseMipLevel = 0, - ._levelCount = 1, - ._baseArrayLayer = 0, - ._layerCount = 1 }); - - VOX_ASSERT(defaultViewIndex.has_value(), - "Failed to create default texture view for texture({})", - _debugName); + createTextureView(TextureViewInfo{ ._viewType = convertToImageViewType(_textureInfo._imageType, _textureInfo._extent), + ._format = _textureInfo._format, + ._aspectFlags = convertToImageAspectFlags(_textureInfo._format), + ._baseMipLevel = 0, + ._levelCount = 1, + ._baseArrayLayer = 0, + ._layerCount = 1 }); + + VOX_ASSERT(defaultViewIndex.has_value(), "Failed to create default texture view for texture({})", _debugName); if (defaultViewIndex.has_value()) { @@ -247,13 +227,10 @@ bool Texture::initializeFromSwapChain(const TextureInfo& swapChainSurfaceInfo, return true; } -std::optional Texture::createTextureView( - const TextureViewInfo& viewInfo) +std::optional Texture::createTextureView(const TextureViewInfo& viewInfo) { const uint32_t viewIndex = static_cast(_ownedTextureViews.size()); - std::shared_ptr textureView = std::make_shared( - fmt::format("{}_View({})", _debugName, viewIndex), _logicalDevice, - this); + std::shared_ptr textureView = std::make_shared(fmt::format("{}_View({})", _debugName, viewIndex), _logicalDevice, this); if (textureView->initialize(_textureInfo, viewInfo) == false) { @@ -272,20 +249,15 @@ void Texture::release() VmaAllocator vmaAllocator = _renderResourceMemoryPool->get(); VkImage vkImage = _vkImage; VmaAllocation vmaAllocation = _allocation; - RenderResourceGarbageCollector::Get().pushRenderResourceGarbage( - RenderResourceGarbage(std::move(_accessedFences), - [vmaAllocator, vkImage, vmaAllocation]() { - vmaDestroyImage(vmaAllocator, vkImage, - vmaAllocation); - })); + RenderResourceGarbageCollector::Get().pushRenderResourceGarbage(RenderResourceGarbage( + std::move(_accessedFences), [vmaAllocator, vkImage, vmaAllocation]() { vmaDestroyImage(vmaAllocator, vkImage, vmaAllocation); })); _vkImage = VK_NULL_HANDLE; _allocation = VK_NULL_HANDLE; } } -TextureView::TextureView(std::string&& debugName, LogicalDevice* logicalDevice, - RenderResource* ownerResource) +TextureView::TextureView(std::string&& debugName, LogicalDevice* logicalDevice, RenderResource* ownerResource) : ResourceView(std::move(debugName), logicalDevice, ownerResource) { } @@ -295,30 +267,25 @@ TextureView::~TextureView() release(); } -bool TextureView::initialize(const TextureInfo& ownerTextureInfo, - const TextureViewInfo& viewInfo) +bool TextureView::initialize(const TextureInfo& ownerTextureInfo, const TextureViewInfo& viewInfo) { _ownerTextureInfo = ownerTextureInfo; _textureViewInfo = viewInfo; - VkImageViewCreateInfo viewCreateInfo = { - .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .image = static_cast(_ownerResource)->get(), - .viewType = VK_IMAGE_VIEW_TYPE_2D, - .format = viewInfo._format, - .components = { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, - VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A }, - .subresourceRange = { .aspectMask = viewInfo._aspectFlags, - .baseMipLevel = viewInfo._baseMipLevel, - .levelCount = viewInfo._levelCount, - .baseArrayLayer = viewInfo._baseArrayLayer, - .layerCount = viewInfo._layerCount } - }; - - VK_ASSERT(vkCreateImageView(_logicalDevice->get(), &viewCreateInfo, nullptr, - &_vkImageView)); + VkImageViewCreateInfo viewCreateInfo = { .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .image = static_cast(_ownerResource)->get(), + .viewType = VK_IMAGE_VIEW_TYPE_2D, + .format = viewInfo._format, + .components = { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A }, + .subresourceRange = { .aspectMask = viewInfo._aspectFlags, + .baseMipLevel = viewInfo._baseMipLevel, + .levelCount = viewInfo._levelCount, + .baseArrayLayer = viewInfo._baseArrayLayer, + .layerCount = viewInfo._layerCount } }; + + VK_ASSERT(vkCreateImageView(_logicalDevice->get(), &viewCreateInfo, nullptr, &_vkImageView)); if (_vkImageView == VK_NULL_HANDLE) { @@ -340,10 +307,7 @@ void TextureView::release() VkDevice vkDevice = _logicalDevice->get(); VkImageView vkImageView = _vkImageView; RenderResourceGarbageCollector::Get().pushRenderResourceGarbage( - RenderResourceGarbage( - std::move(_accessedFences), [vkDevice, vkImageView]() { - vkDestroyImageView(vkDevice, vkImageView, nullptr); - })); + RenderResourceGarbage(std::move(_accessedFences), [vkDevice, vkImageView]() { vkDestroyImageView(vkDevice, vkImageView, nullptr); })); _vkImageView = VK_NULL_HANDLE; } diff --git a/Sources/VoxFlow/Core/Utils/ChromeTracer.cpp b/Sources/VoxFlow/Core/Utils/ChromeTracer.cpp index 29c5bc4b..c9741fd9 100644 --- a/Sources/VoxFlow/Core/Utils/ChromeTracer.cpp +++ b/Sources/VoxFlow/Core/Utils/ChromeTracer.cpp @@ -34,12 +34,8 @@ void ChromeTracer::endTrace(const char* traceFilePath) for (const EventDescriptor& desc : tmpEventDescriptors) { const char* eventTypeString = nullptr; - auto timePoint = - std::chrono::time_point_cast( - desc._timeStamp); - auto timeStamp = std::chrono::duration_cast( - timePoint.time_since_epoch()) - .count(); + auto timePoint = std::chrono::time_point_cast(desc._timeStamp); + auto timeStamp = std::chrono::duration_cast(timePoint.time_since_epoch()).count(); switch (desc._eventType) { @@ -59,10 +55,7 @@ void ChromeTracer::endTrace(const char* traceFilePath) oss << desc._threadId; uint32_t threadId = std::stoi(oss.str()); - events.push_back(nlohmann::json({ { "name", desc._name }, - { "ph", eventTypeString }, - { "ts", timeStamp }, - { "tid", threadId } })); + events.push_back(nlohmann::json({ { "name", desc._name }, { "ph", eventTypeString }, { "ts", timeStamp }, { "tid", threadId } })); } _json["traceEvents"] = events; @@ -78,8 +71,7 @@ void ChromeTracer::endTrace(const char* traceFilePath) _json.clear(); } -ChromeTracer::ScopedChromeTracing ChromeTracer::createScopedTracingHandle( - const char* eventName) +ChromeTracer::ScopedChromeTracing ChromeTracer::createScopedTracingHandle(const char* eventName) { return ChromeTracer::ScopedChromeTracing(this, eventName); } @@ -90,15 +82,11 @@ void ChromeTracer::addTraceEvent(EventType eventType, const char* eventName) { std::lock_guard scopeLock(_mutex); _eventDescriptors.push_back( - { ._name = eventName, - ._eventType = eventType, - ._timeStamp = std::chrono::system_clock::now(), - ._threadId = std::this_thread::get_id() }); + { ._name = eventName, ._eventType = eventType, ._timeStamp = std::chrono::system_clock::now(), ._threadId = std::this_thread::get_id() }); } } -ChromeTracer::ScopedChromeTracing::ScopedChromeTracing( - ChromeTracer* ownerTracer, const char* eventName) +ChromeTracer::ScopedChromeTracing::ScopedChromeTracing(ChromeTracer* ownerTracer, const char* eventName) : _ownerTracer(ownerTracer), _eventName(std::move(eventName)) { _ownerTracer->addTraceEvent(EventType::DurationBegin, _eventName); diff --git a/Sources/VoxFlow/Core/Utils/DebugUtil.cpp b/Sources/VoxFlow/Core/Utils/DebugUtil.cpp index 9beea4e9..51bb296c 100644 --- a/Sources/VoxFlow/Core/Utils/DebugUtil.cpp +++ b/Sources/VoxFlow/Core/Utils/DebugUtil.cpp @@ -7,10 +7,8 @@ namespace VoxFlow { uint64_t DebugUtil::NumValidationErrorDetected = 0; -VKAPI_ATTR VkBool32 VKAPI_CALL DebugUtil::DebugCallback( - VkDebugUtilsMessageSeverityFlagBitsEXT severity, - VkDebugUtilsMessageTypeFlagsEXT flags, - const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* userData) +VKAPI_ATTR VkBool32 VKAPI_CALL DebugUtil::DebugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT severity, VkDebugUtilsMessageTypeFlagsEXT flags, + const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* userData) { (void)flags; (void)userData; @@ -30,8 +28,7 @@ VKAPI_ATTR VkBool32 VKAPI_CALL DebugUtil::DebugCallback( spdlog::error("[Vulkan Validation] {}", pCallbackData->pMessage); break; default: - assert(severity < - VK_DEBUG_UTILS_MESSAGE_SEVERITY_FLAG_BITS_MAX_ENUM_EXT); + assert(severity < VK_DEBUG_UTILS_MESSAGE_SEVERITY_FLAG_BITS_MAX_ENUM_EXT); break; } @@ -57,21 +54,15 @@ void DebugUtil::DebugBreak() } #if defined(VK_DEBUG_NAME_ENABLED) -void DebugUtil::setObjectName(LogicalDevice* logicalDevice, uint64_t object, - const char* name, - VkObjectType type) +void DebugUtil::setObjectName(LogicalDevice* logicalDevice, uint64_t object, const char* name, VkObjectType type) { // static PFN_vkSetDebugUtilsObjectNameEXT setObjectName = const VkDebugUtilsObjectNameInfoEXT nameInfo = { - .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT, - .pNext = nullptr, - .objectType = type, - .objectHandle = object, - .pObjectName = name + .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT, .pNext = nullptr, .objectType = type, .objectHandle = object, .pObjectName = name }; vkSetDebugUtilsObjectNameEXT(logicalDevice->get(), &nameInfo); } -#endif +#endif DeviceRemoveTracker* DeviceRemoveTracker::get() { diff --git a/Sources/VoxFlow/Core/Utils/DecisionMaker.cpp b/Sources/VoxFlow/Core/Utils/DecisionMaker.cpp index 4f63c1c5..5c82a60e 100644 --- a/Sources/VoxFlow/Core/Utils/DecisionMaker.cpp +++ b/Sources/VoxFlow/Core/Utils/DecisionMaker.cpp @@ -5,45 +5,33 @@ namespace VoxFlow { -VkResult DecisionMaker::pickLayers( - std::vector& used, - const std::vector& properties, - const std::vector& requested) +VkResult DecisionMaker::pickLayers(std::vector& used, const std::vector& properties, + const std::vector& requested) { for (const auto& entry : requested) { - if (auto ranges = std::find_if(properties.begin(), properties.end(), - [&entry](const VkLayerProperties& p) { - return strcmp(entry.entryName, - p.layerName) == 0; - }); + if (auto ranges = + std::find_if(properties.begin(), properties.end(), [&entry](const VkLayerProperties& p) { return strcmp(entry.entryName, p.layerName) == 0; }); ranges != properties.end()) { used.emplace_back(entry.entryName); } else if (entry.isOptional == false) { - spdlog::error("Requested Vulkan Layer {} not found.", - entry.entryName); + spdlog::error("Requested Vulkan Layer {} not found.", entry.entryName); return VK_ERROR_LAYER_NOT_PRESENT; } } return VK_SUCCESS; } -VkResult DecisionMaker::pickExtensions( - std::vector& used, - const std::vector& properties, - const std::vector& requested, - std::vector& featureStructs) +VkResult DecisionMaker::pickExtensions(std::vector& used, const std::vector& properties, + const std::vector& requested, std::vector& featureStructs) { for (const auto& entry : requested) { - if (auto ranges = std::find_if( - properties.begin(), properties.end(), - [&entry](const VkExtensionProperties& p) { - return strcmp(entry.entryName, p.extensionName) == 0; - }); + if (auto ranges = std::find_if(properties.begin(), properties.end(), + [&entry](const VkExtensionProperties& p) { return strcmp(entry.entryName, p.extensionName) == 0; }); ranges != properties.end()) { used.emplace_back(entry.entryName); @@ -54,8 +42,7 @@ VkResult DecisionMaker::pickExtensions( } else if (entry.isOptional == false) { - spdlog::error("Requested Vulkan Extension '{}' not found.", - entry.entryName); + spdlog::error("Requested Vulkan Extension '{}' not found.", entry.entryName); return VK_ERROR_EXTENSION_NOT_PRESENT; } } diff --git a/Sources/VoxFlow/Core/Utils/DeviceInputSubscriber.cpp b/Sources/VoxFlow/Core/Utils/DeviceInputSubscriber.cpp index e1ab1a57..e67c3d36 100644 --- a/Sources/VoxFlow/Core/Utils/DeviceInputSubscriber.cpp +++ b/Sources/VoxFlow/Core/Utils/DeviceInputSubscriber.cpp @@ -1,9 +1,9 @@ // Author : snowapril +#include #include #include #include -#include namespace { @@ -11,8 +11,7 @@ std::vector gGlfwWindows; VoxFlow::DeviceInputSubscriber* gDeviceInputRegistrator = nullptr; } // namespace -void deviceKeyInputCallback(GLFWwindow* window, int key, int scancode, - int action, int mod) +void deviceKeyInputCallback(GLFWwindow* window, int key, int scancode, int action, int mod) { using namespace VoxFlow; @@ -46,11 +45,9 @@ void deviceKeyInputCallback(GLFWwindow* window, int key, int scancode, if (gDeviceInputRegistrator != nullptr) { const auto iter = std::find(gGlfwWindows.begin(), gGlfwWindows.end(), window); - VOX_ASSERT(iter != gGlfwWindows.end(), - "Iternal logic error releated to device input registrator"); + VOX_ASSERT(iter != gGlfwWindows.end(), "Iternal logic error releated to device input registrator"); - const auto windowIndex = - static_cast(std::distance(gGlfwWindows.begin(), iter)); + const auto windowIndex = static_cast(std::distance(gGlfwWindows.begin(), iter)); gDeviceInputRegistrator->broadcastKeyInput(windowIndex, keyInputType, isReleased); } @@ -79,8 +76,7 @@ void DeviceInputSubscriber::addObserveTargetWindow(GLFWwindow* window) void DeviceInputSubscriber::removeObserveTargetWindow(GLFWwindow* window) { - auto iter = std::find(gGlfwWindows.begin(), gGlfwWindows.end(), - window); + auto iter = std::find(gGlfwWindows.begin(), gGlfwWindows.end(), window); if (iter != gGlfwWindows.end()) { @@ -88,20 +84,16 @@ void DeviceInputSubscriber::removeObserveTargetWindow(GLFWwindow* window) } else { - VOX_ASSERT(false, "This GLFWwindow({}) has never been registered", - fmt::ptr(window)); + VOX_ASSERT(false, "This GLFWwindow({}) has never been registered", fmt::ptr(window)); } } -void DeviceInputSubscriber::registerDeviceKeyCallback( - const uint32_t swapChainBits, DeviceKeyInputCallback&& callback) +void DeviceInputSubscriber::registerDeviceKeyCallback(const uint32_t swapChainBits, DeviceKeyInputCallback&& callback) { _deviceKeyInputCallbacks.emplace_back(swapChainBits, std::move(callback)); } -void DeviceInputSubscriber::broadcastKeyInput(uint32_t windowIndex, - DeviceKeyInputType key, - bool isReleased) +void DeviceInputSubscriber::broadcastKeyInput(uint32_t windowIndex, DeviceKeyInputType key, bool isReleased) { for (const auto& callback : _deviceKeyInputCallbacks) { diff --git a/Sources/VoxFlow/Core/Utils/MemoryAllocator.cpp b/Sources/VoxFlow/Core/Utils/MemoryAllocator.cpp index ae07a8fb..12aa1d91 100644 --- a/Sources/VoxFlow/Core/Utils/MemoryAllocator.cpp +++ b/Sources/VoxFlow/Core/Utils/MemoryAllocator.cpp @@ -6,8 +6,7 @@ namespace VoxFlow { -BlockAllocator::BlockAllocator(const bool isThreadSafe) - : _isThreadSafe(isThreadSafe) +BlockAllocator::BlockAllocator(const bool isThreadSafe) : _isThreadSafe(isThreadSafe) { } @@ -65,12 +64,10 @@ void BlockAllocator::defragment() } } -LinearBlockAllocator::LinearBlockAllocator(const uint64_t totalSize, - const bool isThreadSafe) - : BlockAllocator(isThreadSafe), _totalSize(totalSize) +LinearBlockAllocator::LinearBlockAllocator(const uint64_t totalSize, const bool isThreadSafe) : BlockAllocator(isThreadSafe), _totalSize(totalSize) { _blockList.push_back({ ._offset = 0, ._size = _totalSize }); -} +} LinearBlockAllocator::~LinearBlockAllocator() { @@ -88,7 +85,7 @@ uint64_t LinearBlockAllocator::allocateInner(const uint64_t size) offset = blockInfo._offset; iter = _blockList.erase(iter); } - else + else { if (blockInfo._size > size) { @@ -102,8 +99,7 @@ uint64_t LinearBlockAllocator::allocateInner(const uint64_t size) return offset; } -void LinearBlockAllocator::deallocateInner(const uint64_t offset, - const uint64_t size) +void LinearBlockAllocator::deallocateInner(const uint64_t offset, const uint64_t size) { (void)offset; (void)size; @@ -114,9 +110,7 @@ void LinearBlockAllocator::defragmentInner() // TODO(snowapril) } -LinearMemoryAllocator::LinearMemoryAllocator(const uint64_t totalSize, - const bool isThreadSafe) - : _linearBlockAllocator(totalSize, isThreadSafe) +LinearMemoryAllocator::LinearMemoryAllocator(const uint64_t totalSize, const bool isThreadSafe) : _linearBlockAllocator(totalSize, isThreadSafe) { _dataAddress = malloc(totalSize); } @@ -142,18 +136,15 @@ uint8_t* LinearMemoryAllocator::allocate(const uint64_t size) void LinearMemoryAllocator::deallocate(void* data, const uint64_t size) { - const bool isInThisAllocator = - (static_cast(_dataAddress) <= static_cast(data)) && - (static_cast(_dataAddress) < - (static_cast(_dataAddress) + size)); + const bool isInThisAllocator = (static_cast(_dataAddress) <= static_cast(data)) && + (static_cast(_dataAddress) < (static_cast(_dataAddress) + size)); if (isInThisAllocator) { VOX_ASSERT(false, "Unknown memory block was given"); } else { - const uint64_t offset = static_cast( - static_cast(data) - static_cast(_dataAddress)); + const uint64_t offset = static_cast(static_cast(data) - static_cast(_dataAddress)); _linearBlockAllocator.deallocate(offset, size); } } diff --git a/Sources/VoxFlow/Core/Utils/Thread.cpp b/Sources/VoxFlow/Core/Utils/Thread.cpp index a2001ff5..75b56b23 100644 --- a/Sources/VoxFlow/Core/Utils/Thread.cpp +++ b/Sources/VoxFlow/Core/Utils/Thread.cpp @@ -19,8 +19,7 @@ void Thread::SetThreadName(const char* threadName) wchar_t threadNameWide[128]; std::mbstowcs(threadNameWide, threadName, std::strlen(threadName) + 1); HRESULT hr = SetThreadDescription(GetCurrentThread(), threadNameWide); - VOX_ASSERT(SUCCEEDED(hr), "Failed to initialize thread name {}", - threadName); + VOX_ASSERT(SUCCEEDED(hr), "Failed to initialize thread name {}", threadName); #else (void)threadName; // TODO(snowapril) #endif diff --git a/Sources/VoxFlow/Editor/RenderPass/PostProcessPass.cpp b/Sources/VoxFlow/Editor/RenderPass/PostProcessPass.cpp index 7af985ea..bbcea5a5 100644 --- a/Sources/VoxFlow/Editor/RenderPass/PostProcessPass.cpp +++ b/Sources/VoxFlow/Editor/RenderPass/PostProcessPass.cpp @@ -1,23 +1,22 @@ // Author : snowapril -#include #include -#include +#include #include #include -#include +#include #include +#include #include -#include #include +#include #include #include namespace VoxFlow { -PostProcessPass::PostProcessPass(LogicalDevice* logicalDevice) - : _logicalDevice(logicalDevice) +PostProcessPass::PostProcessPass(LogicalDevice* logicalDevice) : _logicalDevice(logicalDevice) { } @@ -27,15 +26,12 @@ PostProcessPass::~PostProcessPass() bool PostProcessPass::initialize() { - _toneMapPipeline = - _logicalDevice->getPipelineStreamingContext()->createGraphicsPipeline( - { "tonemap.vert", "tonemap.frag" }); + _toneMapPipeline = _logicalDevice->getPipelineStreamingContext()->createGraphicsPipeline({ "tonemap.vert", "tonemap.frag" }); // Set pipeline state for ToneMap PostProcess pipeline GraphicsPipelineState pipelineState; - pipelineState.blendState.addBlendState().setColorWriteMask( - VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | - VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT); + pipelineState.blendState.addBlendState().setColorWriteMask(VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | + VK_COLOR_COMPONENT_A_BIT); pipelineState.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; _toneMapPipeline->setPipelineState(pipelineState); @@ -55,65 +51,40 @@ void PostProcessPass::renderScene(RenderGraph::FrameGraph* frameGraph) _passData = frameGraph->addCallbackPass( "PostProcessPass", - [&](FrameGraphBuilder& builder, - PostProcessPassData& passData) { - ResourceHandle backBufferHandle = - blackBoard.getHandle("BackBuffer"); + [&](FrameGraphBuilder& builder, PostProcessPassData& passData) { + ResourceHandle backBufferHandle = blackBoard.getHandle("BackBuffer"); - ResourceHandle sceneColorHandle = - blackBoard.getHandle("SceneColor"); + ResourceHandle sceneColorHandle = blackBoard.getHandle("SceneColor"); - const auto& sceneColorDesc = - frameGraph - ->getResourceDescriptor( - sceneColorHandle); + const auto& sceneColorDesc = frameGraph->getResourceDescriptor(sceneColorHandle); builder.read(sceneColorHandle, TextureUsage::Sampled); builder.write(backBufferHandle, TextureUsage::BackBuffer); - auto descriptor = FrameGraphRenderPass::Descriptor{ - ._viewportSize = - glm::uvec2(sceneColorDesc._width, sceneColorDesc._height), - ._writableAttachment = AttachmentMaskFlags::Color0, - ._numSamples = 1 - }; + auto descriptor = FrameGraphRenderPass::Descriptor{ ._viewportSize = glm::uvec2(sceneColorDesc._width, sceneColorDesc._height), + ._writableAttachment = AttachmentMaskFlags::Color0, + ._numSamples = 1 }; descriptor._attachments[0] = backBufferHandle; - passData._renderPassID = builder.declareRenderPass( - "PostProcess RenderPass", std::move(descriptor)); + passData._renderPassID = builder.declareRenderPass("PostProcess RenderPass", std::move(descriptor)); }, - [&](const FrameGraphResources* fgResources, - PostProcessPassData& passData, CommandStream* cmdStream) { - RenderPassData* rpData = - fgResources->getRenderPassData(passData._renderPassID); - - cmdStream->addJob(CommandJobType::BeginRenderPass, - rpData->_attachmentGroup, rpData->_passParams); - - cmdStream->addJob(CommandJobType::BindPipeline, - _toneMapPipeline.get()); - - ResourceHandle sceneColorHandle = - blackBoard.getHandle("SceneColor"); - TextureView* sceneColorView = - fgResources->getTextureView(sceneColorHandle); - - cmdStream->addJob( - CommandJobType::BindResourceGroup, - SetSlotCategory::PerRenderPass, - std::vector{ ShaderVariableBinding{ - ._variableName = "g_sceneColor", - ._view = sceneColorView, - ._usage = ResourceAccessMask::ShaderReadOnly } }); - - const auto& sceneColorDesc = - fgResources - ->getResourceDescriptor( - sceneColorHandle); - - cmdStream->addJob( - CommandJobType::SetViewport, - glm::uvec2(sceneColorDesc._width, sceneColorDesc._height)); + [&](const FrameGraphResources* fgResources, PostProcessPassData& passData, CommandStream* cmdStream) { + RenderPassData* rpData = fgResources->getRenderPassData(passData._renderPassID); + + cmdStream->addJob(CommandJobType::BeginRenderPass, rpData->_attachmentGroup, rpData->_passParams); + + cmdStream->addJob(CommandJobType::BindPipeline, _toneMapPipeline.get()); + + ResourceHandle sceneColorHandle = blackBoard.getHandle("SceneColor"); + TextureView* sceneColorView = fgResources->getTextureView(sceneColorHandle); + + cmdStream->addJob(CommandJobType::BindResourceGroup, SetSlotCategory::PerRenderPass, + std::vector{ ShaderVariableBinding{ + ._variableName = "g_sceneColor", ._view = sceneColorView, ._usage = ResourceAccessMask::ShaderReadOnly } }); + + const auto& sceneColorDesc = fgResources->getResourceDescriptor(sceneColorHandle); + + cmdStream->addJob(CommandJobType::SetViewport, glm::uvec2(sceneColorDesc._width, sceneColorDesc._height)); cmdStream->addJob(CommandJobType::Draw, 4, 1, 0, 0); diff --git a/Sources/VoxFlow/Editor/RenderPass/SceneObjectPass.cpp b/Sources/VoxFlow/Editor/RenderPass/SceneObjectPass.cpp index 86c53c97..93521275 100644 --- a/Sources/VoxFlow/Editor/RenderPass/SceneObjectPass.cpp +++ b/Sources/VoxFlow/Editor/RenderPass/SceneObjectPass.cpp @@ -1,7 +1,7 @@ // Author : snowapril -#include #include +#include #include #include #include @@ -13,8 +13,7 @@ namespace VoxFlow { -SceneObjectPass::SceneObjectPass(LogicalDevice* logicalDevice) - : _logicalDevice(logicalDevice) +SceneObjectPass::SceneObjectPass(LogicalDevice* logicalDevice) : _logicalDevice(logicalDevice) { } @@ -23,9 +22,8 @@ SceneObjectPass::~SceneObjectPass() } const std::vector cubeVertices = { - { -0.5f, -0.5f, 0.5f }, { 0.5f, -0.5f, 0.5f }, { -0.5f, 0.5f, 0.5f }, - { 0.5f, 0.5f, 0.5f }, { -0.5f, -0.5f, -0.5f }, { 0.5f, -0.5f, -0.5f }, - { -0.5f, 0.5f, -0.5f }, { 0.5f, 0.5f, -0.5f }, + { -0.5f, -0.5f, 0.5f }, { 0.5f, -0.5f, 0.5f }, { -0.5f, 0.5f, 0.5f }, { 0.5f, 0.5f, 0.5f }, + { -0.5f, -0.5f, -0.5f }, { 0.5f, -0.5f, -0.5f }, { -0.5f, 0.5f, -0.5f }, { 0.5f, 0.5f, -0.5f }, }; const std::vector cubeIndices = { @@ -39,54 +37,35 @@ const std::vector cubeIndices = { bool SceneObjectPass::initialize() { - _sceneObjectPipeline = - _logicalDevice->getPipelineStreamingContext()->createGraphicsPipeline( - { "scene_object.vert", "scene_object.frag" }); + _sceneObjectPipeline = _logicalDevice->getPipelineStreamingContext()->createGraphicsPipeline({ "scene_object.vert", "scene_object.frag" }); // Set pipeline state for SceneObjectPass pipeline GraphicsPipelineState pipelineState; - pipelineState - .blendState.addBlendState() - .setColorWriteMask(VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | - VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT); + pipelineState.blendState.addBlendState().setColorWriteMask(VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | + VK_COLOR_COMPONENT_A_BIT); pipelineState.inputLayout.addInputLayout( - VertexInputLayout{ ._location = 0, - ._binding = 0, - ._stride = sizeof(glm::vec3), - ._baseType = VertexFormatBaseType::Float32 }); + VertexInputLayout{ ._location = 0, ._binding = 0, ._stride = sizeof(glm::vec3), ._baseType = VertexFormatBaseType::Float32 }); pipelineState.depthStencil.setDepth(true, VK_COMPARE_OP_LESS_OR_EQUAL); _sceneObjectPipeline->setPipelineState(pipelineState); - _cubeVertexBuffer = std::make_unique( - "CubeVertexBuffer", _logicalDevice, - _logicalDevice->getDeviceDefaultResourceMemoryPool()); - _cubeVertexBuffer->makeAllocationResident(BufferInfo{ - ._size = cubeVertices.size() * sizeof(glm::vec3), - ._usage = BufferUsage::VertexBuffer | BufferUsage::CopyDst }); + _cubeVertexBuffer = std::make_unique("CubeVertexBuffer", _logicalDevice, _logicalDevice->getDeviceDefaultResourceMemoryPool()); + _cubeVertexBuffer->makeAllocationResident( + BufferInfo{ ._size = cubeVertices.size() * sizeof(glm::vec3), ._usage = BufferUsage::VertexBuffer | BufferUsage::CopyDst }); - _cubeIndexBuffer = std::make_unique( - "CubeIndexBuffer", _logicalDevice, - _logicalDevice->getDeviceDefaultResourceMemoryPool()); - _cubeIndexBuffer->makeAllocationResident(BufferInfo{ - ._size = cubeIndices.size() * sizeof(uint32_t), - ._usage = BufferUsage::IndexBuffer | BufferUsage::CopyDst }); + _cubeIndexBuffer = std::make_unique("CubeIndexBuffer", _logicalDevice, _logicalDevice->getDeviceDefaultResourceMemoryPool()); + _cubeIndexBuffer->makeAllocationResident( + BufferInfo{ ._size = cubeIndices.size() * sizeof(uint32_t), ._usage = BufferUsage::IndexBuffer | BufferUsage::CopyDst }); return true; } void SceneObjectPass::updateRender(ResourceUploadContext* uploadContext) { - uploadContext->addPendingUpload( - UploadPhase::Immediate, _cubeVertexBuffer.get(), - UploadData{ ._data = &cubeVertices[0].x, - ._size = cubeVertices.size() * sizeof(glm::vec3), - ._dstOffset = 0 }); - - uploadContext->addPendingUpload( - UploadPhase::Immediate, _cubeIndexBuffer.get(), - UploadData{ ._data = &cubeIndices[0], - ._size = cubeIndices.size() * sizeof(uint32_t), - ._dstOffset = 0 }); + uploadContext->addPendingUpload(UploadPhase::Immediate, _cubeVertexBuffer.get(), + UploadData{ ._data = &cubeVertices[0].x, ._size = cubeVertices.size() * sizeof(glm::vec3), ._dstOffset = 0 }); + + uploadContext->addPendingUpload(UploadPhase::Immediate, _cubeIndexBuffer.get(), + UploadData{ ._data = &cubeIndices[0], ._size = cubeIndices.size() * sizeof(uint32_t), ._dstOffset = 0 }); } void SceneObjectPass::renderScene(RenderGraph::FrameGraph* frameGraph) @@ -94,86 +73,59 @@ void SceneObjectPass::renderScene(RenderGraph::FrameGraph* frameGraph) using namespace RenderGraph; BlackBoard& blackBoard = frameGraph->getBlackBoard(); - ResourceHandle backBufferHandle = - blackBoard.getHandle("BackBuffer"); + ResourceHandle backBufferHandle = blackBoard.getHandle("BackBuffer"); - const auto& backBufferDesc = - frameGraph->getResourceDescriptor( - backBufferHandle); + const auto& backBufferDesc = frameGraph->getResourceDescriptor(backBufferHandle); _passData = frameGraph->addCallbackPass( "SceneObjectPass", - [&](FrameGraphBuilder& builder, - SceneObjectPassData& passData) { + [&](FrameGraphBuilder& builder, SceneObjectPassData& passData) { passData._sceneColorHandle = - builder.allocate( - "SceneColor", - FrameGraphTexture::Descriptor{ - ._width = backBufferDesc._width, - ._height = backBufferDesc._height, - ._depth = backBufferDesc._depth, - ._level = backBufferDesc._level, - ._sampleCounts = backBufferDesc._sampleCounts, - ._format = backBufferDesc._format }); + builder.allocate("SceneColor", FrameGraphTexture::Descriptor{ ._width = backBufferDesc._width, + ._height = backBufferDesc._height, + ._depth = backBufferDesc._depth, + ._level = backBufferDesc._level, + ._sampleCounts = backBufferDesc._sampleCounts, + ._format = backBufferDesc._format }); passData._sceneDepthHandle = - builder.allocate( - "SceneDepth", FrameGraphTexture::Descriptor{ - ._width = backBufferDesc._width, - ._height = backBufferDesc._height, - ._depth = 1, - ._level = backBufferDesc._level, - ._sampleCounts = 1, - ._format = VK_FORMAT_D32_SFLOAT_S8_UINT }); + builder.allocate("SceneDepth", FrameGraphTexture::Descriptor{ ._width = backBufferDesc._width, + ._height = backBufferDesc._height, + ._depth = 1, + ._level = backBufferDesc._level, + ._sampleCounts = 1, + ._format = VK_FORMAT_D32_SFLOAT_S8_UINT }); builder.write(passData._sceneColorHandle, TextureUsage::RenderTarget); builder.write(passData._sceneDepthHandle, TextureUsage::DepthStencil); - auto descriptor = FrameGraphRenderPass::Descriptor{ - ._viewportSize = - glm::uvec2(backBufferDesc._width, backBufferDesc._height), - ._writableAttachment = - AttachmentMaskFlags::Color0 | AttachmentMaskFlags::DepthStencil, - ._numSamples = 1 - }; + auto descriptor = FrameGraphRenderPass::Descriptor{ ._viewportSize = glm::uvec2(backBufferDesc._width, backBufferDesc._height), + ._writableAttachment = AttachmentMaskFlags::Color0 | AttachmentMaskFlags::DepthStencil, + ._numSamples = 1 }; descriptor._attachments[0] = passData._sceneColorHandle; - descriptor._attachments[MAX_RENDER_TARGET_COUNTS] = - passData._sceneDepthHandle; - descriptor._clearFlags = - AttachmentMaskFlags::Color0 | AttachmentMaskFlags::DepthStencil; + descriptor._attachments[MAX_RENDER_TARGET_COUNTS] = passData._sceneDepthHandle; + descriptor._clearFlags = AttachmentMaskFlags::Color0 | AttachmentMaskFlags::DepthStencil; descriptor._clearColors[0] = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f); descriptor._clearDepth = 1.0f; - passData._renderPassID = builder.declareRenderPass( - "SceneObjectPass RenderPass", std::move(descriptor)); + passData._renderPassID = builder.declareRenderPass("SceneObjectPass RenderPass", std::move(descriptor)); blackBoard["SceneColor"] = passData._sceneColorHandle; blackBoard["SceneDepth"] = passData._sceneDepthHandle; }, - [&](const FrameGraphResources* fgResources, - SceneObjectPassData& passData, CommandStream* cmdStream) { - RenderPassData* rpData = - fgResources->getRenderPassData(passData._renderPassID); - - cmdStream->addJob(CommandJobType::BeginRenderPass, - rpData->_attachmentGroup, rpData->_passParams); - cmdStream->addJob(CommandJobType::BindPipeline, - _sceneObjectPipeline.get()); - - cmdStream->addJob(CommandJobType::BindVertexBuffer, - _cubeVertexBuffer); - - cmdStream->addJob(CommandJobType::BindIndexBuffer, - _cubeIndexBuffer); - - const auto& sceneColorDesc = - fgResources - ->getResourceDescriptor( - passData._sceneColorHandle); - - cmdStream->addJob( - CommandJobType::SetViewport, - glm::uvec2(sceneColorDesc._width, sceneColorDesc._height)); + [&](const FrameGraphResources* fgResources, SceneObjectPassData& passData, CommandStream* cmdStream) { + RenderPassData* rpData = fgResources->getRenderPassData(passData._renderPassID); + + cmdStream->addJob(CommandJobType::BeginRenderPass, rpData->_attachmentGroup, rpData->_passParams); + cmdStream->addJob(CommandJobType::BindPipeline, _sceneObjectPipeline.get()); + + cmdStream->addJob(CommandJobType::BindVertexBuffer, _cubeVertexBuffer); + + cmdStream->addJob(CommandJobType::BindIndexBuffer, _cubeIndexBuffer); + + const auto& sceneColorDesc = fgResources->getResourceDescriptor(passData._sceneColorHandle); + + cmdStream->addJob(CommandJobType::SetViewport, glm::uvec2(sceneColorDesc._width, sceneColorDesc._height)); cmdStream->addJob(CommandJobType::DrawIndexed, 36, 1, 0, 0, 0); diff --git a/Sources/VoxFlow/Editor/VoxEditor.cpp b/Sources/VoxFlow/Editor/VoxEditor.cpp index 59fa4880..fce39a0f 100644 --- a/Sources/VoxFlow/Editor/VoxEditor.cpp +++ b/Sources/VoxFlow/Editor/VoxEditor.cpp @@ -1,15 +1,15 @@ // Author : snowapril -#include -#include -#include -#include +#include +#include #include #include -#include #include #include -#include +#include +#include +#include +#include namespace VoxFlow { @@ -20,8 +20,7 @@ VoxEditor::VoxEditor(cxxopts::ParseResult&& arguments) { const char* glfwErrorMsg = nullptr; glfwGetError(&glfwErrorMsg); - VOX_ASSERT(false, "Failed to initialize GLWF. LastError : {}", - glfwErrorMsg); + VOX_ASSERT(false, "Failed to initialize GLWF. LastError : {}", glfwErrorMsg); return; } @@ -57,24 +56,17 @@ VoxEditor::VoxEditor(cxxopts::ParseResult&& arguments) _renderDevice = new RenderDevice(context); - LogicalDevice* mainLogicalDevice = - _renderDevice->getLogicalDevice(LogicalDeviceType::MainDevice); + LogicalDevice* mainLogicalDevice = _renderDevice->getLogicalDevice(LogicalDeviceType::MainDevice); - _inputRegistrator.addObserveTargetWindow( - mainLogicalDevice->getSwapChain(0)->getGlfwWindow()); + _inputRegistrator.addObserveTargetWindow(mainLogicalDevice->getSwapChain(0)->getGlfwWindow()); using namespace std::placeholders; auto processKeyCallback = std::mem_fn(&VoxEditor::processKeyInput); - _inputRegistrator.registerDeviceKeyCallback( - uint32_t(-1), std::bind(processKeyCallback, this, _1, _2)); + _inputRegistrator.registerDeviceKeyCallback(uint32_t(-1), std::bind(processKeyCallback, this, _1, _2)); SceneRenderer* sceneRenderer = _renderDevice->getSceneRenderer(); - _sceneObjectPass = - sceneRenderer->getOrCreateSceneRenderPass( - "SceneObjectPass", mainLogicalDevice); - _postProcessPass = - sceneRenderer->getOrCreateSceneRenderPass( - "PostProcessPass", mainLogicalDevice); + _sceneObjectPass = sceneRenderer->getOrCreateSceneRenderPass("SceneObjectPass", mainLogicalDevice); + _postProcessPass = sceneRenderer->getOrCreateSceneRenderPass("PostProcessPass", mainLogicalDevice); _postProcessPass->addDependency("SceneObjectPass"); sceneRenderer->initializePasses(); @@ -97,8 +89,7 @@ void VoxEditor::runEditorLoop() while (_shouldCloseEditor == false) { const auto currentTime = std::chrono::system_clock::now(); - const double elapsed = - std::chrono::duration(currentTime - previousTime).count(); + const double elapsed = std::chrono::duration(currentTime - previousTime).count(); previousTime = currentTime; glfwPollEvents(); diff --git a/Sources/VoxFlow/Editor/WinMain.cpp b/Sources/VoxFlow/Editor/WinMain.cpp index 73f62922..c6c7910c 100644 --- a/Sources/VoxFlow/Editor/WinMain.cpp +++ b/Sources/VoxFlow/Editor/WinMain.cpp @@ -1,13 +1,11 @@ -#include #include +#include int main(int argc, char* argv[]) { - cxxopts::Options options( - "VoxEditor", "CubbyFlow(Voxel-based fluid simulation engine) editor"); + cxxopts::Options options("VoxEditor", "CubbyFlow(Voxel-based fluid simulation engine) editor"); - options.add_options()("d,debug", "Enable vulkan validation layer", - cxxopts::value()->default_value("false")); + options.add_options()("d,debug", "Enable vulkan validation layer", cxxopts::value()->default_value("false")); VoxFlow::VoxEditor editor(options.parse(argc, argv));