From 83be7e0c3137546d47bae225adf335da282a17d1 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sat, 23 Nov 2019 18:00:50 -0800 Subject: clang-formatted GraphicsEngineD3D12 --- .../GraphicsEngineD3D12/include/BufferD3D12Impl.h | 55 +- .../include/BufferViewD3D12Impl.h | 20 +- .../GraphicsEngineD3D12/include/CommandContext.h | 268 +- .../include/CommandListD3D12Impl.h | 14 +- .../include/CommandListManager.h | 25 +- .../include/CommandQueueD3D12Impl.h | 22 +- .../GraphicsEngineD3D12/include/D3D12DynamicHeap.h | 72 +- .../include/D3D12ResourceBase.h | 2 +- .../include/D3D12TypeConversions.h | 35 +- .../include/D3D12TypeDefinitions.h | 222 +- Graphics/GraphicsEngineD3D12/include/D3D12Utils.h | 2 +- .../GraphicsEngineD3D12/include/DescriptorHeap.h | 249 +- .../include/DeviceContextD3D12Impl.h | 206 +- .../GraphicsEngineD3D12/include/FenceD3D12Impl.h | 16 +- .../GraphicsEngineD3D12/include/GenerateMips.h | 28 +- .../include/PipelineStateD3D12Impl.h | 57 +- .../include/RenderDeviceD3D12Impl.h | 75 +- .../GraphicsEngineD3D12/include/RootSignature.h | 386 +-- .../GraphicsEngineD3D12/include/SamplerD3D12Impl.h | 12 +- .../GraphicsEngineD3D12/include/ShaderD3D12Impl.h | 25 +- .../include/ShaderResourceBindingD3D12Impl.h | 38 +- .../include/ShaderResourceCacheD3D12.h | 121 +- .../include/ShaderResourceLayoutD3D12.h | 165 +- .../include/ShaderResourcesD3D12.h | 22 +- .../include/ShaderVariableD3D12.h | 63 +- .../include/SwapChainD3D12Impl.h | 26 +- .../GraphicsEngineD3D12/include/TextureD3D12Impl.h | 46 +- .../include/TextureViewD3D12Impl.h | 24 +- Graphics/GraphicsEngineD3D12/include/d3dx12_win.h | 1332 ++++----- Graphics/GraphicsEngineD3D12/include/pch.h | 6 +- .../GraphicsEngineD3D12/interface/BufferD3D12.h | 11 +- .../interface/BufferViewD3D12.h | 5 +- .../interface/CommandQueueD3D12.h | 12 +- .../interface/DeviceContextD3D12.h | 15 +- .../interface/EngineFactoryD3D12.h | 160 +- .../GraphicsEngineD3D12/interface/FenceD3D12.h | 5 +- .../interface/PipelineStateD3D12.h | 15 +- .../interface/RenderDeviceD3D12.h | 15 +- .../GraphicsEngineD3D12/interface/SamplerD3D12.h | 7 +- .../GraphicsEngineD3D12/interface/ShaderD3D12.h | 5 +- .../interface/ShaderResourceBindingD3D12.h | 6 +- .../GraphicsEngineD3D12/interface/SwapChainD3D12.h | 5 +- .../GraphicsEngineD3D12/interface/TextureD3D12.h | 11 +- .../interface/TextureViewD3D12.h | 5 +- .../GraphicsEngineD3D12/src/BufferD3D12Impl.cpp | 241 +- .../src/BufferViewD3D12Impl.cpp | 18 +- .../GraphicsEngineD3D12/src/CommandContext.cpp | 134 +- .../GraphicsEngineD3D12/src/CommandListManager.cpp | 64 +- .../src/CommandQueueD3D12Impl.cpp | 32 +- .../GraphicsEngineD3D12/src/D3D12DynamicHeap.cpp | 136 +- .../src/D3D12TypeConversions.cpp | 176 +- Graphics/GraphicsEngineD3D12/src/D3D12Utils.cpp | 28 +- .../GraphicsEngineD3D12/src/DescriptorHeap.cpp | 119 +- .../src/DeviceContextD3D12Impl.cpp | 2869 ++++++++++---------- .../GraphicsEngineD3D12/src/EngineFactoryD3D12.cpp | 293 +- .../GraphicsEngineD3D12/src/FenceD3D12Impl.cpp | 20 +- Graphics/GraphicsEngineD3D12/src/GenerateMips.cpp | 391 +-- .../src/PipelineStateD3D12Impl.cpp | 201 +- .../src/RenderDeviceD3D12Impl.cpp | 302 +-- Graphics/GraphicsEngineD3D12/src/RootSignature.cpp | 594 ++-- .../GraphicsEngineD3D12/src/SamplerD3D12Impl.cpp | 40 +- .../GraphicsEngineD3D12/src/ShaderD3D12Impl.cpp | 16 +- .../src/ShaderResourceBindingD3D12Impl.cpp | 66 +- .../src/ShaderResourceCacheD3D12.cpp | 136 +- .../src/ShaderResourceLayoutD3D12.cpp | 391 +-- .../src/ShaderResourcesD3D12.cpp | 7 +- .../src/ShaderVariableD3D12.cpp | 81 +- .../GraphicsEngineD3D12/src/SwapChainD3D12Impl.cpp | 79 +- .../GraphicsEngineD3D12/src/TextureD3D12Impl.cpp | 328 +-- .../src/TextureViewD3D12Impl.cpp | 26 +- 70 files changed, 5508 insertions(+), 5191 deletions(-) (limited to 'Graphics/GraphicsEngineD3D12') diff --git a/Graphics/GraphicsEngineD3D12/include/BufferD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/BufferD3D12Impl.h index dd2a9510..c98d341d 100644 --- a/Graphics/GraphicsEngineD3D12/include/BufferD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/BufferD3D12Impl.h @@ -45,48 +45,48 @@ class BufferD3D12Impl final : public BufferBase; - BufferD3D12Impl(IReferenceCounters* pRefCounters, - FixedBlockMemoryAllocator& BuffViewObjMemAllocator, - class RenderDeviceD3D12Impl* pDeviceD3D12, - const BufferDesc& BuffDesc, - const BufferData* pBuffData = nullptr); - - BufferD3D12Impl(IReferenceCounters* pRefCounters, - FixedBlockMemoryAllocator& BuffViewObjMemAllocator, - class RenderDeviceD3D12Impl* pDeviceD3D12, - const BufferDesc& BuffDesc, + BufferD3D12Impl(IReferenceCounters* pRefCounters, + FixedBlockMemoryAllocator& BuffViewObjMemAllocator, + class RenderDeviceD3D12Impl* pDeviceD3D12, + const BufferDesc& BuffDesc, + const BufferData* pBuffData = nullptr); + + BufferD3D12Impl(IReferenceCounters* pRefCounters, + FixedBlockMemoryAllocator& BuffViewObjMemAllocator, + class RenderDeviceD3D12Impl* pDeviceD3D12, + const BufferDesc& BuffDesc, RESOURCE_STATE InitialState, ID3D12Resource* pd3d12Buffer); ~BufferD3D12Impl(); - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override final; #ifdef DEVELOPMENT - void DvpVerifyDynamicAllocation(class DeviceContextD3D12Impl* pCtx)const; + void DvpVerifyDynamicAllocation(class DeviceContextD3D12Impl* pCtx) const; #endif /// Implementation of IBufferD3D12::GetD3D12Buffer(). - virtual ID3D12Resource* GetD3D12Buffer(size_t& DataStartByteOffset, IDeviceContext* pContext)override final; - + virtual ID3D12Resource* GetD3D12Buffer(size_t& DataStartByteOffset, IDeviceContext* pContext) override final; + /// Implementation of IBuffer::GetNativeHandle(). - virtual void* GetNativeHandle()override final - { + virtual void* GetNativeHandle() override final + { VERIFY(GetD3D12Resource() != nullptr, "The buffer is dynamic and has no pointer to D3D12 resource"); size_t DataStartByteOffset = 0; - auto *pd3d12Buffer = GetD3D12Buffer(DataStartByteOffset, 0); + auto* pd3d12Buffer = GetD3D12Buffer(DataStartByteOffset, 0); VERIFY(DataStartByteOffset == 0, "0 offset expected"); return pd3d12Buffer; } /// Implementation of IBufferD3D12::SetD3D12ResourceState(). - virtual void SetD3D12ResourceState(D3D12_RESOURCE_STATES state)override final; + virtual void SetD3D12ResourceState(D3D12_RESOURCE_STATES state) override final; /// Implementation of IBufferD3D12::GetD3D12ResourceState(). - virtual D3D12_RESOURCE_STATES GetD3D12ResourceState()const override final; + virtual D3D12_RESOURCE_STATES GetD3D12ResourceState() const override final; __forceinline D3D12_GPU_VIRTUAL_ADDRESS GetGPUAddress(Uint32 ContextId, class DeviceContextD3D12Impl* pCtx) { - if(m_Desc.Usage == USAGE_DYNAMIC) + if (m_Desc.Usage == USAGE_DYNAMIC) { #ifdef DEVELOPMENT DvpVerifyDynamicAllocation(pCtx); @@ -99,20 +99,21 @@ public: } } - D3D12_CPU_DESCRIPTOR_HANDLE GetCBVHandle(){return m_CBVDescriptorAllocation.GetCpuHandle();} + D3D12_CPU_DESCRIPTOR_HANDLE GetCBVHandle() { return m_CBVDescriptorAllocation.GetCpuHandle(); } private: - virtual void CreateViewInternal( const struct BufferViewDesc& ViewDesc, IBufferView** ppView, bool bIsDefaultView )override; + virtual void CreateViewInternal(const struct BufferViewDesc& ViewDesc, IBufferView** ppView, bool bIsDefaultView) override; + + void CreateUAV(struct BufferViewDesc& UAVDesc, D3D12_CPU_DESCRIPTOR_HANDLE UAVDescriptor); + void CreateSRV(struct BufferViewDesc& SRVDesc, D3D12_CPU_DESCRIPTOR_HANDLE SRVDescriptor); + void CreateCBV(D3D12_CPU_DESCRIPTOR_HANDLE CBVDescriptor); - void CreateUAV( struct BufferViewDesc& UAVDesc, D3D12_CPU_DESCRIPTOR_HANDLE UAVDescriptor ); - void CreateSRV( struct BufferViewDesc& SRVDesc, D3D12_CPU_DESCRIPTOR_HANDLE SRVDescriptor ); - void CreateCBV( D3D12_CPU_DESCRIPTOR_HANDLE CBVDescriptor ); DescriptorHeapAllocation m_CBVDescriptorAllocation; friend class DeviceContextD3D12Impl; // Array of dynamic allocations for every device context // sizeof(D3D12DynamicAllocation) == 40 (x64) - std::vector > m_DynamicData; + std::vector> m_DynamicData; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/BufferViewD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/BufferViewD3D12Impl.h index 400e8846..61ff2949 100644 --- a/Graphics/GraphicsEngineD3D12/include/BufferViewD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/BufferViewD3D12Impl.h @@ -43,21 +43,21 @@ class BufferViewD3D12Impl final : public BufferViewBase; - BufferViewD3D12Impl( IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pDevice, - const BufferViewDesc& ViewDesc, - class IBuffer* pBuffer, - DescriptorHeapAllocation&& HandleAlloc, - bool bIsDefaultView); + BufferViewD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl* pDevice, + const BufferViewDesc& ViewDesc, + class IBuffer* pBuffer, + DescriptorHeapAllocation&& HandleAlloc, + bool bIsDefaultView); - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override final; /// Implementation of IBufferViewD3D12::GetCPUDescriptorHandle(). - virtual D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle()override final{return m_DescriptorHandle.GetCpuHandle();} - + virtual D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle() override final { return m_DescriptorHandle.GetCpuHandle(); } + protected: // Allocation in a CPU-only descriptor heap DescriptorHeapAllocation m_DescriptorHandle; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/CommandContext.h b/Graphics/GraphicsEngineD3D12/include/CommandContext.h index a8c95d41..8e033744 100644 --- a/Graphics/GraphicsEngineD3D12/include/CommandContext.h +++ b/Graphics/GraphicsEngineD3D12/include/CommandContext.h @@ -38,6 +38,7 @@ namespace Diligent struct DWParam { + // clang-format off DWParam( FLOAT f ) : Float{f} {} DWParam( UINT u ) : Uint {u} {} DWParam( INT i ) : Int {i} {} @@ -45,59 +46,72 @@ struct DWParam void operator= ( FLOAT f ) { Float = f; } void operator= ( UINT u ) { Uint = u; } void operator= ( INT i ) { Int = i; } + // clang-format on - union - { - FLOAT Float; - UINT Uint; - INT Int; - }; + union + { + FLOAT Float; + UINT Uint; + INT Int; + }; }; class CommandContext { public: + CommandContext(class CommandListManager& CmdListManager); - CommandContext( class CommandListManager& CmdListManager); + // clang-format off CommandContext (const CommandContext&) = delete; CommandContext& operator = (const CommandContext&) = delete; CommandContext ( CommandContext&&) = delete; CommandContext& operator = ( CommandContext&&) = delete; + // clang-format on ~CommandContext(); - // Submit the command buffer and reset it. This is encouraged to keep the GPU busy and reduce latency. - // Taking too long to build command lists and submit them can idle the GPU. - ID3D12GraphicsCommandList* Close(CComPtr& pAllocator); - void Reset( CommandListManager& CmdListManager ); + // Submit the command buffer and reset it. This is encouraged to keep the GPU busy and reduce latency. + // Taking too long to build command lists and submit them can idle the GPU. + ID3D12GraphicsCommandList* Close(CComPtr& pAllocator); + void Reset(CommandListManager& CmdListManager); - class GraphicsContext& AsGraphicsContext(); - class ComputeContext& AsComputeContext(); + class GraphicsContext& AsGraphicsContext(); + class ComputeContext& AsComputeContext(); - void ClearUAVFloat( D3D12_GPU_DESCRIPTOR_HANDLE GpuHandle, D3D12_CPU_DESCRIPTOR_HANDLE CpuHandle, ID3D12Resource* pd3d12Resource, const float* Color ) + void ClearUAVFloat(D3D12_GPU_DESCRIPTOR_HANDLE GpuHandle, + D3D12_CPU_DESCRIPTOR_HANDLE CpuHandle, + ID3D12Resource* pd3d12Resource, + const float* Color) { FlushResourceBarriers(); m_pCommandList->ClearUnorderedAccessViewFloat(GpuHandle, CpuHandle, pd3d12Resource, Color, 0, nullptr); } - void ClearUAVUint( D3D12_GPU_DESCRIPTOR_HANDLE GpuHandle, D3D12_CPU_DESCRIPTOR_HANDLE CpuHandle, ID3D12Resource* pd3d12Resource, const UINT* Color ) + void ClearUAVUint(D3D12_GPU_DESCRIPTOR_HANDLE GpuHandle, + D3D12_CPU_DESCRIPTOR_HANDLE CpuHandle, + ID3D12Resource* pd3d12Resource, + const UINT* Color) { FlushResourceBarriers(); m_pCommandList->ClearUnorderedAccessViewUint(GpuHandle, CpuHandle, pd3d12Resource, Color, 0, nullptr); } - void CopyResource(ID3D12Resource *pDstRes, ID3D12Resource *pSrcRes) + void CopyResource(ID3D12Resource* pDstRes, ID3D12Resource* pSrcRes) { m_pCommandList->CopyResource(pDstRes, pSrcRes); } - void TransitionResource(ITextureD3D12 *pTexture, RESOURCE_STATE NewState); - void TransitionResource(IBufferD3D12 *pBuffer, RESOURCE_STATE NewState); + void TransitionResource(ITextureD3D12* pTexture, RESOURCE_STATE NewState); + void TransitionResource(IBufferD3D12* pBuffer, RESOURCE_STATE NewState); void TransitionResource(const StateTransitionDesc& Barrier); - //void BeginResourceTransition(GpuResource& Resource, D3D12_RESOURCE_STATES NewState, bool FlushImmediate = false); - - void ResolveSubresource(ID3D12Resource *pDstResource, UINT DstSubresource, ID3D12Resource *pSrcResource, UINT SrcSubresource, DXGI_FORMAT Format) + //void BeginResourceTransition(GpuResource& Resource, D3D12_RESOURCE_STATES NewState, bool FlushImmediate = false); + + void ResolveSubresource(ID3D12Resource* pDstResource, + UINT DstSubresource, + ID3D12Resource* pSrcResource, + UINT SrcSubresource, + DXGI_FORMAT Format) { FlushResourceBarriers(); m_pCommandList->ResolveSubresource(pDstResource, DstSubresource, pSrcResource, SrcSubresource, Format); @@ -105,10 +119,10 @@ public: void FlushResourceBarriers() { - if (!m_PendingResourceBarriers.empty()) + if (!m_PendingResourceBarriers.empty()) { - m_pCommandList->ResourceBarrier(static_cast(m_PendingResourceBarriers.size()), m_PendingResourceBarriers.data()); - m_PendingResourceBarriers.clear(); + m_pCommandList->ResourceBarrier(static_cast(m_PendingResourceBarriers.size()), m_PendingResourceBarriers.data()); + m_PendingResourceBarriers.clear(); } } @@ -118,30 +132,30 @@ public: ID3D12DescriptorHeap* pSrvCbvUavHeap; ID3D12DescriptorHeap* pSamplerHeap; ShaderDescriptorHeaps(ID3D12DescriptorHeap* _pSrvCbvUavHeap = nullptr, ID3D12DescriptorHeap* _pSamplerHeap = nullptr) : - pSrvCbvUavHeap(_pSrvCbvUavHeap), - pSamplerHeap(_pSamplerHeap) + pSrvCbvUavHeap{_pSrvCbvUavHeap}, + pSamplerHeap{_pSamplerHeap} {} - bool operator == (const ShaderDescriptorHeaps& rhs)const + bool operator==(const ShaderDescriptorHeaps& rhs) const { return pSrvCbvUavHeap == rhs.pSrvCbvUavHeap && pSamplerHeap == rhs.pSamplerHeap; } - operator bool()const + operator bool() const { return pSrvCbvUavHeap != nullptr || pSamplerHeap != nullptr; } }; - void SetDescriptorHeaps( ShaderDescriptorHeaps& Heaps ); + void SetDescriptorHeaps(ShaderDescriptorHeaps& Heaps); - void ExecuteIndirect(ID3D12CommandSignature *pCmdSignature, ID3D12Resource *pBuff, Uint64 ArgsOffset) + void ExecuteIndirect(ID3D12CommandSignature* pCmdSignature, ID3D12Resource* pBuff, Uint64 ArgsOffset) { - FlushResourceBarriers(); - m_pCommandList->ExecuteIndirect(pCmdSignature, 1, pBuff, ArgsOffset, nullptr, 0); + FlushResourceBarriers(); + m_pCommandList->ExecuteIndirect(pCmdSignature, 1, pBuff, ArgsOffset, nullptr, 0); } - void SetID(const Char* ID) { m_ID = ID; } - ID3D12GraphicsCommandList *GetCommandList(){return m_pCommandList;} - - DescriptorHeapAllocation AllocateDynamicGPUVisibleDescriptor( D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT Count = 1 ) + void SetID(const Char* ID) { m_ID = ID; } + ID3D12GraphicsCommandList* GetCommandList() { return m_pCommandList; } + + DescriptorHeapAllocation AllocateDynamicGPUVisibleDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT Count = 1) { VERIFY(m_DynamicGPUDescriptorAllocators != nullptr, "Dynamic GPU descriptor llocators have not been initialized. Did you forget to call SetDynamicGPUDescriptorAllocators() after resetting the context?"); VERIFY(Type >= D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && Type <= D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, "Invalid heap type"); @@ -150,10 +164,10 @@ public: void InsertUAVBarrier(ID3D12Resource* pd3d12Resource); - void SetPipelineState( ID3D12PipelineState* pPSO ) + void SetPipelineState(ID3D12PipelineState* pPSO) { - if (pPSO != m_pCurPipelineState) - { + if (pPSO != m_pCurPipelineState) + { m_pCommandList->SetPipelineState(m_pCurPipelineState = pPSO); } } @@ -166,21 +180,22 @@ public: protected: void InsertAliasBarrier(D3D12ResourceBase& Before, D3D12ResourceBase& After, bool FlushImmediate = false); - CComPtr m_pCommandList; - CComPtr m_pCurrentAllocator; + CComPtr m_pCommandList; + CComPtr m_pCurrentAllocator; ID3D12PipelineState* m_pCurPipelineState = nullptr; - ID3D12RootSignature* m_pCurGraphicsRootSignature = nullptr; - ID3D12RootSignature* m_pCurComputeRootSignature = nullptr; + ID3D12RootSignature* m_pCurGraphicsRootSignature = nullptr; + ID3D12RootSignature* m_pCurComputeRootSignature = nullptr; static constexpr int MaxPendingBarriers = 16; - std::vector > m_PendingResourceBarriers; + + std::vector> m_PendingResourceBarriers; ShaderDescriptorHeaps m_BoundDescriptorHeaps; - + DynamicSuballocationsManager* m_DynamicGPUDescriptorAllocators = nullptr; - String m_ID; + String m_ID; D3D12_PRIMITIVE_TOPOLOGY m_PrimitiveTopology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED; }; @@ -189,193 +204,190 @@ protected: class GraphicsContext : public CommandContext { public: - void ClearRenderTarget( D3D12_CPU_DESCRIPTOR_HANDLE RTV, const float *Color ) + void ClearRenderTarget(D3D12_CPU_DESCRIPTOR_HANDLE RTV, const float* Color) { FlushResourceBarriers(); - m_pCommandList->ClearRenderTargetView(RTV, Color, 0, nullptr); + m_pCommandList->ClearRenderTargetView(RTV, Color, 0, nullptr); } - void ClearDepthStencil( D3D12_CPU_DESCRIPTOR_HANDLE DSV, D3D12_CLEAR_FLAGS ClearFlags, float Depth, UINT8 Stencil ) + void ClearDepthStencil(D3D12_CPU_DESCRIPTOR_HANDLE DSV, D3D12_CLEAR_FLAGS ClearFlags, float Depth, UINT8 Stencil) { FlushResourceBarriers(); m_pCommandList->ClearDepthStencilView(DSV, ClearFlags, Depth, Stencil, 0, nullptr); } - void SetRootSignature( ID3D12RootSignature *pRootSig ) + void SetRootSignature(ID3D12RootSignature* pRootSig) { - if (pRootSig != m_pCurGraphicsRootSignature) + if (pRootSig != m_pCurGraphicsRootSignature) { - m_pCommandList->SetGraphicsRootSignature(m_pCurGraphicsRootSignature = pRootSig); + m_pCommandList->SetGraphicsRootSignature(m_pCurGraphicsRootSignature = pRootSig); } } - void SetViewports( UINT NumVPs, const D3D12_VIEWPORT* pVPs ) + void SetViewports(UINT NumVPs, const D3D12_VIEWPORT* pVPs) { m_pCommandList->RSSetViewports(NumVPs, pVPs); } - void SetScissorRects( UINT NumRects, const D3D12_RECT* pRects ) + void SetScissorRects(UINT NumRects, const D3D12_RECT* pRects) { m_pCommandList->RSSetScissorRects(NumRects, pRects); } - void SetStencilRef( UINT StencilRef ) + void SetStencilRef(UINT StencilRef) { - m_pCommandList->OMSetStencilRef( StencilRef ); + m_pCommandList->OMSetStencilRef(StencilRef); } - void SetBlendFactor( const float* BlendFactor ) + void SetBlendFactor(const float* BlendFactor) { - m_pCommandList->OMSetBlendFactor( BlendFactor ); + m_pCommandList->OMSetBlendFactor(BlendFactor); } - void SetPrimitiveTopology( D3D12_PRIMITIVE_TOPOLOGY Topology ) + void SetPrimitiveTopology(D3D12_PRIMITIVE_TOPOLOGY Topology) { - if(m_PrimitiveTopology != Topology) + if (m_PrimitiveTopology != Topology) { m_PrimitiveTopology = Topology; - m_pCommandList->IASetPrimitiveTopology(Topology); + m_pCommandList->IASetPrimitiveTopology(Topology); } } - void SetConstants( UINT RootIndex, UINT NumConstants, const void* pConstants ) + void SetConstants(UINT RootIndex, UINT NumConstants, const void* pConstants) { - m_pCommandList->SetGraphicsRoot32BitConstants( RootIndex, NumConstants, pConstants, 0 ); + m_pCommandList->SetGraphicsRoot32BitConstants(RootIndex, NumConstants, pConstants, 0); } - void SetConstants( UINT RootIndex, DWParam X ) + void SetConstants(UINT RootIndex, DWParam X) { - m_pCommandList->SetGraphicsRoot32BitConstant( RootIndex, X.Uint, 0 ); + m_pCommandList->SetGraphicsRoot32BitConstant(RootIndex, X.Uint, 0); } - void SetConstants( UINT RootIndex, DWParam X, DWParam Y ) + void SetConstants(UINT RootIndex, DWParam X, DWParam Y) { - m_pCommandList->SetGraphicsRoot32BitConstant( RootIndex, X.Uint, 0 ); - m_pCommandList->SetGraphicsRoot32BitConstant( RootIndex, Y.Uint, 1 ); + m_pCommandList->SetGraphicsRoot32BitConstant(RootIndex, X.Uint, 0); + m_pCommandList->SetGraphicsRoot32BitConstant(RootIndex, Y.Uint, 1); } - void SetConstants( UINT RootIndex, DWParam X, DWParam Y, DWParam Z ) + void SetConstants(UINT RootIndex, DWParam X, DWParam Y, DWParam Z) { - m_pCommandList->SetGraphicsRoot32BitConstant( RootIndex, X.Uint, 0 ); - m_pCommandList->SetGraphicsRoot32BitConstant( RootIndex, Y.Uint, 1 ); - m_pCommandList->SetGraphicsRoot32BitConstant( RootIndex, Z.Uint, 2 ); + m_pCommandList->SetGraphicsRoot32BitConstant(RootIndex, X.Uint, 0); + m_pCommandList->SetGraphicsRoot32BitConstant(RootIndex, Y.Uint, 1); + m_pCommandList->SetGraphicsRoot32BitConstant(RootIndex, Z.Uint, 2); } - void SetConstants( UINT RootIndex, DWParam X, DWParam Y, DWParam Z, DWParam W ) + void SetConstants(UINT RootIndex, DWParam X, DWParam Y, DWParam Z, DWParam W) { - m_pCommandList->SetGraphicsRoot32BitConstant( RootIndex, X.Uint, 0 ); - m_pCommandList->SetGraphicsRoot32BitConstant( RootIndex, Y.Uint, 1 ); - m_pCommandList->SetGraphicsRoot32BitConstant( RootIndex, Z.Uint, 2 ); - m_pCommandList->SetGraphicsRoot32BitConstant( RootIndex, W.Uint, 3 ); + m_pCommandList->SetGraphicsRoot32BitConstant(RootIndex, X.Uint, 0); + m_pCommandList->SetGraphicsRoot32BitConstant(RootIndex, Y.Uint, 1); + m_pCommandList->SetGraphicsRoot32BitConstant(RootIndex, Z.Uint, 2); + m_pCommandList->SetGraphicsRoot32BitConstant(RootIndex, W.Uint, 3); } - void SetConstantBuffer( UINT RootIndex, D3D12_GPU_VIRTUAL_ADDRESS CBV ) + void SetConstantBuffer(UINT RootIndex, D3D12_GPU_VIRTUAL_ADDRESS CBV) { - m_pCommandList->SetGraphicsRootConstantBufferView(RootIndex, CBV); + m_pCommandList->SetGraphicsRootConstantBufferView(RootIndex, CBV); } - void SetDescriptorTable( UINT RootIndex, D3D12_GPU_DESCRIPTOR_HANDLE FirstHandle ) + void SetDescriptorTable(UINT RootIndex, D3D12_GPU_DESCRIPTOR_HANDLE FirstHandle) { - m_pCommandList->SetGraphicsRootDescriptorTable( RootIndex, FirstHandle ); + m_pCommandList->SetGraphicsRootDescriptorTable(RootIndex, FirstHandle); } - void SetIndexBuffer( const D3D12_INDEX_BUFFER_VIEW& IBView ) + void SetIndexBuffer(const D3D12_INDEX_BUFFER_VIEW& IBView) { - m_pCommandList->IASetIndexBuffer(&IBView); + m_pCommandList->IASetIndexBuffer(&IBView); } - void SetVertexBuffers( UINT StartSlot, UINT Count, const D3D12_VERTEX_BUFFER_VIEW VBViews[] ) + void SetVertexBuffers(UINT StartSlot, UINT Count, const D3D12_VERTEX_BUFFER_VIEW VBViews[]) { - m_pCommandList->IASetVertexBuffers(StartSlot, Count, VBViews); + m_pCommandList->IASetVertexBuffers(StartSlot, Count, VBViews); } - void Draw(UINT VertexCountPerInstance, UINT InstanceCount, - UINT StartVertexLocation, UINT StartInstanceLocation) + void Draw(UINT VertexCountPerInstance, UINT InstanceCount, UINT StartVertexLocation, UINT StartInstanceLocation) { - FlushResourceBarriers(); - m_pCommandList->DrawInstanced(VertexCountPerInstance, InstanceCount, StartVertexLocation, StartInstanceLocation); + FlushResourceBarriers(); + m_pCommandList->DrawInstanced(VertexCountPerInstance, InstanceCount, StartVertexLocation, StartInstanceLocation); } - void DrawIndexed(UINT IndexCountPerInstance, UINT InstanceCount, UINT StartIndexLocation, - INT BaseVertexLocation, UINT StartInstanceLocation) + void DrawIndexed(UINT IndexCountPerInstance, UINT InstanceCount, UINT StartIndexLocation, INT BaseVertexLocation, UINT StartInstanceLocation) { - FlushResourceBarriers(); - m_pCommandList->DrawIndexedInstanced(IndexCountPerInstance, InstanceCount, StartIndexLocation, BaseVertexLocation, StartInstanceLocation); + FlushResourceBarriers(); + m_pCommandList->DrawIndexedInstanced(IndexCountPerInstance, InstanceCount, StartIndexLocation, BaseVertexLocation, StartInstanceLocation); } }; class ComputeContext : public CommandContext { public: - - void SetRootSignature( ID3D12RootSignature *pRootSig ) + void SetRootSignature(ID3D12RootSignature* pRootSig) { - if (pRootSig != m_pCurComputeRootSignature) + if (pRootSig != m_pCurComputeRootSignature) { - m_pCommandList->SetComputeRootSignature(m_pCurComputeRootSignature = pRootSig); + m_pCommandList->SetComputeRootSignature(m_pCurComputeRootSignature = pRootSig); } } - void SetConstants( UINT RootIndex, UINT NumConstants, const void* pConstants ) + void SetConstants(UINT RootIndex, UINT NumConstants, const void* pConstants) { - m_pCommandList->SetComputeRoot32BitConstants( RootIndex, NumConstants, pConstants, 0 ); + m_pCommandList->SetComputeRoot32BitConstants(RootIndex, NumConstants, pConstants, 0); } - void SetConstants( UINT RootIndex, DWParam X ) + void SetConstants(UINT RootIndex, DWParam X) { - m_pCommandList->SetComputeRoot32BitConstant( RootIndex, X.Uint, 0 ); + m_pCommandList->SetComputeRoot32BitConstant(RootIndex, X.Uint, 0); } - void SetConstants( UINT RootIndex, DWParam X, DWParam Y ) + void SetConstants(UINT RootIndex, DWParam X, DWParam Y) { - m_pCommandList->SetComputeRoot32BitConstant( RootIndex, X.Uint, 0 ); - m_pCommandList->SetComputeRoot32BitConstant( RootIndex, Y.Uint, 1 ); + m_pCommandList->SetComputeRoot32BitConstant(RootIndex, X.Uint, 0); + m_pCommandList->SetComputeRoot32BitConstant(RootIndex, Y.Uint, 1); } - void SetConstants( UINT RootIndex, DWParam X, DWParam Y, DWParam Z ) + void SetConstants(UINT RootIndex, DWParam X, DWParam Y, DWParam Z) { - m_pCommandList->SetComputeRoot32BitConstant( RootIndex, X.Uint, 0 ); - m_pCommandList->SetComputeRoot32BitConstant( RootIndex, Y.Uint, 1 ); - m_pCommandList->SetComputeRoot32BitConstant( RootIndex, Z.Uint, 2 ); + m_pCommandList->SetComputeRoot32BitConstant(RootIndex, X.Uint, 0); + m_pCommandList->SetComputeRoot32BitConstant(RootIndex, Y.Uint, 1); + m_pCommandList->SetComputeRoot32BitConstant(RootIndex, Z.Uint, 2); } - void SetConstants( UINT RootIndex, DWParam X, DWParam Y, DWParam Z, DWParam W ) + void SetConstants(UINT RootIndex, DWParam X, DWParam Y, DWParam Z, DWParam W) { - m_pCommandList->SetComputeRoot32BitConstant( RootIndex, X.Uint, 0 ); - m_pCommandList->SetComputeRoot32BitConstant( RootIndex, Y.Uint, 1 ); - m_pCommandList->SetComputeRoot32BitConstant( RootIndex, Z.Uint, 2 ); - m_pCommandList->SetComputeRoot32BitConstant( RootIndex, W.Uint, 3 ); + m_pCommandList->SetComputeRoot32BitConstant(RootIndex, X.Uint, 0); + m_pCommandList->SetComputeRoot32BitConstant(RootIndex, Y.Uint, 1); + m_pCommandList->SetComputeRoot32BitConstant(RootIndex, Z.Uint, 2); + m_pCommandList->SetComputeRoot32BitConstant(RootIndex, W.Uint, 3); } - - void SetConstantBuffer( UINT RootIndex, D3D12_GPU_VIRTUAL_ADDRESS CBV ) + + void SetConstantBuffer(UINT RootIndex, D3D12_GPU_VIRTUAL_ADDRESS CBV) { - m_pCommandList->SetComputeRootConstantBufferView(RootIndex, CBV); + m_pCommandList->SetComputeRootConstantBufferView(RootIndex, CBV); } - void SetDescriptorTable( UINT RootIndex, D3D12_GPU_DESCRIPTOR_HANDLE FirstHandle ) + void SetDescriptorTable(UINT RootIndex, D3D12_GPU_DESCRIPTOR_HANDLE FirstHandle) { - m_pCommandList->SetComputeRootDescriptorTable( RootIndex, FirstHandle ); + m_pCommandList->SetComputeRootDescriptorTable(RootIndex, FirstHandle); } - void Dispatch( size_t GroupCountX = 1, size_t GroupCountY = 1, size_t GroupCountZ = 1 ) + void Dispatch(size_t GroupCountX = 1, size_t GroupCountY = 1, size_t GroupCountZ = 1) { - FlushResourceBarriers(); - m_pCommandList->Dispatch((UINT)GroupCountX, (UINT)GroupCountY, (UINT)GroupCountZ); + FlushResourceBarriers(); + m_pCommandList->Dispatch((UINT)GroupCountX, (UINT)GroupCountY, (UINT)GroupCountZ); } }; -inline GraphicsContext& CommandContext::AsGraphicsContext() +inline GraphicsContext& CommandContext::AsGraphicsContext() { return static_cast(*this); } -inline ComputeContext& CommandContext::AsComputeContext() +inline ComputeContext& CommandContext::AsComputeContext() { return static_cast(*this); } -inline void CommandContext::SetDescriptorHeaps( ShaderDescriptorHeaps& Heaps ) +inline void CommandContext::SetDescriptorHeaps(ShaderDescriptorHeaps& Heaps) { #ifdef _DEBUG VERIFY(Heaps.pSrvCbvUavHeap != nullptr || Heaps.pSamplerHeap != nullptr, "At least one heap is expected to be set"); @@ -387,13 +399,13 @@ inline void CommandContext::SetDescriptorHeaps( ShaderDescriptorHeaps& Heaps ) { m_BoundDescriptorHeaps = Heaps; - ID3D12DescriptorHeap **ppHeaps = reinterpret_cast(&Heaps); - UINT NumHeaps = (ppHeaps[0] != nullptr ? 1 : 0) + (ppHeaps[1] != nullptr ? 1 : 0); - if(ppHeaps[0] == nullptr) + ID3D12DescriptorHeap** ppHeaps = reinterpret_cast(&Heaps); + UINT NumHeaps = (ppHeaps[0] != nullptr ? 1 : 0) + (ppHeaps[1] != nullptr ? 1 : 0); + if (ppHeaps[0] == nullptr) ++ppHeaps; m_pCommandList->SetDescriptorHeaps(NumHeaps, ppHeaps); } } -} \ No newline at end of file +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/CommandListD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/CommandListD3D12Impl.h index 2c417a8a..8c044c01 100644 --- a/Graphics/GraphicsEngineD3D12/include/CommandListD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/CommandListD3D12Impl.h @@ -41,10 +41,11 @@ class CommandListD3D12Impl final : public CommandListBase; - CommandListD3D12Impl(IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pDevice, - DeviceContextD3D12Impl* pDeferredCtx, - RenderDeviceD3D12Impl::PooledCommandContext&& pCmdContext) : + CommandListD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl* pDevice, + DeviceContextD3D12Impl* pDeferredCtx, + RenderDeviceD3D12Impl::PooledCommandContext&& pCmdContext) : + // clang-format off TCommandListBase { pRefCounters, @@ -52,9 +53,10 @@ public: }, m_pDeferredCtx {pDeferredCtx }, m_pCmdContext {std::move(pCmdContext)} + // clang-format on { } - + ~CommandListD3D12Impl() { if (m_pCmdContext != nullptr) @@ -79,4 +81,4 @@ private: RenderDeviceD3D12Impl::PooledCommandContext m_pCmdContext; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/CommandListManager.h b/Graphics/GraphicsEngineD3D12/include/CommandListManager.h index 9dbe4493..949f0e8d 100644 --- a/Graphics/GraphicsEngineD3D12/include/CommandListManager.h +++ b/Graphics/GraphicsEngineD3D12/include/CommandListManager.h @@ -35,31 +35,36 @@ class RenderDeviceD3D12Impl; class CommandListManager { public: - CommandListManager(RenderDeviceD3D12Impl& DeviceD3D12Impl); - ~CommandListManager(); + CommandListManager(RenderDeviceD3D12Impl& DeviceD3D12Impl); + ~CommandListManager(); + // clang-format off CommandListManager (const CommandListManager&) = delete; CommandListManager ( CommandListManager&&) = delete; CommandListManager& operator = (const CommandListManager&) = delete; CommandListManager& operator = ( CommandListManager&&) = delete; + // clang-format on + + void CreateNewCommandList(ID3D12GraphicsCommandList** ppList, ID3D12CommandAllocator** ppAllocator); - void CreateNewCommandList( ID3D12GraphicsCommandList** ppList, ID3D12CommandAllocator** ppAllocator ); - void RequestAllocator(ID3D12CommandAllocator** ppAllocator); void ReleaseAllocator(CComPtr&& Allocator, Uint32 CmdQueue, Uint64 FenceValue); // Returns allocator to the list of available allocators. The GPU must have finished using the // allocator - void FreeAllocator( CComPtr&& Allocator ); + void FreeAllocator(CComPtr&& Allocator); #ifdef DEVELOPMENT - Atomics::Long GetAllocatorCounter() const {return m_AllocatorCounter;} + Atomics::Long GetAllocatorCounter() const + { + return m_AllocatorCounter; + } #endif private: - std::mutex m_AllocatorMutex; - std::vector< CComPtr, STDAllocatorRawMem> > m_FreeAllocators; - + std::mutex m_AllocatorMutex; + std::vector, STDAllocatorRawMem>> m_FreeAllocators; + RenderDeviceD3D12Impl& m_DeviceD3D12Impl; Atomics::AtomicLong m_NumAllocators = 0; // For debug purposes only @@ -69,4 +74,4 @@ private: #endif }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/CommandQueueD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/CommandQueueD3D12Impl.h index bb14b79f..b926b0ee 100644 --- a/Graphics/GraphicsEngineD3D12/include/CommandQueueD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/CommandQueueD3D12Impl.h @@ -42,25 +42,25 @@ public: CommandQueueD3D12Impl(IReferenceCounters* pRefCounters, ID3D12CommandQueue* pd3d12NativeCmdQueue, ID3D12Fence* pd3d12Fence); ~CommandQueueD3D12Impl(); - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override final; - // Implementation of ICommandQueueD3D12::GetNextFenceValue(). - virtual Uint64 GetNextFenceValue()override final { return m_NextFenceValue; } + // Implementation of ICommandQueueD3D12::GetNextFenceValue(). + virtual Uint64 GetNextFenceValue() override final { return m_NextFenceValue; } - // Implementation of ICommandQueueD3D12::Submit(). - virtual Uint64 Submit(ID3D12GraphicsCommandList* commandList)override final; + // Implementation of ICommandQueueD3D12::Submit(). + virtual Uint64 Submit(ID3D12GraphicsCommandList* commandList) override final; // Implementation of ICommandQueueD3D12::GetD3D12CommandQueue(). - virtual ID3D12CommandQueue* GetD3D12CommandQueue()override final { return m_pd3d12CmdQueue; } + virtual ID3D12CommandQueue* GetD3D12CommandQueue() override final { return m_pd3d12CmdQueue; } // Implementation of ICommandQueueD3D12::WaitForIdle(). - virtual Uint64 WaitForIdle()override final; + virtual Uint64 WaitForIdle() override final; // Implementation of ICommandQueueD3D12::GetCompletedFenceValue(). - virtual Uint64 GetCompletedFenceValue()override final; + virtual Uint64 GetCompletedFenceValue() override final; // Implementation of ICommandQueueD3D12::SignalFence(). - virtual void SignalFence(ID3D12Fence* pFence, Uint64 Value)override final; + virtual void SignalFence(ID3D12Fence* pFence, Uint64 Value) override final; private: // A value that will be signaled by the command queue next @@ -72,7 +72,7 @@ private: std::mutex m_QueueMtx; CComPtr m_pd3d12CmdQueue; - // The fence is signaled right after the command list has been + // The fence is signaled right after the command list has been // submitted to the command queue for execution. // All command lists with fence value less or equal to the signaled value // are guaranteed to be finished by the GPU @@ -81,4 +81,4 @@ private: HANDLE m_WaitForGPUEventHandle = {}; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/D3D12DynamicHeap.h b/Graphics/GraphicsEngineD3D12/include/D3D12DynamicHeap.h index c6a1a5f6..57dcbe34 100644 --- a/Graphics/GraphicsEngineD3D12/include/D3D12DynamicHeap.h +++ b/Graphics/GraphicsEngineD3D12/include/D3D12DynamicHeap.h @@ -35,16 +35,18 @@ class RenderDeviceD3D12Impl; struct D3D12DynamicAllocation { - D3D12DynamicAllocation()noexcept{} - D3D12DynamicAllocation(ID3D12Resource* pBuff, - Uint64 _Offset, + D3D12DynamicAllocation() noexcept {} + D3D12DynamicAllocation(ID3D12Resource* pBuff, + Uint64 _Offset, Uint64 _Size, void* _CPUAddress, D3D12_GPU_VIRTUAL_ADDRESS _GPUAddress #ifdef DEVELOPMENT - , Uint64 _DvpCtxFrameNumber + , + Uint64 _DvpCtxFrameNumber #endif - )noexcept : + ) noexcept : + // clang-format off pBuffer {pBuff }, Offset {_Offset }, Size {_Size }, @@ -53,28 +55,31 @@ struct D3D12DynamicAllocation #ifdef DEVELOPMENT , DvpCtxFrameNumber(_DvpCtxFrameNumber) #endif + // clang-format on {} - ID3D12Resource* pBuffer = nullptr; // The D3D buffer associated with this memory. - Uint64 Offset = 0; // Offset from start of buffer resource - Uint64 Size = 0; // Reserved size of this allocation - void* CPUAddress = nullptr; // The CPU-writeable address - D3D12_GPU_VIRTUAL_ADDRESS GPUAddress = 0; // The GPU-visible address + ID3D12Resource* pBuffer = nullptr; // The D3D buffer associated with this memory. + Uint64 Offset = 0; // Offset from start of buffer resource + Uint64 Size = 0; // Reserved size of this allocation + void* CPUAddress = nullptr; // The CPU-writeable address + D3D12_GPU_VIRTUAL_ADDRESS GPUAddress = 0; // The GPU-visible address #ifdef DEVELOPMENT Uint64 DvpCtxFrameNumber = static_cast(-1); #endif }; - + class D3D12DynamicPage { public: D3D12DynamicPage(ID3D12Device* pd3d12Device, Uint64 Size); - + + // clang-format off D3D12DynamicPage (const D3D12DynamicPage&) = delete; D3D12DynamicPage ( D3D12DynamicPage&&) = default; D3D12DynamicPage& operator= (const D3D12DynamicPage&) = delete; D3D12DynamicPage& operator= ( D3D12DynamicPage&&) = delete; + // clang-format on void* GetCPUAddress(Uint64 Offset) { @@ -95,34 +100,36 @@ public: return m_pd3d12Buffer; } - Uint64 GetSize()const + Uint64 GetSize() const { VERIFY_EXPR(m_pd3d12Buffer); return m_pd3d12Buffer->GetDesc().Width; } - bool IsValid()const { return m_pd3d12Buffer != nullptr; } + bool IsValid() const { return m_pd3d12Buffer != nullptr; } private: CComPtr m_pd3d12Buffer; void* m_CPUVirtualAddress = nullptr; // The CPU-writeable address - D3D12_GPU_VIRTUAL_ADDRESS m_GPUVirtualAddress = 0; // The GPU-visible address + D3D12_GPU_VIRTUAL_ADDRESS m_GPUVirtualAddress = 0; // The GPU-visible address }; class D3D12DynamicMemoryManager { public: - D3D12DynamicMemoryManager(IMemoryAllocator& Allocator, + D3D12DynamicMemoryManager(IMemoryAllocator& Allocator, RenderDeviceD3D12Impl& DeviceD3D12Impl, Uint32 NumPagesToReserve, Uint64 PageSize); ~D3D12DynamicMemoryManager(); + // clang-format off D3D12DynamicMemoryManager (const D3D12DynamicMemoryManager&) = delete; D3D12DynamicMemoryManager ( D3D12DynamicMemoryManager&&) = delete; D3D12DynamicMemoryManager& operator= (const D3D12DynamicMemoryManager&) = delete; D3D12DynamicMemoryManager& operator= ( D3D12DynamicMemoryManager&&) = delete; + // clang-format on void ReleasePages(std::vector& Pages, Uint64 QueueMask); @@ -131,15 +138,18 @@ public: D3D12DynamicPage AllocatePage(Uint64 SizeInBytes); #ifdef DEVELOPMENT - int32_t GetAllocatedPageCounter()const{return m_AllocatedPageCounter;} + int32_t GetAllocatedPageCounter() const + { + return m_AllocatedPageCounter; + } #endif private: RenderDeviceD3D12Impl& m_DeviceD3D12Impl; - + std::mutex m_AvailablePagesMtx; using AvailablePagesMapElemType = std::pair; - std::multimap, STDAllocatorRawMem > m_AvailablePages; + std::multimap, STDAllocatorRawMem> m_AvailablePages; #ifdef DEVELOPMENT std::atomic_int32_t m_AllocatedPageCounter = 0; @@ -151,35 +161,37 @@ class D3D12DynamicHeap { public: D3D12DynamicHeap(D3D12DynamicMemoryManager& DynamicMemMgr, std::string HeapName, Uint64 PageSize) : - m_GlobalDynamicMemMgr (DynamicMemMgr), - m_HeapName (std::move(HeapName)), - m_PageSize (PageSize) + m_GlobalDynamicMemMgr{DynamicMemMgr}, + m_HeapName{std::move(HeapName)}, + m_PageSize{PageSize} {} + // clang-format off D3D12DynamicHeap (const D3D12DynamicHeap&) = delete; D3D12DynamicHeap (D3D12DynamicHeap&&) = delete; D3D12DynamicHeap& operator= (const D3D12DynamicHeap&) = delete; D3D12DynamicHeap& operator= (D3D12DynamicHeap&&) = delete; - + // clang-format on + ~D3D12DynamicHeap(); D3D12DynamicAllocation Allocate(Uint64 SizeInBytes, Uint64 Alignment, Uint64 DvpCtxFrameNumber); - void ReleaseAllocatedPages(Uint64 QueueMask); + void ReleaseAllocatedPages(Uint64 QueueMask); static constexpr Uint64 InvalidOffset = static_cast(-1); - size_t GetAllocatedPagesCount() const {return m_AllocatedPages.size();} + size_t GetAllocatedPagesCount() const { return m_AllocatedPages.size(); } private: D3D12DynamicMemoryManager& m_GlobalDynamicMemMgr; - const std::string m_HeapName; + const std::string m_HeapName; std::vector m_AllocatedPages; - + const Uint64 m_PageSize; - Uint64 m_CurrOffset = InvalidOffset; - Uint64 m_AvailableSize = 0; + Uint64 m_CurrOffset = InvalidOffset; + Uint64 m_AvailableSize = 0; Uint64 m_CurrAllocatedSize = 0; Uint64 m_CurrUsedSize = 0; @@ -189,4 +201,4 @@ private: Uint64 m_PeakAlignedSize = 0; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/D3D12ResourceBase.h b/Graphics/GraphicsEngineD3D12/include/D3D12ResourceBase.h index cbfa5b33..013cc1e7 100644 --- a/Graphics/GraphicsEngineD3D12/include/D3D12ResourceBase.h +++ b/Graphics/GraphicsEngineD3D12/include/D3D12ResourceBase.h @@ -42,4 +42,4 @@ protected: CComPtr m_pd3d12Resource; ///< D3D12 buffer object }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/D3D12TypeConversions.h b/Graphics/GraphicsEngineD3D12/include/D3D12TypeConversions.h index d0237039..d810238f 100644 --- a/Graphics/GraphicsEngineD3D12/include/D3D12TypeConversions.h +++ b/Graphics/GraphicsEngineD3D12/include/D3D12TypeConversions.h @@ -31,28 +31,37 @@ namespace Diligent { -D3D12_COMPARISON_FUNC ComparisonFuncToD3D12ComparisonFunc(COMPARISON_FUNCTION Func); -D3D12_FILTER FilterTypeToD3D12Filter(FILTER_TYPE MinFilter, FILTER_TYPE MagFilter, FILTER_TYPE MipFilter); +D3D12_COMPARISON_FUNC ComparisonFuncToD3D12ComparisonFunc(COMPARISON_FUNCTION Func); +D3D12_FILTER FilterTypeToD3D12Filter(FILTER_TYPE MinFilter, FILTER_TYPE MagFilter, FILTER_TYPE MipFilter); D3D12_TEXTURE_ADDRESS_MODE TexAddressModeToD3D12AddressMode(TEXTURE_ADDRESS_MODE Mode); -D3D12_PRIMITIVE_TOPOLOGY TopologyToD3D12Topology(PRIMITIVE_TOPOLOGY Topology); +D3D12_PRIMITIVE_TOPOLOGY TopologyToD3D12Topology(PRIMITIVE_TOPOLOGY Topology); -void DepthStencilStateDesc_To_D3D12_DEPTH_STENCIL_DESC(const DepthStencilStateDesc &DepthStencilDesc, D3D12_DEPTH_STENCIL_DESC &d3d12DSSDesc); -void RasterizerStateDesc_To_D3D12_RASTERIZER_DESC(const RasterizerStateDesc &RasterizerDesc, D3D12_RASTERIZER_DESC &d3d11RSDesc); -void BlendStateDesc_To_D3D12_BLEND_DESC(const BlendStateDesc &BSDesc, D3D12_BLEND_DESC &d3d12BlendDesc); +void DepthStencilStateDesc_To_D3D12_DEPTH_STENCIL_DESC(const DepthStencilStateDesc& DepthStencilDesc, + D3D12_DEPTH_STENCIL_DESC& d3d12DSSDesc); +void RasterizerStateDesc_To_D3D12_RASTERIZER_DESC(const RasterizerStateDesc& RasterizerDesc, + D3D12_RASTERIZER_DESC& d3d11RSDesc); +void BlendStateDesc_To_D3D12_BLEND_DESC(const BlendStateDesc& BSDesc, + D3D12_BLEND_DESC& d3d12BlendDesc); -void LayoutElements_To_D3D12_INPUT_ELEMENT_DESCs(const InputLayoutDesc& InputLayout, - std::vector > &d3d12InputElements); +void LayoutElements_To_D3D12_INPUT_ELEMENT_DESCs(const InputLayoutDesc& InputLayout, + std::vector>& d3d12InputElements); +// clang-format off void TextureViewDesc_to_D3D12_SRV_DESC(const TextureViewDesc& SRVDesc, D3D12_SHADER_RESOURCE_VIEW_DESC &D3D12SRVDesc, Uint32 SampleCount); void TextureViewDesc_to_D3D12_RTV_DESC(const TextureViewDesc& RTVDesc, D3D12_RENDER_TARGET_VIEW_DESC &D3D12RTVDesc, Uint32 SampleCount); void TextureViewDesc_to_D3D12_DSV_DESC(const TextureViewDesc& DSVDesc, D3D12_DEPTH_STENCIL_VIEW_DESC &D3D12DSVDesc, Uint32 SampleCount); void TextureViewDesc_to_D3D12_UAV_DESC(const TextureViewDesc& UAVDesc, D3D12_UNORDERED_ACCESS_VIEW_DESC &D3D12UAVDesc); +// clang-format on -void BufferViewDesc_to_D3D12_SRV_DESC(const BufferDesc &BuffDesc, const BufferViewDesc& SRVDesc, D3D12_SHADER_RESOURCE_VIEW_DESC &D3D12SRVDesc); -void BufferViewDesc_to_D3D12_UAV_DESC(const BufferDesc &BuffDesc, const BufferViewDesc& UAVDesc, D3D12_UNORDERED_ACCESS_VIEW_DESC &D3D12UAVDesc); +void BufferViewDesc_to_D3D12_SRV_DESC(const BufferDesc& BuffDesc, + const BufferViewDesc& SRVDesc, + D3D12_SHADER_RESOURCE_VIEW_DESC& D3D12SRVDesc); +void BufferViewDesc_to_D3D12_UAV_DESC(const BufferDesc& BuffDesc, + const BufferViewDesc& UAVDesc, + D3D12_UNORDERED_ACCESS_VIEW_DESC& D3D12UAVDesc); D3D12_STATIC_BORDER_COLOR BorderColorToD3D12StaticBorderColor(const Float32 BorderColor[]); -D3D12_RESOURCE_STATES ResourceStateFlagsToD3D12ResourceStates(RESOURCE_STATE StateFlags); -RESOURCE_STATE D3D12ResourceStatesToResourceStateFlags(D3D12_RESOURCE_STATES StateFlags); +D3D12_RESOURCE_STATES ResourceStateFlagsToD3D12ResourceStates(RESOURCE_STATE StateFlags); +RESOURCE_STATE D3D12ResourceStatesToResourceStateFlags(D3D12_RESOURCE_STATES StateFlags); -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/D3D12TypeDefinitions.h b/Graphics/GraphicsEngineD3D12/include/D3D12TypeDefinitions.h index 1d0af1da..d4c5be96 100644 --- a/Graphics/GraphicsEngineD3D12/include/D3D12TypeDefinitions.h +++ b/Graphics/GraphicsEngineD3D12/include/D3D12TypeDefinitions.h @@ -27,55 +27,55 @@ /// Definitions of D3D12 types // Filters -#define D3D_FILTER_MIN_MAG_MIP_POINT D3D12_FILTER_MIN_MAG_MIP_POINT -#define D3D_FILTER_MIN_MAG_POINT_MIP_LINEAR D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR -#define D3D_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT D3D12_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT -#define D3D_FILTER_MIN_POINT_MAG_MIP_LINEAR D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR -#define D3D_FILTER_MIN_LINEAR_MAG_MIP_POINT D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT -#define D3D_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR -#define D3D_FILTER_MIN_MAG_LINEAR_MIP_POINT D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT -#define D3D_FILTER_MIN_MAG_MIP_LINEAR D3D12_FILTER_MIN_MAG_MIP_LINEAR -#define D3D_FILTER_ANISOTROPIC D3D12_FILTER_ANISOTROPIC - -#define D3D_FILTER_COMPARISON_MIN_MAG_MIP_POINT D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT -#define D3D_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR D3D12_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR -#define D3D_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT D3D12_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT -#define D3D_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR D3D12_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR -#define D3D_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT -#define D3D_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR -#define D3D_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT -#define D3D_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR -#define D3D_FILTER_COMPARISON_ANISOTROPIC D3D12_FILTER_COMPARISON_ANISOTROPIC - -#define D3D_FILTER_MINIMUM_MIN_MAG_MIP_POINT D3D12_FILTER_MINIMUM_MIN_MAG_MIP_POINT -#define D3D_FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR D3D12_FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR -#define D3D_FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT D3D12_FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT -#define D3D_FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR D3D12_FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR -#define D3D_FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT -#define D3D_FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR -#define D3D_FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT D3D12_FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT -#define D3D_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR D3D12_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR -#define D3D_FILTER_MINIMUM_ANISOTROPIC D3D12_FILTER_MINIMUM_ANISOTROPIC - -#define D3D_FILTER_MAXIMUM_MIN_MAG_MIP_POINT D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_POINT -#define D3D_FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR D3D12_FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR -#define D3D_FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT -#define D3D_FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR -#define D3D_FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT -#define D3D_FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR -#define D3D_FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT D3D12_FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT -#define D3D_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR -#define D3D_FILTER_MAXIMUM_ANISOTROPIC D3D12_FILTER_MAXIMUM_ANISOTROPIC +#define D3D_FILTER_MIN_MAG_MIP_POINT D3D12_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MIN_MAG_POINT_MIP_LINEAR D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR +#define D3D_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT D3D12_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT +#define D3D_FILTER_MIN_POINT_MAG_MIP_LINEAR D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR +#define D3D_FILTER_MIN_LINEAR_MAG_MIP_POINT D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT +#define D3D_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR +#define D3D_FILTER_MIN_MAG_LINEAR_MIP_POINT D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT +#define D3D_FILTER_MIN_MAG_MIP_LINEAR D3D12_FILTER_MIN_MAG_MIP_LINEAR +#define D3D_FILTER_ANISOTROPIC D3D12_FILTER_ANISOTROPIC + +#define D3D_FILTER_COMPARISON_MIN_MAG_MIP_POINT D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT +#define D3D_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR D3D12_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR +#define D3D_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT D3D12_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT +#define D3D_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR D3D12_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR +#define D3D_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT +#define D3D_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR +#define D3D_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT +#define D3D_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR +#define D3D_FILTER_COMPARISON_ANISOTROPIC D3D12_FILTER_COMPARISON_ANISOTROPIC + +#define D3D_FILTER_MINIMUM_MIN_MAG_MIP_POINT D3D12_FILTER_MINIMUM_MIN_MAG_MIP_POINT +#define D3D_FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR D3D12_FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR +#define D3D_FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT D3D12_FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT +#define D3D_FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR D3D12_FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR +#define D3D_FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT +#define D3D_FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR +#define D3D_FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT D3D12_FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT +#define D3D_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR D3D12_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR +#define D3D_FILTER_MINIMUM_ANISOTROPIC D3D12_FILTER_MINIMUM_ANISOTROPIC + +#define D3D_FILTER_MAXIMUM_MIN_MAG_MIP_POINT D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_POINT +#define D3D_FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR D3D12_FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR +#define D3D_FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT +#define D3D_FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR +#define D3D_FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT +#define D3D_FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR +#define D3D_FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT D3D12_FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT +#define D3D_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR +#define D3D_FILTER_MAXIMUM_ANISOTROPIC D3D12_FILTER_MAXIMUM_ANISOTROPIC // Comparison functions -#define D3D_COMPARISON_FUNC_NEVER D3D12_COMPARISON_FUNC_NEVER -#define D3D_COMPARISON_FUNC_LESS D3D12_COMPARISON_FUNC_LESS -#define D3D_COMPARISON_FUNC_EQUAL D3D12_COMPARISON_FUNC_EQUAL -#define D3D_COMPARISON_FUNC_LESS_EQUAL D3D12_COMPARISON_FUNC_LESS_EQUAL -#define D3D_COMPARISON_FUNC_GREATER D3D12_COMPARISON_FUNC_GREATER -#define D3D_COMPARISON_FUNC_NOT_EQUAL D3D12_COMPARISON_FUNC_NOT_EQUAL -#define D3D_COMPARISON_FUNC_GREATER_EQUAL D3D12_COMPARISON_FUNC_GREATER_EQUAL -#define D3D_COMPARISON_FUNC_ALWAYS D3D12_COMPARISON_FUNC_ALWAYS +#define D3D_COMPARISON_FUNC_NEVER D3D12_COMPARISON_FUNC_NEVER +#define D3D_COMPARISON_FUNC_LESS D3D12_COMPARISON_FUNC_LESS +#define D3D_COMPARISON_FUNC_EQUAL D3D12_COMPARISON_FUNC_EQUAL +#define D3D_COMPARISON_FUNC_LESS_EQUAL D3D12_COMPARISON_FUNC_LESS_EQUAL +#define D3D_COMPARISON_FUNC_GREATER D3D12_COMPARISON_FUNC_GREATER +#define D3D_COMPARISON_FUNC_NOT_EQUAL D3D12_COMPARISON_FUNC_NOT_EQUAL +#define D3D_COMPARISON_FUNC_GREATER_EQUAL D3D12_COMPARISON_FUNC_GREATER_EQUAL +#define D3D_COMPARISON_FUNC_ALWAYS D3D12_COMPARISON_FUNC_ALWAYS // Stencil operations #define D3D_STENCIL_OP_KEEP D3D12_STENCIL_OP_KEEP @@ -88,8 +88,8 @@ #define D3D_STENCIL_OP_DECR D3D12_STENCIL_OP_DECR // Depth write masks -#define D3D_DEPTH_WRITE_MASK_ALL D3D12_DEPTH_WRITE_MASK_ALL -#define D3D_DEPTH_WRITE_MASK_ZERO D3D12_DEPTH_WRITE_MASK_ZERO +#define D3D_DEPTH_WRITE_MASK_ALL D3D12_DEPTH_WRITE_MASK_ALL +#define D3D_DEPTH_WRITE_MASK_ZERO D3D12_DEPTH_WRITE_MASK_ZERO // Cull modes #define D3D_CULL_MODE_NONE D3D12_CULL_MODE_NONE @@ -101,23 +101,23 @@ #define D3D_FILL_MODE_SOLID D3D12_FILL_MODE_SOLID // Blend sources -#define D3D_BLEND_ZERO D3D12_BLEND_ZERO -#define D3D_BLEND_ONE D3D12_BLEND_ONE -#define D3D_BLEND_SRC_COLOR D3D12_BLEND_SRC_COLOR -#define D3D_BLEND_INV_SRC_COLOR D3D12_BLEND_INV_SRC_COLOR -#define D3D_BLEND_SRC_ALPHA D3D12_BLEND_SRC_ALPHA -#define D3D_BLEND_INV_SRC_ALPHA D3D12_BLEND_INV_SRC_ALPHA -#define D3D_BLEND_DEST_ALPHA D3D12_BLEND_DEST_ALPHA -#define D3D_BLEND_INV_DEST_ALPHA D3D12_BLEND_INV_DEST_ALPHA -#define D3D_BLEND_DEST_COLOR D3D12_BLEND_DEST_COLOR -#define D3D_BLEND_INV_DEST_COLOR D3D12_BLEND_INV_DEST_COLOR -#define D3D_BLEND_SRC_ALPHA_SAT D3D12_BLEND_SRC_ALPHA_SAT -#define D3D_BLEND_BLEND_FACTOR D3D12_BLEND_BLEND_FACTOR -#define D3D_BLEND_INV_BLEND_FACTOR D3D12_BLEND_INV_BLEND_FACTOR -#define D3D_BLEND_SRC1_COLOR D3D12_BLEND_SRC1_COLOR -#define D3D_BLEND_INV_SRC1_COLOR D3D12_BLEND_INV_SRC1_COLOR -#define D3D_BLEND_SRC1_ALPHA D3D12_BLEND_SRC1_ALPHA -#define D3D_BLEND_INV_SRC1_ALPHA D3D12_BLEND_INV_SRC1_ALPHA +#define D3D_BLEND_ZERO D3D12_BLEND_ZERO +#define D3D_BLEND_ONE D3D12_BLEND_ONE +#define D3D_BLEND_SRC_COLOR D3D12_BLEND_SRC_COLOR +#define D3D_BLEND_INV_SRC_COLOR D3D12_BLEND_INV_SRC_COLOR +#define D3D_BLEND_SRC_ALPHA D3D12_BLEND_SRC_ALPHA +#define D3D_BLEND_INV_SRC_ALPHA D3D12_BLEND_INV_SRC_ALPHA +#define D3D_BLEND_DEST_ALPHA D3D12_BLEND_DEST_ALPHA +#define D3D_BLEND_INV_DEST_ALPHA D3D12_BLEND_INV_DEST_ALPHA +#define D3D_BLEND_DEST_COLOR D3D12_BLEND_DEST_COLOR +#define D3D_BLEND_INV_DEST_COLOR D3D12_BLEND_INV_DEST_COLOR +#define D3D_BLEND_SRC_ALPHA_SAT D3D12_BLEND_SRC_ALPHA_SAT +#define D3D_BLEND_BLEND_FACTOR D3D12_BLEND_BLEND_FACTOR +#define D3D_BLEND_INV_BLEND_FACTOR D3D12_BLEND_INV_BLEND_FACTOR +#define D3D_BLEND_SRC1_COLOR D3D12_BLEND_SRC1_COLOR +#define D3D_BLEND_INV_SRC1_COLOR D3D12_BLEND_INV_SRC1_COLOR +#define D3D_BLEND_SRC1_ALPHA D3D12_BLEND_SRC1_ALPHA +#define D3D_BLEND_INV_SRC1_ALPHA D3D12_BLEND_INV_SRC1_ALPHA // Blend operations #define D3D_BLEND_OP_ADD D3D12_BLEND_OP_ADD @@ -127,10 +127,10 @@ #define D3D_BLEND_OP_MAX D3D12_BLEND_OP_MAX // Color masks -#define D3D_COLOR_WRITE_ENABLE_RED D3D12_COLOR_WRITE_ENABLE_RED -#define D3D_COLOR_WRITE_ENABLE_GREEN D3D12_COLOR_WRITE_ENABLE_GREEN -#define D3D_COLOR_WRITE_ENABLE_BLUE D3D12_COLOR_WRITE_ENABLE_BLUE -#define D3D_COLOR_WRITE_ENABLE_ALPHA D3D12_COLOR_WRITE_ENABLE_ALPHA +#define D3D_COLOR_WRITE_ENABLE_RED D3D12_COLOR_WRITE_ENABLE_RED +#define D3D_COLOR_WRITE_ENABLE_GREEN D3D12_COLOR_WRITE_ENABLE_GREEN +#define D3D_COLOR_WRITE_ENABLE_BLUE D3D12_COLOR_WRITE_ENABLE_BLUE +#define D3D_COLOR_WRITE_ENABLE_ALPHA D3D12_COLOR_WRITE_ENABLE_ALPHA // Input classification #define D3D_INPUT_CLASSIFICATION_PER_VERTEX_DATA D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA @@ -144,48 +144,48 @@ #define D3D_TEXTURE_ADDRESS_MIRROR_ONCE D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE // SRV Dimensions -#define D3D_SRV_DIMENSION_UNKNOWN D3D12_SRV_DIMENSION_UNKNOWN -#define D3D_SRV_DIMENSION_BUFFER D3D12_SRV_DIMENSION_BUFFER -#define D3D_SRV_DIMENSION_TEXTURE1D D3D12_SRV_DIMENSION_TEXTURE1D -#define D3D_SRV_DIMENSION_TEXTURE1DARRAY D3D12_SRV_DIMENSION_TEXTURE1DARRAY -#define D3D_SRV_DIMENSION_TEXTURE2D D3D12_SRV_DIMENSION_TEXTURE2D -#define D3D_SRV_DIMENSION_TEXTURE2DARRAY D3D12_SRV_DIMENSION_TEXTURE2DARRAY -#define D3D_SRV_DIMENSION_TEXTURE2DMS D3D12_SRV_DIMENSION_TEXTURE2DMS -#define D3D_SRV_DIMENSION_TEXTURE2DMSARRAY D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY -#define D3D_SRV_DIMENSION_TEXTURE3D D3D12_SRV_DIMENSION_TEXTURE3D -#define D3D_SRV_DIMENSION_TEXTURECUBE D3D12_SRV_DIMENSION_TEXTURECUBE -#define D3D_SRV_DIMENSION_TEXTURECUBEARRAY D3D12_SRV_DIMENSION_TEXTURECUBEARRAY - -// RTV Dimensions -#define D3D_RTV_DIMENSION_UNKNOWN D3D12_RTV_DIMENSION_UNKNOWN -#define D3D_RTV_DIMENSION_BUFFER D3D12_RTV_DIMENSION_BUFFER -#define D3D_RTV_DIMENSION_TEXTURE1D D3D12_RTV_DIMENSION_TEXTURE1D -#define D3D_RTV_DIMENSION_TEXTURE1DARRAY D3D12_RTV_DIMENSION_TEXTURE1DARRAY -#define D3D_RTV_DIMENSION_TEXTURE2D D3D12_RTV_DIMENSION_TEXTURE2D -#define D3D_RTV_DIMENSION_TEXTURE2DARRAY D3D12_RTV_DIMENSION_TEXTURE2DARRAY -#define D3D_RTV_DIMENSION_TEXTURE2DMS D3D12_RTV_DIMENSION_TEXTURE2DMS -#define D3D_RTV_DIMENSION_TEXTURE2DMSARRAY D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY -#define D3D_RTV_DIMENSION_TEXTURE3D D3D12_RTV_DIMENSION_TEXTURE3D - - -// DSV Dimensions -#define D3D_DSV_DIMENSION_UNKNOWN D3D12_DSV_DIMENSION_UNKNOWN -#define D3D_DSV_DIMENSION_TEXTURE1D D3D12_DSV_DIMENSION_TEXTURE1D -#define D3D_DSV_DIMENSION_TEXTURE1DARRAY D3D12_DSV_DIMENSION_TEXTURE1DARRAY -#define D3D_DSV_DIMENSION_TEXTURE2D D3D12_DSV_DIMENSION_TEXTURE2D -#define D3D_DSV_DIMENSION_TEXTURE2DARRAY D3D12_DSV_DIMENSION_TEXTURE2DARRAY -#define D3D_DSV_DIMENSION_TEXTURE2DMS D3D12_DSV_DIMENSION_TEXTURE2DMS -#define D3D_DSV_DIMENSION_TEXTURE2DMSARRAY D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY +#define D3D_SRV_DIMENSION_UNKNOWN D3D12_SRV_DIMENSION_UNKNOWN +#define D3D_SRV_DIMENSION_BUFFER D3D12_SRV_DIMENSION_BUFFER +#define D3D_SRV_DIMENSION_TEXTURE1D D3D12_SRV_DIMENSION_TEXTURE1D +#define D3D_SRV_DIMENSION_TEXTURE1DARRAY D3D12_SRV_DIMENSION_TEXTURE1DARRAY +#define D3D_SRV_DIMENSION_TEXTURE2D D3D12_SRV_DIMENSION_TEXTURE2D +#define D3D_SRV_DIMENSION_TEXTURE2DARRAY D3D12_SRV_DIMENSION_TEXTURE2DARRAY +#define D3D_SRV_DIMENSION_TEXTURE2DMS D3D12_SRV_DIMENSION_TEXTURE2DMS +#define D3D_SRV_DIMENSION_TEXTURE2DMSARRAY D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY +#define D3D_SRV_DIMENSION_TEXTURE3D D3D12_SRV_DIMENSION_TEXTURE3D +#define D3D_SRV_DIMENSION_TEXTURECUBE D3D12_SRV_DIMENSION_TEXTURECUBE +#define D3D_SRV_DIMENSION_TEXTURECUBEARRAY D3D12_SRV_DIMENSION_TEXTURECUBEARRAY + +// RTV Dimensions +#define D3D_RTV_DIMENSION_UNKNOWN D3D12_RTV_DIMENSION_UNKNOWN +#define D3D_RTV_DIMENSION_BUFFER D3D12_RTV_DIMENSION_BUFFER +#define D3D_RTV_DIMENSION_TEXTURE1D D3D12_RTV_DIMENSION_TEXTURE1D +#define D3D_RTV_DIMENSION_TEXTURE1DARRAY D3D12_RTV_DIMENSION_TEXTURE1DARRAY +#define D3D_RTV_DIMENSION_TEXTURE2D D3D12_RTV_DIMENSION_TEXTURE2D +#define D3D_RTV_DIMENSION_TEXTURE2DARRAY D3D12_RTV_DIMENSION_TEXTURE2DARRAY +#define D3D_RTV_DIMENSION_TEXTURE2DMS D3D12_RTV_DIMENSION_TEXTURE2DMS +#define D3D_RTV_DIMENSION_TEXTURE2DMSARRAY D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY +#define D3D_RTV_DIMENSION_TEXTURE3D D3D12_RTV_DIMENSION_TEXTURE3D + + +// DSV Dimensions +#define D3D_DSV_DIMENSION_UNKNOWN D3D12_DSV_DIMENSION_UNKNOWN +#define D3D_DSV_DIMENSION_TEXTURE1D D3D12_DSV_DIMENSION_TEXTURE1D +#define D3D_DSV_DIMENSION_TEXTURE1DARRAY D3D12_DSV_DIMENSION_TEXTURE1DARRAY +#define D3D_DSV_DIMENSION_TEXTURE2D D3D12_DSV_DIMENSION_TEXTURE2D +#define D3D_DSV_DIMENSION_TEXTURE2DARRAY D3D12_DSV_DIMENSION_TEXTURE2DARRAY +#define D3D_DSV_DIMENSION_TEXTURE2DMS D3D12_DSV_DIMENSION_TEXTURE2DMS +#define D3D_DSV_DIMENSION_TEXTURE2DMSARRAY D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY // UAV Dimensions -#define D3D_UAV_DIMENSION_UNKNOWN D3D12_UAV_DIMENSION_UNKNOWN -#define D3D_UAV_DIMENSION_BUFFER D3D12_UAV_DIMENSION_BUFFER -#define D3D_UAV_DIMENSION_TEXTURE1D D3D12_UAV_DIMENSION_TEXTURE1D -#define D3D_UAV_DIMENSION_TEXTURE1DARRAY D3D12_UAV_DIMENSION_TEXTURE1DARRAY -#define D3D_UAV_DIMENSION_TEXTURE2D D3D12_UAV_DIMENSION_TEXTURE2D -#define D3D_UAV_DIMENSION_TEXTURE2DARRAY D3D12_UAV_DIMENSION_TEXTURE2DARRAY -#define D3D_UAV_DIMENSION_TEXTURE3D D3D12_UAV_DIMENSION_TEXTURE3D +#define D3D_UAV_DIMENSION_UNKNOWN D3D12_UAV_DIMENSION_UNKNOWN +#define D3D_UAV_DIMENSION_BUFFER D3D12_UAV_DIMENSION_BUFFER +#define D3D_UAV_DIMENSION_TEXTURE1D D3D12_UAV_DIMENSION_TEXTURE1D +#define D3D_UAV_DIMENSION_TEXTURE1DARRAY D3D12_UAV_DIMENSION_TEXTURE1DARRAY +#define D3D_UAV_DIMENSION_TEXTURE2D D3D12_UAV_DIMENSION_TEXTURE2D +#define D3D_UAV_DIMENSION_TEXTURE2DARRAY D3D12_UAV_DIMENSION_TEXTURE2DARRAY +#define D3D_UAV_DIMENSION_TEXTURE3D D3D12_UAV_DIMENSION_TEXTURE3D // Buffer flags -#define D3D_BUFFER_UAV_FLAG_RAW D3D12_BUFFER_UAV_FLAG_RAW -#define D3D_BUFFER_UAV_FLAG_NONE D3D12_BUFFER_UAV_FLAG_NONE \ No newline at end of file +#define D3D_BUFFER_UAV_FLAG_RAW D3D12_BUFFER_UAV_FLAG_RAW +#define D3D_BUFFER_UAV_FLAG_NONE D3D12_BUFFER_UAV_FLAG_NONE diff --git a/Graphics/GraphicsEngineD3D12/include/D3D12Utils.h b/Graphics/GraphicsEngineD3D12/include/D3D12Utils.h index ab30281b..4985d4d4 100644 --- a/Graphics/GraphicsEngineD3D12/include/D3D12Utils.h +++ b/Graphics/GraphicsEngineD3D12/include/D3D12Utils.h @@ -26,5 +26,5 @@ #include "BasicTypes.h" namespace Diligent { - const Char* GetD3D12DescriptorHeapTypeLiteralName(D3D12_DESCRIPTOR_HEAP_TYPE Type); +const Char* GetD3D12DescriptorHeapTypeLiteralName(D3D12_DESCRIPTOR_HEAP_TYPE Type); } diff --git a/Graphics/GraphicsEngineD3D12/include/DescriptorHeap.h b/Graphics/GraphicsEngineD3D12/include/DescriptorHeap.h index 2f992c9b..51df3573 100644 --- a/Graphics/GraphicsEngineD3D12/include/DescriptorHeap.h +++ b/Graphics/GraphicsEngineD3D12/include/DescriptorHeap.h @@ -21,7 +21,7 @@ * of the possibility of such damages. */ -// Descriptor heap management utilities. +// Descriptor heap management utilities. // See http://diligentgraphics.com/diligent-engine/architecture/d3d12/managing-descriptor-heaps/ for details #pragma once @@ -46,14 +46,14 @@ class IDescriptorAllocator { public: // Allocate Count descriptors - virtual DescriptorHeapAllocation Allocate( uint32_t Count ) = 0; - virtual void Free(DescriptorHeapAllocation&& Allocation, Uint64 CmdQueueMask) = 0; - virtual Uint32 GetDescriptorSize()const = 0; + virtual DescriptorHeapAllocation Allocate(uint32_t Count) = 0; + virtual void Free(DescriptorHeapAllocation&& Allocation, Uint64 CmdQueueMask) = 0; + virtual Uint32 GetDescriptorSize() const = 0; }; // The class represents descriptor heap allocation (continuous descriptor range in a descriptor heap) -// +// // m_FirstCpuHandle // | // | ~ ~ ~ ~ ~ X X X X X X X ~ ~ ~ ~ ~ ~ | D3D12 Descriptor Heap @@ -64,37 +64,42 @@ class DescriptorHeapAllocation { public: // Creates null allocation - DescriptorHeapAllocation() noexcept : + DescriptorHeapAllocation() noexcept : + // clang-format off m_NumHandles {1 }, // One null descriptor handle m_pDescriptorHeap {nullptr}, m_DescriptorSize {0 } - { - m_FirstCpuHandle.ptr = 0; - m_FirstGpuHandle.ptr = 0; - } - - // Initializes non-null allocation - DescriptorHeapAllocation(IDescriptorAllocator& Allocator, - ID3D12DescriptorHeap* pHeap, - D3D12_CPU_DESCRIPTOR_HANDLE CpuHandle, - D3D12_GPU_DESCRIPTOR_HANDLE GpuHandle, - Uint32 NHandles, - Uint16 AllocationManagerId)noexcept : + // clang-format on + { + m_FirstCpuHandle.ptr = 0; + m_FirstGpuHandle.ptr = 0; + } + + // Initializes non-null allocation + DescriptorHeapAllocation(IDescriptorAllocator& Allocator, + ID3D12DescriptorHeap* pHeap, + D3D12_CPU_DESCRIPTOR_HANDLE CpuHandle, + D3D12_GPU_DESCRIPTOR_HANDLE GpuHandle, + Uint32 NHandles, + Uint16 AllocationManagerId) noexcept : + // clang-format off m_FirstCpuHandle {CpuHandle }, m_FirstGpuHandle {GpuHandle }, m_pAllocator {&Allocator }, m_NumHandles {NHandles }, m_pDescriptorHeap {pHeap }, m_AllocationManagerId {AllocationManagerId} - { + // clang-format on + { VERIFY_EXPR(m_pAllocator != nullptr && m_pDescriptorHeap != nullptr); auto DescriptorSize = m_pAllocator->GetDescriptorSize(); VERIFY(DescriptorSize < std::numeric_limits::max(), "DescriptorSize exceeds allowed limit"); - m_DescriptorSize = static_cast( DescriptorSize ); - } + m_DescriptorSize = static_cast(DescriptorSize); + } // Move constructor (copy is not allowed) - DescriptorHeapAllocation(DescriptorHeapAllocation&& Allocation)noexcept : + DescriptorHeapAllocation(DescriptorHeapAllocation&& Allocation) noexcept : + // clang-format off m_FirstCpuHandle {std::move(Allocation.m_FirstCpuHandle) }, m_FirstGpuHandle {std::move(Allocation.m_FirstGpuHandle) }, m_NumHandles {std::move(Allocation.m_NumHandles) }, @@ -102,15 +107,16 @@ public: m_AllocationManagerId {std::move(Allocation.m_AllocationManagerId)}, m_pDescriptorHeap {std::move(Allocation.m_pDescriptorHeap) }, m_DescriptorSize {std::move(Allocation.m_DescriptorSize) } + // clang-format on { Allocation.Reset(); } // Move assignment (assignment is not allowed) - DescriptorHeapAllocation& operator = (DescriptorHeapAllocation&& Allocation)noexcept - { - m_FirstCpuHandle = std::move(Allocation.m_FirstCpuHandle); - m_FirstGpuHandle = std::move(Allocation.m_FirstGpuHandle); + DescriptorHeapAllocation& operator=(DescriptorHeapAllocation&& Allocation) noexcept + { + m_FirstCpuHandle = std::move(Allocation.m_FirstCpuHandle); + m_FirstGpuHandle = std::move(Allocation.m_FirstGpuHandle); m_NumHandles = std::move(Allocation.m_NumHandles); m_pAllocator = std::move(Allocation.m_pAllocator); m_AllocationManagerId = std::move(Allocation.m_AllocationManagerId); @@ -133,35 +139,36 @@ public: m_DescriptorSize = 0; } - // No copies, only moves are allowed - DescriptorHeapAllocation (const DescriptorHeapAllocation&) = delete; - DescriptorHeapAllocation& operator= (const DescriptorHeapAllocation&) = delete; + // clang-format off + DescriptorHeapAllocation (const DescriptorHeapAllocation&) = delete; + DescriptorHeapAllocation& operator=(const DescriptorHeapAllocation&) = delete; + // clang-format on // Destructor automatically releases this allocation through the allocator ~DescriptorHeapAllocation() { - if(!IsNull() && m_pAllocator) + if (!IsNull() && m_pAllocator) m_pAllocator->Free(std::move(*this), ~Uint64{0}); // Allocation must have been disposed by the allocator VERIFY(IsNull(), "Non-null descriptor is being destroyed"); } // Returns CPU descriptor handle at the specified offset - D3D12_CPU_DESCRIPTOR_HANDLE GetCpuHandle(Uint32 Offset = 0) const - { - VERIFY_EXPR(Offset >= 0 && Offset < m_NumHandles); + D3D12_CPU_DESCRIPTOR_HANDLE GetCpuHandle(Uint32 Offset = 0) const + { + VERIFY_EXPR(Offset >= 0 && Offset < m_NumHandles); - D3D12_CPU_DESCRIPTOR_HANDLE CPUHandle = m_FirstCpuHandle; + D3D12_CPU_DESCRIPTOR_HANDLE CPUHandle = m_FirstCpuHandle; CPUHandle.ptr += m_DescriptorSize * Offset; return CPUHandle; } // Returns GPU descriptor handle at the specified offset - D3D12_GPU_DESCRIPTOR_HANDLE GetGpuHandle(Uint32 Offset = 0) const - { - VERIFY_EXPR(Offset >= 0 && Offset < m_NumHandles); + D3D12_GPU_DESCRIPTOR_HANDLE GetGpuHandle(Uint32 Offset = 0) const + { + VERIFY_EXPR(Offset >= 0 && Offset < m_NumHandles); D3D12_GPU_DESCRIPTOR_HANDLE GPUHandle = m_FirstGpuHandle; GPUHandle.ptr += m_DescriptorSize * Offset; @@ -169,51 +176,52 @@ public: } // Returns pointer to D3D12 descriptor heap that contains this allocation - ID3D12DescriptorHeap* GetDescriptorHeap(){return m_pDescriptorHeap;} + ID3D12DescriptorHeap* GetDescriptorHeap() { return m_pDescriptorHeap; } + - + // clang-format off size_t GetNumHandles() const { return m_NumHandles; } bool IsNull() const { return m_FirstCpuHandle.ptr == 0; } bool IsShaderVisible() const { return m_FirstGpuHandle.ptr != 0; } size_t GetAllocationManagerId() const { return m_AllocationManagerId; } UINT GetDescriptorSize() const { return m_DescriptorSize; } + // clang-format on private: - // First CPU descriptor handle in this allocation - D3D12_CPU_DESCRIPTOR_HANDLE m_FirstCpuHandle = {0}; - + D3D12_CPU_DESCRIPTOR_HANDLE m_FirstCpuHandle = {0}; + // First GPU descriptor handle in this allocation - D3D12_GPU_DESCRIPTOR_HANDLE m_FirstGpuHandle = {0}; + D3D12_GPU_DESCRIPTOR_HANDLE m_FirstGpuHandle = {0}; // Keep strong reference to the parent heap to make sure it is alive while allocation is alive - TOO EXPENSIVE //RefCntAutoPtr m_pAllocator; - + // Pointer to the descriptor heap allocator that created this allocation IDescriptorAllocator* m_pAllocator = nullptr; // Pointer to the D3D12 descriptor heap that contains descriptors in this allocation ID3D12DescriptorHeap* m_pDescriptorHeap = nullptr; - + // Number of descriptors in the allocation Uint32 m_NumHandles = 0; - // Allocation manager ID. One allocator may support several + // Allocation manager ID. One allocator may support several // allocation managers. This field is required to identify // the manager within the allocator that was used to create // this allocation Uint16 m_AllocationManagerId = static_cast(-1); - - // Descriptor size + + // Descriptor size Uint16 m_DescriptorSize = 0; }; -// The class performs suballocations within one D3D12 descriptor heap. +// The class performs suballocations within one D3D12 descriptor heap. // It uses VariableSizeAllocationsManager to manage free space in the heap // // | X X X X O O O X X O O X O O O O | D3D12 descriptor heap -// +// // X - used descriptor // O - available descriptor // @@ -221,7 +229,7 @@ class DescriptorHeapAllocationManager { public: // Creates a new D3D12 descriptor heap - DescriptorHeapAllocationManager(IMemoryAllocator& Allocator, + DescriptorHeapAllocationManager(IMemoryAllocator& Allocator, RenderDeviceD3D12Impl& DeviceD3D12Impl, IDescriptorAllocator& ParentAllocator, size_t ThisManagerId, @@ -229,17 +237,18 @@ public: // Uses subrange of descriptors in the existing D3D12 descriptor heap // that starts at offset FirstDescriptor and uses NumDescriptors descriptors - DescriptorHeapAllocationManager(IMemoryAllocator& Allocator, - RenderDeviceD3D12Impl& DeviceD3D12Impl, - IDescriptorAllocator& ParentAllocator, - size_t ThisManagerId, - ID3D12DescriptorHeap* pd3d12DescriptorHeap, - Uint32 FirstDescriptor, - Uint32 NumDescriptors); + DescriptorHeapAllocationManager(IMemoryAllocator& Allocator, + RenderDeviceD3D12Impl& DeviceD3D12Impl, + IDescriptorAllocator& ParentAllocator, + size_t ThisManagerId, + ID3D12DescriptorHeap* pd3d12DescriptorHeap, + Uint32 FirstDescriptor, + Uint32 NumDescriptors); // = default causes compiler error when instantiating std::vector::emplace_back() in Visual Studio 2015 (Version 14.0.23107.0 D14REL) - DescriptorHeapAllocationManager(DescriptorHeapAllocationManager&& rhs)noexcept : + DescriptorHeapAllocationManager(DescriptorHeapAllocationManager&& rhs) noexcept : + // clang-format off m_ParentAllocator {rhs.m_ParentAllocator }, m_DeviceD3D12Impl {rhs.m_DeviceD3D12Impl }, m_ThisManagerId {rhs.m_ThisManagerId }, @@ -253,10 +262,11 @@ public: //m_FreeBlockManagerMutex (std::move(rhs.m_FreeBlockManagerMutex)) m_FreeBlockManager {std::move(rhs.m_FreeBlockManager) }, m_pd3d12DescriptorHeap {std::move(rhs.m_pd3d12DescriptorHeap)} + // clang-format on { rhs.m_NumDescriptorsInAllocation = 0; // Must be set to zero so that debug check in dtor passes rhs.m_ThisManagerId = static_cast(-1); - rhs.m_FirstCPUHandle.ptr = 0; + rhs.m_FirstCPUHandle.ptr = 0; rhs.m_FirstGPUHandle.ptr = 0; rhs.m_MaxAllocatedSize = 0; #ifdef DEVELOPMENT @@ -265,23 +275,30 @@ public: #endif } + // clang-format off // No copies or move-assignments DescriptorHeapAllocationManager& operator = (DescriptorHeapAllocationManager&&) = delete; DescriptorHeapAllocationManager (const DescriptorHeapAllocationManager&) = delete; DescriptorHeapAllocationManager& operator = (const DescriptorHeapAllocationManager&) = delete; + // clang-format on ~DescriptorHeapAllocationManager(); // Allocates Count descriptors - DescriptorHeapAllocation Allocate( uint32_t Count ); - void FreeAllocation(DescriptorHeapAllocation&& Allocation); + DescriptorHeapAllocation Allocate(uint32_t Count); + void FreeAllocation(DescriptorHeapAllocation&& Allocation); + // clang-format off size_t GetNumAvailableDescriptors()const { return m_FreeBlockManager.GetFreeSize(); } Uint32 GetMaxDescriptors() const { return m_NumDescriptorsInAllocation; } size_t GetMaxAllocatedSize() const { return m_MaxAllocatedSize; } + // clang-format on #ifdef DEVELOPMENT - int32_t DvpGetAllocationsCounter() const { return m_AllocationsCounter; } + int32_t DvpGetAllocationsCounter() const + { + return m_AllocationsCounter; + } #endif private: @@ -290,13 +307,13 @@ private: // External ID assigned to this descriptor allocations manager size_t m_ThisManagerId = static_cast(-1); - + // Heap description const D3D12_DESCRIPTOR_HEAP_DESC m_HeapDesc; const UINT m_DescriptorSize = 0; - // Number of descriptors in the allocation. + // Number of descriptors in the allocation. // If this manager was initialized as a subrange in the existing heap, // this value may be different from m_HeapDesc.NumDescriptors Uint32 m_NumDescriptorsInAllocation = 0; @@ -306,11 +323,11 @@ private: VariableSizeAllocationsManager m_FreeBlockManager; // Strong reference to D3D12 descriptor heap object - CComPtr m_pd3d12DescriptorHeap; - + CComPtr m_pd3d12DescriptorHeap; + // First CPU descriptor handle in the available descriptor range - D3D12_CPU_DESCRIPTOR_HANDLE m_FirstCPUHandle = {0}; - + D3D12_CPU_DESCRIPTOR_HANDLE m_FirstCPUHandle = {0}; + // First GPU descriptor handle in the available descriptor range D3D12_GPU_DESCRIPTOR_HANDLE m_FirstGPUHandle = {0}; @@ -333,8 +350,8 @@ private: // X - used descriptor m_AvailableHeaps = {1,2} // O - available descriptor // -// Allocation routine goes through the list of managers that have available descriptors and tries to process -// the request using every manager. If there are no available managers or no manager was able to handle the request, +// Allocation routine goes through the list of managers that have available descriptors and tries to process +// the request using every manager. If there are no available managers or no manager was able to handle the request, // the function creates a new descriptor heap manager and lets it handle the request // // Render device contains four CPUDescriptorHeap object instances (one for each D3D12 heap type). The heaps are accessed @@ -344,22 +361,24 @@ class CPUDescriptorHeap final : public IDescriptorAllocator { public: // Initializes the heap - CPUDescriptorHeap(IMemoryAllocator& Allocator, - RenderDeviceD3D12Impl& DeviceD3D12Impl, - Uint32 NumDescriptorsInHeap, - D3D12_DESCRIPTOR_HEAP_TYPE Type, + CPUDescriptorHeap(IMemoryAllocator& Allocator, + RenderDeviceD3D12Impl& DeviceD3D12Impl, + Uint32 NumDescriptorsInHeap, + D3D12_DESCRIPTOR_HEAP_TYPE Type, D3D12_DESCRIPTOR_HEAP_FLAGS Flags); + // clang-format off CPUDescriptorHeap (const CPUDescriptorHeap&) = delete; CPUDescriptorHeap (CPUDescriptorHeap&&) = delete; CPUDescriptorHeap& operator = (const CPUDescriptorHeap&) = delete; CPUDescriptorHeap& operator = (CPUDescriptorHeap&&) = delete; + // clang-format on ~CPUDescriptorHeap(); - virtual DescriptorHeapAllocation Allocate( uint32_t Count )override final; - virtual void Free(DescriptorHeapAllocation&& Allocation, Uint64 CmdQueueMask)override final; - virtual Uint32 GetDescriptorSize()const override final {return m_DescriptorSize;} + virtual DescriptorHeapAllocation Allocate(uint32_t Count) override final; + virtual void Free(DescriptorHeapAllocation&& Allocation, Uint64 CmdQueueMask) override final; + virtual Uint32 GetDescriptorSize() const override final { return m_DescriptorSize; } #ifdef DEVELOPMENT int32_t DvpGetTotalAllocationCount(); @@ -368,20 +387,20 @@ public: private: void FreeAllocation(DescriptorHeapAllocation&& Allocation); - IMemoryAllocator& m_MemAllocator; - RenderDeviceD3D12Impl& m_DeviceD3D12Impl; + IMemoryAllocator& m_MemAllocator; + RenderDeviceD3D12Impl& m_DeviceD3D12Impl; // Pool of descriptor heap managers std::mutex m_HeapPoolMutex; std::vector> m_HeapPool; // Indices of available descriptor heap managers - std::unordered_set, std::equal_to, STDAllocatorRawMem> m_AvailableHeaps; - + std::unordered_set, std::equal_to, STDAllocatorRawMem> m_AvailableHeaps; + D3D12_DESCRIPTOR_HEAP_DESC m_HeapDesc; - const UINT m_DescriptorSize = 0; + const UINT m_DescriptorSize = 0; // Maximum heap size during the application lifetime - for statistic purposes - Uint32 m_MaxSize = 0; + Uint32 m_MaxSize = 0; Uint32 m_CurrentSize = 0; }; @@ -392,7 +411,7 @@ private: // Space for dynamic resources is allocated in chunks, and then descriptors are suballocated within every // chunk. DynamicSuballocationsManager facilitates this process. // -// +// // static and mutable handles || dynamic space // || chunk 0 chunk 1 chunk 2 unused // | X O O X X O X O O O O X X X X O || | X X X O | | X X O O | | O O O O | O O O O || @@ -416,8 +435,8 @@ private: // | m_GPUDescriptorHeaps[SAMPLER] | X X O O X O X X X O O X O O O O || | X X O O | | X O O O | | O O O O | O O O O || | // | | // |_______________________________________________________________________________________________________________________________| -// -// ________________________________________________ ________________________________________________ +// +// ________________________________________________ ________________________________________________ // |Device Context 1 | |Device Context 2 | // | | | | // | m_DynamicGPUDescriptorAllocator[CBV_SRV_UAV] | | m_DynamicGPUDescriptorAllocator[CBV_SRV_UAV] | @@ -427,42 +446,44 @@ private: class GPUDescriptorHeap final : public IDescriptorAllocator { public: - GPUDescriptorHeap(IMemoryAllocator& Allocator, - RenderDeviceD3D12Impl& Device, - Uint32 NumDescriptorsInHeap, + GPUDescriptorHeap(IMemoryAllocator& Allocator, + RenderDeviceD3D12Impl& Device, + Uint32 NumDescriptorsInHeap, Uint32 NumDynamicDescriptors, - D3D12_DESCRIPTOR_HEAP_TYPE Type, + D3D12_DESCRIPTOR_HEAP_TYPE Type, D3D12_DESCRIPTOR_HEAP_FLAGS Flags); + // clang-format off GPUDescriptorHeap (const GPUDescriptorHeap&) = delete; GPUDescriptorHeap (GPUDescriptorHeap&&) = delete; GPUDescriptorHeap& operator = (const GPUDescriptorHeap&) = delete; GPUDescriptorHeap& operator = (GPUDescriptorHeap&&) = delete; + // clang-format on ~GPUDescriptorHeap(); - virtual DescriptorHeapAllocation Allocate( uint32_t Count )override final + virtual DescriptorHeapAllocation Allocate(uint32_t Count) override final { return m_HeapAllocationManager.Allocate(Count); } - virtual void Free(DescriptorHeapAllocation&& Allocation, Uint64 CmdQueueMask)override final; - virtual Uint32 GetDescriptorSize()const override final{return m_DescriptorSize;} + virtual void Free(DescriptorHeapAllocation&& Allocation, Uint64 CmdQueueMask) override final; + virtual Uint32 GetDescriptorSize() const override final { return m_DescriptorSize; } - DescriptorHeapAllocation AllocateDynamic( uint32_t Count ) + DescriptorHeapAllocation AllocateDynamic(uint32_t Count) { return m_DynamicAllocationsManager.Allocate(Count); } - const D3D12_DESCRIPTOR_HEAP_DESC& GetHeapDesc()const{return m_HeapDesc;} - Uint32 GetMaxStaticDescriptors() const { return m_HeapAllocationManager.GetMaxDescriptors(); } - Uint32 GetMaxDynamicDescriptors()const { return m_DynamicAllocationsManager.GetMaxDescriptors(); } + const D3D12_DESCRIPTOR_HEAP_DESC& GetHeapDesc() const { return m_HeapDesc; } + Uint32 GetMaxStaticDescriptors() const { return m_HeapAllocationManager.GetMaxDescriptors(); } + Uint32 GetMaxDynamicDescriptors() const { return m_DynamicAllocationsManager.GetMaxDescriptors(); } #ifdef DEVELOPMENT - int32_t DvpGetTotalAllocationCount()const + int32_t DvpGetTotalAllocationCount() const { - return m_HeapAllocationManager.DvpGetAllocationsCounter() + - m_DynamicAllocationsManager.DvpGetAllocationsCounter(); + return m_HeapAllocationManager.DvpGetAllocationsCounter() + + m_DynamicAllocationsManager.DvpGetAllocationsCounter(); } #endif @@ -470,13 +491,13 @@ protected: RenderDeviceD3D12Impl& m_DeviceD3D12Impl; const D3D12_DESCRIPTOR_HEAP_DESC m_HeapDesc; - CComPtr m_pd3d12DescriptorHeap; + CComPtr m_pd3d12DescriptorHeap; const UINT m_DescriptorSize; // Allocation manager for static/mutable part DescriptorHeapAllocationManager m_HeapAllocationManager; - + // Allocation manager for dynamic part DescriptorHeapAllocationManager m_DynamicAllocationsManager; }; @@ -487,7 +508,7 @@ protected: // At the end of the frame all allocations are disposed. // static and mutable handles || dynamic space -// || chunk 0 chunk 2 +// || chunk 0 chunk 2 // | || | X X X O | | O O O O | || GPU Descriptor Heap // | | // m_Suballocations[0] m_Suballocations[1] @@ -500,26 +521,28 @@ public: Uint32 DynamicChunkSize, String ManagerName); + // clang-format off DynamicSuballocationsManager (const DynamicSuballocationsManager&) = delete; DynamicSuballocationsManager (DynamicSuballocationsManager&&) = delete; DynamicSuballocationsManager& operator = (const DynamicSuballocationsManager&) = delete; DynamicSuballocationsManager& operator = (DynamicSuballocationsManager&&) = delete; + // clang-format on ~DynamicSuballocationsManager(); void ReleaseAllocations(Uint64 CmdQueueMask); - virtual DescriptorHeapAllocation Allocate(Uint32 Count)override final; - virtual void Free(DescriptorHeapAllocation&& Allocation, Uint64 CmdQueueMask)override final + virtual DescriptorHeapAllocation Allocate(Uint32 Count) override final; + virtual void Free(DescriptorHeapAllocation&& Allocation, Uint64 CmdQueueMask) override final { - // Do nothing. Dynamic allocations are not disposed individually, but as whole chunks + // Do nothing. Dynamic allocations are not disposed individually, but as whole chunks // at the end of the frame by ReleaseAllocations() Allocation.Reset(); } - virtual Uint32 GetDescriptorSize()const override final{return m_ParentGPUHeap.GetDescriptorSize();} + virtual Uint32 GetDescriptorSize() const override final { return m_ParentGPUHeap.GetDescriptorSize(); } - size_t GetSuballocationCount()const {return m_Suballocations.size();} + size_t GetSuballocationCount() const { return m_Suballocations.size(); } private: // Parent GPU descriptor heap that is used to allocate chunks @@ -528,10 +551,10 @@ private: // List of chunks allocated from the master GPU descriptor heap. All chunks are disposed at the end // of the frame - std::vector > m_Suballocations; + std::vector> m_Suballocations; - Uint32 m_CurrentSuballocationOffset = 0; - Uint32 m_DynamicChunkSize = 0; + Uint32 m_CurrentSuballocationOffset = 0; + Uint32 m_DynamicChunkSize = 0; Uint32 m_CurrDescriptorCount = 0; Uint32 m_PeakDescriptorCount = 0; @@ -539,4 +562,4 @@ private: Uint32 m_PeakSuballocationsTotalSize = 0; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/DeviceContextD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/DeviceContextD3D12Impl.h index 077fcd7c..00a7e5b4 100644 --- a/Graphics/GraphicsEngineD3D12/include/DeviceContextD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/DeviceContextD3D12Impl.h @@ -55,87 +55,90 @@ class DeviceContextD3D12Impl final : public DeviceContextNextGenBase; - DeviceContextD3D12Impl(IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pDevice, - bool bIsDeferred, - const EngineD3D12CreateInfo& EngineCI, - Uint32 ContextId, - Uint32 CommandQueueId); + DeviceContextD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl* pDevice, + bool bIsDeferred, + const EngineD3D12CreateInfo& EngineCI, + Uint32 ContextId, + Uint32 CommandQueueId); ~DeviceContextD3D12Impl(); - - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; + + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override final; /// Implementation of IDeviceContext::SetPipelineState() in Direct3D12 backend. - virtual void SetPipelineState(IPipelineState* pPipelineState)override final; + virtual void SetPipelineState(IPipelineState* pPipelineState) override final; /// Implementation of IDeviceContext::TransitionShaderResources() in Direct3D12 backend. - virtual void TransitionShaderResources(IPipelineState* pPipelineState, IShaderResourceBinding* pShaderResourceBinding)override final; + virtual void TransitionShaderResources(IPipelineState* pPipelineState, IShaderResourceBinding* pShaderResourceBinding) override final; /// Implementation of IDeviceContext::CommitShaderResources() in Direct3D12 backend. - virtual void CommitShaderResources(IShaderResourceBinding* pShaderResourceBinding, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)override final; + virtual void CommitShaderResources(IShaderResourceBinding* pShaderResourceBinding, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) override final; /// Implementation of IDeviceContext::SetStencilRef() in Direct3D12 backend. - virtual void SetStencilRef(Uint32 StencilRef)override final; + virtual void SetStencilRef(Uint32 StencilRef) override final; /// Implementation of IDeviceContext::SetBlendFactors() in Direct3D12 backend. - virtual void SetBlendFactors(const float* pBlendFactors = nullptr)override final; + virtual void SetBlendFactors(const float* pBlendFactors = nullptr) override final; /// Implementation of IDeviceContext::SetVertexBuffers() in Direct3D12 backend. - virtual void SetVertexBuffers( Uint32 StartSlot, - Uint32 NumBuffersSet, - IBuffer** ppBuffers, - Uint32* pOffsets, - RESOURCE_STATE_TRANSITION_MODE StateTransitionMode, - SET_VERTEX_BUFFERS_FLAGS Flags )override final; - + virtual void SetVertexBuffers(Uint32 StartSlot, + Uint32 NumBuffersSet, + IBuffer** ppBuffers, + Uint32* pOffsets, + RESOURCE_STATE_TRANSITION_MODE StateTransitionMode, + SET_VERTEX_BUFFERS_FLAGS Flags) override final; + /// Implementation of IDeviceContext::InvalidateState() in Direct3D12 backend. - virtual void InvalidateState()override final; + virtual void InvalidateState() override final; /// Implementation of IDeviceContext::SetIndexBuffer() in Direct3D12 backend. - virtual void SetIndexBuffer( IBuffer* pIndexBuffer, Uint32 ByteOffset, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode )override final; + virtual void SetIndexBuffer(IBuffer* pIndexBuffer, Uint32 ByteOffset, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) override final; /// Implementation of IDeviceContext::SetViewports() in Direct3D12 backend. - virtual void SetViewports( Uint32 NumViewports, const Viewport* pViewports, Uint32 RTWidth, Uint32 RTHeight )override final; + virtual void SetViewports(Uint32 NumViewports, const Viewport* pViewports, Uint32 RTWidth, Uint32 RTHeight) override final; /// Implementation of IDeviceContext::SetScissorRects() in Direct3D12 backend. - virtual void SetScissorRects( Uint32 NumRects, const Rect* pRects, Uint32 RTWidth, Uint32 RTHeight )override final; + virtual void SetScissorRects(Uint32 NumRects, const Rect* pRects, Uint32 RTWidth, Uint32 RTHeight) override final; /// Implementation of IDeviceContext::SetRenderTargets() in Direct3D12 backend. - virtual void SetRenderTargets( Uint32 NumRenderTargets, - ITextureView* ppRenderTargets[], - ITextureView* pDepthStencil, - RESOURCE_STATE_TRANSITION_MODE StateTransitionMode )override final; + virtual void SetRenderTargets(Uint32 NumRenderTargets, + ITextureView* ppRenderTargets[], + ITextureView* pDepthStencil, + RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) override final; + // clang-format off /// Implementation of IDeviceContext::Draw() in Direct3D12 backend. - virtual void Draw (const DrawAttribs& Attribs)override final; + virtual void Draw (const DrawAttribs& Attribs) override final; /// Implementation of IDeviceContext::DrawIndexed() in Direct3D12 backend. - virtual void DrawIndexed (const DrawIndexedAttribs& Attribs)override final; + virtual void DrawIndexed (const DrawIndexedAttribs& Attribs) override final; /// Implementation of IDeviceContext::DrawIndirect() in Direct3D12 backend. - virtual void DrawIndirect (const DrawIndirectAttribs& Attribs, IBuffer* pAttribsBuffer)override final; + virtual void DrawIndirect (const DrawIndirectAttribs& Attribs, IBuffer* pAttribsBuffer) override final; /// Implementation of IDeviceContext::DrawIndexedIndirect() in Direct3D12 backend. - virtual void DrawIndexedIndirect(const DrawIndexedIndirectAttribs& Attribs, IBuffer* pAttribsBuffer)override final; + virtual void DrawIndexedIndirect(const DrawIndexedIndirectAttribs& Attribs, IBuffer* pAttribsBuffer) override final; + /// Implementation of IDeviceContext::DispatchCompute() in Direct3D12 backend. - virtual void DispatchCompute(const DispatchComputeAttribs& Attribs)override final; + virtual void DispatchCompute (const DispatchComputeAttribs& Attribs) override final; /// Implementation of IDeviceContext::DispatchComputeIndirect() in Direct3D12 backend. - virtual void DispatchComputeIndirect(const DispatchComputeIndirectAttribs& Attribs, IBuffer* pAttribsBuffer)override final; + virtual void DispatchComputeIndirect(const DispatchComputeIndirectAttribs& Attribs, IBuffer* pAttribsBuffer) override final; + // clang-format on /// Implementation of IDeviceContext::ClearDepthStencil() in Direct3D12 backend. virtual void ClearDepthStencil(ITextureView* pView, CLEAR_DEPTH_STENCIL_FLAGS ClearFlags, float fDepth, Uint8 Stencil, - RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)override final; + RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) override final; /// Implementation of IDeviceContext::ClearRenderTarget() in Direct3D12 backend. - virtual void ClearRenderTarget( ITextureView* pView, const float* RGBA, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode )override final; + virtual void ClearRenderTarget(ITextureView* pView, const float* RGBA, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) override final; /// Implementation of IDeviceContext::UpdateBuffer() in Direct3D12 backend. virtual void UpdateBuffer(IBuffer* pBuffer, Uint32 Offset, Uint32 Size, const PVoid pData, - RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)override final; + RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) override final; /// Implementation of IDeviceContext::CopyBuffer() in Direct3D12 backend. virtual void CopyBuffer(IBuffer* pSrcBuffer, @@ -144,13 +147,13 @@ public: IBuffer* pDstBuffer, Uint32 DstOffset, Uint32 Size, - RESOURCE_STATE_TRANSITION_MODE DstBufferTransitionMode)override final; + RESOURCE_STATE_TRANSITION_MODE DstBufferTransitionMode) override final; /// Implementation of IDeviceContext::MapBuffer() in Direct3D12 backend. - virtual void MapBuffer(IBuffer* pBuffer, MAP_TYPE MapType, MAP_FLAGS MapFlags, PVoid& pMappedData)override final; + virtual void MapBuffer(IBuffer* pBuffer, MAP_TYPE MapType, MAP_FLAGS MapFlags, PVoid& pMappedData) override final; /// Implementation of IDeviceContext::UnmapBuffer() in Direct3D12 backend. - virtual void UnmapBuffer(IBuffer* pBuffer, MAP_TYPE MapType)override final; + virtual void UnmapBuffer(IBuffer* pBuffer, MAP_TYPE MapType) override final; /// Implementation of IDeviceContext::UpdateTexture() in Direct3D12 backend. virtual void UpdateTexture(ITexture* pTexture, @@ -159,80 +162,80 @@ public: const Box& DstBox, const TextureSubResData& SubresData, RESOURCE_STATE_TRANSITION_MODE SrcBufferTransitionMode, - RESOURCE_STATE_TRANSITION_MODE TextureTransitionMode)override final; + RESOURCE_STATE_TRANSITION_MODE TextureTransitionMode) override final; /// Implementation of IDeviceContext::CopyTexture() in Direct3D12 backend. - virtual void CopyTexture(const CopyTextureAttribs& CopyAttribs)override final; + virtual void CopyTexture(const CopyTextureAttribs& CopyAttribs) override final; /// Implementation of IDeviceContext::MapTextureSubresource() in Direct3D12 backend. - virtual void MapTextureSubresource( ITexture* pTexture, - Uint32 MipLevel, - Uint32 ArraySlice, - MAP_TYPE MapType, - MAP_FLAGS MapFlags, - const Box* pMapRegion, - MappedTextureSubresource& MappedData )override final; + virtual void MapTextureSubresource(ITexture* pTexture, + Uint32 MipLevel, + Uint32 ArraySlice, + MAP_TYPE MapType, + MAP_FLAGS MapFlags, + const Box* pMapRegion, + MappedTextureSubresource& MappedData) override final; /// Implementation of IDeviceContext::UnmapTextureSubresource() in Direct3D12 backend. - virtual void UnmapTextureSubresource(ITexture* pTexture, Uint32 MipLevel, Uint32 ArraySlice)override final; + virtual void UnmapTextureSubresource(ITexture* pTexture, Uint32 MipLevel, Uint32 ArraySlice) override final; /// Implementation of IDeviceContext::FinishFrame() in Direct3D12 backend. - virtual void FinishFrame()override final; + virtual void FinishFrame() override final; /// Implementation of IDeviceContext::TransitionResourceStates() in Direct3D12 backend. - virtual void TransitionResourceStates(Uint32 BarrierCount, StateTransitionDesc* pResourceBarriers)override final; - + virtual void TransitionResourceStates(Uint32 BarrierCount, StateTransitionDesc* pResourceBarriers) override final; + /// Implementation of IDeviceContext::ResolveTextureSubresource() in Direct3D12 backend. virtual void ResolveTextureSubresource(ITexture* pSrcTexture, ITexture* pDstTexture, - const ResolveTextureSubresourceAttribs& ResolveAttribs)override final; + const ResolveTextureSubresourceAttribs& ResolveAttribs) override final; /// Implementation of IDeviceContext::FinishCommandList() in Direct3D12 backend. - virtual void FinishCommandList(class ICommandList** ppCommandList)override final; + virtual void FinishCommandList(class ICommandList** ppCommandList) override final; /// Implementation of IDeviceContext::ExecuteCommandList() in Direct3D12 backend. - virtual void ExecuteCommandList(class ICommandList* pCommandList)override final; + virtual void ExecuteCommandList(class ICommandList* pCommandList) override final; /// Implementation of IDeviceContext::SignalFence() in Direct3D12 backend. - virtual void SignalFence(IFence* pFence, Uint64 Value)override final; + virtual void SignalFence(IFence* pFence, Uint64 Value) override final; /// Implementation of IDeviceContext::WaitForFence() in Direct3D12 backend. - virtual void WaitForFence(IFence* pFence, Uint64 Value, bool FlushContext)override final; + virtual void WaitForFence(IFence* pFence, Uint64 Value, bool FlushContext) override final; /// Implementation of IDeviceContext::WaitForIdle() in Direct3D12 backend. - virtual void WaitForIdle()override final; + virtual void WaitForIdle() override final; /// Implementation of IDeviceContext::Flush() in Direct3D12 backend. - virtual void Flush()override final; + virtual void Flush() override final; /// Implementation of IDeviceContext::TransitionTextureState() in Direct3D12 backend. - virtual void TransitionTextureState(ITexture *pTexture, D3D12_RESOURCE_STATES State)override final; + virtual void TransitionTextureState(ITexture* pTexture, D3D12_RESOURCE_STATES State) override final; /// Implementation of IDeviceContext::TransitionBufferState() in Direct3D12 backend. - virtual void TransitionBufferState(IBuffer *pBuffer, D3D12_RESOURCE_STATES State)override final; + virtual void TransitionBufferState(IBuffer* pBuffer, D3D12_RESOURCE_STATES State) override final; /// Implementation of IDeviceContextD3D12::ID3D12GraphicsCommandList() in Direct3D12 backend. - virtual ID3D12GraphicsCommandList* GetD3D12CommandList()override final; + virtual ID3D12GraphicsCommandList* GetD3D12CommandList() override final; ///// Number of different shader types (Vertex, Pixel, Geometry, Domain, Hull, Compute) //static constexpr int NumShaderTypes = 6; - void UpdateBufferRegion(class BufferD3D12Impl* pBuffD3D12, - D3D12DynamicAllocation& Allocation, - Uint64 DstOffset, - Uint64 NumBytes, + void UpdateBufferRegion(class BufferD3D12Impl* pBuffD3D12, + D3D12DynamicAllocation& Allocation, + Uint64 DstOffset, + Uint64 NumBytes, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode); - void CopyTextureRegion(class TextureD3D12Impl* pSrcTexture, - Uint32 SrcSubResIndex, - const D3D12_BOX* pD3D12SrcBox, - RESOURCE_STATE_TRANSITION_MODE SrcTextureTransitionMode, - class TextureD3D12Impl* pDstTexture, - Uint32 DstSubResIndex, - Uint32 DstX, - Uint32 DstY, - Uint32 DstZ, - RESOURCE_STATE_TRANSITION_MODE DstTextureTransitionMode); + void CopyTextureRegion(class TextureD3D12Impl* pSrcTexture, + Uint32 SrcSubResIndex, + const D3D12_BOX* pD3D12SrcBox, + RESOURCE_STATE_TRANSITION_MODE SrcTextureTransitionMode, + class TextureD3D12Impl* pDstTexture, + Uint32 DstSubResIndex, + Uint32 DstX, + Uint32 DstY, + Uint32 DstZ, + RESOURCE_STATE_TRANSITION_MODE DstTextureTransitionMode); void CopyTextureRegion(IBuffer* pSrcBuffer, Uint32 SrcOffset, @@ -261,24 +264,26 @@ public: const Box& DstBox, RESOURCE_STATE_TRANSITION_MODE TextureTransitionMode); - virtual void GenerateMips(ITextureView *pTexView)override final; + virtual void GenerateMips(ITextureView* pTexView) override final; D3D12DynamicAllocation AllocateDynamicSpace(size_t NumBytes, size_t Alignment); - - Uint32 GetContextId()const{return m_ContextId;} - size_t GetNumCommandsInCtx()const { return m_State.NumCommands; } + Uint32 GetContextId() const { return m_ContextId; } - Int64 GetCurrentFrameNumber()const {return m_ContextFrameNumber; } + size_t GetNumCommandsInCtx() const { return m_State.NumCommands; } + + Int64 GetCurrentFrameNumber() const { return m_ContextFrameNumber; } private: void CommitD3D12IndexBuffer(GraphicsContext& GraphCtx, VALUE_TYPE IndexType); void CommitD3D12VertexBuffers(class GraphicsContext& GraphCtx); void CommitRenderTargets(RESOURCE_STATE_TRANSITION_MODE StateTransitionMode); void CommitViewports(); - void CommitScissorRects(class GraphicsContext &GraphCtx, bool ScissorEnable); + void CommitScissorRects(class GraphicsContext& GraphCtx, bool ScissorEnable); void Flush(bool RequestNewCmdCtx); + __forceinline void RequestCommandContext(RenderDeviceD3D12Impl* pDeviceD3D12Impl); + __forceinline void TransitionOrVerifyBufferState(CommandContext& CmdCtx, BufferD3D12Impl& Buffer, RESOURCE_STATE_TRANSITION_MODE TransitionMode, @@ -312,8 +317,8 @@ private: Uint32 RowCount = 0; Box Region; }; - TextureUploadSpace AllocateTextureUploadSpace(TEXTURE_FORMAT TexFmt, - const Box& Region); + TextureUploadSpace AllocateTextureUploadSpace(TEXTURE_FORMAT TexFmt, + const Box& Region); friend class SwapChainD3D12Impl; @@ -324,12 +329,12 @@ private: m_State.NumCommands = m_State.NumCommands != 0 ? m_State.NumCommands : 1; return *m_CurrCmdCtx; } - std::unique_ptr > m_CurrCmdCtx; + std::unique_ptr> m_CurrCmdCtx; struct State { - size_t NumCommands = 0; - + size_t NumCommands = 0; + CComPtr CommittedD3D12IndexBuffer; VALUE_TYPE CommittedIBFormat = VT_UNDEFINED; Uint32 CommittedD3D12IndexDataStartOffset = 0; @@ -338,43 +343,42 @@ private: bool bCommittedD3D12VBsUpToDate = false; // Indicates if currently committed D3D11 index buffer is up to date - bool bCommittedD3D12IBUpToDate = false; + bool bCommittedD3D12IBUpToDate = false; // Indicates if root views have been committed since the time SRB // has been committed. - bool bRootViewsCommitted = false; + bool bRootViewsCommitted = false; class ShaderResourceCacheD3D12* pCommittedResourceCache = nullptr; - }m_State; + } m_State; CComPtr m_pDrawIndirectSignature; CComPtr m_pDrawIndexedIndirectSignature; CComPtr m_pDispatchIndirectSignature; - + D3D12DynamicHeap m_DynamicHeap; - - // Every context must use its own allocator that maintains individual list of retired descriptor heaps to + + // Every context must use its own allocator that maintains individual list of retired descriptor heaps to // avoid interference with other command contexts // The allocations in heaps are discarded at the end of the frame. DynamicSuballocationsManager m_DynamicGPUDescriptorAllocator[2]; FixedBlockMemoryAllocator m_CmdListAllocator; - std::vector > > m_PendingFences; + std::vector>> m_PendingFences; struct MappedTextureKey { TextureD3D12Impl* const Texture; - UINT const Subresource; + UINT const Subresource; - bool operator == (const MappedTextureKey& rhs)const + bool operator==(const MappedTextureKey& rhs) const { - return Texture == rhs.Texture && - Subresource == rhs.Subresource; + return Texture == rhs.Texture && Subresource == rhs.Subresource; } struct Hasher { - size_t operator()(const MappedTextureKey& Key)const + size_t operator()(const MappedTextureKey& Key) const { return ComputeHash(Key.Texture, Key.Subresource); } @@ -383,4 +387,4 @@ private: std::unordered_map m_MappedTextures; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/FenceD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/FenceD3D12Impl.h index 8eace8e1..4f6423b9 100644 --- a/Graphics/GraphicsEngineD3D12/include/FenceD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/FenceD3D12Impl.h @@ -42,25 +42,25 @@ class FenceD3D12Impl final : public FenceBase; - FenceD3D12Impl(IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pDevice, - const FenceDesc& Desc); + FenceD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl* pDevice, + const FenceDesc& Desc); ~FenceD3D12Impl(); /// Implementation of IFence::GetCompletedValue() in Direct3D12 backend. - virtual Uint64 GetCompletedValue()override final; + virtual Uint64 GetCompletedValue() override final; /// Implementation of IFence::GetCompletedValue() in Direct3D12 backend. - virtual void Reset(Uint64 Value)override final; + virtual void Reset(Uint64 Value) override final; /// Implementation of IFenceD3D12::GetD3D12Fence(). - ID3D12Fence* GetD3D12Fence()override final{ return m_pd3d12Fence; } + ID3D12Fence* GetD3D12Fence() override final { return m_pd3d12Fence; } /// Implementation of IFenceD3D12::WaitForCompletion(). - virtual void WaitForCompletion(Uint64 Value)override final; + virtual void WaitForCompletion(Uint64 Value) override final; private: CComPtr m_pd3d12Fence; ///< D3D12 Fence object }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/GenerateMips.h b/Graphics/GraphicsEngineD3D12/include/GenerateMips.h index 330cafbb..ac0a2831 100644 --- a/Graphics/GraphicsEngineD3D12/include/GenerateMips.h +++ b/Graphics/GraphicsEngineD3D12/include/GenerateMips.h @@ -35,7 +35,7 @@ // // Developed by Minigraph // -// Author: James Stanard +// Author: James Stanard // @@ -47,16 +47,16 @@ namespace Diligent { - class GenerateMipsHelper - { - public: - GenerateMipsHelper(ID3D12Device* pd3d12Device); - - void GenerateMips(ID3D12Device* pd3d12Device, class TextureViewD3D12Impl* pTexView, class CommandContext& Ctx)const; - - private: - CComPtr m_pGenerateMipsRS; - CComPtr m_pGenerateMipsLinearPSO[4]; - CComPtr m_pGenerateMipsGammaPSO[4]; - }; -} +class GenerateMipsHelper +{ +public: + GenerateMipsHelper(ID3D12Device* pd3d12Device); + + void GenerateMips(ID3D12Device* pd3d12Device, class TextureViewD3D12Impl* pTexView, class CommandContext& Ctx) const; + +private: + CComPtr m_pGenerateMipsRS; + CComPtr m_pGenerateMipsLinearPSO[4]; + CComPtr m_pGenerateMipsGammaPSO[4]; +}; +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h index bb8541c0..78486bf0 100644 --- a/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h @@ -46,13 +46,13 @@ class PipelineStateD3D12Impl final : public PipelineStateBase; - PipelineStateD3D12Impl( IReferenceCounters *pRefCounters, RenderDeviceD3D12Impl *pDeviceD3D12, const PipelineStateDesc &PipelineDesc ); + PipelineStateD3D12Impl(IReferenceCounters* pRefCounters, RenderDeviceD3D12Impl* pDeviceD3D12, const PipelineStateDesc& PipelineDesc); ~PipelineStateD3D12Impl(); - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; - + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override final; + /// Implementation of IPipelineState::BindStaticResources() in Direct3D12 backend. - virtual void BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags)override final; + virtual void BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags) override final; /// Implementation of IPipelineState::GetStaticVariableCount() in Direct3D12 backend. virtual Uint32 GetStaticVariableCount(SHADER_TYPE ShaderType) const override final; @@ -64,50 +64,50 @@ public: virtual IShaderResourceVariable* GetStaticVariableByIndex(SHADER_TYPE ShaderType, Uint32 Index) override final; /// Implementation of IPipelineState::CreateShaderResourceBinding() in Direct3D12 backend. - virtual void CreateShaderResourceBinding( IShaderResourceBinding **ppShaderResourceBinding, bool InitStaticResources )override final; + virtual void CreateShaderResourceBinding(IShaderResourceBinding** ppShaderResourceBinding, bool InitStaticResources) override final; /// Implementation of IPipelineState::IsCompatibleWith() in Direct3D12 backend. - virtual bool IsCompatibleWith(const IPipelineState *pPSO)const override final; + virtual bool IsCompatibleWith(const IPipelineState* pPSO) const override final; /// Implementation of IPipelineStateD3D12::GetD3D12PipelineState(). - virtual ID3D12PipelineState* GetD3D12PipelineState()const override final{return m_pd3d12PSO;} + virtual ID3D12PipelineState* GetD3D12PipelineState() const override final { return m_pd3d12PSO; } /// Implementation of IPipelineStateD3D12::GetD3D12RootSignature(). - virtual ID3D12RootSignature* GetD3D12RootSignature()const override final{return m_RootSig.GetD3D12RootSignature(); } + virtual ID3D12RootSignature* GetD3D12RootSignature() const override final { return m_RootSig.GetD3D12RootSignature(); } struct CommitAndTransitionResourcesAttribs { - Uint32 CtxId = 0; - IShaderResourceBinding* pShaderResourceBinding = nullptr; - bool CommitResources = false; - bool TransitionResources = false; - bool ValidateStates = false; + Uint32 CtxId = 0; + IShaderResourceBinding* pShaderResourceBinding = nullptr; + bool CommitResources = false; + bool TransitionResources = false; + bool ValidateStates = false; }; ShaderResourceCacheD3D12* CommitAndTransitionShaderResources(class DeviceContextD3D12Impl* pDeviceCtx, class CommandContext& CmdCtx, - CommitAndTransitionResourcesAttribs& Attrib)const; - - const RootSignature& GetRootSignature()const{return m_RootSig;} - - const ShaderResourceLayoutD3D12& GetShaderResLayout(Uint32 ShaderInd)const + CommitAndTransitionResourcesAttribs& Attrib) const; + + const RootSignature& GetRootSignature() const { return m_RootSig; } + + const ShaderResourceLayoutD3D12& GetShaderResLayout(Uint32 ShaderInd) const { VERIFY_EXPR(ShaderInd < m_NumShaders); return m_pShaderResourceLayouts[ShaderInd]; } - const ShaderResourceLayoutD3D12& GetStaticShaderResLayout(Uint32 ShaderInd)const + const ShaderResourceLayoutD3D12& GetStaticShaderResLayout(Uint32 ShaderInd) const { VERIFY_EXPR(ShaderInd < m_NumShaders); return m_pShaderResourceLayouts[m_NumShaders + ShaderInd]; } - - ShaderResourceCacheD3D12& GetStaticShaderResCache(Uint32 ShaderInd)const + + ShaderResourceCacheD3D12& GetStaticShaderResCache(Uint32 ShaderInd) const { VERIFY_EXPR(ShaderInd < m_NumShaders); return m_pStaticResourceCaches[ShaderInd]; } - bool ContainsShaderResources()const; + bool ContainsShaderResources() const; SRBMemoryAllocator& GetSRBMemoryAllocator() { @@ -115,18 +115,17 @@ public: } private: - CComPtr m_pd3d12PSO; - RootSignature m_RootSig; - + RootSignature m_RootSig; + // Must be defined before default SRB SRBMemoryAllocator m_SRBMemAllocator; - ShaderResourceLayoutD3D12* m_pShaderResourceLayouts = nullptr; - ShaderResourceCacheD3D12* m_pStaticResourceCaches = nullptr; - ShaderVariableManagerD3D12* m_pStaticVarManagers = nullptr; + ShaderResourceLayoutD3D12* m_pShaderResourceLayouts = nullptr; + ShaderResourceCacheD3D12* m_pStaticResourceCaches = nullptr; + ShaderVariableManagerD3D12* m_pStaticVarManagers = nullptr; // Resource layout index in m_ResourceLayouts[] array for every shader stage Int8 m_ResourceLayoutIndex[6] = {-1, -1, -1, -1, -1, -1}; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.h index c24dc306..9a1364db 100644 --- a/Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.h @@ -40,73 +40,78 @@ namespace Diligent { /// Render device implementation in Direct3D12 backend. -class RenderDeviceD3D12Impl final : public RenderDeviceNextGenBase< RenderDeviceD3DBase, ICommandQueueD3D12 > +class RenderDeviceD3D12Impl final : public RenderDeviceNextGenBase, ICommandQueueD3D12> { public: - using TRenderDeviceBase = RenderDeviceNextGenBase< RenderDeviceD3DBase, ICommandQueueD3D12 >; + using TRenderDeviceBase = RenderDeviceNextGenBase, ICommandQueueD3D12>; - RenderDeviceD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl(IReferenceCounters* pRefCounters, IMemoryAllocator& RawMemAllocator, IEngineFactory* pEngineFactory, - const EngineD3D12CreateInfo& EngineCI, - ID3D12Device* pD3D12Device, + const EngineD3D12CreateInfo& EngineCI, + ID3D12Device* pD3D12Device, size_t CommandQueueCount, ICommandQueueD3D12** ppCmdQueues); ~RenderDeviceD3D12Impl(); - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override final; /// Implementation of IRenderDevice::CreatePipelineState() in Direct3D12 backend. - virtual void CreatePipelineState(const PipelineStateDesc& PipelineDesc, IPipelineState** ppPipelineState)override final; + virtual void CreatePipelineState(const PipelineStateDesc& PipelineDesc, IPipelineState** ppPipelineState) override final; /// Implementation of IRenderDevice::CreateBuffer() in Direct3D12 backend. - virtual void CreateBuffer(const BufferDesc& BuffDesc, const BufferData* pBuffData, IBuffer** ppBuffer)override final; + virtual void CreateBuffer(const BufferDesc& BuffDesc, const BufferData* pBuffData, IBuffer** ppBuffer) override final; /// Implementation of IRenderDevice::CreateShader() in Direct3D12 backend. - virtual void CreateShader(const ShaderCreateInfo& ShaderCreateInfo, IShader** ppShader)override final; + virtual void CreateShader(const ShaderCreateInfo& ShaderCreateInfo, IShader** ppShader) override final; /// Implementation of IRenderDevice::CreateTexture() in Direct3D12 backend. - virtual void CreateTexture(const TextureDesc& TexDesc, const TextureData* pData, ITexture** ppTexture)override final; - + virtual void CreateTexture(const TextureDesc& TexDesc, const TextureData* pData, ITexture** ppTexture) override final; + void CreateTexture(const TextureDesc& TexDesc, ID3D12Resource* pd3d12Texture, RESOURCE_STATE InitialState, class TextureD3D12Impl** ppTexture); - + /// Implementation of IRenderDevice::CreateSampler() in Direct3D12 backend. - virtual void CreateSampler(const SamplerDesc& SamplerDesc, ISampler** ppSampler)override final; + virtual void CreateSampler(const SamplerDesc& SamplerDesc, ISampler** ppSampler) override final; /// Implementation of IRenderDevice::CreateFence() in Direct3D12 backend. - virtual void CreateFence(const FenceDesc& Desc, IFence** ppFence)override final; + virtual void CreateFence(const FenceDesc& Desc, IFence** ppFence) override final; /// Implementation of IRenderDeviceD3D12::GetD3D12Device(). - virtual ID3D12Device* GetD3D12Device()override final{return m_pd3d12Device;} - + virtual ID3D12Device* GetD3D12Device() override final { return m_pd3d12Device; } + /// Implementation of IRenderDeviceD3D12::CreateTextureFromD3DResource(). - virtual void CreateTextureFromD3DResource(ID3D12Resource* pd3d12Texture, RESOURCE_STATE InitialState, ITexture** ppTexture)override final; + virtual void CreateTextureFromD3DResource(ID3D12Resource* pd3d12Texture, RESOURCE_STATE InitialState, ITexture** ppTexture) override final; /// Implementation of IRenderDeviceD3D12::CreateBufferFromD3DResource(). - virtual void CreateBufferFromD3DResource(ID3D12Resource* pd3d12Buffer, const BufferDesc& BuffDesc, RESOURCE_STATE InitialState, IBuffer** ppBuffer)override final; + virtual void CreateBufferFromD3DResource(ID3D12Resource* pd3d12Buffer, const BufferDesc& BuffDesc, RESOURCE_STATE InitialState, IBuffer** ppBuffer) override final; - DescriptorHeapAllocation AllocateDescriptor( D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT Count = 1 ); - DescriptorHeapAllocation AllocateGPUDescriptors( D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT Count = 1 ); + DescriptorHeapAllocation AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT Count = 1); + DescriptorHeapAllocation AllocateGPUDescriptors(D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT Count = 1); /// Implementation of IRenderDevice::IdleGPU() in Direct3D12 backend. - virtual void IdleGPU()override final; + virtual void IdleGPU() override final; - using PooledCommandContext = std::unique_ptr >; + using PooledCommandContext = std::unique_ptr>; PooledCommandContext AllocateCommandContext(const Char* ID = ""); + void CloseAndExecuteTransientCommandContext(Uint32 CommandQueueIndex, PooledCommandContext&& Ctx); - Uint64 CloseAndExecuteCommandContext(Uint32 QueueIndex, PooledCommandContext&& Ctx, bool DiscardStaleObjects, std::vector > >* pSignalFences); - void SignalFences(Uint32 QueueIndex, std::vector > >& SignalFences); - + Uint64 CloseAndExecuteCommandContext(Uint32 QueueIndex, + PooledCommandContext&& Ctx, + bool DiscardStaleObjects, + std::vector>>* pSignalFences); + + void SignalFences(Uint32 QueueIndex, std::vector>>& SignalFences); + // Disposes an unused command context void DisposeCommandContext(PooledCommandContext&& Ctx); void FlushStaleResources(Uint32 CmdQueueIndex); /// Implementation of IRenderDevice::() in Direct3D12 backend. - virtual void ReleaseStaleResources(bool ForceRelease = false)override final; + virtual void ReleaseStaleResources(bool ForceRelease = false) override final; - D3D12DynamicMemoryManager& GetDynamicMemoryManager() {return m_DynamicMemoryManager;} + D3D12DynamicMemoryManager& GetDynamicMemoryManager() { return m_DynamicMemoryManager; } GPUDescriptorHeap& GetGPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE Type) { @@ -114,13 +119,13 @@ public: return m_GPUDescriptorHeaps[Type]; } - const GenerateMipsHelper& GetMipsGenerator()const {return m_MipsGenerator;} + const GenerateMipsHelper& GetMipsGenerator() const { return m_MipsGenerator; } - D3D_FEATURE_LEVEL GetD3DFeatureLevel()const; + D3D_FEATURE_LEVEL GetD3DFeatureLevel() const; private: - virtual void TestTextureFormat( TEXTURE_FORMAT TexFormat )override final; - void FreeCommandContext(PooledCommandContext&& Ctx); + virtual void TestTextureFormat(TEXTURE_FORMAT TexFormat) override final; + void FreeCommandContext(PooledCommandContext&& Ctx); CComPtr m_pd3d12Device; @@ -129,11 +134,11 @@ private: CPUDescriptorHeap m_CPUDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES]; GPUDescriptorHeap m_GPUDescriptorHeaps[2]; // D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV == 0 // D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER == 1 - + CommandListManager m_CmdListManager; - std::mutex m_ContextPoolMutex; - std::vector< PooledCommandContext, STDAllocatorRawMem > m_ContextPool; + std::mutex m_ContextPoolMutex; + std::vector> m_ContextPool; #ifdef DEVELOPMENT Atomics::AtomicLong m_AllocatedCtxCounter = 0; #endif @@ -144,4 +149,4 @@ private: GenerateMipsHelper m_MipsGenerator; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/RootSignature.h b/Graphics/GraphicsEngineD3D12/include/RootSignature.h index 59f2102e..388b3296 100644 --- a/Graphics/GraphicsEngineD3D12/include/RootSignature.h +++ b/Graphics/GraphicsEngineD3D12/include/RootSignature.h @@ -33,92 +33,101 @@ namespace Diligent { -SHADER_TYPE ShaderTypeFromShaderVisibility(D3D12_SHADER_VISIBILITY ShaderVisibility); -D3D12_SHADER_VISIBILITY GetShaderVisibility(SHADER_TYPE ShaderType); +SHADER_TYPE ShaderTypeFromShaderVisibility(D3D12_SHADER_VISIBILITY ShaderVisibility); +D3D12_SHADER_VISIBILITY GetShaderVisibility(SHADER_TYPE ShaderType); D3D12_DESCRIPTOR_HEAP_TYPE dbgHeapTypeFromRangeType(D3D12_DESCRIPTOR_RANGE_TYPE RangeType); class RootParameter { public: - - RootParameter(D3D12_ROOT_PARAMETER_TYPE ParameterType, - Uint32 RootIndex, - UINT Register, - UINT RegisterSpace, - D3D12_SHADER_VISIBILITY Visibility, - SHADER_RESOURCE_VARIABLE_TYPE VarType)noexcept : + RootParameter(D3D12_ROOT_PARAMETER_TYPE ParameterType, + Uint32 RootIndex, + UINT Register, + UINT RegisterSpace, + D3D12_SHADER_VISIBILITY Visibility, + SHADER_RESOURCE_VARIABLE_TYPE VarType) noexcept : + // clang-format off m_RootIndex {RootIndex}, m_ShaderVarType{VarType } - { + // clang-format on + { VERIFY(ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV || ParameterType == D3D12_ROOT_PARAMETER_TYPE_SRV || ParameterType == D3D12_ROOT_PARAMETER_TYPE_UAV, "Unexpected parameter type - verify argument list"); - m_RootParam.ParameterType = ParameterType; - m_RootParam.ShaderVisibility = Visibility; - m_RootParam.Descriptor.ShaderRegister = Register; - m_RootParam.Descriptor.RegisterSpace = RegisterSpace; - } - - RootParameter(D3D12_ROOT_PARAMETER_TYPE ParameterType, - Uint32 RootIndex, - UINT Register, - UINT RegisterSpace, - UINT NumDwords, - D3D12_SHADER_VISIBILITY Visibility, - SHADER_RESOURCE_VARIABLE_TYPE VarType)noexcept : + m_RootParam.ParameterType = ParameterType; + m_RootParam.ShaderVisibility = Visibility; + m_RootParam.Descriptor.ShaderRegister = Register; + m_RootParam.Descriptor.RegisterSpace = RegisterSpace; + } + + RootParameter(D3D12_ROOT_PARAMETER_TYPE ParameterType, + Uint32 RootIndex, + UINT Register, + UINT RegisterSpace, + UINT NumDwords, + D3D12_SHADER_VISIBILITY Visibility, + SHADER_RESOURCE_VARIABLE_TYPE VarType) noexcept : + // clang-format off m_RootIndex {RootIndex}, m_ShaderVarType{VarType } - { + // clang-format on + { VERIFY(ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, "Unexpected parameter type - verify argument list"); - m_RootParam.ParameterType = ParameterType; - m_RootParam.ShaderVisibility = Visibility; - m_RootParam.Constants.Num32BitValues = NumDwords; - m_RootParam.Constants.ShaderRegister = Register; - m_RootParam.Constants.RegisterSpace = RegisterSpace; - } - - RootParameter(D3D12_ROOT_PARAMETER_TYPE ParameterType, - Uint32 RootIndex, - UINT NumRanges, - D3D12_DESCRIPTOR_RANGE* pRanges, - D3D12_SHADER_VISIBILITY Visibility, - SHADER_RESOURCE_VARIABLE_TYPE VarType)noexcept : + m_RootParam.ParameterType = ParameterType; + m_RootParam.ShaderVisibility = Visibility; + m_RootParam.Constants.Num32BitValues = NumDwords; + m_RootParam.Constants.ShaderRegister = Register; + m_RootParam.Constants.RegisterSpace = RegisterSpace; + } + + RootParameter(D3D12_ROOT_PARAMETER_TYPE ParameterType, + Uint32 RootIndex, + UINT NumRanges, + D3D12_DESCRIPTOR_RANGE* pRanges, + D3D12_SHADER_VISIBILITY Visibility, + SHADER_RESOURCE_VARIABLE_TYPE VarType) noexcept : + // clang-format off m_RootIndex {RootIndex}, m_ShaderVarType{VarType } - { + // clang-format on + { VERIFY(ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, "Unexpected parameter type - verify argument list"); VERIFY_EXPR(pRanges != nullptr); - m_RootParam.ParameterType = ParameterType; - m_RootParam.ShaderVisibility = Visibility; - m_RootParam.DescriptorTable.NumDescriptorRanges = NumRanges; - m_RootParam.DescriptorTable.pDescriptorRanges = pRanges; + m_RootParam.ParameterType = ParameterType; + m_RootParam.ShaderVisibility = Visibility; + m_RootParam.DescriptorTable.NumDescriptorRanges = NumRanges; + m_RootParam.DescriptorTable.pDescriptorRanges = pRanges; #ifdef _DEBUG - for(Uint32 r=0; r < NumRanges; ++r) + for (Uint32 r = 0; r < NumRanges; ++r) pRanges[r].RangeType = static_cast(-1); #endif - } + } - RootParameter(const RootParameter& RP)noexcept : - m_RootParam (RP.m_RootParam), - m_DescriptorTableSize(RP.m_DescriptorTableSize), - m_ShaderVarType (RP.m_ShaderVarType), - m_RootIndex (RP.m_RootIndex) + RootParameter(const RootParameter& RP) noexcept : + // clang-format off + m_RootParam {RP.m_RootParam }, + m_DescriptorTableSize{RP.m_DescriptorTableSize}, + m_ShaderVarType {RP.m_ShaderVarType }, + m_RootIndex {RP.m_RootIndex } + // clang-format on { VERIFY(m_RootParam.ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, "Use another constructor to copy descriptor table"); } - RootParameter(const RootParameter& RP, - UINT NumRanges, - D3D12_DESCRIPTOR_RANGE* pRanges)noexcept : + RootParameter(const RootParameter& RP, + UINT NumRanges, + D3D12_DESCRIPTOR_RANGE* pRanges) noexcept : + // clang-format off m_RootParam {RP.m_RootParam }, m_DescriptorTableSize{RP.m_DescriptorTableSize}, m_ShaderVarType {RP.m_ShaderVarType }, m_RootIndex {RP.m_RootIndex } + // clang-format on { VERIFY(m_RootParam.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, "Root parameter is expected to be a descriptor table"); VERIFY(NumRanges >= m_RootParam.DescriptorTable.NumDescriptorRanges, "New table must be larger than source one"); - auto& DstTbl = m_RootParam.DescriptorTable; + auto& DstTbl = m_RootParam.DescriptorTable; DstTbl.NumDescriptorRanges = NumRanges; DstTbl.pDescriptorRanges = pRanges; - const auto& SrcTbl = RP.m_RootParam.DescriptorTable; + const auto& SrcTbl = RP.m_RootParam.DescriptorTable; memcpy(pRanges, SrcTbl.pDescriptorRanges, SrcTbl.NumDescriptorRanges * sizeof(D3D12_DESCRIPTOR_RANGE)); #ifdef _DEBUG { @@ -126,76 +135,78 @@ public: for (Uint32 r = 0; r < SrcTbl.NumDescriptorRanges; ++r) { const auto& Range = SrcTbl.pDescriptorRanges[r]; - dbgTableSize = std::max(dbgTableSize, Range.OffsetInDescriptorsFromTableStart + Range.NumDescriptors); + dbgTableSize = std::max(dbgTableSize, Range.OffsetInDescriptorsFromTableStart + Range.NumDescriptors); } VERIFY(dbgTableSize == m_DescriptorTableSize, "Incorrect descriptor table size"); - + for (Uint32 r = SrcTbl.NumDescriptorRanges; r < DstTbl.NumDescriptorRanges; ++r) pRanges[r].RangeType = static_cast(-1); } #endif } - RootParameter& operator = (const RootParameter&) = delete; - RootParameter& operator = (RootParameter&&) = delete; + RootParameter& operator=(const RootParameter&) = delete; + RootParameter& operator=(RootParameter&&) = delete; - void SetDescriptorRange(UINT RangeIndex, - D3D12_DESCRIPTOR_RANGE_TYPE Type, - UINT Register, - UINT Count, - UINT Space = 0, - UINT OffsetFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) - { + void SetDescriptorRange(UINT RangeIndex, + D3D12_DESCRIPTOR_RANGE_TYPE Type, + UINT Register, + UINT Count, + UINT Space = 0, + UINT OffsetFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) + { VERIFY(m_RootParam.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, "Incorrect parameter table: descriptor table is expected"); auto& Tbl = m_RootParam.DescriptorTable; VERIFY(RangeIndex < Tbl.NumDescriptorRanges, "Invalid descriptor range index"); - D3D12_DESCRIPTOR_RANGE &range = const_cast(Tbl.pDescriptorRanges[RangeIndex]); + D3D12_DESCRIPTOR_RANGE& range = const_cast(Tbl.pDescriptorRanges[RangeIndex]); VERIFY(range.RangeType == static_cast(-1), "Descriptor range has already been initialized. m_DescriptorTableSize may be updated incorrectly"); - range.RangeType = Type; - range.NumDescriptors = Count; - range.BaseShaderRegister = Register; - range.RegisterSpace = Space; - range.OffsetInDescriptorsFromTableStart = OffsetFromTableStart; - m_DescriptorTableSize = std::max(m_DescriptorTableSize, OffsetFromTableStart + Count); - } - - SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType()const{ return m_ShaderVarType; } - Uint32 GetDescriptorTableSize()const + range.RangeType = Type; + range.NumDescriptors = Count; + range.BaseShaderRegister = Register; + range.RegisterSpace = Space; + range.OffsetInDescriptorsFromTableStart = OffsetFromTableStart; + m_DescriptorTableSize = std::max(m_DescriptorTableSize, OffsetFromTableStart + Count); + } + + SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType() const { return m_ShaderVarType; } + + Uint32 GetDescriptorTableSize() const { VERIFY(m_RootParam.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, "Incorrect parameter table: descriptor table is expected"); return m_DescriptorTableSize; } - D3D12_SHADER_VISIBILITY GetShaderVisibility()const { return m_RootParam.ShaderVisibility; } - D3D12_ROOT_PARAMETER_TYPE GetParameterType() const { return m_RootParam.ParameterType; } - Uint32 GetRootIndex()const { return m_RootIndex; } + D3D12_SHADER_VISIBILITY GetShaderVisibility() const { return m_RootParam.ShaderVisibility; } + D3D12_ROOT_PARAMETER_TYPE GetParameterType() const { return m_RootParam.ParameterType; } + + Uint32 GetRootIndex() const { return m_RootIndex; } + + operator const D3D12_ROOT_PARAMETER&() const { return m_RootParam; } - operator const D3D12_ROOT_PARAMETER&()const { return m_RootParam; } - - bool operator == (const RootParameter&rhs)const + bool operator==(const RootParameter& rhs) const { - if (m_ShaderVarType != rhs.m_ShaderVarType || + if (m_ShaderVarType != rhs.m_ShaderVarType || m_DescriptorTableSize != rhs.m_DescriptorTableSize || - m_RootIndex != rhs.m_RootIndex) + m_RootIndex != rhs.m_RootIndex) return false; - if (m_RootParam.ParameterType != rhs.m_RootParam.ParameterType || + if (m_RootParam.ParameterType != rhs.m_RootParam.ParameterType || m_RootParam.ShaderVisibility != rhs.m_RootParam.ShaderVisibility) return false; - switch(m_RootParam.ParameterType) + switch (m_RootParam.ParameterType) { case D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE: { const auto& tbl0 = m_RootParam.DescriptorTable; const auto& tbl1 = rhs.m_RootParam.DescriptorTable; - if(tbl0.NumDescriptorRanges != tbl1.NumDescriptorRanges) + if (tbl0.NumDescriptorRanges != tbl1.NumDescriptorRanges) return false; - for(UINT r=0; r < tbl0.NumDescriptorRanges; ++r) + for (UINT r = 0; r < tbl0.NumDescriptorRanges; ++r) { const auto& rng0 = tbl0.pDescriptorRanges[r]; const auto& rng1 = tbl1.pDescriptorRanges[r]; - if( memcmp(&rng0, &rng1, sizeof(rng0)) != 0) + if (memcmp(&rng0, &rng1, sizeof(rng0)) != 0) return false; } } @@ -223,16 +234,16 @@ public: default: UNEXPECTED("Unexpected root parameter type"); } - + return true; } - bool operator != (const RootParameter&rhs)const + bool operator!=(const RootParameter& rhs) const { return !(*this == rhs); } - size_t GetHash()const + size_t GetHash() const { size_t hash = ComputeHash(m_ShaderVarType, m_DescriptorTableSize, m_RootIndex); HashCombine(hash, m_RootParam.ParameterType, m_RootParam.ShaderVisibility); @@ -274,7 +285,6 @@ public: } private: - SHADER_RESOURCE_VARIABLE_TYPE m_ShaderVarType = static_cast(-1); D3D12_ROOT_PARAMETER m_RootParam = {}; Uint32 m_DescriptorTableSize = 0; @@ -293,42 +303,42 @@ public: void Finalize(ID3D12Device* pd3d12Device); - ID3D12RootSignature* GetD3D12RootSignature()const{return m_pd3d12RootSignature;} + ID3D12RootSignature* GetD3D12RootSignature() const { return m_pd3d12RootSignature; } + + size_t GetResourceCacheRequiredMemSize() const; - size_t GetResourceCacheRequiredMemSize()const; + void InitResourceCache(class RenderDeviceD3D12Impl* pDeviceD3D12Impl, class ShaderResourceCacheD3D12& ResourceCache, IMemoryAllocator& CacheMemAllocator) const; - void InitResourceCache(class RenderDeviceD3D12Impl* pDeviceD3D12Impl, class ShaderResourceCacheD3D12& ResourceCache, IMemoryAllocator& CacheMemAllocator)const; - void InitStaticSampler(SHADER_TYPE ShaderType, const char* SamplerName, const char* SamplerSuffix, const D3DShaderResourceAttribs& ShaderResAttribs); - void AllocateResourceSlot(SHADER_TYPE ShaderType, - const D3DShaderResourceAttribs& ShaderResAttribs, - SHADER_RESOURCE_VARIABLE_TYPE VariableType, - D3D12_DESCRIPTOR_RANGE_TYPE RangeType, - Uint32& RootIndex, - Uint32& OffsetFromTableStart); + void AllocateResourceSlot(SHADER_TYPE ShaderType, + const D3DShaderResourceAttribs& ShaderResAttribs, + SHADER_RESOURCE_VARIABLE_TYPE VariableType, + D3D12_DESCRIPTOR_RANGE_TYPE RangeType, + Uint32& RootIndex, + Uint32& OffsetFromTableStart); // This method should be thread-safe as it does not modify any object state - void (RootSignature::*CommitDescriptorHandles)(class RenderDeviceD3D12Impl* pRenderDeviceD3D12, - ShaderResourceCacheD3D12& ResourceCache, - class CommandContext& Ctx, - bool IsCompute, - bool ValidateStates)const = nullptr; - - void (RootSignature::*TransitionAndCommitDescriptorHandles)(class RenderDeviceD3D12Impl* pRenderDeviceD3D12, - ShaderResourceCacheD3D12& ResourceCache, - class CommandContext& Ctx, + void (RootSignature::*CommitDescriptorHandles)(class RenderDeviceD3D12Impl* pRenderDeviceD3D12, + ShaderResourceCacheD3D12& ResourceCache, + class CommandContext& Ctx, + bool IsCompute, + bool ValidateStates) const = nullptr; + + void (RootSignature::*TransitionAndCommitDescriptorHandles)(class RenderDeviceD3D12Impl* pRenderDeviceD3D12, + ShaderResourceCacheD3D12& ResourceCache, + class CommandContext& Ctx, bool IsCompute, - bool ValidateStates)const = nullptr; + bool ValidateStates) const = nullptr; - void TransitionResources(ShaderResourceCacheD3D12& ResourceCache, - class CommandContext& Ctx)const; + void TransitionResources(ShaderResourceCacheD3D12& ResourceCache, + class CommandContext& Ctx) const; - __forceinline void CommitRootViews(ShaderResourceCacheD3D12& ResourceCache, - class CommandContext& CmdCtx, + __forceinline void CommitRootViews(ShaderResourceCacheD3D12& ResourceCache, + class CommandContext& CmdCtx, bool IsCompute, Uint32 DeviceCtxId, class DeviceContextD3D12Impl* pDeviceCtx, @@ -336,62 +346,64 @@ public: bool ProcessDynamicBuffers, bool ProcessNonDynamicBuffers, bool TransitionStates, - bool ValidateStates)const; + bool ValidateStates) const; - Uint32 GetTotalSrvCbvUavSlots(SHADER_RESOURCE_VARIABLE_TYPE VarType)const + Uint32 GetTotalSrvCbvUavSlots(SHADER_RESOURCE_VARIABLE_TYPE VarType) const { return m_TotalSrvCbvUavSlots[VarType]; } - Uint32 GetTotalSamplerSlots(SHADER_RESOURCE_VARIABLE_TYPE VarType)const + Uint32 GetTotalSamplerSlots(SHADER_RESOURCE_VARIABLE_TYPE VarType) const { return m_TotalSamplerSlots[VarType]; } - Uint32 GetTotalRootViews(SHADER_RESOURCE_VARIABLE_TYPE VarType)const + Uint32 GetTotalRootViews(SHADER_RESOURCE_VARIABLE_TYPE VarType) const { return m_TotalRootViews[VarType]; } - bool IsSameAs(const RootSignature& RS)const + bool IsSameAs(const RootSignature& RS) const { return m_RootParams == RS.m_RootParams; } - size_t GetHash()const + size_t GetHash() const { return m_RootParams.GetHash(); } private: #ifdef _DEBUG - void dbgVerifyRootParameters()const; + void dbgVerifyRootParameters() const; #endif #ifdef DEVELOPMENT static void DvpVerifyResourceState(const ShaderResourceCacheD3D12::Resource& Res, D3D12_DESCRIPTOR_RANGE_TYPE RangeType); #endif - - std::vector > GetCacheTableSizes()const; + + std::vector> GetCacheTableSizes() const; std::array m_TotalSrvCbvUavSlots = {}; std::array m_TotalSamplerSlots = {}; std::array m_TotalRootViews = {}; - + CComPtr m_pd3d12RootSignature; class RootParamsManager { public: - RootParamsManager(IMemoryAllocator &MemAllocator); - - RootParamsManager (const RootParamsManager&) = delete; - RootParamsManager& operator= (const RootParamsManager&) = delete; - RootParamsManager (RootParamsManager&&) = delete; - RootParamsManager& operator= (RootParamsManager&&) = delete; - - Uint32 GetNumRootTables()const { return m_NumRootTables; } - Uint32 GetNumRootViews() const { return m_NumRootViews; } - - const RootParameter& GetRootTable(Uint32 TableInd)const + RootParamsManager(IMemoryAllocator& MemAllocator); + + // clang-format off + RootParamsManager (const RootParamsManager&) = delete; + RootParamsManager& operator=(const RootParamsManager&) = delete; + RootParamsManager (RootParamsManager&&) = delete; + RootParamsManager& operator=(RootParamsManager&&) = delete; + // clang-format on + + Uint32 GetNumRootTables() const { return m_NumRootTables; } + Uint32 GetNumRootViews() const { return m_NumRootViews; } + + const RootParameter& GetRootTable(Uint32 TableInd) const { VERIFY_EXPR(TableInd < m_NumRootTables); return m_pRootTables[TableInd]; @@ -403,7 +415,7 @@ private: return m_pRootTables[TableInd]; } - const RootParameter& GetRootView(Uint32 ViewInd)const + const RootParameter& GetRootView(Uint32 ViewInd) const { VERIFY_EXPR(ViewInd < m_NumRootViews); return m_pRootViews[ViewInd]; @@ -421,42 +433,42 @@ private: D3D12_SHADER_VISIBILITY Visibility, SHADER_RESOURCE_VARIABLE_TYPE VarType); - void AddRootTable(Uint32 RootIndex, - D3D12_SHADER_VISIBILITY Visibility, - SHADER_RESOURCE_VARIABLE_TYPE VarType, - Uint32 NumRangesInNewTable = 1); + void AddRootTable(Uint32 RootIndex, + D3D12_SHADER_VISIBILITY Visibility, + SHADER_RESOURCE_VARIABLE_TYPE VarType, + Uint32 NumRangesInNewTable = 1); void AddDescriptorRanges(Uint32 RootTableInd, Uint32 NumExtraRanges = 1); - template - void ProcessRootTables(TOperation)const; + template + void ProcessRootTables(TOperation) const; - bool operator == (const RootParamsManager& RootParams)const; - size_t GetHash()const; + bool operator==(const RootParamsManager& RootParams) const; + size_t GetHash() const; private: size_t GetRequiredMemorySize(Uint32 NumExtraRootTables, Uint32 NumExtraRootViews, - Uint32 NumExtraDescriptorRanges)const; + Uint32 NumExtraDescriptorRanges) const; D3D12_DESCRIPTOR_RANGE* Extend(Uint32 NumExtraRootTables, Uint32 NumExtraRootViews, Uint32 NumExtraDescriptorRanges, Uint32 RootTableToAddRanges = static_cast(-1)); - IMemoryAllocator &m_MemAllocator; + IMemoryAllocator& m_MemAllocator; std::unique_ptr> m_pMemory; - Uint32 m_NumRootTables = 0; - Uint32 m_NumRootViews = 0; - Uint32 m_TotalDescriptorRanges = 0; - RootParameter* m_pRootTables = nullptr; - RootParameter* m_pRootViews = nullptr; + Uint32 m_NumRootTables = 0; + Uint32 m_NumRootViews = 0; + Uint32 m_TotalDescriptorRanges = 0; + RootParameter* m_pRootTables = nullptr; + RootParameter* m_pRootViews = nullptr; }; static constexpr Uint8 InvalidRootTableIndex = static_cast(-1); - - // The array below contains array index of a CBV/SRV/UAV root table - // in m_RootParams (NOT the Root Index!), for every variable type + + // The array below contains array index of a CBV/SRV/UAV root table + // in m_RootParams (NOT the Root Index!), for every variable type // (static, mutable, dynamic) and every shader type, // or -1, if the table is not yet assigned to the combination std::array m_SrvCbvUavRootTablesMap; @@ -464,44 +476,44 @@ private: std::array m_SamplerRootTablesMap; RootParamsManager m_RootParams; - + struct StaticSamplerAttribs { - StaticSamplerDesc SamplerDesc; - UINT ShaderRegister = static_cast(-1); - UINT ArraySize = 0; - UINT RegisterSpace = 0; + StaticSamplerDesc SamplerDesc; + UINT ShaderRegister = static_cast(-1); + UINT ArraySize = 0; + UINT RegisterSpace = 0; D3D12_SHADER_VISIBILITY ShaderVisibility = static_cast(-1); - - StaticSamplerAttribs()noexcept{} - StaticSamplerAttribs(const StaticSamplerDesc& SamDesc, D3D12_SHADER_VISIBILITY Visibility)noexcept : - SamplerDesc (SamDesc), + + StaticSamplerAttribs() noexcept {} + StaticSamplerAttribs(const StaticSamplerDesc& SamDesc, D3D12_SHADER_VISIBILITY Visibility) noexcept : + SamplerDesc(SamDesc), ShaderVisibility(Visibility) {} }; // Note: sizeof(m_StaticSamplers) == 56 (MS compiler, release x64) - std::vector > m_StaticSamplers; + std::vector> m_StaticSamplers; - IMemoryAllocator &m_MemAllocator; + IMemoryAllocator& m_MemAllocator; // Commits descriptor handles for static and mutable variables - template - void CommitDescriptorHandlesInternal_SM(class RenderDeviceD3D12Impl* pRenderDeviceD3D12, - ShaderResourceCacheD3D12& ResourceCache, - class CommandContext& Ctx, + template + void CommitDescriptorHandlesInternal_SM(class RenderDeviceD3D12Impl* pRenderDeviceD3D12, + ShaderResourceCacheD3D12& ResourceCache, + class CommandContext& Ctx, bool IsCompute, - bool ValidateStates)const; - template + bool ValidateStates) const; + template // Commits descriptor handles for static, mutable, and dynamic variables - void CommitDescriptorHandlesInternal_SMD(class RenderDeviceD3D12Impl* pRenderDeviceD3D12, - ShaderResourceCacheD3D12& ResourceCache, - class CommandContext& Ctx, - bool IsCompute, - bool ValidateStates)const; + void CommitDescriptorHandlesInternal_SMD(class RenderDeviceD3D12Impl* pRenderDeviceD3D12, + ShaderResourceCacheD3D12& ResourceCache, + class CommandContext& Ctx, + bool IsCompute, + bool ValidateStates) const; }; -void RootSignature::CommitRootViews(ShaderResourceCacheD3D12& ResourceCache, - CommandContext& CmdCtx, +void RootSignature::CommitRootViews(ShaderResourceCacheD3D12& ResourceCache, + CommandContext& CmdCtx, bool IsCompute, Uint32 DeviceCtxId, DeviceContextD3D12Impl* pDeviceCtx, @@ -509,17 +521,17 @@ void RootSignature::CommitRootViews(ShaderResourceCacheD3D12& ResourceCache, bool ProcessDynamicBuffers, bool ProcessNonDynamicBuffers, bool TransitionStates, - bool ValidateStates)const + bool ValidateStates) const { for (Uint32 rv = 0; rv < m_RootParams.GetNumRootViews(); ++rv) { auto& RootView = m_RootParams.GetRootView(rv); - auto RootInd = RootView.GetRootIndex(); - + auto RootInd = RootView.GetRootIndex(); + SHADER_TYPE dbgShaderType = SHADER_TYPE_UNKNOWN; #ifdef _DEBUG { - auto& Param = static_cast( RootView ); + auto& Param = static_cast(RootView); VERIFY_EXPR(Param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV); dbgShaderType = ShaderTypeFromShaderVisibility(Param.ShaderVisibility); } @@ -562,7 +574,7 @@ void RootSignature::CommitRootViews(ShaderResourceCacheD3D12& ResourceCache, if (CommitViews) { D3D12_GPU_VIRTUAL_ADDRESS CBVAddress = pBuffToTransition->GetGPUAddress(DeviceCtxId, pDeviceCtx); - if(IsCompute) + if (IsCompute) CmdCtx.GetCommandList()->SetComputeRootConstantBufferView(RootInd, CBVAddress); else CmdCtx.GetCommandList()->SetGraphicsRootConstantBufferView(RootInd, CBVAddress); @@ -572,4 +584,4 @@ void RootSignature::CommitRootViews(ShaderResourceCacheD3D12& ResourceCache, } } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/SamplerD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/SamplerD3D12Impl.h index 190b6a37..de19d1b1 100644 --- a/Graphics/GraphicsEngineD3D12/include/SamplerD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/SamplerD3D12Impl.h @@ -43,15 +43,15 @@ class SamplerD3D12Impl final : public SamplerBase; - SamplerD3D12Impl(IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pRenderDeviceD3D12, - const SamplerDesc& SamplerDesc); + SamplerD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl* pRenderDeviceD3D12, + const SamplerDesc& SamplerDesc); ~SamplerD3D12Impl(); - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override final; /// Implementation of ISamplerD3D12::GetCPUDescriptorHandle(). - virtual D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle()override{ return m_Descriptor.GetCpuHandle(); } + virtual D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle() override { return m_Descriptor.GetCpuHandle(); } private: friend class ShaderD3D12Impl; @@ -59,4 +59,4 @@ private: DescriptorHeapAllocation m_Descriptor; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/ShaderD3D12Impl.h index dd1ad955..de27908a 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderD3D12Impl.h @@ -45,38 +45,39 @@ class ShaderD3D12Impl final : public ShaderBase; - ShaderD3D12Impl(IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pRenderDeviceD3D12, - const ShaderCreateInfo& ShaderCI); + ShaderD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl* pRenderDeviceD3D12, + const ShaderCreateInfo& ShaderCI); ~ShaderD3D12Impl(); - - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; + + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override final; /// Implementation of IShader::GetResourceCount() in Direct3D12 backend. - virtual Uint32 GetResourceCount()const override final + virtual Uint32 GetResourceCount() const override final { return m_pShaderResources->GetTotalResources(); } /// Implementation of IShader::GetResource() in Direct3D12 backend. - virtual ShaderResourceDesc GetResource(Uint32 Index)const override final + virtual ShaderResourceDesc GetResource(Uint32 Index) const override final { return GetHLSLResource(Index); } /// Implementation of IShaderD3D::GetHLSLResource() in Direct3D12 backend. - virtual HLSLShaderResourceDesc GetHLSLResource(Uint32 Index)const override final + virtual HLSLShaderResourceDesc GetHLSLResource(Uint32 Index) const override final { return m_pShaderResources->GetHLSLShaderResourceDesc(Index); } - ID3DBlob* GetShaderByteCode(){return m_pShaderByteCode;} - const std::shared_ptr& GetShaderResources()const { return m_pShaderResources; } + ID3DBlob* GetShaderByteCode() { return m_pShaderByteCode; } + + const std::shared_ptr& GetShaderResources() const { return m_pShaderResources; } private: - // ShaderResources class instance must be referenced through the shared pointer, because + // ShaderResources class instance must be referenced through the shared pointer, because // it is referenced by ShaderResourceLayoutD3D12 class instances std::shared_ptr m_pShaderResources; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h index 974929d9..e8f4162f 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h @@ -44,39 +44,41 @@ class ShaderResourceBindingD3D12Impl final : public ShaderResourceBindingBase; - ShaderResourceBindingD3D12Impl(IReferenceCounters* pRefCounters, - class PipelineStateD3D12Impl* pPSO, - bool IsPSOInternal); + ShaderResourceBindingD3D12Impl(IReferenceCounters* pRefCounters, + class PipelineStateD3D12Impl* pPSO, + bool IsPSOInternal); ~ShaderResourceBindingD3D12Impl(); - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override final; - virtual void BindResources(Uint32 ShaderFlags, IResourceMapping* pResMapping, Uint32 Flags)override; + virtual void BindResources(Uint32 ShaderFlags, IResourceMapping* pResMapping, Uint32 Flags) override; - virtual IShaderResourceVariable* GetVariableByName(SHADER_TYPE ShaderType, const char* Name)override; + virtual IShaderResourceVariable* GetVariableByName(SHADER_TYPE ShaderType, const char* Name) override; virtual Uint32 GetVariableCount(SHADER_TYPE ShaderType) const override final; - virtual IShaderResourceVariable* GetVariableByIndex(SHADER_TYPE ShaderType, Uint32 Index)override final; + virtual IShaderResourceVariable* GetVariableByIndex(SHADER_TYPE ShaderType, Uint32 Index) override final; - virtual void InitializeStaticResources(const IPipelineState* pPipelineState)override final; - - ShaderResourceCacheD3D12& GetResourceCache(){return m_ShaderResourceCache;} + virtual void InitializeStaticResources(const IPipelineState* pPipelineState) override final; + + ShaderResourceCacheD3D12& GetResourceCache() { return m_ShaderResourceCache; } #ifdef DEVELOPMENT - void dvpVerifyResourceBindings(const PipelineStateD3D12Impl* pPSO)const; + void dvpVerifyResourceBindings(const PipelineStateD3D12Impl* pPSO) const; #endif - bool StaticResourcesInitialized()const{return m_bStaticResourcesInitialized;} + bool StaticResourcesInitialized() const + { + return m_bStaticResourcesInitialized; + } private: - - ShaderResourceCacheD3D12 m_ShaderResourceCache; + ShaderResourceCacheD3D12 m_ShaderResourceCache; ShaderVariableManagerD3D12* m_pShaderVarMgrs = nullptr; // Resource layout index in m_ResourceLayouts[] array for every shader stage - Int8 m_ResourceLayoutIndex[6] = {-1, -1, -1, -1, -1, -1}; - bool m_bStaticResourcesInitialized = false; - const Uint8 m_NumShaders = 0; + Int8 m_ResourceLayoutIndex[6] = {-1, -1, -1, -1, -1, -1}; + bool m_bStaticResourcesInitialized = false; + const Uint8 m_NumShaders = 0; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderResourceCacheD3D12.h b/Graphics/GraphicsEngineD3D12/include/ShaderResourceCacheD3D12.h index 4f210d2c..243c508a 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderResourceCacheD3D12.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderResourceCacheD3D12.h @@ -29,7 +29,7 @@ // http://diligentgraphics.com/diligent-engine/architecture/d3d12/shader-resource-cache/ // Shader resource cache stores D3D12 resources in a continuous chunk of memory: -// +// // // __________________________________________________________ // m_pMemory | m_pResources, m_NumResources == m | @@ -39,24 +39,24 @@ // | A \ // | | \ // |________________________________________________| \RefCntAutoPtr -// m_pResources, m_NumResources == n \_________ +// m_pResources, m_NumResources == n \_________ // | Object | -// --------- +// --------- // // Nrt = m_NumTables // // // The cache is also assigned decriptor heap space to store shader visible descriptor handles (for non-dynamic resources). // -// +// // DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV -// | DescrptHndl[0] ... DescrptHndl[n-1] | DescrptHndl[0] ... DescrptHndl[m-1] | +// | DescrptHndl[0] ... DescrptHndl[n-1] | DescrptHndl[0] ... DescrptHndl[m-1] | // A A // | | // | TableStartOffset | TableStartOffset // | | // | RootTable[0] | RootTable[1] | RootTable[2] | .... | RootTable[Nrt] | -// | | +// | | // | TableStartOffset | InvalidDescriptorOffset // | | // V V @@ -87,7 +87,7 @@ namespace Diligent enum class CachedResourceType : Int32 { Unknown = -1, - CBV = 0, + CBV = 0, TexSRV, BufSRV, TexUAV, @@ -107,16 +107,21 @@ public: }; ShaderResourceCacheD3D12(DbgCacheContentType dbgContentType) + // clang-format off #ifdef _DEBUG - : m_DbgContentType{dbgContentType} + : m_DbgContentType + { + dbgContentType + } #endif + // clang-format on { } ~ShaderResourceCacheD3D12(); - static size_t GetRequiredMemorySize(Uint32 NumTables, - Uint32 TableSizes[]); + static size_t GetRequiredMemorySize(Uint32 NumTables, + Uint32 TableSizes[]); void Initialize(IMemoryAllocator& MemAllocator, Uint32 NumTables, @@ -130,57 +135,59 @@ public: CachedResourceType Type = CachedResourceType::Unknown; // CPU descriptor handle of a cached resource in CPU-only descriptor heap // Note that for dynamic resources, this is the only available CPU descriptor handle - D3D12_CPU_DESCRIPTOR_HANDLE CPUDescriptorHandle = {0}; + D3D12_CPU_DESCRIPTOR_HANDLE CPUDescriptorHandle = {0}; RefCntAutoPtr pObject; }; class RootTable { public: - RootTable(Uint32 NumResources, Resource *pResources)noexcept : + RootTable(Uint32 NumResources, Resource* pResources) noexcept : + // clang-format off m_NumResources{NumResources}, m_pResources {pResources } + // clang-format on {} - inline const Resource& GetResource(Uint32 OffsetFromTableStart)const + inline const Resource& GetResource(Uint32 OffsetFromTableStart) const { - VERIFY(OffsetFromTableStart < m_NumResources, "Root table is not large enough to store descriptor at offset ", OffsetFromTableStart ); + VERIFY(OffsetFromTableStart < m_NumResources, "Root table is not large enough to store descriptor at offset ", OffsetFromTableStart); return m_pResources[OffsetFromTableStart]; } - inline const Resource& GetResource(Uint32 OffsetFromTableStart, - const D3D12_DESCRIPTOR_HEAP_TYPE dbgDescriptorHeapType, - const SHADER_TYPE dbgRefShaderType)const + inline const Resource& GetResource(Uint32 OffsetFromTableStart, + const D3D12_DESCRIPTOR_HEAP_TYPE dbgDescriptorHeapType, + const SHADER_TYPE dbgRefShaderType) const { - VERIFY(m_dbgHeapType == dbgDescriptorHeapType, "Incosistent descriptor heap type" ); - VERIFY(m_dbgShaderType == dbgRefShaderType, "Incosistent shader type" ); + VERIFY(m_dbgHeapType == dbgDescriptorHeapType, "Incosistent descriptor heap type"); + VERIFY(m_dbgShaderType == dbgRefShaderType, "Incosistent shader type"); - VERIFY(OffsetFromTableStart < m_NumResources, "Root table is not large enough to store descriptor at offset ", OffsetFromTableStart ); + VERIFY(OffsetFromTableStart < m_NumResources, "Root table is not large enough to store descriptor at offset ", OffsetFromTableStart); return m_pResources[OffsetFromTableStart]; } - inline Resource& GetResource(Uint32 OffsetFromTableStart, - const D3D12_DESCRIPTOR_HEAP_TYPE dbgDescriptorHeapType, + inline Resource& GetResource(Uint32 OffsetFromTableStart, + const D3D12_DESCRIPTOR_HEAP_TYPE dbgDescriptorHeapType, const SHADER_TYPE dbgRefShaderType) { return const_cast(const_cast(this)->GetResource(OffsetFromTableStart, dbgDescriptorHeapType, dbgRefShaderType)); } - inline Uint32 GetSize()const{return m_NumResources; } + inline Uint32 GetSize() const { return m_NumResources; } // Offset from the start of the descriptor heap allocation to the start of the table Uint32 m_TableStartOffset = InvalidDescriptorOffset; #ifdef _DEBUG - void SetDebugAttribs(Uint32 MaxOffset, - const D3D12_DESCRIPTOR_HEAP_TYPE dbgDescriptorHeapType, + void SetDebugAttribs(Uint32 MaxOffset, + const D3D12_DESCRIPTOR_HEAP_TYPE dbgDescriptorHeapType, const SHADER_TYPE dbgRefShaderType) - { + { VERIFY_EXPR(m_NumResources == MaxOffset); m_dbgHeapType = dbgDescriptorHeapType; m_dbgShaderType = dbgRefShaderType; } - D3D12_DESCRIPTOR_HEAP_TYPE DbgGetHeapType()const{return m_dbgHeapType;} + D3D12_DESCRIPTOR_HEAP_TYPE DbgGetHeapType() const { return m_dbgHeapType; } #endif const Uint32 m_NumResources = 0; @@ -199,13 +206,13 @@ public: VERIFY_EXPR(RootIndex < m_NumTables); return reinterpret_cast(m_pMemory)[RootIndex]; } - inline const RootTable& GetRootTable(Uint32 RootIndex)const + inline const RootTable& GetRootTable(Uint32 RootIndex) const { VERIFY_EXPR(RootIndex < m_NumTables); return reinterpret_cast(m_pMemory)[RootIndex]; } - inline Uint32 GetNumRootTables()const{return m_NumTables; } + inline Uint32 GetNumRootTables() const { return m_NumTables; } void SetDescriptorHeapSpace(DescriptorHeapAllocation&& CbcSrvUavHeapSpace, DescriptorHeapAllocation&& SamplerHeapSpace) { @@ -214,10 +221,10 @@ public: Uint32 NumSamplerDescriptors = 0, NumSrvCbvUavDescriptors = 0; for (Uint32 rt = 0; rt < m_NumTables; ++rt) { - auto &Tbl = GetRootTable(rt); - if(Tbl.m_TableStartOffset != InvalidDescriptorOffset) + auto& Tbl = GetRootTable(rt); + if (Tbl.m_TableStartOffset != InvalidDescriptorOffset) { - if(Tbl.DbgGetHeapType() == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + if (Tbl.DbgGetHeapType() == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { VERIFY(Tbl.m_TableStartOffset == NumSrvCbvUavDescriptors, "Descriptor space allocation is not continuous"); NumSrvCbvUavDescriptors = std::max(NumSrvCbvUavDescriptors, Tbl.m_TableStartOffset + Tbl.GetSize()); @@ -229,37 +236,37 @@ public: } } } - VERIFY(NumSrvCbvUavDescriptors == CbcSrvUavHeapSpace.GetNumHandles() || NumSrvCbvUavDescriptors == 0 && CbcSrvUavHeapSpace.GetCpuHandle(0).ptr == 0, "Unexpected descriptor heap allocation size" ); - VERIFY(NumSamplerDescriptors == SamplerHeapSpace.GetNumHandles() || NumSamplerDescriptors == 0 && SamplerHeapSpace.GetCpuHandle(0).ptr == 0, "Unexpected descriptor heap allocation size" ); + VERIFY(NumSrvCbvUavDescriptors == CbcSrvUavHeapSpace.GetNumHandles() || NumSrvCbvUavDescriptors == 0 && CbcSrvUavHeapSpace.GetCpuHandle(0).ptr == 0, "Unexpected descriptor heap allocation size"); + VERIFY(NumSamplerDescriptors == SamplerHeapSpace.GetNumHandles() || NumSamplerDescriptors == 0 && SamplerHeapSpace.GetCpuHandle(0).ptr == 0, "Unexpected descriptor heap allocation size"); #endif m_CbvSrvUavHeapSpace = std::move(CbcSrvUavHeapSpace); - m_SamplerHeapSpace = std::move(SamplerHeapSpace); + m_SamplerHeapSpace = std::move(SamplerHeapSpace); } ID3D12DescriptorHeap* GetSrvCbvUavDescriptorHeap() { return m_CbvSrvUavHeapSpace.GetDescriptorHeap(); } - ID3D12DescriptorHeap* GetSamplerDescriptorHeap() { return m_SamplerHeapSpace.GetDescriptorHeap(); } + ID3D12DescriptorHeap* GetSamplerDescriptorHeap() { return m_SamplerHeapSpace.GetDescriptorHeap(); } // Returns CPU descriptor handle of a shader visible descriptor heap allocation - template + template D3D12_CPU_DESCRIPTOR_HANDLE GetShaderVisibleTableCPUDescriptorHandle(Uint32 RootParamInd, Uint32 OffsetFromTableStart = 0) const { const auto& RootParam = GetRootTable(RootParamInd); VERIFY(HeapType == RootParam.DbgGetHeapType(), "Invalid descriptor heap type"); D3D12_CPU_DESCRIPTOR_HANDLE CPUDescriptorHandle = {0}; - // Descriptor heap allocation is not assigned for dynamic resources or - // in a special case when resource cache is used to store static + // Descriptor heap allocation is not assigned for dynamic resources or + // in a special case when resource cache is used to store static // variable assignments for a shader. It is also not assigned to root views - if( RootParam.m_TableStartOffset != InvalidDescriptorOffset ) + if (RootParam.m_TableStartOffset != InvalidDescriptorOffset) { VERIFY(OffsetFromTableStart < RootParam.m_NumResources, "Offset is out of range"); - if( HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER ) + if (HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) { VERIFY_EXPR(!m_SamplerHeapSpace.IsNull()); CPUDescriptorHandle = m_SamplerHeapSpace.GetCpuHandle(RootParam.m_TableStartOffset + OffsetFromTableStart); } - else if( HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ) + else if (HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { VERIFY_EXPR(!m_CbvSrvUavHeapSpace.IsNull()); CPUDescriptorHandle = m_CbvSrvUavHeapSpace.GetCpuHandle(RootParam.m_TableStartOffset + OffsetFromTableStart); @@ -274,7 +281,7 @@ public: } // Returns GPU descriptor handle of a shader visible descriptor table - template + template D3D12_GPU_DESCRIPTOR_HANDLE GetShaderVisibleTableGPUDescriptorHandle(Uint32 RootParamInd, Uint32 OffsetFromTableStart = 0) const { const auto& RootParam = GetRootTable(RootParamInd); @@ -282,13 +289,13 @@ public: VERIFY(OffsetFromTableStart < RootParam.m_NumResources, "Offset is out of range"); D3D12_GPU_DESCRIPTOR_HANDLE GPUDescriptorHandle = {0}; - VERIFY( HeapType == RootParam.DbgGetHeapType(), "Invalid descriptor heap type"); - if( HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER ) + VERIFY(HeapType == RootParam.DbgGetHeapType(), "Invalid descriptor heap type"); + if (HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) { VERIFY_EXPR(!m_SamplerHeapSpace.IsNull()); GPUDescriptorHandle = m_SamplerHeapSpace.GetGpuHandle(RootParam.m_TableStartOffset + OffsetFromTableStart); } - else if( HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ) + else if (HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { VERIFY_EXPR(!m_CbvSrvUavHeapSpace.IsNull()); GPUDescriptorHandle = m_CbvSrvUavHeapSpace.GetGpuHandle(RootParam.m_TableStartOffset + OffsetFromTableStart); @@ -301,34 +308,36 @@ public: return GPUDescriptorHandle; } - Uint32& GetBoundDynamicCBsCounter() {return m_NumDynamicCBsBound;} + Uint32& GetBoundDynamicCBsCounter() { return m_NumDynamicCBsBound; } // Returns the number of dynamic constant buffers bound in the cache regardless of their variable types - Uint32 GetNumDynamicCBsBound()const{return m_NumDynamicCBsBound;} + Uint32 GetNumDynamicCBsBound() const { return m_NumDynamicCBsBound; } #ifdef _DEBUG // Only for debug purposes: indicates what types of resources are stored in the cache - DbgCacheContentType DbgGetContentType()const{return m_DbgContentType;} - void DbgVerifyBoundDynamicCBsCounter()const; + DbgCacheContentType DbgGetContentType() const { return m_DbgContentType; } + void DbgVerifyBoundDynamicCBsCounter() const; #endif private: + // clang-format off ShaderResourceCacheD3D12 (const ShaderResourceCacheD3D12&) = delete; ShaderResourceCacheD3D12 (ShaderResourceCacheD3D12&&) = delete; ShaderResourceCacheD3D12& operator = (const ShaderResourceCacheD3D12&) = delete; ShaderResourceCacheD3D12& operator = (ShaderResourceCacheD3D12&&) = delete; + // clang-format on // Allocation in a GPU-visible sampler descriptor heap DescriptorHeapAllocation m_SamplerHeapSpace; - + // Allocation in a GPU-visible CBV/SRV/UAV descriptor heap DescriptorHeapAllocation m_CbvSrvUavHeapSpace; - IMemoryAllocator* m_pAllocator = nullptr; - void* m_pMemory = nullptr; - Uint32 m_NumTables = 0; + IMemoryAllocator* m_pAllocator = nullptr; + void* m_pMemory = nullptr; + Uint32 m_NumTables = 0; // The number of the dynamic buffers bound in the resource cache regardless of their variable type - Uint32 m_NumDynamicCBsBound = 0; + Uint32 m_NumDynamicCBsBound = 0; #ifdef _DEBUG // Only for debug purposes: indicates what types of resources are stored in the cache @@ -336,4 +345,4 @@ private: #endif }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h b/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h index 6a251a24..0d670dd9 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h @@ -35,7 +35,7 @@ // | D3D12Resource[0] ... | D3D12Resource[s] ... | D3D12Resource[s+m] ... | D3D12Resource[smd] ... | D3D12Resource[smd+s'] ... | D3D12Resource[smd+s'+m'] ... D3D12Resource[s+m+d+s'+m'+d'-1] || // | | | | | | || // | SRV/CBV/UAV - STATIC | SRV/CBV/UAV - MUTABLE | SRV/CBV/UAV - DYNAMIC | Samplers - STATIC | Samplers - MUTABLE | Samplers - DYNAMIC || -// | | | | +// | | | | // // s == NumCbvSrvUav[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] // m == NumCbvSrvUav[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE] @@ -47,29 +47,29 @@ // d' == NumSamplers[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC] // // Every D3D12Resource structure holds a reference to D3DShaderResourceAttribs structure from ShaderResourcesD3D12. -// ShaderResourceLayoutD3D12 holds shared pointer to ShaderResourcesD3D12 instance. Note that ShaderResourcesD3D12::SamplerId -// references a sampler in ShaderResourcesD3D12, while D3D12Resource::SamplerId references a sampler in ShaderResourceLayoutD3D12, +// ShaderResourceLayoutD3D12 holds shared pointer to ShaderResourcesD3D12 instance. Note that ShaderResourcesD3D12::SamplerId +// references a sampler in ShaderResourcesD3D12, while D3D12Resource::SamplerId references a sampler in ShaderResourceLayoutD3D12, // and the two are not necessarily the same // -// +// // ________________SamplerId____________________ // | | // _____________________ ______________|_____________________________________________V________ // | | unique_ptr | | | | | | | // |ShaderResourcesD3D12 |--------------->| CBs | TexSRVs | TexUAVs | BufSRVs | BufUAVs | Samplers | // |_____________________| |________|___________|___________|___________|___________|____________| -// A A A A +// A A A A // | \ / \ // |shared_ptr Ref Ref Ref // ________|__________________ ________\________________________/_________________________\________________________________________________ // | | unique_ptr | | | | | | | // | ShaderResourceLayoutD3D12 |--------------->| D3D12Resource[0] | D3D12Resource[1] | ... | D3D12Resource[smd] | D3D12Resource[smd+1] | ... | // |___________________________| |__________________|__________________|_______________|____________________|______________________|__________| -// A A | A A -// | \ |______________\____SamplerId________________________| +// A A | A A +// | \ |______________\____SamplerId________________________| // | \ \ -// | Ref Ref -// | \ \_____ +// | Ref Ref +// | \ \_____ // | \ \ // ____________|_______________ ________\_______________________\__________________________________________ // | | | | | | @@ -80,7 +80,7 @@ // http://diligentgraphics.com/diligent-engine/architecture/d3d12/shader-resource-layout#Figure2 // Resources in the resource cache are identified by the root index and offset in the descriptor table // -// +// // ShaderResourceLayoutD3D12 is used as follows: // * Every pipeline state object (PipelineStateD3D12Impl) maintains shader resource layout for every active shader stage // ** These resource layouts are used as reference layouts for shader resource binding objects @@ -90,7 +90,7 @@ // ** The resource layout defines artificial layout where root index matches the resource type (CBV/SRV/UAV/SAM) // ** Only static variables are referenced // -// * Every shader resource binding object (ShaderResourceBindingD3D12Impl) encompasses shader variable +// * Every shader resource binding object (ShaderResourceBindingD3D12Impl) encompasses shader variable // manager (ShaderVariableManagerD3D12) for every active shader stage in the parent pipeline state that // handles mutable and dynamic resources @@ -108,11 +108,10 @@ namespace Diligent class ShaderResourceLayoutD3D12 final { public: - // There are two modes a layout can be constructed: // - initialize static resource layout and initialize shader resource cache to hold static resources - // - initialize reference layouts that address all types of resources (static, mutable, dynamic). - // Root indices and descriptor table offsets are assigned during the initialization; + // - initialize reference layouts that address all types of resources (static, mutable, dynamic). + // Root indices and descriptor table offsets are assigned during the initialization; // no shader resource cache is provided ShaderResourceLayoutD3D12(IObject& Owner, ID3D12Device* pd3d12Device, @@ -124,16 +123,20 @@ public: ShaderResourceCacheD3D12* pResourceCache, class RootSignature* pRootSig); + // clang-format off ShaderResourceLayoutD3D12 (const ShaderResourceLayoutD3D12&) = delete; ShaderResourceLayoutD3D12 (ShaderResourceLayoutD3D12&&) = delete; ShaderResourceLayoutD3D12& operator =(const ShaderResourceLayoutD3D12&) = delete; ShaderResourceLayoutD3D12& operator =(ShaderResourceLayoutD3D12&&) = delete; - + // clang-format on + ~ShaderResourceLayoutD3D12(); // sizeof(D3D12Resource) == 24 (x64) struct D3D12Resource final { + // clang-format off + D3D12Resource (const D3D12Resource&) = delete; D3D12Resource ( D3D12Resource&&) = delete; D3D12Resource& operator = (const D3D12Resource&) = delete; @@ -162,13 +165,16 @@ public: /*22 */ const Uint16 SamplerId; /*24 */ // End of data - D3D12Resource(const ShaderResourceLayoutD3D12& _ParentLayout, + // clang-format on + + D3D12Resource(const ShaderResourceLayoutD3D12& _ParentLayout, const D3DShaderResourceAttribs& _Attribs, SHADER_RESOURCE_VARIABLE_TYPE _VariableType, CachedResourceType _ResType, - Uint32 _RootIndex, - Uint32 _OffsetFromTableStart, - Uint32 _SamplerId)noexcept : + Uint32 _RootIndex, + Uint32 _OffsetFromTableStart, + Uint32 _SamplerId) noexcept : + // clang-format off ParentResLayout {_ParentLayout }, Attribs {_Attribs }, ResourceType {static_cast(_ResType) }, @@ -176,106 +182,112 @@ public: RootIndex {static_cast(_RootIndex) }, SamplerId {static_cast(_SamplerId) }, OffsetFromTableStart{ _OffsetFromTableStart } + // clang-format on { - VERIFY(IsValidOffset(), "Offset must be valid"); + VERIFY(IsValidOffset(), "Offset must be valid"); VERIFY(IsValidRootIndex(), "Root index must be valid"); - VERIFY(_RootIndex <= MaxRootIndex, "Root index (", _RootIndex, ") exceeds max allowed value (", MaxRootIndex, ")" ); + VERIFY(_RootIndex <= MaxRootIndex, "Root index (", _RootIndex, ") exceeds max allowed value (", MaxRootIndex, ")"); VERIFY(_VariableType < (1 << VariableTypeBits), "Variable type is out of representable range"); - VERIFY(_SamplerId == InvalidSamplerId || _SamplerId <= MaxSamplerId, "Sampler id (", _SamplerId, ") exceeds max allowed value (", MaxSamplerId, ")" ); + VERIFY(_SamplerId == InvalidSamplerId || _SamplerId <= MaxSamplerId, "Sampler id (", _SamplerId, ") exceeds max allowed value (", MaxSamplerId, ")"); VERIFY(_SamplerId == InvalidSamplerId || GetResType() == CachedResourceType::TexSRV, "A sampler can only be assigned to a Texture SRV"); } - bool IsBound(Uint32 ArrayIndex, - const ShaderResourceCacheD3D12& ResourceCache)const; + bool IsBound(Uint32 ArrayIndex, + const ShaderResourceCacheD3D12& ResourceCache) const; void BindResource(IDeviceObject* pObject, Uint32 ArrayIndex, - ShaderResourceCacheD3D12& ResourceCache)const; + ShaderResourceCacheD3D12& ResourceCache) const; + // clang-format off bool ValidSamplerAssigned()const { return SamplerId != InvalidSamplerId; } bool IsValidRootIndex() const { return RootIndex != InvalidRootIndex; } bool IsValidOffset() const { return OffsetFromTableStart != InvalidOffset; } + // clang-format on - CachedResourceType GetResType() const { return static_cast( ResourceType ); } + CachedResourceType GetResType() const { return static_cast(ResourceType); } SHADER_RESOURCE_VARIABLE_TYPE GetVariableType() const { return static_cast(VariableType); } private: - void CacheCB(IDeviceObject* pBuffer, - ShaderResourceCacheD3D12::Resource& DstRes, - Uint32 ArrayInd, + void CacheCB(IDeviceObject* pBuffer, + ShaderResourceCacheD3D12::Resource& DstRes, + Uint32 ArrayInd, D3D12_CPU_DESCRIPTOR_HANDLE ShdrVisibleHeapCPUDescriptorHandle, - Uint32& BoundDynamicCBsCounter)const; + Uint32& BoundDynamicCBsCounter) const; - template - void CacheResourceView(IDeviceObject* pView, - ShaderResourceCacheD3D12::Resource& DstRes, + template + void CacheResourceView(IDeviceObject* pView, + ShaderResourceCacheD3D12::Resource& DstRes, Uint32 ArrayIndex, - D3D12_CPU_DESCRIPTOR_HANDLE ShdrVisibleHeapCPUDescriptorHandle, - TViewTypeEnum dbgExpectedViewType, - TBindSamplerProcType BindSamplerProc)const; + D3D12_CPU_DESCRIPTOR_HANDLE ShdrVisibleHeapCPUDescriptorHandle, + TViewTypeEnum dbgExpectedViewType, + TBindSamplerProcType BindSamplerProc) const; void CacheSampler(IDeviceObject* pSampler, - ShaderResourceCacheD3D12::Resource& DstSam, + ShaderResourceCacheD3D12::Resource& DstSam, Uint32 ArrayIndex, - D3D12_CPU_DESCRIPTOR_HANDLE ShdrVisibleHeapCPUDescriptorHandle)const; + D3D12_CPU_DESCRIPTOR_HANDLE ShdrVisibleHeapCPUDescriptorHandle) const; }; - void CopyStaticResourceDesriptorHandles(const ShaderResourceCacheD3D12& SrcCache, + void CopyStaticResourceDesriptorHandles(const ShaderResourceCacheD3D12& SrcCache, const ShaderResourceLayoutD3D12& DstLayout, - ShaderResourceCacheD3D12& DstCache)const; + ShaderResourceCacheD3D12& DstCache) const; #ifdef DEVELOPMENT - bool dvpVerifyBindings(const ShaderResourceCacheD3D12& ResourceCache)const; + bool dvpVerifyBindings(const ShaderResourceCacheD3D12& ResourceCache) const; #endif - IObject& GetOwner(){return m_Owner;} + IObject& GetOwner() + { + return m_Owner; + } - Uint32 GetCbvSrvUavCount(SHADER_RESOURCE_VARIABLE_TYPE VarType)const + Uint32 GetCbvSrvUavCount(SHADER_RESOURCE_VARIABLE_TYPE VarType) const { return m_CbvSrvUavOffsets[VarType + 1] - m_CbvSrvUavOffsets[VarType]; } - Uint32 GetSamplerCount(SHADER_RESOURCE_VARIABLE_TYPE VarType)const + Uint32 GetSamplerCount(SHADER_RESOURCE_VARIABLE_TYPE VarType) const { return m_SamplersOffsets[VarType + 1] - m_SamplersOffsets[VarType]; } - const D3D12Resource& GetSrvCbvUav(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 r)const + const D3D12Resource& GetSrvCbvUav(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 r) const { - VERIFY_EXPR( r < GetCbvSrvUavCount(VarType) ); - return GetResource(GetSrvCbvUavOffset(VarType,r)); + VERIFY_EXPR(r < GetCbvSrvUavCount(VarType)); + return GetResource(GetSrvCbvUavOffset(VarType, r)); } - const D3D12Resource& GetSampler(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 s)const + const D3D12Resource& GetSampler(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 s) const { - VERIFY_EXPR( s < GetSamplerCount(VarType) ); - return GetResource(GetSamplerOffset(VarType,s)); + VERIFY_EXPR(s < GetSamplerCount(VarType)); + return GetResource(GetSamplerOffset(VarType, s)); } - const bool IsUsingSeparateSamplers() const {return !m_pResources->IsUsingCombinedTextureSamplers();} - - SHADER_TYPE GetShaderType() const {return m_pResources->GetShaderType();} + const bool IsUsingSeparateSamplers() const { return !m_pResources->IsUsingCombinedTextureSamplers(); } + + SHADER_TYPE GetShaderType() const { return m_pResources->GetShaderType(); } private: - const D3D12Resource& GetAssignedSampler(const D3D12Resource& TexSrv)const; - D3D12Resource& GetAssignedSampler(const D3D12Resource& TexSrv); + const D3D12Resource& GetAssignedSampler(const D3D12Resource& TexSrv) const; + D3D12Resource& GetAssignedSampler(const D3D12Resource& TexSrv); - const Char* GetShaderName()const + const Char* GetShaderName() const { return m_pResources->GetShaderName(); } - Uint32 GetTotalSrvCbvUavCount()const + Uint32 GetTotalSrvCbvUavCount() const { VERIFY_EXPR(m_CbvSrvUavOffsets[0] == 0); return m_CbvSrvUavOffsets[SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES]; } - Uint32 GetTotalSamplerCount()const + Uint32 GetTotalSamplerCount() const { return m_SamplersOffsets[SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES] - m_SamplersOffsets[0]; } - Uint32 GetTotalResourceCount()const + Uint32 GetTotalResourceCount() const { return m_SamplersOffsets[SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES]; } @@ -286,47 +298,48 @@ private: auto* Resource = reinterpret_cast(m_ResourceBuffer.get()); return Resource[r]; } - const D3D12Resource& GetResource(Uint32 r)const + const D3D12Resource& GetResource(Uint32 r) const { VERIFY_EXPR(r < GetTotalResourceCount()); auto* Resource = reinterpret_cast(m_ResourceBuffer.get()); return Resource[r]; } - Uint32 GetSrvCbvUavOffset(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 r)const + Uint32 GetSrvCbvUavOffset(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 r) const { Uint32 Offset = m_CbvSrvUavOffsets[VarType] + r; - VERIFY_EXPR( Offset < m_CbvSrvUavOffsets[VarType+1] ); + VERIFY_EXPR(Offset < m_CbvSrvUavOffsets[VarType + 1]); return Offset; } D3D12Resource& GetSrvCbvUav(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 r) { - VERIFY_EXPR( r < GetCbvSrvUavCount(VarType) ); - return GetResource(GetSrvCbvUavOffset(VarType,r)); + VERIFY_EXPR(r < GetCbvSrvUavCount(VarType)); + return GetResource(GetSrvCbvUavOffset(VarType, r)); } - Uint32 GetSamplerOffset(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 s)const + Uint32 GetSamplerOffset(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 s) const { auto Offset = m_SamplersOffsets[VarType] + s; - VERIFY_EXPR( Offset < m_SamplersOffsets[VarType+1] ); + VERIFY_EXPR(Offset < m_SamplersOffsets[VarType + 1]); return Offset; } D3D12Resource& GetSampler(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 s) { - VERIFY_EXPR( s < GetSamplerCount(VarType) ); - return GetResource(GetSamplerOffset(VarType,s)); + VERIFY_EXPR(s < GetSamplerCount(VarType)); + return GetResource(GetSamplerOffset(VarType, s)); } - const D3D12Resource& GetSampler(Uint32 s)const + const D3D12Resource& GetSampler(Uint32 s) const { - VERIFY_EXPR( s < GetTotalSamplerCount() ); + VERIFY_EXPR(s < GetTotalSamplerCount()); return GetResource(m_SamplersOffsets[0] + s); } - void AllocateMemory(IMemoryAllocator& Allocator, + void AllocateMemory(IMemoryAllocator& Allocator, const std::array& CbvSrvUavCount, const std::array& SamplerCount); + // clang-format off -/* 0 */ std::unique_ptr > m_ResourceBuffer; +/* 0 */ std::unique_ptr > m_ResourceBuffer; /* 16 */ std::array m_CbvSrvUavOffsets = {}; /* 24 */ std::array m_SamplersOffsets = {}; @@ -336,6 +349,8 @@ private: // there may be multiple objects referencing the same set of resources /* 48 */ std::shared_ptr m_pResources; /* 64 */ // End of data + + // clang-format on }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderResourcesD3D12.h b/Graphics/GraphicsEngineD3D12/include/ShaderResourcesD3D12.h index 60009e8c..6a9d2735 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderResourcesD3D12.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderResourcesD3D12.h @@ -39,7 +39,7 @@ // | | unique_ptr | | | | | | | // | ShaderResourcesD3D12 |--------------->| CBs | TexSRVs | TexUAVs | BufSRVs | BufUAVs | Samplers | // |______________________| |________|___________|___________|___________|___________|____________| -// A A A A +// A A A A // | \ / \ // |shared_ptr Ref Ref Ref // ________|__________________ ________\________________________/_________________________\_________________________________________ @@ -57,15 +57,15 @@ // // // One ShaderResourcesD3D12 instance can be referenced by multiple objects -// -// -// ________________________ __ __________ ________________________________ -// | | | | | | | | +// +// +// ________________________ __ __________ ________________________________ +// | | | | | | | | // | PipelineStateD3D12Impl |========>| ShaderResourceLayoutD3D12 |<-------| ShaderVariableManagerD3D12 |<====| ShaderResourceBindingD3D12Impl | -// |________________________| |____________________________| |____________________________| |________________________________| -// | A +// |________________________| |____________________________| |____________________________| |________________________________| +// | A // |shared_ptr \ -// _________________ ___________V__________ \ __________ ________________________________ +// _________________ ___________V__________ \ __________ ________________________________ // | | shared_ptr | | \ | | | | // | ShaderD3D12Impl |---------------->| ShaderResourcesD3D12 | '-------| ShaderVariableManagerD3D12 |<====| ShaderResourceBindingD3D12Impl | // |_________________| |______________________| |____________________________| |________________________________| @@ -76,7 +76,7 @@ // | | | | // | ShaderVariableManagerD3D12 |------>| ShaderResourceLayoutD3D12 | // |____________________________| |___________________________| -// +// #include "ShaderResources.h" @@ -90,10 +90,12 @@ public: // Loads shader resources from the compiled shader bytecode ShaderResourcesD3D12(ID3DBlob* pShaderBytecode, const ShaderDesc& ShdrDesc, const char* CombinedSamplerSuffix); + // clang-format off ShaderResourcesD3D12 (const ShaderResourcesD3D12&) = delete; ShaderResourcesD3D12 ( ShaderResourcesD3D12&&) = delete; ShaderResourcesD3D12& operator = (const ShaderResourcesD3D12&) = delete; ShaderResourcesD3D12& operator = ( ShaderResourcesD3D12&&) = delete; + // clang-format on }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h b/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h index 1670f6a6..01790145 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h @@ -26,7 +26,7 @@ /// \file /// Declaration of Diligent::ShaderVariableManagerD3D12 and Diligent::ShaderVariableD3D12Impl classes -// +// // * ShaderVariableManagerD3D12 keeps list of variables of specific types // * Every ShaderVariableD3D12Impl references D3D12Resource from ShaderResourceLayoutD3D12 // * ShaderVariableManagerD3D12 keeps pointer to ShaderResourceCacheD3D12 @@ -72,12 +72,12 @@ class ShaderVariableD3D12Impl; class ShaderVariableManagerD3D12 { public: - ShaderVariableManagerD3D12(IObject& Owner, - const ShaderResourceLayoutD3D12& Layout, - IMemoryAllocator& Allocator, - const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - ShaderResourceCacheD3D12& ResourceCache); + ShaderVariableManagerD3D12(IObject& Owner, + const ShaderResourceLayoutD3D12& Layout, + IMemoryAllocator& Allocator, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes, + ShaderResourceCacheD3D12& ResourceCache); ~ShaderVariableManagerD3D12(); void Destroy(IMemoryAllocator& Allocator); @@ -85,20 +85,22 @@ public: ShaderVariableD3D12Impl* GetVariable(const Char* Name); ShaderVariableD3D12Impl* GetVariable(Uint32 Index); - void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags); + void BindResources(IResourceMapping* pResourceMapping, Uint32 Flags); - static size_t GetRequiredMemorySize(const ShaderResourceLayoutD3D12& Layout, - const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - Uint32& NumVariables); + static size_t GetRequiredMemorySize(const ShaderResourceLayoutD3D12& Layout, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes, + Uint32& NumVariables); - Uint32 GetVariableCount()const { return m_NumVariables; } + Uint32 GetVariableCount() const { return m_NumVariables; } private: friend ShaderVariableD3D12Impl; Uint32 GetVariableIndex(const ShaderVariableD3D12Impl& Variable); + // clang-format off + IObject& m_Owner; // Variable mgr is owned by either Pipeline state object (in which case m_ResourceCache references @@ -116,39 +118,42 @@ private: #ifdef _DEBUG IMemoryAllocator& m_DbgAllocator; #endif + // clang-format on }; // sizeof(ShaderVariableD3D12Impl) == 24 (x64) class ShaderVariableD3D12Impl final : public IShaderResourceVariableD3D { public: - ShaderVariableD3D12Impl(ShaderVariableManagerD3D12& ParentManager, - const ShaderResourceLayoutD3D12::D3D12Resource& Resource) : + ShaderVariableD3D12Impl(ShaderVariableManagerD3D12& ParentManager, + const ShaderResourceLayoutD3D12::D3D12Resource& Resource) : m_ParentManager{ParentManager}, - m_Resource {Resource } + m_Resource{Resource} {} + // clang-format off ShaderVariableD3D12Impl (const ShaderVariableD3D12Impl&) = delete; ShaderVariableD3D12Impl (ShaderVariableD3D12Impl&&) = delete; ShaderVariableD3D12Impl& operator= (const ShaderVariableD3D12Impl&) = delete; ShaderVariableD3D12Impl& operator= (ShaderVariableD3D12Impl&&) = delete; + // clang-format on - virtual IReferenceCounters* GetReferenceCounters()const override final + virtual IReferenceCounters* GetReferenceCounters() const override final { return m_ParentManager.m_Owner.GetReferenceCounters(); } - virtual Atomics::Long AddRef()override final + virtual Atomics::Long AddRef() override final { return m_ParentManager.m_Owner.AddRef(); } - virtual Atomics::Long Release()override final + virtual Atomics::Long Release() override final { return m_ParentManager.m_Owner.Release(); } - void QueryInterface(const INTERFACE_ID &IID, IObject **ppInterface)override final + void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override final { if (ppInterface == nullptr) return; @@ -161,34 +166,34 @@ public: } } - virtual SHADER_RESOURCE_VARIABLE_TYPE GetType()const override final + virtual SHADER_RESOURCE_VARIABLE_TYPE GetType() const override final { return m_Resource.GetVariableType(); } - virtual void Set(IDeviceObject *pObject)override final + virtual void Set(IDeviceObject* pObject) override final { - m_Resource.BindResource(pObject, 0, m_ParentManager.m_ResourceCache); + m_Resource.BindResource(pObject, 0, m_ParentManager.m_ResourceCache); } - virtual void SetArray(IDeviceObject* const* ppObjects, Uint32 FirstElement, Uint32 NumElements)override final + virtual void SetArray(IDeviceObject* const* ppObjects, Uint32 FirstElement, Uint32 NumElements) override final { VerifyAndCorrectSetArrayArguments(m_Resource.Attribs.Name, m_Resource.Attribs.BindCount, FirstElement, NumElements); for (Uint32 Elem = 0; Elem < NumElements; ++Elem) m_Resource.BindResource(ppObjects[Elem], FirstElement + Elem, m_ParentManager.m_ResourceCache); } - virtual ShaderResourceDesc GetResourceDesc()const override final + virtual ShaderResourceDesc GetResourceDesc() const override final { return GetHLSLResourceDesc(); } - virtual HLSLShaderResourceDesc GetHLSLResourceDesc()const override final + virtual HLSLShaderResourceDesc GetHLSLResourceDesc() const override final { return m_Resource.Attribs.GetHLSLResourceDesc(); } - virtual Uint32 GetIndex()const override final + virtual Uint32 GetIndex() const override final { return m_ParentManager.GetVariableIndex(*this); } @@ -198,7 +203,7 @@ public: return m_Resource.IsBound(ArrayIndex, m_ParentManager.m_ResourceCache); } - const ShaderResourceLayoutD3D12::D3D12Resource& GetResource()const + const ShaderResourceLayoutD3D12::D3D12Resource& GetResource() const { return m_Resource; } @@ -210,4 +215,4 @@ private: const ShaderResourceLayoutD3D12::D3D12Resource& m_Resource; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/SwapChainD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/SwapChainD3D12Impl.h index 434fce0a..ad3beb16 100644 --- a/Graphics/GraphicsEngineD3D12/include/SwapChainD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/SwapChainD3D12Impl.h @@ -43,26 +43,26 @@ public: using TSwapChainBase = SwapChainD3DBase; SwapChainD3D12Impl(IReferenceCounters* pRefCounters, - const SwapChainDesc& SwapChainDesc, + const SwapChainDesc& SwapChainDesc, const FullScreenModeDesc& FSDesc, class RenderDeviceD3D12Impl* pRenderDeviceD3D12, class DeviceContextD3D12Impl* pDeviceContextD3D12, - void* pNativeWndHandle); + void* pNativeWndHandle); ~SwapChainD3D12Impl(); - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override final; /// Implementation of ISwapChain::Present() in Direct3D12 backend. - virtual void Present(Uint32 SyncInterval)override final; + virtual void Present(Uint32 SyncInterval) override final; /// Implementation of ISwapChain::Resize() in Direct3D12 backend. - virtual void Resize( Uint32 NewWidth, Uint32 NewHeight )override final; + virtual void Resize(Uint32 NewWidth, Uint32 NewHeight) override final; /// Implementation of ISwapChainD3D12::GetDXGISwapChain(). - virtual IDXGISwapChain* GetDXGISwapChain()override final{ return m_pSwapChain; } + virtual IDXGISwapChain* GetDXGISwapChain() override final { return m_pSwapChain; } /// Implementation of ISwapChain::GetCurrentBackBufferRTV() in Direct3D12 backend. - virtual ITextureViewD3D12* GetCurrentBackBufferRTV()override final + virtual ITextureViewD3D12* GetCurrentBackBufferRTV() override final { auto CurrentBackBufferIndex = m_pSwapChain->GetCurrentBackBufferIndex(); VERIFY_EXPR(CurrentBackBufferIndex >= 0 && CurrentBackBufferIndex < m_SwapChainDesc.BufferCount); @@ -70,14 +70,14 @@ public: } /// Implementation of ISwapChain::GetDepthBufferDSV() in Direct3D12 backend. - virtual ITextureViewD3D12* GetDepthBufferDSV()override final{return m_pDepthBufferDSV;} + virtual ITextureViewD3D12* GetDepthBufferDSV() override final { return m_pDepthBufferDSV; } private: - virtual void UpdateSwapChain(bool CreateNew)override final; - void InitBuffersAndViews(); + virtual void UpdateSwapChain(bool CreateNew) override final; + void InitBuffersAndViews(); - std::vector< RefCntAutoPtr, STDAllocatorRawMem> > m_pBackBufferRTV; - RefCntAutoPtr m_pDepthBufferDSV; + std::vector, STDAllocatorRawMem>> m_pBackBufferRTV; + RefCntAutoPtr m_pDepthBufferDSV; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/TextureD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/TextureD3D12Impl.h index d661850f..2c8a5828 100644 --- a/Graphics/GraphicsEngineD3D12/include/TextureD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/TextureD3D12Impl.h @@ -46,36 +46,36 @@ public: using ViewImplType = TextureViewD3D12Impl; // Creates a new D3D12 resource - TextureD3D12Impl(IReferenceCounters* pRefCounters, - FixedBlockMemoryAllocator& TexViewObjAllocator, - RenderDeviceD3D12Impl* pDeviceD3D12, - const TextureDesc& TexDesc, - const TextureData* pInitData = nullptr); + TextureD3D12Impl(IReferenceCounters* pRefCounters, + FixedBlockMemoryAllocator& TexViewObjAllocator, + RenderDeviceD3D12Impl* pDeviceD3D12, + const TextureDesc& TexDesc, + const TextureData* pInitData = nullptr); // Attaches to an existing D3D12 resource - TextureD3D12Impl(IReferenceCounters* pRefCounters, - FixedBlockMemoryAllocator& TexViewObjAllocator, - class RenderDeviceD3D12Impl* pDeviceD3D12, - const TextureDesc& TexDesc, - RESOURCE_STATE InitialState, - ID3D12Resource* pTexture); + TextureD3D12Impl(IReferenceCounters* pRefCounters, + FixedBlockMemoryAllocator& TexViewObjAllocator, + class RenderDeviceD3D12Impl* pDeviceD3D12, + const TextureDesc& TexDesc, + RESOURCE_STATE InitialState, + ID3D12Resource* pTexture); ~TextureD3D12Impl(); - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override final; /// Implementation of ITextureD3D12::GetD3D12Texture(). - virtual ID3D12Resource* GetD3D12Texture()override final{ return GetD3D12Resource(); } + virtual ID3D12Resource* GetD3D12Texture() override final { return GetD3D12Resource(); } /// Implementation of ITexture::GetNativeHandle() in Direct3D12 backend. - virtual void* GetNativeHandle()override final { return GetD3D12Texture(); } + virtual void* GetNativeHandle() override final { return GetD3D12Texture(); } /// Implementation of ITextureD3D12::SetD3D12ResourceState(). - virtual void SetD3D12ResourceState(D3D12_RESOURCE_STATES state)override final; + virtual void SetD3D12ResourceState(D3D12_RESOURCE_STATES state) override final; /// Implementation of ITextureD3D12::GetD3D12ResourceState(). - virtual D3D12_RESOURCE_STATES GetD3D12ResourceState()const override final; + virtual D3D12_RESOURCE_STATES GetD3D12ResourceState() const override final; - D3D12_RESOURCE_DESC GetD3D12TextureDesc()const; + D3D12_RESOURCE_DESC GetD3D12TextureDesc() const; const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& GetStagingFootprint(Uint32 Subresource) { @@ -85,17 +85,17 @@ public: } protected: - void CreateViewInternal( const struct TextureViewDesc &ViewDesc, ITextureView **ppView, bool bIsDefaultView )override final; + void CreateViewInternal(const struct TextureViewDesc& ViewDesc, ITextureView** ppView, bool bIsDefaultView) override final; //void PrepareD3D12InitData(const TextureData &InitData, Uint32 NumSubresources, std::vector &D3D12InitData); - void CreateSRV( TextureViewDesc& SRVDesc, D3D12_CPU_DESCRIPTOR_HANDLE SRVHandle ); - void CreateRTV( TextureViewDesc& RTVDesc, D3D12_CPU_DESCRIPTOR_HANDLE RTVHandle ); - void CreateDSV( TextureViewDesc& DSVDesc, D3D12_CPU_DESCRIPTOR_HANDLE DSVHandle ); - void CreateUAV( TextureViewDesc& UAVDesc, D3D12_CPU_DESCRIPTOR_HANDLE UAVHandle ); + void CreateSRV(TextureViewDesc& SRVDesc, D3D12_CPU_DESCRIPTOR_HANDLE SRVHandle); + void CreateRTV(TextureViewDesc& RTVDesc, D3D12_CPU_DESCRIPTOR_HANDLE RTVHandle); + void CreateDSV(TextureViewDesc& DSVDesc, D3D12_CPU_DESCRIPTOR_HANDLE DSVHandle); + void CreateUAV(TextureViewDesc& UAVDesc, D3D12_CPU_DESCRIPTOR_HANDLE UAVHandle); D3D12_PLACED_SUBRESOURCE_FOOTPRINT* m_StagingFootprints = nullptr; friend class RenderDeviceD3D12Impl; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/TextureViewD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/TextureViewD3D12Impl.h index eb032db8..e0d4c3eb 100644 --- a/Graphics/GraphicsEngineD3D12/include/TextureViewD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/TextureViewD3D12Impl.h @@ -43,27 +43,27 @@ class TextureViewD3D12Impl final : public TextureViewBase; - TextureViewD3D12Impl( IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pDevice, - const TextureViewDesc& ViewDesc, - class ITexture* pTexture, - DescriptorHeapAllocation&& Descriptor, - DescriptorHeapAllocation&& TexArraySRVDescriptor, - DescriptorHeapAllocation&& MipLevelUAVDescriptors, - bool bIsDefaultView); + TextureViewD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl* pDevice, + const TextureViewDesc& ViewDesc, + class ITexture* pTexture, + DescriptorHeapAllocation&& Descriptor, + DescriptorHeapAllocation&& TexArraySRVDescriptor, + DescriptorHeapAllocation&& MipLevelUAVDescriptors, + bool bIsDefaultView); ~TextureViewD3D12Impl(); - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override final; /// Implementation of ITextureViewD3D12::GetCPUDescriptorHandle(). - virtual D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle()override final + virtual D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle() override final { return m_Descriptor.GetCpuHandle(); } D3D12_CPU_DESCRIPTOR_HANDLE GetMipLevelUAV(Uint32 Mip) { - VERIFY_EXPR((m_Desc.Flags & TEXTURE_VIEW_FLAG_ALLOW_MIP_MAP_GENERATION) != 0 && m_MipGenerationDescriptors != nullptr && Mip < m_Desc.NumMipLevels ); + VERIFY_EXPR((m_Desc.Flags & TEXTURE_VIEW_FLAG_ALLOW_MIP_MAP_GENERATION) != 0 && m_MipGenerationDescriptors != nullptr && Mip < m_Desc.NumMipLevels); return m_MipGenerationDescriptors[1].GetCpuHandle(Mip); } @@ -83,4 +83,4 @@ protected: DescriptorHeapAllocation* m_MipGenerationDescriptors = nullptr; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/include/d3dx12_win.h b/Graphics/GraphicsEngineD3D12/include/d3dx12_win.h index ba59dfc7..87dd6088 100644 --- a/Graphics/GraphicsEngineD3D12/include/d3dx12_win.h +++ b/Graphics/GraphicsEngineD3D12/include/d3dx12_win.h @@ -12,39 +12,42 @@ #include "d3d12.h" -#if defined( __cplusplus ) +#if defined(__cplusplus) -struct CD3DX12_DEFAULT {}; +struct CD3DX12_DEFAULT +{}; extern const DECLSPEC_SELECTANY CD3DX12_DEFAULT D3D12_DEFAULT; //------------------------------------------------------------------------------------------------ -inline bool operator==( const D3D12_VIEWPORT& l, const D3D12_VIEWPORT& r ) +inline bool operator==(const D3D12_VIEWPORT& l, const D3D12_VIEWPORT& r) { return l.TopLeftX == r.TopLeftX && l.TopLeftY == r.TopLeftY && l.Width == r.Width && l.Height == r.Height && l.MinDepth == r.MinDepth && l.MaxDepth == r.MaxDepth; } //------------------------------------------------------------------------------------------------ -inline bool operator!=( const D3D12_VIEWPORT& l, const D3D12_VIEWPORT& r ) -{ return !( l == r ); } +inline bool operator!=(const D3D12_VIEWPORT& l, const D3D12_VIEWPORT& r) +{ + return !(l == r); +} //------------------------------------------------------------------------------------------------ struct CD3DX12_RECT : public D3D12_RECT { CD3DX12_RECT() {} - explicit CD3DX12_RECT( const D3D12_RECT& o ) : - D3D12_RECT( o ) + explicit CD3DX12_RECT(const D3D12_RECT& o) : + D3D12_RECT(o) {} explicit CD3DX12_RECT( LONG Left, LONG Top, LONG Right, - LONG Bottom ) + LONG Bottom) { - left = Left; - top = Top; - right = Right; + left = Left; + top = Top; + right = Right; bottom = Bottom; } ~CD3DX12_RECT() {} @@ -56,32 +59,32 @@ struct CD3DX12_BOX : public D3D12_BOX { CD3DX12_BOX() {} - explicit CD3DX12_BOX( const D3D12_BOX& o ) : - D3D12_BOX( o ) + explicit CD3DX12_BOX(const D3D12_BOX& o) : + D3D12_BOX(o) {} explicit CD3DX12_BOX( LONG Left, - LONG Right ) + LONG Right) { - left = Left; - top = 0; - front = 0; - right = Right; + left = Left; + top = 0; + front = 0; + right = Right; bottom = 1; - back = 1; + back = 1; } explicit CD3DX12_BOX( LONG Left, LONG Top, LONG Right, - LONG Bottom ) + LONG Bottom) { - left = Left; - top = Top; - front = 0; - right = Right; + left = Left; + top = Top; + front = 0; + right = Right; bottom = Bottom; - back = 1; + back = 1; } explicit CD3DX12_BOX( LONG Left, @@ -89,77 +92,79 @@ struct CD3DX12_BOX : public D3D12_BOX LONG Front, LONG Right, LONG Bottom, - LONG Back ) + LONG Back) { - left = Left; - top = Top; - front = Front; - right = Right; + left = Left; + top = Top; + front = Front; + right = Right; bottom = Bottom; - back = Back; + back = Back; } ~CD3DX12_BOX() {} operator const D3D12_BOX&() const { return *this; } }; -inline bool operator==( const D3D12_BOX& l, const D3D12_BOX& r ) +inline bool operator==(const D3D12_BOX& l, const D3D12_BOX& r) { return l.left == r.left && l.top == r.top && l.front == r.front && l.right == r.right && l.bottom == r.bottom && l.back == r.back; } -inline bool operator!=( const D3D12_BOX& l, const D3D12_BOX& r ) -{ return !( l == r ); } +inline bool operator!=(const D3D12_BOX& l, const D3D12_BOX& r) +{ + return !(l == r); +} //------------------------------------------------------------------------------------------------ struct CD3DX12_DEPTH_STENCIL_DESC : public D3D12_DEPTH_STENCIL_DESC { CD3DX12_DEPTH_STENCIL_DESC() {} - explicit CD3DX12_DEPTH_STENCIL_DESC( const D3D12_DEPTH_STENCIL_DESC& o ) : - D3D12_DEPTH_STENCIL_DESC( o ) + explicit CD3DX12_DEPTH_STENCIL_DESC(const D3D12_DEPTH_STENCIL_DESC& o) : + D3D12_DEPTH_STENCIL_DESC(o) {} - explicit CD3DX12_DEPTH_STENCIL_DESC( CD3DX12_DEFAULT ) + explicit CD3DX12_DEPTH_STENCIL_DESC(CD3DX12_DEFAULT) { - DepthEnable = TRUE; - DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; - DepthFunc = D3D12_COMPARISON_FUNC_LESS; - StencilEnable = FALSE; - StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; + DepthEnable = TRUE; + DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + DepthFunc = D3D12_COMPARISON_FUNC_LESS; + StencilEnable = FALSE; + StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK; const D3D12_DEPTH_STENCILOP_DESC defaultStencilOp = - { D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS }; + {D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS}; FrontFace = defaultStencilOp; - BackFace = defaultStencilOp; + BackFace = defaultStencilOp; } explicit CD3DX12_DEPTH_STENCIL_DESC( - BOOL depthEnable, + BOOL depthEnable, D3D12_DEPTH_WRITE_MASK depthWriteMask, - D3D12_COMPARISON_FUNC depthFunc, - BOOL stencilEnable, - UINT8 stencilReadMask, - UINT8 stencilWriteMask, - D3D12_STENCIL_OP frontStencilFailOp, - D3D12_STENCIL_OP frontStencilDepthFailOp, - D3D12_STENCIL_OP frontStencilPassOp, - D3D12_COMPARISON_FUNC frontStencilFunc, - D3D12_STENCIL_OP backStencilFailOp, - D3D12_STENCIL_OP backStencilDepthFailOp, - D3D12_STENCIL_OP backStencilPassOp, - D3D12_COMPARISON_FUNC backStencilFunc ) - { - DepthEnable = depthEnable; - DepthWriteMask = depthWriteMask; - DepthFunc = depthFunc; - StencilEnable = stencilEnable; - StencilReadMask = stencilReadMask; - StencilWriteMask = stencilWriteMask; - FrontFace.StencilFailOp = frontStencilFailOp; + D3D12_COMPARISON_FUNC depthFunc, + BOOL stencilEnable, + UINT8 stencilReadMask, + UINT8 stencilWriteMask, + D3D12_STENCIL_OP frontStencilFailOp, + D3D12_STENCIL_OP frontStencilDepthFailOp, + D3D12_STENCIL_OP frontStencilPassOp, + D3D12_COMPARISON_FUNC frontStencilFunc, + D3D12_STENCIL_OP backStencilFailOp, + D3D12_STENCIL_OP backStencilDepthFailOp, + D3D12_STENCIL_OP backStencilPassOp, + D3D12_COMPARISON_FUNC backStencilFunc) + { + DepthEnable = depthEnable; + DepthWriteMask = depthWriteMask; + DepthFunc = depthFunc; + StencilEnable = stencilEnable; + StencilReadMask = stencilReadMask; + StencilWriteMask = stencilWriteMask; + FrontFace.StencilFailOp = frontStencilFailOp; FrontFace.StencilDepthFailOp = frontStencilDepthFailOp; - FrontFace.StencilPassOp = frontStencilPassOp; - FrontFace.StencilFunc = frontStencilFunc; - BackFace.StencilFailOp = backStencilFailOp; - BackFace.StencilDepthFailOp = backStencilDepthFailOp; - BackFace.StencilPassOp = backStencilPassOp; - BackFace.StencilFunc = backStencilFunc; + FrontFace.StencilPassOp = frontStencilPassOp; + FrontFace.StencilFunc = frontStencilFunc; + BackFace.StencilFailOp = backStencilFailOp; + BackFace.StencilDepthFailOp = backStencilDepthFailOp; + BackFace.StencilPassOp = backStencilPassOp; + BackFace.StencilFunc = backStencilFunc; } ~CD3DX12_DEPTH_STENCIL_DESC() {} operator const D3D12_DEPTH_STENCIL_DESC&() const { return *this; } @@ -170,23 +175,28 @@ struct CD3DX12_BLEND_DESC : public D3D12_BLEND_DESC { CD3DX12_BLEND_DESC() {} - explicit CD3DX12_BLEND_DESC( const D3D12_BLEND_DESC& o ) : - D3D12_BLEND_DESC( o ) + explicit CD3DX12_BLEND_DESC(const D3D12_BLEND_DESC& o) : + D3D12_BLEND_DESC(o) {} - explicit CD3DX12_BLEND_DESC( CD3DX12_DEFAULT ) + explicit CD3DX12_BLEND_DESC(CD3DX12_DEFAULT) { - AlphaToCoverageEnable = FALSE; + AlphaToCoverageEnable = FALSE; IndependentBlendEnable = FALSE; const D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc = - { - FALSE,FALSE, - D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, - D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, - D3D12_LOGIC_OP_NOOP, - D3D12_COLOR_WRITE_ENABLE_ALL, - }; + { + FALSE, + FALSE, + D3D12_BLEND_ONE, + D3D12_BLEND_ZERO, + D3D12_BLEND_OP_ADD, + D3D12_BLEND_ONE, + D3D12_BLEND_ZERO, + D3D12_BLEND_OP_ADD, + D3D12_LOGIC_OP_NOOP, + D3D12_COLOR_WRITE_ENABLE_ALL, + }; for (UINT i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i) - RenderTarget[ i ] = defaultRenderTargetBlendDesc; + RenderTarget[i] = defaultRenderTargetBlendDesc; } ~CD3DX12_BLEND_DESC() {} operator const D3D12_BLEND_DESC&() const { return *this; } @@ -197,47 +207,47 @@ struct CD3DX12_RASTERIZER_DESC : public D3D12_RASTERIZER_DESC { CD3DX12_RASTERIZER_DESC() {} - explicit CD3DX12_RASTERIZER_DESC( const D3D12_RASTERIZER_DESC& o ) : - D3D12_RASTERIZER_DESC( o ) + explicit CD3DX12_RASTERIZER_DESC(const D3D12_RASTERIZER_DESC& o) : + D3D12_RASTERIZER_DESC(o) {} - explicit CD3DX12_RASTERIZER_DESC( CD3DX12_DEFAULT ) + explicit CD3DX12_RASTERIZER_DESC(CD3DX12_DEFAULT) { - FillMode = D3D12_FILL_MODE_SOLID; - CullMode = D3D12_CULL_MODE_BACK; + FillMode = D3D12_FILL_MODE_SOLID; + CullMode = D3D12_CULL_MODE_BACK; FrontCounterClockwise = FALSE; - DepthBias = D3D12_DEFAULT_DEPTH_BIAS; - DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP; - SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS; - DepthClipEnable = TRUE; - MultisampleEnable = FALSE; + DepthBias = D3D12_DEFAULT_DEPTH_BIAS; + DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP; + SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS; + DepthClipEnable = TRUE; + MultisampleEnable = FALSE; AntialiasedLineEnable = FALSE; - ForcedSampleCount = 0; - ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; + ForcedSampleCount = 0; + ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; } explicit CD3DX12_RASTERIZER_DESC( - D3D12_FILL_MODE fillMode, - D3D12_CULL_MODE cullMode, - BOOL frontCounterClockwise, - INT depthBias, - FLOAT depthBiasClamp, - FLOAT slopeScaledDepthBias, - BOOL depthClipEnable, - BOOL multisampleEnable, - BOOL antialiasedLineEnable, - UINT forcedSampleCount, + D3D12_FILL_MODE fillMode, + D3D12_CULL_MODE cullMode, + BOOL frontCounterClockwise, + INT depthBias, + FLOAT depthBiasClamp, + FLOAT slopeScaledDepthBias, + BOOL depthClipEnable, + BOOL multisampleEnable, + BOOL antialiasedLineEnable, + UINT forcedSampleCount, D3D12_CONSERVATIVE_RASTERIZATION_MODE conservativeRaster) { - FillMode = fillMode; - CullMode = cullMode; + FillMode = fillMode; + CullMode = cullMode; FrontCounterClockwise = frontCounterClockwise; - DepthBias = depthBias; - DepthBiasClamp = depthBiasClamp; - SlopeScaledDepthBias = slopeScaledDepthBias; - DepthClipEnable = depthClipEnable; - MultisampleEnable = multisampleEnable; + DepthBias = depthBias; + DepthBiasClamp = depthBiasClamp; + SlopeScaledDepthBias = slopeScaledDepthBias; + DepthClipEnable = depthClipEnable; + MultisampleEnable = multisampleEnable; AntialiasedLineEnable = antialiasedLineEnable; - ForcedSampleCount = forcedSampleCount; - ConservativeRaster = conservativeRaster; + ForcedSampleCount = forcedSampleCount; + ConservativeRaster = conservativeRaster; } ~CD3DX12_RASTERIZER_DESC() {} operator const D3D12_RASTERIZER_DESC&() const { return *this; } @@ -248,15 +258,15 @@ struct CD3DX12_RESOURCE_ALLOCATION_INFO : public D3D12_RESOURCE_ALLOCATION_INFO { CD3DX12_RESOURCE_ALLOCATION_INFO() {} - explicit CD3DX12_RESOURCE_ALLOCATION_INFO( const D3D12_RESOURCE_ALLOCATION_INFO& o ) : - D3D12_RESOURCE_ALLOCATION_INFO( o ) + explicit CD3DX12_RESOURCE_ALLOCATION_INFO(const D3D12_RESOURCE_ALLOCATION_INFO& o) : + D3D12_RESOURCE_ALLOCATION_INFO(o) {} CD3DX12_RESOURCE_ALLOCATION_INFO( UINT64 size, - UINT64 alignment ) + UINT64 alignment) { SizeInBytes = size; - Alignment = alignment; + Alignment = alignment; } operator const D3D12_RESOURCE_ALLOCATION_INFO&() const { return *this; } }; @@ -266,159 +276,164 @@ struct CD3DX12_HEAP_PROPERTIES : public D3D12_HEAP_PROPERTIES { CD3DX12_HEAP_PROPERTIES() {} - explicit CD3DX12_HEAP_PROPERTIES(const D3D12_HEAP_PROPERTIES &o) : + explicit CD3DX12_HEAP_PROPERTIES(const D3D12_HEAP_PROPERTIES& o) : D3D12_HEAP_PROPERTIES(o) {} - CD3DX12_HEAP_PROPERTIES( - D3D12_CPU_PAGE_PROPERTY cpuPageProperty, - D3D12_MEMORY_POOL memoryPoolPreference, - UINT creationNodeMask = 1, - UINT nodeMask = 1 ) - { - Type = D3D12_HEAP_TYPE_CUSTOM; - CPUPageProperty = cpuPageProperty; + CD3DX12_HEAP_PROPERTIES( + D3D12_CPU_PAGE_PROPERTY cpuPageProperty, + D3D12_MEMORY_POOL memoryPoolPreference, + UINT creationNodeMask = 1, + UINT nodeMask = 1) + { + Type = D3D12_HEAP_TYPE_CUSTOM; + CPUPageProperty = cpuPageProperty; MemoryPoolPreference = memoryPoolPreference; - CreationNodeMask = creationNodeMask; - VisibleNodeMask = nodeMask; + CreationNodeMask = creationNodeMask; + VisibleNodeMask = nodeMask; } - explicit CD3DX12_HEAP_PROPERTIES( - D3D12_HEAP_TYPE type, - UINT creationNodeMask = 1, - UINT nodeMask = 1 ) + explicit CD3DX12_HEAP_PROPERTIES( + D3D12_HEAP_TYPE type, + UINT creationNodeMask = 1, + UINT nodeMask = 1) { - Type = type; - CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; + Type = type; + CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; - CreationNodeMask = creationNodeMask; - VisibleNodeMask = nodeMask; + CreationNodeMask = creationNodeMask; + VisibleNodeMask = nodeMask; } operator const D3D12_HEAP_PROPERTIES&() const { return *this; } bool IsCPUAccessible() const { - return Type == D3D12_HEAP_TYPE_UPLOAD || Type == D3D12_HEAP_TYPE_READBACK || (Type == D3D12_HEAP_TYPE_CUSTOM && - (CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE || CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK)); + return Type == D3D12_HEAP_TYPE_UPLOAD || Type == D3D12_HEAP_TYPE_READBACK || (Type == D3D12_HEAP_TYPE_CUSTOM && (CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE || CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK)); } }; -inline bool operator==( const D3D12_HEAP_PROPERTIES& l, const D3D12_HEAP_PROPERTIES& r ) +inline bool operator==(const D3D12_HEAP_PROPERTIES& l, const D3D12_HEAP_PROPERTIES& r) { - return l.Type == r.Type && l.CPUPageProperty == r.CPUPageProperty && + return l.Type == r.Type && l.CPUPageProperty == r.CPUPageProperty && l.MemoryPoolPreference == r.MemoryPoolPreference && l.CreationNodeMask == r.CreationNodeMask && l.VisibleNodeMask == r.VisibleNodeMask; } -inline bool operator!=( const D3D12_HEAP_PROPERTIES& l, const D3D12_HEAP_PROPERTIES& r ) -{ return !( l == r ); } +inline bool operator!=(const D3D12_HEAP_PROPERTIES& l, const D3D12_HEAP_PROPERTIES& r) +{ + return !(l == r); +} //------------------------------------------------------------------------------------------------ struct CD3DX12_HEAP_DESC : public D3D12_HEAP_DESC { CD3DX12_HEAP_DESC() {} - explicit CD3DX12_HEAP_DESC(const D3D12_HEAP_DESC &o) : + explicit CD3DX12_HEAP_DESC(const D3D12_HEAP_DESC& o) : D3D12_HEAP_DESC(o) {} - CD3DX12_HEAP_DESC( - UINT64 size, - D3D12_HEAP_PROPERTIES properties, - UINT64 alignment = 0, - D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) + CD3DX12_HEAP_DESC( + UINT64 size, + D3D12_HEAP_PROPERTIES properties, + UINT64 alignment = 0, + D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE) { SizeInBytes = size; - Properties = properties; - Alignment = alignment; - Flags = flags; + Properties = properties; + Alignment = alignment; + Flags = flags; } - CD3DX12_HEAP_DESC( - UINT64 size, - D3D12_HEAP_TYPE type, - UINT64 alignment = 0, - D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) + CD3DX12_HEAP_DESC( + UINT64 size, + D3D12_HEAP_TYPE type, + UINT64 alignment = 0, + D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE) { SizeInBytes = size; - Properties = CD3DX12_HEAP_PROPERTIES( type ); - Alignment = alignment; - Flags = flags; + Properties = CD3DX12_HEAP_PROPERTIES(type); + Alignment = alignment; + Flags = flags; } - CD3DX12_HEAP_DESC( - UINT64 size, - D3D12_CPU_PAGE_PROPERTY cpuPageProperty, - D3D12_MEMORY_POOL memoryPoolPreference, - UINT64 alignment = 0, - D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) + CD3DX12_HEAP_DESC( + UINT64 size, + D3D12_CPU_PAGE_PROPERTY cpuPageProperty, + D3D12_MEMORY_POOL memoryPoolPreference, + UINT64 alignment = 0, + D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE) { SizeInBytes = size; - Properties = CD3DX12_HEAP_PROPERTIES( cpuPageProperty, memoryPoolPreference ); - Alignment = alignment; - Flags = flags; + Properties = CD3DX12_HEAP_PROPERTIES(cpuPageProperty, memoryPoolPreference); + Alignment = alignment; + Flags = flags; } - CD3DX12_HEAP_DESC( + CD3DX12_HEAP_DESC( const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo, - D3D12_HEAP_PROPERTIES properties, - D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) + D3D12_HEAP_PROPERTIES properties, + D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE) { SizeInBytes = resAllocInfo.SizeInBytes; - Properties = properties; - Alignment = resAllocInfo.Alignment; - Flags = flags; + Properties = properties; + Alignment = resAllocInfo.Alignment; + Flags = flags; } - CD3DX12_HEAP_DESC( + CD3DX12_HEAP_DESC( const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo, - D3D12_HEAP_TYPE type, - D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) + D3D12_HEAP_TYPE type, + D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE) { SizeInBytes = resAllocInfo.SizeInBytes; - Properties = CD3DX12_HEAP_PROPERTIES( type ); - Alignment = resAllocInfo.Alignment; - Flags = flags; + Properties = CD3DX12_HEAP_PROPERTIES(type); + Alignment = resAllocInfo.Alignment; + Flags = flags; } - CD3DX12_HEAP_DESC( + CD3DX12_HEAP_DESC( const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo, - D3D12_CPU_PAGE_PROPERTY cpuPageProperty, - D3D12_MEMORY_POOL memoryPoolPreference, - D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) + D3D12_CPU_PAGE_PROPERTY cpuPageProperty, + D3D12_MEMORY_POOL memoryPoolPreference, + D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE) { SizeInBytes = resAllocInfo.SizeInBytes; - Properties = CD3DX12_HEAP_PROPERTIES( cpuPageProperty, memoryPoolPreference ); - Alignment = resAllocInfo.Alignment; - Flags = flags; + Properties = CD3DX12_HEAP_PROPERTIES(cpuPageProperty, memoryPoolPreference); + Alignment = resAllocInfo.Alignment; + Flags = flags; } operator const D3D12_HEAP_DESC&() const { return *this; } bool IsCPUAccessible() const - { return static_cast< const CD3DX12_HEAP_PROPERTIES* >( &Properties )->IsCPUAccessible(); } + { + return static_cast(&Properties)->IsCPUAccessible(); + } }; -inline bool operator==( const D3D12_HEAP_DESC& l, const D3D12_HEAP_DESC& r ) +inline bool operator==(const D3D12_HEAP_DESC& l, const D3D12_HEAP_DESC& r) { return l.SizeInBytes == r.SizeInBytes && - l.Properties == r.Properties && + l.Properties == r.Properties && l.Alignment == r.Alignment && l.Flags == r.Flags; } -inline bool operator!=( const D3D12_HEAP_DESC& l, const D3D12_HEAP_DESC& r ) -{ return !( l == r ); } +inline bool operator!=(const D3D12_HEAP_DESC& l, const D3D12_HEAP_DESC& r) +{ + return !(l == r); +} //------------------------------------------------------------------------------------------------ struct CD3DX12_CLEAR_VALUE : public D3D12_CLEAR_VALUE { CD3DX12_CLEAR_VALUE() {} - explicit CD3DX12_CLEAR_VALUE(const D3D12_CLEAR_VALUE &o) : + explicit CD3DX12_CLEAR_VALUE(const D3D12_CLEAR_VALUE& o) : D3D12_CLEAR_VALUE(o) {} - CD3DX12_CLEAR_VALUE( - DXGI_FORMAT format, - const FLOAT color[4] ) + CD3DX12_CLEAR_VALUE( + DXGI_FORMAT format, + const FLOAT color[4]) { Format = format; - memcpy( Color, color, sizeof( Color ) ); + memcpy(Color, color, sizeof(Color)); } - CD3DX12_CLEAR_VALUE( - DXGI_FORMAT format, - FLOAT depth, - UINT8 stencil ) + CD3DX12_CLEAR_VALUE( + DXGI_FORMAT format, + FLOAT depth, + UINT8 stencil) { Format = format; /* Use memcpy to preserve NAN values */ - memcpy( &DepthStencil.Depth, &depth, sizeof( depth ) ); + memcpy(&DepthStencil.Depth, &depth, sizeof(depth)); DepthStencil.Stencil = stencil; } operator const D3D12_CLEAR_VALUE&() const { return *this; } @@ -429,15 +444,15 @@ struct CD3DX12_RANGE : public D3D12_RANGE { CD3DX12_RANGE() {} - explicit CD3DX12_RANGE(const D3D12_RANGE &o) : + explicit CD3DX12_RANGE(const D3D12_RANGE& o) : D3D12_RANGE(o) {} - CD3DX12_RANGE( - SIZE_T begin, - SIZE_T end ) + CD3DX12_RANGE( + SIZE_T begin, + SIZE_T end) { Begin = begin; - End = end; + End = end; } operator const D3D12_RANGE&() const { return *this; } }; @@ -447,18 +462,18 @@ struct CD3DX12_TILED_RESOURCE_COORDINATE : public D3D12_TILED_RESOURCE_COORDINAT { CD3DX12_TILED_RESOURCE_COORDINATE() {} - explicit CD3DX12_TILED_RESOURCE_COORDINATE(const D3D12_TILED_RESOURCE_COORDINATE &o) : + explicit CD3DX12_TILED_RESOURCE_COORDINATE(const D3D12_TILED_RESOURCE_COORDINATE& o) : D3D12_TILED_RESOURCE_COORDINATE(o) {} - CD3DX12_TILED_RESOURCE_COORDINATE( - UINT x, - UINT y, - UINT z, - UINT subresource ) - { - X = x; - Y = y; - Z = z; + CD3DX12_TILED_RESOURCE_COORDINATE( + UINT x, + UINT y, + UINT z, + UINT subresource) + { + X = x; + Y = y; + Z = z; Subresource = subresource; } operator const D3D12_TILED_RESOURCE_COORDINATE&() const { return *this; } @@ -469,21 +484,21 @@ struct CD3DX12_TILE_REGION_SIZE : public D3D12_TILE_REGION_SIZE { CD3DX12_TILE_REGION_SIZE() {} - explicit CD3DX12_TILE_REGION_SIZE(const D3D12_TILE_REGION_SIZE &o) : + explicit CD3DX12_TILE_REGION_SIZE(const D3D12_TILE_REGION_SIZE& o) : D3D12_TILE_REGION_SIZE(o) {} - CD3DX12_TILE_REGION_SIZE( - UINT numTiles, - BOOL useBox, - UINT width, - UINT16 height, - UINT16 depth ) + CD3DX12_TILE_REGION_SIZE( + UINT numTiles, + BOOL useBox, + UINT width, + UINT16 height, + UINT16 depth) { NumTiles = numTiles; - UseBox = useBox; - Width = width; - Height = height; - Depth = depth; + UseBox = useBox; + Width = width; + Height = height; + Depth = depth; } operator const D3D12_TILE_REGION_SIZE&() const { return *this; } }; @@ -493,18 +508,18 @@ struct CD3DX12_SUBRESOURCE_TILING : public D3D12_SUBRESOURCE_TILING { CD3DX12_SUBRESOURCE_TILING() {} - explicit CD3DX12_SUBRESOURCE_TILING(const D3D12_SUBRESOURCE_TILING &o) : + explicit CD3DX12_SUBRESOURCE_TILING(const D3D12_SUBRESOURCE_TILING& o) : D3D12_SUBRESOURCE_TILING(o) {} - CD3DX12_SUBRESOURCE_TILING( - UINT widthInTiles, - UINT16 heightInTiles, - UINT16 depthInTiles, - UINT startTileIndexInOverallResource ) - { - WidthInTiles = widthInTiles; - HeightInTiles = heightInTiles; - DepthInTiles = depthInTiles; + CD3DX12_SUBRESOURCE_TILING( + UINT widthInTiles, + UINT16 heightInTiles, + UINT16 depthInTiles, + UINT startTileIndexInOverallResource) + { + WidthInTiles = widthInTiles; + HeightInTiles = heightInTiles; + DepthInTiles = depthInTiles; StartTileIndexInOverallResource = startTileIndexInOverallResource; } operator const D3D12_SUBRESOURCE_TILING&() const { return *this; } @@ -515,17 +530,17 @@ struct CD3DX12_TILE_SHAPE : public D3D12_TILE_SHAPE { CD3DX12_TILE_SHAPE() {} - explicit CD3DX12_TILE_SHAPE(const D3D12_TILE_SHAPE &o) : + explicit CD3DX12_TILE_SHAPE(const D3D12_TILE_SHAPE& o) : D3D12_TILE_SHAPE(o) {} - CD3DX12_TILE_SHAPE( - UINT widthInTexels, - UINT heightInTexels, - UINT depthInTexels ) + CD3DX12_TILE_SHAPE( + UINT widthInTexels, + UINT heightInTexels, + UINT depthInTexels) { - WidthInTexels = widthInTexels; + WidthInTexels = widthInTexels; HeightInTexels = heightInTexels; - DepthInTexels = depthInTexels; + DepthInTexels = depthInTexels; } operator const D3D12_TILE_SHAPE&() const { return *this; } }; @@ -535,25 +550,25 @@ struct CD3DX12_RESOURCE_BARRIER : public D3D12_RESOURCE_BARRIER { CD3DX12_RESOURCE_BARRIER() {} - explicit CD3DX12_RESOURCE_BARRIER(const D3D12_RESOURCE_BARRIER &o) : + explicit CD3DX12_RESOURCE_BARRIER(const D3D12_RESOURCE_BARRIER& o) : D3D12_RESOURCE_BARRIER(o) {} static inline CD3DX12_RESOURCE_BARRIER Transition( - _In_ ID3D12Resource* pResource, - D3D12_RESOURCE_STATES stateBefore, - D3D12_RESOURCE_STATES stateAfter, - UINT subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, - D3D12_RESOURCE_BARRIER_FLAGS flags = D3D12_RESOURCE_BARRIER_FLAG_NONE) + _In_ ID3D12Resource* pResource, + D3D12_RESOURCE_STATES stateBefore, + D3D12_RESOURCE_STATES stateAfter, + UINT subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_BARRIER_FLAGS flags = D3D12_RESOURCE_BARRIER_FLAG_NONE) { CD3DX12_RESOURCE_BARRIER result; ZeroMemory(&result, sizeof(result)); - D3D12_RESOURCE_BARRIER &barrier = result; - result.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - result.Flags = flags; - barrier.Transition.pResource = pResource; - barrier.Transition.StateBefore = stateBefore; - barrier.Transition.StateAfter = stateAfter; - barrier.Transition.Subresource = subresource; + D3D12_RESOURCE_BARRIER& barrier = result; + result.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + result.Flags = flags; + barrier.Transition.pResource = pResource; + barrier.Transition.StateBefore = stateBefore; + barrier.Transition.StateAfter = stateAfter; + barrier.Transition.Subresource = subresource; return result; } static inline CD3DX12_RESOURCE_BARRIER Aliasing( @@ -562,10 +577,10 @@ struct CD3DX12_RESOURCE_BARRIER : public D3D12_RESOURCE_BARRIER { CD3DX12_RESOURCE_BARRIER result; ZeroMemory(&result, sizeof(result)); - D3D12_RESOURCE_BARRIER &barrier = result; - result.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; + D3D12_RESOURCE_BARRIER& barrier = result; + result.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; barrier.Aliasing.pResourceBefore = pResourceBefore; - barrier.Aliasing.pResourceAfter = pResourceAfter; + barrier.Aliasing.pResourceAfter = pResourceAfter; return result; } static inline CD3DX12_RESOURCE_BARRIER UAV( @@ -573,9 +588,9 @@ struct CD3DX12_RESOURCE_BARRIER : public D3D12_RESOURCE_BARRIER { CD3DX12_RESOURCE_BARRIER result; ZeroMemory(&result, sizeof(result)); - D3D12_RESOURCE_BARRIER &barrier = result; - result.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; - barrier.UAV.pResource = pResource; + D3D12_RESOURCE_BARRIER& barrier = result; + result.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + barrier.UAV.pResource = pResource; return result; } operator const D3D12_RESOURCE_BARRIER&() const { return *this; } @@ -586,18 +601,18 @@ struct CD3DX12_PACKED_MIP_INFO : public D3D12_PACKED_MIP_INFO { CD3DX12_PACKED_MIP_INFO() {} - explicit CD3DX12_PACKED_MIP_INFO(const D3D12_PACKED_MIP_INFO &o) : + explicit CD3DX12_PACKED_MIP_INFO(const D3D12_PACKED_MIP_INFO& o) : D3D12_PACKED_MIP_INFO(o) {} - CD3DX12_PACKED_MIP_INFO( - UINT8 numStandardMips, - UINT8 numPackedMips, - UINT numTilesForPackedMips, - UINT startTileIndexInOverallResource ) - { - NumStandardMips = numStandardMips; - NumPackedMips = numPackedMips; - NumTilesForPackedMips = numTilesForPackedMips; + CD3DX12_PACKED_MIP_INFO( + UINT8 numStandardMips, + UINT8 numPackedMips, + UINT numTilesForPackedMips, + UINT startTileIndexInOverallResource) + { + NumStandardMips = numStandardMips; + NumPackedMips = numPackedMips; + NumTilesForPackedMips = numTilesForPackedMips; StartTileIndexInOverallResource = startTileIndexInOverallResource; } operator const D3D12_PACKED_MIP_INFO&() const { return *this; } @@ -608,30 +623,30 @@ struct CD3DX12_SUBRESOURCE_FOOTPRINT : public D3D12_SUBRESOURCE_FOOTPRINT { CD3DX12_SUBRESOURCE_FOOTPRINT() {} - explicit CD3DX12_SUBRESOURCE_FOOTPRINT(const D3D12_SUBRESOURCE_FOOTPRINT &o) : + explicit CD3DX12_SUBRESOURCE_FOOTPRINT(const D3D12_SUBRESOURCE_FOOTPRINT& o) : D3D12_SUBRESOURCE_FOOTPRINT(o) {} - CD3DX12_SUBRESOURCE_FOOTPRINT( - DXGI_FORMAT format, - UINT width, - UINT height, - UINT depth, - UINT rowPitch ) - { - Format = format; - Width = width; - Height = height; - Depth = depth; + CD3DX12_SUBRESOURCE_FOOTPRINT( + DXGI_FORMAT format, + UINT width, + UINT height, + UINT depth, + UINT rowPitch) + { + Format = format; + Width = width; + Height = height; + Depth = depth; RowPitch = rowPitch; } - explicit CD3DX12_SUBRESOURCE_FOOTPRINT( - const D3D12_RESOURCE_DESC& resDesc, - UINT rowPitch ) + explicit CD3DX12_SUBRESOURCE_FOOTPRINT( + const D3D12_RESOURCE_DESC& resDesc, + UINT rowPitch) { - Format = resDesc.Format; - Width = UINT( resDesc.Width ); - Height = resDesc.Height; - Depth = (resDesc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? resDesc.DepthOrArraySize : 1); + Format = resDesc.Format; + Width = UINT(resDesc.Width); + Height = resDesc.Height; + Depth = (resDesc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? resDesc.DepthOrArraySize : 1); RowPitch = rowPitch; } operator const D3D12_SUBRESOURCE_FOOTPRINT&() const { return *this; } @@ -639,69 +654,69 @@ struct CD3DX12_SUBRESOURCE_FOOTPRINT : public D3D12_SUBRESOURCE_FOOTPRINT //------------------------------------------------------------------------------------------------ struct CD3DX12_TEXTURE_COPY_LOCATION : public D3D12_TEXTURE_COPY_LOCATION -{ +{ CD3DX12_TEXTURE_COPY_LOCATION() {} - explicit CD3DX12_TEXTURE_COPY_LOCATION(const D3D12_TEXTURE_COPY_LOCATION &o) : + explicit CD3DX12_TEXTURE_COPY_LOCATION(const D3D12_TEXTURE_COPY_LOCATION& o) : D3D12_TEXTURE_COPY_LOCATION(o) {} CD3DX12_TEXTURE_COPY_LOCATION(ID3D12Resource* pRes) { pResource = pRes; } CD3DX12_TEXTURE_COPY_LOCATION(ID3D12Resource* pRes, D3D12_PLACED_SUBRESOURCE_FOOTPRINT const& Footprint) { - pResource = pRes; - Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + pResource = pRes; + Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; PlacedFootprint = Footprint; } CD3DX12_TEXTURE_COPY_LOCATION(ID3D12Resource* pRes, UINT Sub) { - pResource = pRes; - Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + pResource = pRes; + Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; SubresourceIndex = Sub; } -}; +}; //------------------------------------------------------------------------------------------------ struct CD3DX12_DESCRIPTOR_RANGE : public D3D12_DESCRIPTOR_RANGE { - CD3DX12_DESCRIPTOR_RANGE() { } - explicit CD3DX12_DESCRIPTOR_RANGE(const D3D12_DESCRIPTOR_RANGE &o) : + CD3DX12_DESCRIPTOR_RANGE() {} + explicit CD3DX12_DESCRIPTOR_RANGE(const D3D12_DESCRIPTOR_RANGE& o) : D3D12_DESCRIPTOR_RANGE(o) {} CD3DX12_DESCRIPTOR_RANGE( D3D12_DESCRIPTOR_RANGE_TYPE rangeType, - UINT numDescriptors, - UINT baseShaderRegister, - UINT registerSpace = 0, - UINT offsetInDescriptorsFromTableStart = - D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) + UINT numDescriptors, + UINT baseShaderRegister, + UINT registerSpace = 0, + UINT offsetInDescriptorsFromTableStart = + D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) { Init(rangeType, numDescriptors, baseShaderRegister, registerSpace, offsetInDescriptorsFromTableStart); } - + inline void Init( D3D12_DESCRIPTOR_RANGE_TYPE rangeType, - UINT numDescriptors, - UINT baseShaderRegister, - UINT registerSpace = 0, - UINT offsetInDescriptorsFromTableStart = - D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) + UINT numDescriptors, + UINT baseShaderRegister, + UINT registerSpace = 0, + UINT offsetInDescriptorsFromTableStart = + D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) { Init(*this, rangeType, numDescriptors, baseShaderRegister, registerSpace, offsetInDescriptorsFromTableStart); } - + static inline void Init( - _Out_ D3D12_DESCRIPTOR_RANGE &range, - D3D12_DESCRIPTOR_RANGE_TYPE rangeType, - UINT numDescriptors, - UINT baseShaderRegister, - UINT registerSpace = 0, - UINT offsetInDescriptorsFromTableStart = - D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) - { - range.RangeType = rangeType; - range.NumDescriptors = numDescriptors; - range.BaseShaderRegister = baseShaderRegister; - range.RegisterSpace = registerSpace; + _Out_ D3D12_DESCRIPTOR_RANGE& range, + D3D12_DESCRIPTOR_RANGE_TYPE rangeType, + UINT numDescriptors, + UINT baseShaderRegister, + UINT registerSpace = 0, + UINT offsetInDescriptorsFromTableStart = + D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) + { + range.RangeType = rangeType; + range.NumDescriptors = numDescriptors; + range.BaseShaderRegister = baseShaderRegister; + range.RegisterSpace = registerSpace; range.OffsetInDescriptorsFromTableStart = offsetInDescriptorsFromTableStart; } }; @@ -710,30 +725,30 @@ struct CD3DX12_DESCRIPTOR_RANGE : public D3D12_DESCRIPTOR_RANGE struct CD3DX12_ROOT_DESCRIPTOR_TABLE : public D3D12_ROOT_DESCRIPTOR_TABLE { CD3DX12_ROOT_DESCRIPTOR_TABLE() {} - explicit CD3DX12_ROOT_DESCRIPTOR_TABLE(const D3D12_ROOT_DESCRIPTOR_TABLE &o) : + explicit CD3DX12_ROOT_DESCRIPTOR_TABLE(const D3D12_ROOT_DESCRIPTOR_TABLE& o) : D3D12_ROOT_DESCRIPTOR_TABLE(o) {} CD3DX12_ROOT_DESCRIPTOR_TABLE( - UINT numDescriptorRanges, + UINT numDescriptorRanges, _In_reads_opt_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* _pDescriptorRanges) { Init(numDescriptorRanges, _pDescriptorRanges); } - + inline void Init( - UINT numDescriptorRanges, + UINT numDescriptorRanges, _In_reads_opt_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* _pDescriptorRanges) { Init(*this, numDescriptorRanges, _pDescriptorRanges); } - + static inline void Init( - _Out_ D3D12_ROOT_DESCRIPTOR_TABLE &rootDescriptorTable, - UINT numDescriptorRanges, + _Out_ D3D12_ROOT_DESCRIPTOR_TABLE& rootDescriptorTable, + UINT numDescriptorRanges, _In_reads_opt_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* _pDescriptorRanges) { rootDescriptorTable.NumDescriptorRanges = numDescriptorRanges; - rootDescriptorTable.pDescriptorRanges = _pDescriptorRanges; + rootDescriptorTable.pDescriptorRanges = _pDescriptorRanges; } }; @@ -741,7 +756,7 @@ struct CD3DX12_ROOT_DESCRIPTOR_TABLE : public D3D12_ROOT_DESCRIPTOR_TABLE struct CD3DX12_ROOT_CONSTANTS : public D3D12_ROOT_CONSTANTS { CD3DX12_ROOT_CONSTANTS() {} - explicit CD3DX12_ROOT_CONSTANTS(const D3D12_ROOT_CONSTANTS &o) : + explicit CD3DX12_ROOT_CONSTANTS(const D3D12_ROOT_CONSTANTS& o) : D3D12_ROOT_CONSTANTS(o) {} CD3DX12_ROOT_CONSTANTS( @@ -751,7 +766,7 @@ struct CD3DX12_ROOT_CONSTANTS : public D3D12_ROOT_CONSTANTS { Init(num32BitValues, shaderRegister, registerSpace); } - + inline void Init( UINT num32BitValues, UINT shaderRegister, @@ -759,16 +774,16 @@ struct CD3DX12_ROOT_CONSTANTS : public D3D12_ROOT_CONSTANTS { Init(*this, num32BitValues, shaderRegister, registerSpace); } - + static inline void Init( - _Out_ D3D12_ROOT_CONSTANTS &rootConstants, - UINT num32BitValues, - UINT shaderRegister, - UINT registerSpace = 0) + _Out_ D3D12_ROOT_CONSTANTS& rootConstants, + UINT num32BitValues, + UINT shaderRegister, + UINT registerSpace = 0) { rootConstants.Num32BitValues = num32BitValues; rootConstants.ShaderRegister = shaderRegister; - rootConstants.RegisterSpace = registerSpace; + rootConstants.RegisterSpace = registerSpace; } }; @@ -776,7 +791,7 @@ struct CD3DX12_ROOT_CONSTANTS : public D3D12_ROOT_CONSTANTS struct CD3DX12_ROOT_DESCRIPTOR : public D3D12_ROOT_DESCRIPTOR { CD3DX12_ROOT_DESCRIPTOR() {} - explicit CD3DX12_ROOT_DESCRIPTOR(const D3D12_ROOT_DESCRIPTOR &o) : + explicit CD3DX12_ROOT_DESCRIPTOR(const D3D12_ROOT_DESCRIPTOR& o) : D3D12_ROOT_DESCRIPTOR(o) {} CD3DX12_ROOT_DESCRIPTOR( @@ -785,18 +800,18 @@ struct CD3DX12_ROOT_DESCRIPTOR : public D3D12_ROOT_DESCRIPTOR { Init(shaderRegister, registerSpace); } - + inline void Init( UINT shaderRegister, UINT registerSpace = 0) { Init(*this, shaderRegister, registerSpace); } - - static inline void Init(_Out_ D3D12_ROOT_DESCRIPTOR &table, UINT shaderRegister, UINT registerSpace = 0) + + static inline void Init(_Out_ D3D12_ROOT_DESCRIPTOR& table, UINT shaderRegister, UINT registerSpace = 0) { table.ShaderRegister = shaderRegister; - table.RegisterSpace = registerSpace; + table.RegisterSpace = registerSpace; } }; @@ -804,103 +819,103 @@ struct CD3DX12_ROOT_DESCRIPTOR : public D3D12_ROOT_DESCRIPTOR struct CD3DX12_ROOT_PARAMETER : public D3D12_ROOT_PARAMETER { CD3DX12_ROOT_PARAMETER() {} - explicit CD3DX12_ROOT_PARAMETER(const D3D12_ROOT_PARAMETER &o) : + explicit CD3DX12_ROOT_PARAMETER(const D3D12_ROOT_PARAMETER& o) : D3D12_ROOT_PARAMETER(o) {} - + static inline void InitAsDescriptorTable( - _Out_ D3D12_ROOT_PARAMETER &rootParam, - UINT numDescriptorRanges, + _Out_ D3D12_ROOT_PARAMETER& rootParam, + UINT numDescriptorRanges, _In_reads_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* pDescriptorRanges, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) { - rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; rootParam.ShaderVisibility = visibility; CD3DX12_ROOT_DESCRIPTOR_TABLE::Init(rootParam.DescriptorTable, numDescriptorRanges, pDescriptorRanges); } static inline void InitAsConstants( - _Out_ D3D12_ROOT_PARAMETER &rootParam, - UINT num32BitValues, - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) + _Out_ D3D12_ROOT_PARAMETER& rootParam, + UINT num32BitValues, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) { - rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; rootParam.ShaderVisibility = visibility; CD3DX12_ROOT_CONSTANTS::Init(rootParam.Constants, num32BitValues, shaderRegister, registerSpace); } static inline void InitAsConstantBufferView( - _Out_ D3D12_ROOT_PARAMETER &rootParam, - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) + _Out_ D3D12_ROOT_PARAMETER& rootParam, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) { - rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; rootParam.ShaderVisibility = visibility; CD3DX12_ROOT_DESCRIPTOR::Init(rootParam.Descriptor, shaderRegister, registerSpace); } static inline void InitAsShaderResourceView( - _Out_ D3D12_ROOT_PARAMETER &rootParam, - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) + _Out_ D3D12_ROOT_PARAMETER& rootParam, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) { - rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; rootParam.ShaderVisibility = visibility; CD3DX12_ROOT_DESCRIPTOR::Init(rootParam.Descriptor, shaderRegister, registerSpace); } static inline void InitAsUnorderedAccessView( - _Out_ D3D12_ROOT_PARAMETER &rootParam, - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) + _Out_ D3D12_ROOT_PARAMETER& rootParam, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) { - rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; rootParam.ShaderVisibility = visibility; CD3DX12_ROOT_DESCRIPTOR::Init(rootParam.Descriptor, shaderRegister, registerSpace); } - + inline void InitAsDescriptorTable( - UINT numDescriptorRanges, + UINT numDescriptorRanges, _In_reads_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* pDescriptorRanges, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) { InitAsDescriptorTable(*this, numDescriptorRanges, pDescriptorRanges, visibility); } - + inline void InitAsConstants( - UINT num32BitValues, - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) + UINT num32BitValues, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) { InitAsConstants(*this, num32BitValues, shaderRegister, registerSpace, visibility); } inline void InitAsConstantBufferView( - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) { InitAsConstantBufferView(*this, shaderRegister, registerSpace, visibility); } inline void InitAsShaderResourceView( - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) { InitAsShaderResourceView(*this, shaderRegister, registerSpace, visibility); } inline void InitAsUnorderedAccessView( - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) { InitAsUnorderedAccessView(*this, shaderRegister, registerSpace, visibility); } @@ -910,23 +925,23 @@ struct CD3DX12_ROOT_PARAMETER : public D3D12_ROOT_PARAMETER struct CD3DX12_STATIC_SAMPLER_DESC : public D3D12_STATIC_SAMPLER_DESC { CD3DX12_STATIC_SAMPLER_DESC() {} - explicit CD3DX12_STATIC_SAMPLER_DESC(const D3D12_STATIC_SAMPLER_DESC &o) : + explicit CD3DX12_STATIC_SAMPLER_DESC(const D3D12_STATIC_SAMPLER_DESC& o) : D3D12_STATIC_SAMPLER_DESC(o) {} CD3DX12_STATIC_SAMPLER_DESC( - UINT shaderRegister, - D3D12_FILTER filter = D3D12_FILTER_ANISOTROPIC, - D3D12_TEXTURE_ADDRESS_MODE addressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - D3D12_TEXTURE_ADDRESS_MODE addressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - D3D12_TEXTURE_ADDRESS_MODE addressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - FLOAT mipLODBias = 0, - UINT maxAnisotropy = 16, - D3D12_COMPARISON_FUNC comparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL, - D3D12_STATIC_BORDER_COLOR borderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, - FLOAT minLOD = 0.f, - FLOAT maxLOD = D3D12_FLOAT32_MAX, - D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, - UINT registerSpace = 0) + UINT shaderRegister, + D3D12_FILTER filter = D3D12_FILTER_ANISOTROPIC, + D3D12_TEXTURE_ADDRESS_MODE addressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE addressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE addressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + FLOAT mipLODBias = 0, + UINT maxAnisotropy = 16, + D3D12_COMPARISON_FUNC comparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL, + D3D12_STATIC_BORDER_COLOR borderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, + FLOAT minLOD = 0.f, + FLOAT maxLOD = D3D12_FLOAT32_MAX, + D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, + UINT registerSpace = 0) { Init( shaderRegister, @@ -943,51 +958,51 @@ struct CD3DX12_STATIC_SAMPLER_DESC : public D3D12_STATIC_SAMPLER_DESC shaderVisibility, registerSpace); } - + static inline void Init( - _Out_ D3D12_STATIC_SAMPLER_DESC &samplerDesc, - UINT shaderRegister, - D3D12_FILTER filter = D3D12_FILTER_ANISOTROPIC, - D3D12_TEXTURE_ADDRESS_MODE addressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - D3D12_TEXTURE_ADDRESS_MODE addressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - D3D12_TEXTURE_ADDRESS_MODE addressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - FLOAT mipLODBias = 0, - UINT maxAnisotropy = 16, - D3D12_COMPARISON_FUNC comparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL, - D3D12_STATIC_BORDER_COLOR borderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, - FLOAT minLOD = 0.f, - FLOAT maxLOD = D3D12_FLOAT32_MAX, - D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, - UINT registerSpace = 0) - { - samplerDesc.ShaderRegister = shaderRegister; - samplerDesc.Filter = filter; - samplerDesc.AddressU = addressU; - samplerDesc.AddressV = addressV; - samplerDesc.AddressW = addressW; - samplerDesc.MipLODBias = mipLODBias; - samplerDesc.MaxAnisotropy = maxAnisotropy; - samplerDesc.ComparisonFunc = comparisonFunc; - samplerDesc.BorderColor = borderColor; - samplerDesc.MinLOD = minLOD; - samplerDesc.MaxLOD = maxLOD; + _Out_ D3D12_STATIC_SAMPLER_DESC& samplerDesc, + UINT shaderRegister, + D3D12_FILTER filter = D3D12_FILTER_ANISOTROPIC, + D3D12_TEXTURE_ADDRESS_MODE addressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE addressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE addressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + FLOAT mipLODBias = 0, + UINT maxAnisotropy = 16, + D3D12_COMPARISON_FUNC comparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL, + D3D12_STATIC_BORDER_COLOR borderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, + FLOAT minLOD = 0.f, + FLOAT maxLOD = D3D12_FLOAT32_MAX, + D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, + UINT registerSpace = 0) + { + samplerDesc.ShaderRegister = shaderRegister; + samplerDesc.Filter = filter; + samplerDesc.AddressU = addressU; + samplerDesc.AddressV = addressV; + samplerDesc.AddressW = addressW; + samplerDesc.MipLODBias = mipLODBias; + samplerDesc.MaxAnisotropy = maxAnisotropy; + samplerDesc.ComparisonFunc = comparisonFunc; + samplerDesc.BorderColor = borderColor; + samplerDesc.MinLOD = minLOD; + samplerDesc.MaxLOD = maxLOD; samplerDesc.ShaderVisibility = shaderVisibility; - samplerDesc.RegisterSpace = registerSpace; + samplerDesc.RegisterSpace = registerSpace; } inline void Init( - UINT shaderRegister, - D3D12_FILTER filter = D3D12_FILTER_ANISOTROPIC, - D3D12_TEXTURE_ADDRESS_MODE addressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - D3D12_TEXTURE_ADDRESS_MODE addressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - D3D12_TEXTURE_ADDRESS_MODE addressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - FLOAT mipLODBias = 0, - UINT maxAnisotropy = 16, - D3D12_COMPARISON_FUNC comparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL, - D3D12_STATIC_BORDER_COLOR borderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, - FLOAT minLOD = 0.f, - FLOAT maxLOD = D3D12_FLOAT32_MAX, - D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, - UINT registerSpace = 0) + UINT shaderRegister, + D3D12_FILTER filter = D3D12_FILTER_ANISOTROPIC, + D3D12_TEXTURE_ADDRESS_MODE addressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE addressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE addressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + FLOAT mipLODBias = 0, + UINT maxAnisotropy = 16, + D3D12_COMPARISON_FUNC comparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL, + D3D12_STATIC_BORDER_COLOR borderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, + FLOAT minLOD = 0.f, + FLOAT maxLOD = D3D12_FLOAT32_MAX, + D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, + UINT registerSpace = 0) { Init( *this, @@ -1005,22 +1020,21 @@ struct CD3DX12_STATIC_SAMPLER_DESC : public D3D12_STATIC_SAMPLER_DESC shaderVisibility, registerSpace); } - }; //------------------------------------------------------------------------------------------------ struct CD3DX12_ROOT_SIGNATURE_DESC : public D3D12_ROOT_SIGNATURE_DESC { CD3DX12_ROOT_SIGNATURE_DESC() {} - explicit CD3DX12_ROOT_SIGNATURE_DESC(const D3D12_ROOT_SIGNATURE_DESC &o) : + explicit CD3DX12_ROOT_SIGNATURE_DESC(const D3D12_ROOT_SIGNATURE_DESC& o) : D3D12_ROOT_SIGNATURE_DESC(o) {} CD3DX12_ROOT_SIGNATURE_DESC( - UINT numParameters, - _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters, - UINT numStaticSamplers = 0, - _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = NULL, - D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) + UINT numParameters, + _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters, + UINT numStaticSamplers = 0, + _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = NULL, + D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) { Init(numParameters, _pParameters, numStaticSamplers, _pStaticSamplers, flags); } @@ -1028,30 +1042,30 @@ struct CD3DX12_ROOT_SIGNATURE_DESC : public D3D12_ROOT_SIGNATURE_DESC { Init(0, NULL, 0, NULL, D3D12_ROOT_SIGNATURE_FLAG_NONE); } - + inline void Init( - UINT numParameters, - _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters, - UINT numStaticSamplers = 0, - _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = NULL, - D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) + UINT numParameters, + _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters, + UINT numStaticSamplers = 0, + _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = NULL, + D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) { Init(*this, numParameters, _pParameters, numStaticSamplers, _pStaticSamplers, flags); } static inline void Init( - _Out_ D3D12_ROOT_SIGNATURE_DESC &desc, - UINT numParameters, - _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters, - UINT numStaticSamplers = 0, - _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = NULL, - D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) - { - desc.NumParameters = numParameters; - desc.pParameters = _pParameters; + _Out_ D3D12_ROOT_SIGNATURE_DESC& desc, + UINT numParameters, + _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters, + UINT numStaticSamplers = 0, + _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = NULL, + D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) + { + desc.NumParameters = numParameters; + desc.pParameters = _pParameters; desc.NumStaticSamplers = numStaticSamplers; - desc.pStaticSamplers = _pStaticSamplers; - desc.Flags = flags; + desc.pStaticSamplers = _pStaticSamplers; + desc.Flags = flags; } }; @@ -1059,25 +1073,25 @@ struct CD3DX12_ROOT_SIGNATURE_DESC : public D3D12_ROOT_SIGNATURE_DESC struct CD3DX12_CPU_DESCRIPTOR_HANDLE : public D3D12_CPU_DESCRIPTOR_HANDLE { CD3DX12_CPU_DESCRIPTOR_HANDLE() {} - explicit CD3DX12_CPU_DESCRIPTOR_HANDLE(const D3D12_CPU_DESCRIPTOR_HANDLE &o) : + explicit CD3DX12_CPU_DESCRIPTOR_HANDLE(const D3D12_CPU_DESCRIPTOR_HANDLE& o) : D3D12_CPU_DESCRIPTOR_HANDLE(o) {} CD3DX12_CPU_DESCRIPTOR_HANDLE(CD3DX12_DEFAULT) { ptr = 0; } - CD3DX12_CPU_DESCRIPTOR_HANDLE(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &other, INT offsetScaledByIncrementSize) + CD3DX12_CPU_DESCRIPTOR_HANDLE(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE& other, INT offsetScaledByIncrementSize) { InitOffsetted(other, offsetScaledByIncrementSize); } - CD3DX12_CPU_DESCRIPTOR_HANDLE(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &other, INT offsetInDescriptors, UINT descriptorIncrementSize) + CD3DX12_CPU_DESCRIPTOR_HANDLE(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE& other, INT offsetInDescriptors, UINT descriptorIncrementSize) { InitOffsetted(other, offsetInDescriptors, descriptorIncrementSize); } CD3DX12_CPU_DESCRIPTOR_HANDLE& Offset(INT offsetInDescriptors, UINT descriptorIncrementSize) - { + { ptr += offsetInDescriptors * descriptorIncrementSize; return *this; } - CD3DX12_CPU_DESCRIPTOR_HANDLE& Offset(INT offsetScaledByIncrementSize) - { + CD3DX12_CPU_DESCRIPTOR_HANDLE& Offset(INT offsetScaledByIncrementSize) + { ptr += offsetScaledByIncrementSize; return *this; } @@ -1089,28 +1103,28 @@ struct CD3DX12_CPU_DESCRIPTOR_HANDLE : public D3D12_CPU_DESCRIPTOR_HANDLE { return (ptr != other.ptr); } - CD3DX12_CPU_DESCRIPTOR_HANDLE &operator=(const D3D12_CPU_DESCRIPTOR_HANDLE &other) + CD3DX12_CPU_DESCRIPTOR_HANDLE& operator=(const D3D12_CPU_DESCRIPTOR_HANDLE& other) { ptr = other.ptr; return *this; } - - inline void InitOffsetted(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetScaledByIncrementSize) + + inline void InitOffsetted(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE& base, INT offsetScaledByIncrementSize) { InitOffsetted(*this, base, offsetScaledByIncrementSize); } - - inline void InitOffsetted(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetInDescriptors, UINT descriptorIncrementSize) + + inline void InitOffsetted(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE& base, INT offsetInDescriptors, UINT descriptorIncrementSize) { InitOffsetted(*this, base, offsetInDescriptors, descriptorIncrementSize); } - - static inline void InitOffsetted(_Out_ D3D12_CPU_DESCRIPTOR_HANDLE &handle, _In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetScaledByIncrementSize) + + static inline void InitOffsetted(_Out_ D3D12_CPU_DESCRIPTOR_HANDLE& handle, _In_ const D3D12_CPU_DESCRIPTOR_HANDLE& base, INT offsetScaledByIncrementSize) { handle.ptr = base.ptr + offsetScaledByIncrementSize; } - - static inline void InitOffsetted(_Out_ D3D12_CPU_DESCRIPTOR_HANDLE &handle, _In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetInDescriptors, UINT descriptorIncrementSize) + + static inline void InitOffsetted(_Out_ D3D12_CPU_DESCRIPTOR_HANDLE& handle, _In_ const D3D12_CPU_DESCRIPTOR_HANDLE& base, INT offsetInDescriptors, UINT descriptorIncrementSize) { handle.ptr = base.ptr + offsetInDescriptors * descriptorIncrementSize; } @@ -1120,25 +1134,25 @@ struct CD3DX12_CPU_DESCRIPTOR_HANDLE : public D3D12_CPU_DESCRIPTOR_HANDLE struct CD3DX12_GPU_DESCRIPTOR_HANDLE : public D3D12_GPU_DESCRIPTOR_HANDLE { CD3DX12_GPU_DESCRIPTOR_HANDLE() {} - explicit CD3DX12_GPU_DESCRIPTOR_HANDLE(const D3D12_GPU_DESCRIPTOR_HANDLE &o) : + explicit CD3DX12_GPU_DESCRIPTOR_HANDLE(const D3D12_GPU_DESCRIPTOR_HANDLE& o) : D3D12_GPU_DESCRIPTOR_HANDLE(o) {} CD3DX12_GPU_DESCRIPTOR_HANDLE(CD3DX12_DEFAULT) { ptr = 0; } - CD3DX12_GPU_DESCRIPTOR_HANDLE(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE &other, INT offsetScaledByIncrementSize) + CD3DX12_GPU_DESCRIPTOR_HANDLE(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE& other, INT offsetScaledByIncrementSize) { InitOffsetted(other, offsetScaledByIncrementSize); } - CD3DX12_GPU_DESCRIPTOR_HANDLE(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE &other, INT offsetInDescriptors, UINT descriptorIncrementSize) + CD3DX12_GPU_DESCRIPTOR_HANDLE(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE& other, INT offsetInDescriptors, UINT descriptorIncrementSize) { InitOffsetted(other, offsetInDescriptors, descriptorIncrementSize); } CD3DX12_GPU_DESCRIPTOR_HANDLE& Offset(INT offsetInDescriptors, UINT descriptorIncrementSize) - { + { ptr += offsetInDescriptors * descriptorIncrementSize; return *this; } - CD3DX12_GPU_DESCRIPTOR_HANDLE& Offset(INT offsetScaledByIncrementSize) - { + CD3DX12_GPU_DESCRIPTOR_HANDLE& Offset(INT offsetScaledByIncrementSize) + { ptr += offsetScaledByIncrementSize; return *this; } @@ -1150,44 +1164,44 @@ struct CD3DX12_GPU_DESCRIPTOR_HANDLE : public D3D12_GPU_DESCRIPTOR_HANDLE { return (ptr != other.ptr); } - CD3DX12_GPU_DESCRIPTOR_HANDLE &operator=(const D3D12_GPU_DESCRIPTOR_HANDLE &other) + CD3DX12_GPU_DESCRIPTOR_HANDLE& operator=(const D3D12_GPU_DESCRIPTOR_HANDLE& other) { ptr = other.ptr; return *this; } - - inline void InitOffsetted(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE &base, INT offsetScaledByIncrementSize) + + inline void InitOffsetted(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE& base, INT offsetScaledByIncrementSize) { InitOffsetted(*this, base, offsetScaledByIncrementSize); } - - inline void InitOffsetted(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE &base, INT offsetInDescriptors, UINT descriptorIncrementSize) + + inline void InitOffsetted(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE& base, INT offsetInDescriptors, UINT descriptorIncrementSize) { InitOffsetted(*this, base, offsetInDescriptors, descriptorIncrementSize); } - - static inline void InitOffsetted(_Out_ D3D12_GPU_DESCRIPTOR_HANDLE &handle, _In_ const D3D12_GPU_DESCRIPTOR_HANDLE &base, INT offsetScaledByIncrementSize) + + static inline void InitOffsetted(_Out_ D3D12_GPU_DESCRIPTOR_HANDLE& handle, _In_ const D3D12_GPU_DESCRIPTOR_HANDLE& base, INT offsetScaledByIncrementSize) { handle.ptr = base.ptr + offsetScaledByIncrementSize; } - - static inline void InitOffsetted(_Out_ D3D12_GPU_DESCRIPTOR_HANDLE &handle, _In_ const D3D12_GPU_DESCRIPTOR_HANDLE &base, INT offsetInDescriptors, UINT descriptorIncrementSize) + + static inline void InitOffsetted(_Out_ D3D12_GPU_DESCRIPTOR_HANDLE& handle, _In_ const D3D12_GPU_DESCRIPTOR_HANDLE& base, INT offsetInDescriptors, UINT descriptorIncrementSize) { handle.ptr = base.ptr + offsetInDescriptors * descriptorIncrementSize; } }; //------------------------------------------------------------------------------------------------ -inline UINT D3D12CalcSubresource( UINT MipSlice, UINT ArraySlice, UINT PlaneSlice, UINT MipLevels, UINT ArraySize ) -{ - return MipSlice + ArraySlice * MipLevels + PlaneSlice * MipLevels * ArraySize; +inline UINT D3D12CalcSubresource(UINT MipSlice, UINT ArraySlice, UINT PlaneSlice, UINT MipLevels, UINT ArraySize) +{ + return MipSlice + ArraySlice * MipLevels + PlaneSlice * MipLevels * ArraySize; } //------------------------------------------------------------------------------------------------ template -inline void D3D12DecomposeSubresource( UINT Subresource, UINT MipLevels, UINT ArraySize, _Out_ T& MipSlice, _Out_ U& ArraySlice, _Out_ V& PlaneSlice ) +inline void D3D12DecomposeSubresource(UINT Subresource, UINT MipLevels, UINT ArraySize, _Out_ T& MipSlice, _Out_ U& ArraySlice, _Out_ V& PlaneSlice) { - MipSlice = static_cast(Subresource % MipLevels); + MipSlice = static_cast(Subresource % MipLevels); ArraySlice = static_cast((Subresource / MipLevels) % ArraySize); PlaneSlice = static_cast(Subresource / (MipLevels * ArraySize)); } @@ -1195,8 +1209,7 @@ inline void D3D12DecomposeSubresource( UINT Subresource, UINT MipLevels, UINT Ar //------------------------------------------------------------------------------------------------ inline UINT8 D3D12GetFormatPlaneCount( _In_ ID3D12Device* pDevice, - DXGI_FORMAT Format - ) + DXGI_FORMAT Format) { D3D12_FEATURE_DATA_FORMAT_INFO formatInfo = {Format}; if (FAILED(pDevice->CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO, &formatInfo, sizeof(formatInfo)))) @@ -1211,102 +1224,112 @@ struct CD3DX12_RESOURCE_DESC : public D3D12_RESOURCE_DESC { CD3DX12_RESOURCE_DESC() {} - explicit CD3DX12_RESOURCE_DESC( const D3D12_RESOURCE_DESC& o ) : - D3D12_RESOURCE_DESC( o ) + explicit CD3DX12_RESOURCE_DESC(const D3D12_RESOURCE_DESC& o) : + D3D12_RESOURCE_DESC(o) {} - CD3DX12_RESOURCE_DESC( + CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION dimension, - UINT64 alignment, - UINT64 width, - UINT height, - UINT16 depthOrArraySize, - UINT16 mipLevels, - DXGI_FORMAT format, - UINT sampleCount, - UINT sampleQuality, - D3D12_TEXTURE_LAYOUT layout, - D3D12_RESOURCE_FLAGS flags ) - { - Dimension = dimension; - Alignment = alignment; - Width = width; - Height = height; - DepthOrArraySize = depthOrArraySize; - MipLevels = mipLevels; - Format = format; - SampleDesc.Count = sampleCount; + UINT64 alignment, + UINT64 width, + UINT height, + UINT16 depthOrArraySize, + UINT16 mipLevels, + DXGI_FORMAT format, + UINT sampleCount, + UINT sampleQuality, + D3D12_TEXTURE_LAYOUT layout, + D3D12_RESOURCE_FLAGS flags) + { + Dimension = dimension; + Alignment = alignment; + Width = width; + Height = height; + DepthOrArraySize = depthOrArraySize; + MipLevels = mipLevels; + Format = format; + SampleDesc.Count = sampleCount; SampleDesc.Quality = sampleQuality; - Layout = layout; - Flags = flags; + Layout = layout; + Flags = flags; } - static inline CD3DX12_RESOURCE_DESC Buffer( + static inline CD3DX12_RESOURCE_DESC Buffer( const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo, - D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE ) - { - return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_BUFFER, resAllocInfo.Alignment, resAllocInfo.SizeInBytes, - 1, 1, 1, DXGI_FORMAT_UNKNOWN, 1, 0, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, flags ); + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) + { + return CD3DX12_RESOURCE_DESC(D3D12_RESOURCE_DIMENSION_BUFFER, resAllocInfo.Alignment, resAllocInfo.SizeInBytes, + 1, 1, 1, DXGI_FORMAT_UNKNOWN, 1, 0, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, flags); + } + static inline CD3DX12_RESOURCE_DESC Buffer( + UINT64 width, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, + UINT64 alignment = 0) + { + return CD3DX12_RESOURCE_DESC(D3D12_RESOURCE_DIMENSION_BUFFER, alignment, width, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, 1, 0, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, flags); + } + static inline CD3DX12_RESOURCE_DESC Tex1D( + DXGI_FORMAT format, + UINT64 width, + UINT16 arraySize = 1, + UINT16 mipLevels = 0, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, + D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN, + UINT64 alignment = 0) + { + return CD3DX12_RESOURCE_DESC(D3D12_RESOURCE_DIMENSION_TEXTURE1D, alignment, width, 1, arraySize, + mipLevels, format, 1, 0, layout, flags); + } + static inline CD3DX12_RESOURCE_DESC Tex2D( + DXGI_FORMAT format, + UINT64 width, + UINT height, + UINT16 arraySize = 1, + UINT16 mipLevels = 0, + UINT sampleCount = 1, + UINT sampleQuality = 0, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, + D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN, + UINT64 alignment = 0) + { + return CD3DX12_RESOURCE_DESC(D3D12_RESOURCE_DIMENSION_TEXTURE2D, alignment, width, height, arraySize, + mipLevels, format, sampleCount, sampleQuality, layout, flags); + } + static inline CD3DX12_RESOURCE_DESC Tex3D( + DXGI_FORMAT format, + UINT64 width, + UINT height, + UINT16 depth, + UINT16 mipLevels = 0, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, + D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN, + UINT64 alignment = 0) + { + return CD3DX12_RESOURCE_DESC(D3D12_RESOURCE_DIMENSION_TEXTURE3D, alignment, width, height, depth, + mipLevels, format, 1, 0, layout, flags); } - static inline CD3DX12_RESOURCE_DESC Buffer( - UINT64 width, - D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, - UINT64 alignment = 0 ) + inline UINT16 Depth() const { - return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_BUFFER, alignment, width, 1, 1, 1, - DXGI_FORMAT_UNKNOWN, 1, 0, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, flags ); + return (Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? DepthOrArraySize : 1); } - static inline CD3DX12_RESOURCE_DESC Tex1D( - DXGI_FORMAT format, - UINT64 width, - UINT16 arraySize = 1, - UINT16 mipLevels = 0, - D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, - D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN, - UINT64 alignment = 0 ) + inline UINT16 ArraySize() const { - return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_TEXTURE1D, alignment, width, 1, arraySize, - mipLevels, format, 1, 0, layout, flags ); + return (Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D ? DepthOrArraySize : 1); } - static inline CD3DX12_RESOURCE_DESC Tex2D( - DXGI_FORMAT format, - UINT64 width, - UINT height, - UINT16 arraySize = 1, - UINT16 mipLevels = 0, - UINT sampleCount = 1, - UINT sampleQuality = 0, - D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, - D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN, - UINT64 alignment = 0 ) - { - return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_TEXTURE2D, alignment, width, height, arraySize, - mipLevels, format, sampleCount, sampleQuality, layout, flags ); - } - static inline CD3DX12_RESOURCE_DESC Tex3D( - DXGI_FORMAT format, - UINT64 width, - UINT height, - UINT16 depth, - UINT16 mipLevels = 0, - D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, - D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN, - UINT64 alignment = 0 ) + inline UINT8 PlaneCount(_In_ ID3D12Device* pDevice) const { - return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_TEXTURE3D, alignment, width, height, depth, - mipLevels, format, 1, 0, layout, flags ); + return D3D12GetFormatPlaneCount(pDevice, Format); } - inline UINT16 Depth() const - { return (Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? DepthOrArraySize : 1); } - inline UINT16 ArraySize() const - { return (Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D ? DepthOrArraySize : 1); } - inline UINT8 PlaneCount(_In_ ID3D12Device* pDevice) const - { return D3D12GetFormatPlaneCount(pDevice, Format); } inline UINT Subresources(_In_ ID3D12Device* pDevice) const - { return MipLevels * ArraySize() * PlaneCount(pDevice); } + { + return MipLevels * ArraySize() * PlaneCount(pDevice); + } inline UINT CalcSubresource(UINT MipSlice, UINT ArraySlice, UINT PlaneSlice) - { return D3D12CalcSubresource(MipSlice, ArraySlice, PlaneSlice, MipLevels, ArraySize()); } + { + return D3D12CalcSubresource(MipSlice, ArraySlice, PlaneSlice, MipLevels, ArraySize()); + } operator const D3D12_RESOURCE_DESC&() const { return *this; } }; -inline bool operator==( const D3D12_RESOURCE_DESC& l, const D3D12_RESOURCE_DESC& r ) +inline bool operator==(const D3D12_RESOURCE_DESC& l, const D3D12_RESOURCE_DESC& r) { return l.Dimension == r.Dimension && l.Alignment == r.Alignment && @@ -1320,22 +1343,24 @@ inline bool operator==( const D3D12_RESOURCE_DESC& l, const D3D12_RESOURCE_DESC& l.Layout == r.Layout && l.Flags == r.Flags; } -inline bool operator!=( const D3D12_RESOURCE_DESC& l, const D3D12_RESOURCE_DESC& r ) -{ return !( l == r ); } +inline bool operator!=(const D3D12_RESOURCE_DESC& l, const D3D12_RESOURCE_DESC& r) +{ + return !(l == r); +} //------------------------------------------------------------------------------------------------ // Row-by-row memcpy inline void MemcpySubresource( _In_ const D3D12_MEMCPY_DEST* pDest, _In_ const D3D12_SUBRESOURCE_DATA* pSrc, - SIZE_T RowSizeInBytes, - UINT NumRows, - UINT NumSlices) + SIZE_T RowSizeInBytes, + UINT NumRows, + UINT NumSlices) { for (UINT z = 0; z < NumSlices; ++z) { - BYTE* pDestSlice = reinterpret_cast(pDest->pData) + pDest->SlicePitch * z; - const BYTE* pSrcSlice = reinterpret_cast(pSrc->pData) + pSrc->SlicePitch * z; + BYTE* pDestSlice = reinterpret_cast(pDest->pData) + pDest->SlicePitch * z; + const BYTE* pSrcSlice = reinterpret_cast(pSrc->pData) + pSrc->SlicePitch * z; for (UINT y = 0; y < NumRows; ++y) { memcpy(pDestSlice + pDest->RowPitch * y, @@ -1348,18 +1373,18 @@ inline void MemcpySubresource( //------------------------------------------------------------------------------------------------ // Returns required size of a buffer to be used for data upload inline UINT64 GetRequiredIntermediateSize( - _In_ ID3D12Resource* pDestinationResource, - _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, - _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources) + _In_ ID3D12Resource* pDestinationResource, + _In_range_(0, D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, + _In_range_(0, D3D12_REQ_SUBRESOURCES - FirstSubresource) UINT NumSubresources) { - D3D12_RESOURCE_DESC Desc = pDestinationResource->GetDesc(); - UINT64 RequiredSize = 0; - + D3D12_RESOURCE_DESC Desc = pDestinationResource->GetDesc(); + UINT64 RequiredSize = 0; + ID3D12Device* pDevice; pDestinationResource->GetDevice(__uuidof(*pDevice), reinterpret_cast(&pDevice)); pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, 0, nullptr, nullptr, nullptr, &RequiredSize); pDevice->Release(); - + return RequiredSize; } @@ -1368,45 +1393,45 @@ inline UINT64 GetRequiredIntermediateSize( inline UINT64 UpdateSubresources( _In_ ID3D12GraphicsCommandList* pCmdList, _In_ ID3D12Resource* pDestinationResource, - _In_ ID3D12Resource* pIntermediate, - _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, - _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources, - UINT64 RequiredSize, + _In_ ID3D12Resource* pIntermediate, + _In_range_(0, D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, + _In_range_(0, D3D12_REQ_SUBRESOURCES - FirstSubresource) UINT NumSubresources, + UINT64 RequiredSize, _In_reads_(NumSubresources) const D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts, - _In_reads_(NumSubresources) const UINT* pNumRows, - _In_reads_(NumSubresources) const UINT64* pRowSizesInBytes, - _In_reads_(NumSubresources) const D3D12_SUBRESOURCE_DATA* pSrcData) + _In_reads_(NumSubresources) const UINT* pNumRows, + _In_reads_(NumSubresources) const UINT64* pRowSizesInBytes, + _In_reads_(NumSubresources) const D3D12_SUBRESOURCE_DATA* pSrcData) { // Minor validation D3D12_RESOURCE_DESC IntermediateDesc = pIntermediate->GetDesc(); - D3D12_RESOURCE_DESC DestinationDesc = pDestinationResource->GetDesc(); - if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || - IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset || - RequiredSize > (SIZE_T)-1 || - (DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && - (FirstSubresource != 0 || NumSubresources != 1))) + D3D12_RESOURCE_DESC DestinationDesc = pDestinationResource->GetDesc(); + if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || + IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset || + RequiredSize > (SIZE_T)-1 || + (DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && + (FirstSubresource != 0 || NumSubresources != 1))) { return 0; } - - BYTE* pData; + + BYTE* pData; HRESULT hr = pIntermediate->Map(0, NULL, reinterpret_cast(&pData)); if (FAILED(hr)) { return 0; } - + for (UINT i = 0; i < NumSubresources; ++i) { if (pRowSizesInBytes[i] > (SIZE_T)-1) return 0; - D3D12_MEMCPY_DEST DestData = { pData + pLayouts[i].Offset, pLayouts[i].Footprint.RowPitch, pLayouts[i].Footprint.RowPitch * pNumRows[i] }; + D3D12_MEMCPY_DEST DestData = {pData + pLayouts[i].Offset, pLayouts[i].Footprint.RowPitch, pLayouts[i].Footprint.RowPitch * pNumRows[i]}; MemcpySubresource(&DestData, &pSrcData[i], (SIZE_T)pRowSizesInBytes[i], pNumRows[i], pLayouts[i].Footprint.Depth); } pIntermediate->Unmap(0, NULL); - + if (DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { - CD3DX12_BOX SrcBox( UINT( pLayouts[0].Offset ), UINT( pLayouts[0].Offset + pLayouts[0].Footprint.Width ) ); + CD3DX12_BOX SrcBox(UINT(pLayouts[0].Offset), UINT(pLayouts[0].Offset + pLayouts[0].Footprint.Width)); pCmdList->CopyBufferRegion( pDestinationResource, 0, pIntermediate, pLayouts[0].Offset, pLayouts[0].Footprint.Width); } @@ -1424,36 +1449,36 @@ inline UINT64 UpdateSubresources( //------------------------------------------------------------------------------------------------ // Heap-allocating UpdateSubresources implementation -inline UINT64 UpdateSubresources( +inline UINT64 UpdateSubresources( _In_ ID3D12GraphicsCommandList* pCmdList, _In_ ID3D12Resource* pDestinationResource, - _In_ ID3D12Resource* pIntermediate, - UINT64 IntermediateOffset, - _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, - _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources, - _In_reads_(NumSubresources) D3D12_SUBRESOURCE_DATA* pSrcData) + _In_ ID3D12Resource* pIntermediate, + UINT64 IntermediateOffset, + _In_range_(0, D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, + _In_range_(0, D3D12_REQ_SUBRESOURCES - FirstSubresource) UINT NumSubresources, + _In_reads_(NumSubresources) D3D12_SUBRESOURCE_DATA* pSrcData) { UINT64 RequiredSize = 0; - UINT64 MemToAlloc = static_cast(sizeof(D3D12_PLACED_SUBRESOURCE_FOOTPRINT) + sizeof(UINT) + sizeof(UINT64)) * NumSubresources; + UINT64 MemToAlloc = static_cast(sizeof(D3D12_PLACED_SUBRESOURCE_FOOTPRINT) + sizeof(UINT) + sizeof(UINT64)) * NumSubresources; if (MemToAlloc > SIZE_MAX) { - return 0; + return 0; } void* pMem = HeapAlloc(GetProcessHeap(), 0, static_cast(MemToAlloc)); if (pMem == NULL) { - return 0; + return 0; } - D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts = reinterpret_cast(pMem); - UINT64* pRowSizesInBytes = reinterpret_cast(pLayouts + NumSubresources); - UINT* pNumRows = reinterpret_cast(pRowSizesInBytes + NumSubresources); - + D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts = reinterpret_cast(pMem); + UINT64* pRowSizesInBytes = reinterpret_cast(pLayouts + NumSubresources); + UINT* pNumRows = reinterpret_cast(pRowSizesInBytes + NumSubresources); + D3D12_RESOURCE_DESC Desc = pDestinationResource->GetDesc(); - ID3D12Device* pDevice; + ID3D12Device* pDevice; pDestinationResource->GetDevice(__uuidof(*pDevice), reinterpret_cast(&pDevice)); pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, &RequiredSize); pDevice->Release(); - + UINT64 Result = UpdateSubresources(pCmdList, pDestinationResource, pIntermediate, FirstSubresource, NumSubresources, RequiredSize, pLayouts, pNumRows, pRowSizesInBytes, pSrcData); HeapFree(GetProcessHeap(), 0, pMem); return Result; @@ -1462,47 +1487,46 @@ inline UINT64 UpdateSubresources( //------------------------------------------------------------------------------------------------ // Stack-allocating UpdateSubresources implementation template -inline UINT64 UpdateSubresources( +inline UINT64 UpdateSubresources( _In_ ID3D12GraphicsCommandList* pCmdList, _In_ ID3D12Resource* pDestinationResource, - _In_ ID3D12Resource* pIntermediate, - UINT64 IntermediateOffset, - _In_range_(0, MaxSubresources) UINT FirstSubresource, + _In_ ID3D12Resource* pIntermediate, + UINT64 IntermediateOffset, + _In_range_(0, MaxSubresources) UINT FirstSubresource, _In_range_(1, MaxSubresources - FirstSubresource) UINT NumSubresources, - _In_reads_(NumSubresources) D3D12_SUBRESOURCE_DATA* pSrcData) + _In_reads_(NumSubresources) D3D12_SUBRESOURCE_DATA* pSrcData) { - UINT64 RequiredSize = 0; + UINT64 RequiredSize = 0; D3D12_PLACED_SUBRESOURCE_FOOTPRINT Layouts[MaxSubresources]; - UINT NumRows[MaxSubresources]; - UINT64 RowSizesInBytes[MaxSubresources]; - + UINT NumRows[MaxSubresources]; + UINT64 RowSizesInBytes[MaxSubresources]; + D3D12_RESOURCE_DESC Desc = pDestinationResource->GetDesc(); - ID3D12Device* pDevice; + ID3D12Device* pDevice; pDestinationResource->GetDevice(__uuidof(*pDevice), reinterpret_cast(&pDevice)); pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, Layouts, NumRows, RowSizesInBytes, &RequiredSize); pDevice->Release(); - + return UpdateSubresources(pCmdList, pDestinationResource, pIntermediate, FirstSubresource, NumSubresources, RequiredSize, Layouts, NumRows, RowSizesInBytes, pSrcData); } //------------------------------------------------------------------------------------------------ -inline bool D3D12IsLayoutOpaque( D3D12_TEXTURE_LAYOUT Layout ) -{ return Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN || Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; } +inline bool D3D12IsLayoutOpaque(D3D12_TEXTURE_LAYOUT Layout) +{ + return Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN || Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; +} //------------------------------------------------------------------------------------------------ -inline ID3D12CommandList * const * CommandListCast(ID3D12GraphicsCommandList * const * pp) +inline ID3D12CommandList* const* CommandListCast(ID3D12GraphicsCommandList* const* pp) { // This cast is useful for passing strongly typed command list pointers into // ExecuteCommandLists. // This cast is valid as long as the const-ness is respected. D3D12 APIs do // respect the const-ness of their arguments. - return reinterpret_cast(pp); + return reinterpret_cast(pp); } #endif // defined( __cplusplus ) #endif //__D3DX12_H__ - - - diff --git a/Graphics/GraphicsEngineD3D12/include/pch.h b/Graphics/GraphicsEngineD3D12/include/pch.h index 733f3ef6..7afa4a77 100644 --- a/Graphics/GraphicsEngineD3D12/include/pch.h +++ b/Graphics/GraphicsEngineD3D12/include/pch.h @@ -29,11 +29,11 @@ #pragma once #ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +# define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #endif #ifndef NOMINMAX -# define NOMINMAX +# define NOMINMAX #endif @@ -49,4 +49,4 @@ #include "D3DErrors.h" #include "RenderDeviceBase.h" #include "ValidatedCast.h" -#include \ No newline at end of file +#include diff --git a/Graphics/GraphicsEngineD3D12/interface/BufferD3D12.h b/Graphics/GraphicsEngineD3D12/interface/BufferD3D12.h index 66a8fa82..24517c6e 100644 --- a/Graphics/GraphicsEngineD3D12/interface/BufferD3D12.h +++ b/Graphics/GraphicsEngineD3D12/interface/BufferD3D12.h @@ -35,13 +35,12 @@ class IDeviceContext; // {3E9B15ED-A289-48DC-8214-C6E3E6177378} static constexpr INTERFACE_ID IID_BufferD3D12 = -{ 0x3e9b15ed, 0xa289, 0x48dc, { 0x82, 0x14, 0xc6, 0xe3, 0xe6, 0x17, 0x73, 0x78 } }; + {0x3e9b15ed, 0xa289, 0x48dc, {0x82, 0x14, 0xc6, 0xe3, 0xe6, 0x17, 0x73, 0x78}}; /// Exposes Direct3D12-specific functionality of a buffer object. class IBufferD3D12 : public IBuffer { public: - /// Returns a pointer to the ID3D12Resource interface of the internal Direct3D12 object. /// The method does *NOT* call AddRef() on the returned interface, @@ -58,10 +57,10 @@ public: /// \param [in] state - D3D12 resource state to be set for this buffer virtual void SetD3D12ResourceState(D3D12_RESOURCE_STATES state) = 0; - /// Returns current D3D12 buffer state. - /// If the state is unknown to the engine (Diligent::RESOURCE_STATE_UNKNOWN), + /// Returns current D3D12 buffer state. + /// If the state is unknown to the engine (Diligent::RESOURCE_STATE_UNKNOWN), /// returns D3D12_RESOURCE_STATE_COMMON (0). - virtual D3D12_RESOURCE_STATES GetD3D12ResourceState()const = 0; + virtual D3D12_RESOURCE_STATES GetD3D12ResourceState() const = 0; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/interface/BufferViewD3D12.h b/Graphics/GraphicsEngineD3D12/interface/BufferViewD3D12.h index c9a3b2ba..f96c7328 100644 --- a/Graphics/GraphicsEngineD3D12/interface/BufferViewD3D12.h +++ b/Graphics/GraphicsEngineD3D12/interface/BufferViewD3D12.h @@ -33,15 +33,14 @@ namespace Diligent // {09643F2F-40D4-4076-B086-9E5CDC2CC4FC} static constexpr INTERFACE_ID IID_BufferViewD3D12 = -{ 0x9643f2f, 0x40d4, 0x4076, { 0xb0, 0x86, 0x9e, 0x5c, 0xdc, 0x2c, 0xc4, 0xfc } }; + {0x9643f2f, 0x40d4, 0x4076, {0xb0, 0x86, 0x9e, 0x5c, 0xdc, 0x2c, 0xc4, 0xfc}}; /// Exposes Direct3D12-specific functionality of a buffer view object. class IBufferViewD3D12 : public IBufferView { public: - /// Returns CPU descriptor handle of the buffer view. virtual D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle() = 0; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/interface/CommandQueueD3D12.h b/Graphics/GraphicsEngineD3D12/interface/CommandQueueD3D12.h index b429fddc..f135b34a 100644 --- a/Graphics/GraphicsEngineD3D12/interface/CommandQueueD3D12.h +++ b/Graphics/GraphicsEngineD3D12/interface/CommandQueueD3D12.h @@ -31,19 +31,19 @@ namespace Diligent // {D89693CE-F3F4-44B5-B7EF-24115AAD085E} static constexpr INTERFACE_ID IID_CommandQueueD3D12 = -{ 0xd89693ce, 0xf3f4, 0x44b5, { 0xb7, 0xef, 0x24, 0x11, 0x5a, 0xad, 0x8, 0x5e } }; + {0xd89693ce, 0xf3f4, 0x44b5, {0xb7, 0xef, 0x24, 0x11, 0x5a, 0xad, 0x8, 0x5e}}; /// Command queue interface class ICommandQueueD3D12 : public Diligent::IObject { public: - /// Returns the fence value that will be signaled next time - virtual Uint64 GetNextFenceValue() = 0; + /// Returns the fence value that will be signaled next time + virtual Uint64 GetNextFenceValue() = 0; - /// Executes a given command list + /// Executes a given command list /// \return Fence value associated with the executed command list - virtual Uint64 Submit(ID3D12GraphicsCommandList* commandList) = 0; + virtual Uint64 Submit(ID3D12GraphicsCommandList* commandList) = 0; /// Returns D3D12 command queue. May return null if queue is anavailable virtual ID3D12CommandQueue* GetD3D12CommandQueue() = 0; @@ -58,4 +58,4 @@ public: virtual void SignalFence(ID3D12Fence* pFence, Uint64 Value) = 0; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/interface/DeviceContextD3D12.h b/Graphics/GraphicsEngineD3D12/interface/DeviceContextD3D12.h index 616661b3..5aa8fa96 100644 --- a/Graphics/GraphicsEngineD3D12/interface/DeviceContextD3D12.h +++ b/Graphics/GraphicsEngineD3D12/interface/DeviceContextD3D12.h @@ -34,13 +34,12 @@ namespace Diligent // {DDE9E3AB-5109-4026-92B7-F5E7EC83E21E} static constexpr INTERFACE_ID IID_DeviceContextD3D12 = -{ 0xdde9e3ab, 0x5109, 0x4026, { 0x92, 0xb7, 0xf5, 0xe7, 0xec, 0x83, 0xe2, 0x1e } }; + {0xdde9e3ab, 0x5109, 0x4026, {0x92, 0xb7, 0xf5, 0xe7, 0xec, 0x83, 0xe2, 0x1e}}; /// Exposes Direct3D12-specific functionality of a device context. class IDeviceContextD3D12 : public IDeviceContext { public: - /// Transitions internal D3D12 texture object to a specified state /// \param [in] pTexture - texture to transition @@ -58,16 +57,16 @@ public: /// \return - a pointer to the current command list /// /// \remarks Any command on the device context may potentially submit the command list for - /// execution into the command queue and make it invalid. An application should - /// never cache the pointer and should instead request the command list every time it + /// execution into the command queue and make it invalid. An application should + /// never cache the pointer and should instead request the command list every time it /// needs it. /// /// The engine manages the lifetimes of all command buffers, so an application must /// not call AddRef/Release methods on the returned interface. /// - /// Diligent Engine internally keeps track of all resource state changes (vertex and index + /// Diligent Engine internally keeps track of all resource state changes (vertex and index /// buffers, pipeline states, render targets, etc.). If an application changes any of these - /// states in the command list, it must invalidate the engine's internal state tracking by + /// states in the command list, it must invalidate the engine's internal state tracking by /// calling IDeviceContext::InvalidateState() and then manually restore all required states via /// appropriate Diligent API calls. virtual ID3D12GraphicsCommandList* GetD3D12CommandList() = 0; @@ -80,7 +79,7 @@ public: /// /// The engine locks the internal mutex to prevent simultaneous access to the command queue. /// An application must release the lock by calling IDeviceContextD3D12::UnlockCommandQueue() - /// when it is done working with the queue or the engine will not be able to submit any command + /// when it is done working with the queue or the engine will not be able to submit any command /// list to the queue. Nested calls to LockCommandQueue() are not allowed. /// The queue pointer never changes while the context is alive, so an application may cache and /// use the pointer if it does not need to prevent potential simultaneous access to the queue from @@ -94,4 +93,4 @@ public: virtual void UnlockCommandQueue() = 0; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/interface/EngineFactoryD3D12.h b/Graphics/GraphicsEngineD3D12/interface/EngineFactoryD3D12.h index 5e9f9cba..b02deaa0 100644 --- a/Graphics/GraphicsEngineD3D12/interface/EngineFactoryD3D12.h +++ b/Graphics/GraphicsEngineD3D12/interface/EngineFactoryD3D12.h @@ -34,15 +34,15 @@ #include "../../GraphicsEngine/interface/SwapChain.h" #if PLATFORM_UNIVERSAL_WINDOWS && defined(ENGINE_DLL) -# include "../../../Common/interface/StringTools.h" +# include "../../../Common/interface/StringTools.h" #endif namespace Diligent { // {72BD38B0-684A-4889-9C68-0A80EC802DDE} -static const INTERFACE_ID IID_EngineFactoryD3D12 = -{ 0x72bd38b0, 0x684a, 0x4889, { 0x9c, 0x68, 0xa, 0x80, 0xec, 0x80, 0x2d, 0xde } }; +static const INTERFACE_ID IID_EngineFactoryD3D12 = + {0x72bd38b0, 0x684a, 0x4889, {0x9c, 0x68, 0xa, 0x80, 0xec, 0x80, 0x2d, 0xde}}; /// Engine factory for Direct3D12 rendering backend class IEngineFactoryD3D12 : public IEngineFactory @@ -51,14 +51,14 @@ public: /// Creates a render device and device contexts for Direct3D12-based engine implementation. /// \param [in] EngineCI - Engine creation info. - /// \param [out] ppDevice - Address of the memory location where pointer to + /// \param [out] ppDevice - Address of the memory location where pointer to /// the created device will be written. - /// \param [out] ppContexts - Address of the memory location where pointers to + /// \param [out] ppContexts - Address of the memory location where pointers to /// the contexts will be written. Immediate context goes at /// position 0. If EngineCI.NumDeferredContexts > 0, /// pointers to the deferred contexts are written afterwards. - virtual void CreateDeviceAndContextsD3D12(const EngineD3D12CreateInfo& EngineCI, - IRenderDevice** ppDevice, + virtual void CreateDeviceAndContextsD3D12(const EngineD3D12CreateInfo& EngineCI, + IRenderDevice** ppDevice, IDeviceContext** ppContexts) = 0; @@ -68,18 +68,18 @@ public: /// \param [in] CommandQueueCount - Number of command queues. /// \param [in] ppCommandQueues - Pointer to the array of command queues. /// \param [in] EngineCI - Engine creation info. - /// \param [out] ppDevice - Address of the memory location where pointer to + /// \param [out] ppDevice - Address of the memory location where pointer to /// the created device will be written - /// \param [out] ppContexts - Address of the memory location where pointers to + /// \param [out] ppContexts - Address of the memory location where pointers to /// the contexts will be written. Immediate context goes at /// position 0. If EngineCI.NumDeferredContexts > 0, /// pointers to the deferred contexts are written afterwards. - virtual void AttachToD3D12Device(void* pd3d12NativeDevice, - size_t CommandQueueCount, - class ICommandQueueD3D12** ppCommandQueues, - const EngineD3D12CreateInfo& EngineCI, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts) = 0; + virtual void AttachToD3D12Device(void* pd3d12NativeDevice, + size_t CommandQueueCount, + class ICommandQueueD3D12** ppCommandQueues, + const EngineD3D12CreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts) = 0; /// Creates a swap chain for Direct3D12-based engine implementation. @@ -88,20 +88,20 @@ public: /// \param [in] pImmediateContext - Pointer to the immediate device context. /// \param [in] SCDesc - Swap chain description. /// \param [in] FSDesc - Fullscreen mode description. - /// \param [in] pNativeWndHandle - Platform-specific native handle of the window + /// \param [in] pNativeWndHandle - Platform-specific native handle of the window /// the swap chain will be associated with: /// * On Win32 platform, this should be the window handle (HWND) /// * On Universal Windows Platform, this should be the reference /// to the core window (Windows::UI::Core::CoreWindow) - /// - /// \param [out] ppSwapChain - Address of the memory location where pointer to the new + /// + /// \param [out] ppSwapChain - Address of the memory location where pointer to the new /// swap chain will be written - virtual void CreateSwapChainD3D12( IRenderDevice* pDevice, - IDeviceContext* pImmediateContext, - const SwapChainDesc& SwapChainDesc, - const FullScreenModeDesc& FSDesc, - void* pNativeWndHandle, - ISwapChain** ppSwapChain ) = 0; + virtual void CreateSwapChainD3D12(IRenderDevice* pDevice, + IDeviceContext* pImmediateContext, + const SwapChainDesc& SwapChainDesc, + const FullScreenModeDesc& FSDesc, + void* pNativeWndHandle, + ISwapChain** ppSwapChain) = 0; /// Enumerates hardware adapters available on this machine. @@ -110,16 +110,16 @@ public: /// \param [in,out] NumAdapters - Number of adapters. If Adapters is null, this value /// will be overwritten with the number of adapters available /// on this system. If Adapters is not null, this value should - /// contain maximum number of elements reserved in the array + /// contain maximum number of elements reserved in the array /// pointed to by Adapters. In the latter case, this value /// is overwritten with the actual number of elements written to /// Adapters. /// \param [out] Adapters - Pointer to the array conataining adapter information. If - /// null is provided, the number of available adapters is written to + /// null is provided, the number of available adapters is written to /// NumAdapters - virtual void EnumerateHardwareAdapters(DIRECT3D_FEATURE_LEVEL MinFeatureLevel, - Uint32& NumAdapters, - HardwareAdapterAttribs* Adapters) = 0; + virtual void EnumerateHardwareAdapters(DIRECT3D_FEATURE_LEVEL MinFeatureLevel, + Uint32& NumAdapters, + HardwareAdapterAttribs* Adapters) = 0; /// Enumerates available display modes for the specified output of the specified adapter. @@ -129,74 +129,74 @@ public: /// \param [in] OutputId - Adapter output id. /// \param [in] Format - Display mode format. /// \param [in, out] NumDisplayModes - Number of display modes. If DisplayModes is null, this - /// value is overwritten with the number of display modes + /// value is overwritten with the number of display modes /// available for this output. If DisplayModes is not null, /// this value should contain the maximum number of elements /// to be written to DisplayModes array. It is overwritten with /// the actual number of display modes written. virtual void EnumerateDisplayModes(DIRECT3D_FEATURE_LEVEL MinFeatureLevel, - Uint32 AdapterId, - Uint32 OutputId, - TEXTURE_FORMAT Format, - Uint32& NumDisplayModes, + Uint32 AdapterId, + Uint32 OutputId, + TEXTURE_FORMAT Format, + Uint32& NumDisplayModes, DisplayModeAttribs* DisplayModes) = 0; }; #if ENGINE_DLL - typedef IEngineFactoryD3D12* (*GetEngineFactoryD3D12Type)(); +typedef IEngineFactoryD3D12* (*GetEngineFactoryD3D12Type)(); - static bool LoadGraphicsEngineD3D12(GetEngineFactoryD3D12Type &GetFactoryFunc) +static bool LoadGraphicsEngineD3D12(GetEngineFactoryD3D12Type& GetFactoryFunc) +{ + GetFactoryFunc = nullptr; + std::string LibName = "GraphicsEngineD3D12_"; + +# if _WIN64 + LibName += "64"; +# else + LibName += "32"; +# endif + +# ifdef _DEBUG + LibName += "d"; +# else + LibName += "r"; +# endif + + LibName += ".dll"; +# if PLATFORM_WIN32 + auto hModule = LoadLibraryA(LibName.c_str()); +# elif PLATFORM_UNIVERSAL_WINDOWS + auto hModule = LoadPackagedLibrary(WidenString(LibName).c_str(), 0); +# else +# error Unexpected platform +# endif + + if (hModule == NULL) { - GetFactoryFunc = nullptr; - std::string LibName = "GraphicsEngineD3D12_"; - -#if _WIN64 - LibName += "64"; -#else - LibName += "32"; -#endif - -#ifdef _DEBUG - LibName += "d"; -#else - LibName += "r"; -#endif - - LibName += ".dll"; -#if PLATFORM_WIN32 - auto hModule = LoadLibraryA(LibName.c_str()); -#elif PLATFORM_UNIVERSAL_WINDOWS - auto hModule = LoadPackagedLibrary(WidenString(LibName).c_str(), 0); -#else -# error Unexpected platform -#endif + std::stringstream ss; + ss << "Failed to load " << LibName << " library.\n"; + OutputDebugStringA(ss.str().c_str()); + return false; + } - if( hModule == NULL ) - { - std::stringstream ss; - ss << "Failed to load " << LibName << " library.\n"; - OutputDebugStringA(ss.str().c_str()); - return false; - } - - GetFactoryFunc = reinterpret_cast( GetProcAddress(hModule, "GetEngineFactoryD3D12") ); - if( GetFactoryFunc == NULL ) - { - std::stringstream ss; - ss << "Failed to load GetEngineFactoryD3D12() from " << LibName << " library.\n"; - OutputDebugStringA(ss.str().c_str()); - FreeLibrary( hModule ); - return false; - } - - return true; + GetFactoryFunc = reinterpret_cast(GetProcAddress(hModule, "GetEngineFactoryD3D12")); + if (GetFactoryFunc == NULL) + { + std::stringstream ss; + ss << "Failed to load GetEngineFactoryD3D12() from " << LibName << " library.\n"; + OutputDebugStringA(ss.str().c_str()); + FreeLibrary(hModule); + return false; } + + return true; +} #else - IEngineFactoryD3D12* GetEngineFactoryD3D12(); +IEngineFactoryD3D12* GetEngineFactoryD3D12(); #endif -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/interface/FenceD3D12.h b/Graphics/GraphicsEngineD3D12/interface/FenceD3D12.h index 2481a58e..09d9d856 100644 --- a/Graphics/GraphicsEngineD3D12/interface/FenceD3D12.h +++ b/Graphics/GraphicsEngineD3D12/interface/FenceD3D12.h @@ -33,14 +33,13 @@ namespace Diligent // {053C0D8C-3757-4220-A9CC-4749EC4794AD} static constexpr INTERFACE_ID IID_FenceD3D12 = -{ 0x53c0d8c, 0x3757, 0x4220, { 0xa9, 0xcc, 0x47, 0x49, 0xec, 0x47, 0x94, 0xad } }; + {0x53c0d8c, 0x3757, 0x4220, {0xa9, 0xcc, 0x47, 0x49, 0xec, 0x47, 0x94, 0xad}}; /// Exposes Direct3D12-specific functionality of a fence object. class IFenceD3D12 : public IFence { public: - /// Returns a pointer to the ID3D12Fence interface of the internal Direct3D12 object. /// The method does *NOT* call AddRef() on the returned interface, @@ -51,4 +50,4 @@ public: virtual void WaitForCompletion(Uint64 Value) = 0; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/interface/PipelineStateD3D12.h b/Graphics/GraphicsEngineD3D12/interface/PipelineStateD3D12.h index 6cb3cf6c..c790eaf9 100644 --- a/Graphics/GraphicsEngineD3D12/interface/PipelineStateD3D12.h +++ b/Graphics/GraphicsEngineD3D12/interface/PipelineStateD3D12.h @@ -32,26 +32,25 @@ namespace Diligent { // {33C9BE4B-6F23-4F83-A665-5AC1836DF35A} -static constexpr INTERFACE_ID IID_PipelineStateD3D12 = -{ 0x33c9be4b, 0x6f23, 0x4f83, { 0xa6, 0x65, 0x5a, 0xc1, 0x83, 0x6d, 0xf3, 0x5a } }; +static constexpr INTERFACE_ID IID_PipelineStateD3D12 = + {0x33c9be4b, 0x6f23, 0x4f83, {0xa6, 0x65, 0x5a, 0xc1, 0x83, 0x6d, 0xf3, 0x5a}}; /// Exposes Direct3D12-specific functionality of a pipeline state object. class IPipelineStateD3D12 : public IPipelineState { public: - /// Returns ID3D12PipelineState interface of the internal D3D12 pipeline state object object. - + /// The method does *NOT* call AddRef() on the returned interface, /// so Release() must not be called. - virtual ID3D12PipelineState* GetD3D12PipelineState()const = 0; + virtual ID3D12PipelineState* GetD3D12PipelineState() const = 0; /// Returns a pointer to the root signature object associated with this pipeline state. - + /// The method does *NOT* call AddRef() on the returned interface, /// so Release() must not be called. - virtual ID3D12RootSignature* GetD3D12RootSignature()const = 0; + virtual ID3D12RootSignature* GetD3D12RootSignature() const = 0; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/interface/RenderDeviceD3D12.h b/Graphics/GraphicsEngineD3D12/interface/RenderDeviceD3D12.h index b9da0e34..8b05cdf1 100644 --- a/Graphics/GraphicsEngineD3D12/interface/RenderDeviceD3D12.h +++ b/Graphics/GraphicsEngineD3D12/interface/RenderDeviceD3D12.h @@ -32,13 +32,12 @@ namespace Diligent { // {C7987C98-87FE-4309-AE88-E98F044B00F6} static constexpr INTERFACE_ID IID_RenderDeviceD3D12 = -{ 0xc7987c98, 0x87fe, 0x4309, { 0xae, 0x88, 0xe9, 0x8f, 0x4, 0x4b, 0x0, 0xf6 } }; + {0xc7987c98, 0x87fe, 0x4309, {0xae, 0x88, 0xe9, 0x8f, 0x4, 0x4b, 0x0, 0xf6}}; /// Exposes Direct3D12-specific functionality of a render device. class IRenderDeviceD3D12 : public IRenderDevice { public: - /// Returns ID3D12Device interface of the internal Direct3D12 device object. /// The method does *NOT* call AddRef() on the returned interface, @@ -60,8 +59,8 @@ public: /// \param [in] pd3d12Texture - pointer to the native D3D12 texture /// \param [in] InitialState - Initial texture state. See Diligent::RESOURCE_STATE. /// \param [out] ppTexture - Address of the memory location where the pointer to the - /// texture interface will be stored. - /// The function calls AddRef(), so that the new object will contain + /// texture interface will be stored. + /// The function calls AddRef(), so that the new object will contain /// one reference. virtual void CreateTextureFromD3DResource(ID3D12Resource* pd3d12Texture, RESOURCE_STATE InitialState, @@ -71,12 +70,12 @@ public: /// \param [in] pd3d12Buffer - Pointer to the native d3d12 buffer resource /// \param [in] BuffDesc - Buffer description. The system can recover buffer size, but - /// the rest of the fields need to be populated by the client + /// the rest of the fields need to be populated by the client /// as they cannot be recovered from d3d12 resource description /// \param [in] InitialState - Initial buffer state. See Diligent::RESOURCE_STATE. /// \param [out] ppBuffer - Address of the memory location where the pointer to the - /// buffer interface will be stored. - /// The function calls AddRef(), so that the new object will contain + /// buffer interface will be stored. + /// The function calls AddRef(), so that the new object will contain /// one reference. virtual void CreateBufferFromD3DResource(ID3D12Resource* pd3d12Buffer, const BufferDesc& BuffDesc, @@ -84,4 +83,4 @@ public: IBuffer** ppBuffer) = 0; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/interface/SamplerD3D12.h b/Graphics/GraphicsEngineD3D12/interface/SamplerD3D12.h index ef25aa08..c418d8b6 100644 --- a/Graphics/GraphicsEngineD3D12/interface/SamplerD3D12.h +++ b/Graphics/GraphicsEngineD3D12/interface/SamplerD3D12.h @@ -33,18 +33,17 @@ namespace Diligent // {31A3BFAF-738E-4D8C-AD18-B021C5D948DD} static constexpr INTERFACE_ID IID_SamplerD3D12 = -{ 0x31a3bfaf, 0x738e, 0x4d8c, { 0xad, 0x18, 0xb0, 0x21, 0xc5, 0xd9, 0x48, 0xdd } }; + {0x31a3bfaf, 0x738e, 0x4d8c, {0xad, 0x18, 0xb0, 0x21, 0xc5, 0xd9, 0x48, 0xdd}}; /// Exposes Direct3D12-specific functionality of a sampler object. class ISamplerD3D12 : public ISampler { public: - /// Returns a CPU descriptor handle of the D3D12 sampler object - + /// The method does *NOT* call AddRef() on the returned interface, /// so Release() must not be called. virtual D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle() = 0; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/interface/ShaderD3D12.h b/Graphics/GraphicsEngineD3D12/interface/ShaderD3D12.h index 15d59b49..f242a7da 100644 --- a/Graphics/GraphicsEngineD3D12/interface/ShaderD3D12.h +++ b/Graphics/GraphicsEngineD3D12/interface/ShaderD3D12.h @@ -33,13 +33,12 @@ namespace Diligent // {C059B160-7F31-4029-943D-0996B98EE79A} static constexpr INTERFACE_ID IID_ShaderD3D12 = -{ 0xc059b160, 0x7f31, 0x4029, { 0x94, 0x3d, 0x9, 0x96, 0xb9, 0x8e, 0xe7, 0x9a } }; + {0xc059b160, 0x7f31, 0x4029, {0x94, 0x3d, 0x9, 0x96, 0xb9, 0x8e, 0xe7, 0x9a}}; /// Exposes Direct3D12-specific functionality of a shader object. class IShaderD3D12 : public IShaderD3D { public: - /// Returns a pointer to the ID3D12DeviceChild interface of the internal Direct3D12 object. /// The method does *NOT* call AddRef() on the returned interface, @@ -47,4 +46,4 @@ public: //virtual ID3D12DeviceChild* GetD3D12Shader() = 0; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/interface/ShaderResourceBindingD3D12.h b/Graphics/GraphicsEngineD3D12/interface/ShaderResourceBindingD3D12.h index fbf3cfb4..916f1486 100644 --- a/Graphics/GraphicsEngineD3D12/interface/ShaderResourceBindingD3D12.h +++ b/Graphics/GraphicsEngineD3D12/interface/ShaderResourceBindingD3D12.h @@ -33,13 +33,11 @@ namespace Diligent // {70DD5C7C-81FA-4D9A-942F-D1B91423FAAC} static constexpr INTERFACE_ID IID_ShaderResourceBindingD3D12 = -{ 0x70dd5c7c, 0x81fa, 0x4d9a, { 0x94, 0x2f, 0xd1, 0xb9, 0x14, 0x23, 0xfa, 0xac } }; + {0x70dd5c7c, 0x81fa, 0x4d9a, {0x94, 0x2f, 0xd1, 0xb9, 0x14, 0x23, 0xfa, 0xac}}; /// Exposes Direct3D12-specific functionality of a shader resource binding. class IShaderResourceBindingD3D12 : public IShaderResourceBinding { -public: - }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/interface/SwapChainD3D12.h b/Graphics/GraphicsEngineD3D12/interface/SwapChainD3D12.h index 862d6b51..8d47d4fa 100644 --- a/Graphics/GraphicsEngineD3D12/interface/SwapChainD3D12.h +++ b/Graphics/GraphicsEngineD3D12/interface/SwapChainD3D12.h @@ -36,13 +36,12 @@ namespace Diligent // {C9F8384D-A45E-4970-8447-394177E5B0EE} static constexpr INTERFACE_ID IID_SwapChainD3D12 = -{ 0xc9f8384d, 0xa45e, 0x4970, { 0x84, 0x47, 0x39, 0x41, 0x77, 0xe5, 0xb0, 0xee } }; + {0xc9f8384d, 0xa45e, 0x4970, {0x84, 0x47, 0x39, 0x41, 0x77, 0xe5, 0xb0, 0xee}}; /// Exposes Direct3D12-specific functionality of a swap chain. class ISwapChainD3D12 : public ISwapChain { public: - /// Returns a pointer to the IDXGISwapChain interface of the internal DXGI object. /// The method does *NOT* call AddRef() on the returned interface, @@ -50,4 +49,4 @@ public: virtual IDXGISwapChain* GetDXGISwapChain() = 0; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/interface/TextureD3D12.h b/Graphics/GraphicsEngineD3D12/interface/TextureD3D12.h index d721add8..ee62b7c0 100644 --- a/Graphics/GraphicsEngineD3D12/interface/TextureD3D12.h +++ b/Graphics/GraphicsEngineD3D12/interface/TextureD3D12.h @@ -33,13 +33,12 @@ namespace Diligent // {CF5522EF-8116-4D76-ADF1-5CC8FB31FF66} static constexpr INTERFACE_ID IID_TextureD3D12 = -{ 0xcf5522ef, 0x8116, 0x4d76, { 0xad, 0xf1, 0x5c, 0xc8, 0xfb, 0x31, 0xff, 0x66 } }; + {0xcf5522ef, 0x8116, 0x4d76, {0xad, 0xf1, 0x5c, 0xc8, 0xfb, 0x31, 0xff, 0x66}}; /// Exposes Direct3D12-specific functionality of a texture object. class ITextureD3D12 : public ITexture { public: - /// Returns a pointer to the ID3D12Resource interface of the internal Direct3D12 object. /// The method does *NOT* call AddRef() on the returned interface, @@ -51,10 +50,10 @@ public: /// \param [in] state - D3D12 resource state to be set for this texture virtual void SetD3D12ResourceState(D3D12_RESOURCE_STATES state) = 0; - /// Returns current D3D12 texture state. - /// If the state is unknown to the engine (Diligent::RESOURCE_STATE_UNKNOWN), + /// Returns current D3D12 texture state. + /// If the state is unknown to the engine (Diligent::RESOURCE_STATE_UNKNOWN), /// returns D3D12_RESOURCE_STATE_COMMON (0). - virtual D3D12_RESOURCE_STATES GetD3D12ResourceState()const = 0; + virtual D3D12_RESOURCE_STATES GetD3D12ResourceState() const = 0; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/interface/TextureViewD3D12.h b/Graphics/GraphicsEngineD3D12/interface/TextureViewD3D12.h index 9e53f4ad..b7a449ea 100644 --- a/Graphics/GraphicsEngineD3D12/interface/TextureViewD3D12.h +++ b/Graphics/GraphicsEngineD3D12/interface/TextureViewD3D12.h @@ -33,15 +33,14 @@ namespace Diligent // {BDFBD325-0699-4720-BC0E-BF84086EC033} static constexpr INTERFACE_ID IID_TextureViewD3D12 = -{ 0xbdfbd325, 0x699, 0x4720, { 0xbc, 0xe, 0xbf, 0x84, 0x8, 0x6e, 0xc0, 0x33 } }; + {0xbdfbd325, 0x699, 0x4720, {0xbc, 0xe, 0xbf, 0x84, 0x8, 0x6e, 0xc0, 0x33}}; /// Exposes Direct3D12-specific functionality of a texture view object. class ITextureViewD3D12 : public ITextureView { public: - /// Returns CPU descriptor handle of the texture view. virtual D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle() = 0; }; -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/BufferD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/BufferD3D12Impl.cpp index e2c92780..b3000d83 100644 --- a/Graphics/GraphicsEngineD3D12/src/BufferD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/BufferD3D12Impl.cpp @@ -35,11 +35,12 @@ namespace Diligent { -BufferD3D12Impl :: BufferD3D12Impl(IReferenceCounters* pRefCounters, - FixedBlockMemoryAllocator& BuffViewObjMemAllocator, - RenderDeviceD3D12Impl* pRenderDeviceD3D12, - const BufferDesc& BuffDesc, - const BufferData* pBuffData /*= nullptr*/) : +BufferD3D12Impl::BufferD3D12Impl(IReferenceCounters* pRefCounters, + FixedBlockMemoryAllocator& BuffViewObjMemAllocator, + RenderDeviceD3D12Impl* pRenderDeviceD3D12, + const BufferDesc& BuffDesc, + const BufferData* pBuffData /*= nullptr*/) : + // clang-format off TBufferBase { pRefCounters, @@ -54,37 +55,38 @@ BufferD3D12Impl :: BufferD3D12Impl(IReferenceCounters* pRefCounters, D3D12DynamicAllocation{}, STD_ALLOCATOR_RAW_MEM(D3D12DynamicAllocation, GetRawAllocator(), "Allocator for vector") } +// clang-format on { -#define LOG_BUFFER_ERROR_AND_THROW(...) LOG_ERROR_AND_THROW("Buffer \"", BuffDesc.Name ? BuffDesc.Name : "", "\": ", ##__VA_ARGS__); +#define LOG_BUFFER_ERROR_AND_THROW(...) LOG_ERROR_AND_THROW("Buffer \"", BuffDesc.Name ? BuffDesc.Name : "", "\": ", ##__VA_ARGS__) - if( m_Desc.Usage == USAGE_STATIC && (pBuffData == nullptr || pBuffData->pData == nullptr)) - LOG_BUFFER_ERROR_AND_THROW("Static buffer must be initialized with data at creation time") + if (m_Desc.Usage == USAGE_STATIC && (pBuffData == nullptr || pBuffData->pData == nullptr)) + LOG_BUFFER_ERROR_AND_THROW("Static buffer must be initialized with data at creation time"); - if( m_Desc.Usage == USAGE_DYNAMIC && pBuffData != nullptr && pBuffData->pData != nullptr ) - LOG_BUFFER_ERROR_AND_THROW("Dynamic buffer must be initialized via Map()") + if (m_Desc.Usage == USAGE_DYNAMIC && pBuffData != nullptr && pBuffData->pData != nullptr) + LOG_BUFFER_ERROR_AND_THROW("Dynamic buffer must be initialized via Map()"); Uint32 AlignmentMask = 1; if (m_Desc.BindFlags & BIND_UNIFORM_BUFFER) AlignmentMask = 255; - + if (m_Desc.Usage == USAGE_STAGING) { if (m_Desc.CPUAccessFlags != CPU_ACCESS_WRITE && m_Desc.CPUAccessFlags != CPU_ACCESS_READ) - LOG_BUFFER_ERROR_AND_THROW("Exactly one of the CPU_ACCESS_WRITE or CPU_ACCESS_READ flags must be specified for a cpu-accessible buffer") + LOG_BUFFER_ERROR_AND_THROW("Exactly one of the CPU_ACCESS_WRITE or CPU_ACCESS_READ flags must be specified for a cpu-accessible buffer"); if (m_Desc.CPUAccessFlags == CPU_ACCESS_WRITE) { if (pBuffData != nullptr && pBuffData->pData != nullptr) - LOG_BUFFER_ERROR_AND_THROW("CPU-writable staging buffers must be updated via map") + LOG_BUFFER_ERROR_AND_THROW("CPU-writable staging buffers must be updated via map"); AlignmentMask = D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1; } } - - if(AlignmentMask != 1) + + if (AlignmentMask != 1) m_Desc.uiSizeInBytes = (m_Desc.uiSizeInBytes + AlignmentMask) & (~AlignmentMask); - if(m_Desc.Usage == USAGE_DYNAMIC && (m_Desc.BindFlags & (BIND_SHADER_RESOURCE|BIND_UNORDERED_ACCESS)) == 0) + if (m_Desc.Usage == USAGE_DYNAMIC && (m_Desc.BindFlags & (BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS)) == 0) { // Dynamic constant/vertex/index buffers are suballocated in the upload heap when Map() is called. // Dynamic buffers with SRV or UAV flags need to be allocated in GPU-only memory @@ -96,25 +98,25 @@ BufferD3D12Impl :: BufferD3D12Impl(IReferenceCounters* pRefCounters, else { D3D12_RESOURCE_DESC D3D12BuffDesc = {}; - D3D12BuffDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - D3D12BuffDesc.Alignment = 0; - D3D12BuffDesc.Width = m_Desc.uiSizeInBytes; - D3D12BuffDesc.Height = 1; - D3D12BuffDesc.DepthOrArraySize = 1; - D3D12BuffDesc.MipLevels = 1; - D3D12BuffDesc.Format = DXGI_FORMAT_UNKNOWN; - D3D12BuffDesc.SampleDesc.Count = 1; - D3D12BuffDesc.SampleDesc.Quality = 0; - // Layout must be D3D12_TEXTURE_LAYOUT_ROW_MAJOR, as buffer memory layouts are + D3D12BuffDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + D3D12BuffDesc.Alignment = 0; + D3D12BuffDesc.Width = m_Desc.uiSizeInBytes; + D3D12BuffDesc.Height = 1; + D3D12BuffDesc.DepthOrArraySize = 1; + D3D12BuffDesc.MipLevels = 1; + D3D12BuffDesc.Format = DXGI_FORMAT_UNKNOWN; + D3D12BuffDesc.SampleDesc.Count = 1; + D3D12BuffDesc.SampleDesc.Quality = 0; + // Layout must be D3D12_TEXTURE_LAYOUT_ROW_MAJOR, as buffer memory layouts are // understood by applications and row-major texture data is commonly marshaled through buffers. D3D12BuffDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - D3D12BuffDesc.Flags = D3D12_RESOURCE_FLAG_NONE; - if( m_Desc.BindFlags & BIND_UNORDERED_ACCESS ) + D3D12BuffDesc.Flags = D3D12_RESOURCE_FLAG_NONE; + if (m_Desc.BindFlags & BIND_UNORDERED_ACCESS) D3D12BuffDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - if( !(m_Desc.BindFlags & BIND_SHADER_RESOURCE) ) + if (!(m_Desc.BindFlags & BIND_SHADER_RESOURCE)) D3D12BuffDesc.Flags |= D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; - auto *pd3d12Device = pRenderDeviceD3D12->GetD3D12Device(); + auto* pd3d12Device = pRenderDeviceD3D12->GetD3D12Device(); D3D12_HEAP_PROPERTIES HeapProps; if (m_Desc.Usage == USAGE_STAGING) @@ -122,68 +124,72 @@ BufferD3D12Impl :: BufferD3D12Impl(IReferenceCounters* pRefCounters, else HeapProps.Type = D3D12_HEAP_TYPE_DEFAULT; - if(HeapProps.Type == D3D12_HEAP_TYPE_READBACK) + if (HeapProps.Type == D3D12_HEAP_TYPE_READBACK) SetState(RESOURCE_STATE_COPY_DEST); - else if(HeapProps.Type == D3D12_HEAP_TYPE_UPLOAD) + else if (HeapProps.Type == D3D12_HEAP_TYPE_UPLOAD) SetState(RESOURCE_STATE_GENERIC_READ); - HeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; - HeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; - HeapProps.CreationNodeMask = 1; - HeapProps.VisibleNodeMask = 1; + HeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; + HeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; + HeapProps.CreationNodeMask = 1; + HeapProps.VisibleNodeMask = 1; bool bInitializeBuffer = (pBuffData != nullptr && pBuffData->pData != nullptr && pBuffData->DataSize > 0); - if(bInitializeBuffer) + if (bInitializeBuffer) SetState(RESOURCE_STATE_COPY_DEST); if (!IsInKnownState()) SetState(RESOURCE_STATE_UNDEFINED); auto D3D12State = ResourceStateFlagsToD3D12ResourceStates(GetState()); - auto hr = pd3d12Device->CreateCommittedResource( &HeapProps, D3D12_HEAP_FLAG_NONE, - &D3D12BuffDesc, D3D12State, nullptr, __uuidof(m_pd3d12Resource), reinterpret_cast(static_cast(&m_pd3d12Resource)) ); - if(FAILED(hr)) + + auto hr = pd3d12Device->CreateCommittedResource(&HeapProps, D3D12_HEAP_FLAG_NONE, + &D3D12BuffDesc, D3D12State, nullptr, + __uuidof(m_pd3d12Resource), + reinterpret_cast(static_cast(&m_pd3d12Resource))); + if (FAILED(hr)) LOG_ERROR_AND_THROW("Failed to create D3D12 buffer"); - if( *m_Desc.Name != 0) + if (*m_Desc.Name != 0) m_pd3d12Resource->SetName(WidenString(m_Desc.Name).c_str()); - if( bInitializeBuffer ) + if (bInitializeBuffer) { D3D12_HEAP_PROPERTIES UploadHeapProps; - UploadHeapProps.Type = D3D12_HEAP_TYPE_UPLOAD; - UploadHeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; - UploadHeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; - UploadHeapProps.CreationNodeMask = 1; - UploadHeapProps.VisibleNodeMask = 1; + UploadHeapProps.Type = D3D12_HEAP_TYPE_UPLOAD; + UploadHeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; + UploadHeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; + UploadHeapProps.CreationNodeMask = 1; + UploadHeapProps.VisibleNodeMask = 1; D3D12BuffDesc.Flags = D3D12_RESOURCE_FLAG_NONE; CComPtr UploadBuffer; - hr = pd3d12Device->CreateCommittedResource( &UploadHeapProps, D3D12_HEAP_FLAG_NONE, - &D3D12BuffDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, __uuidof(UploadBuffer), - reinterpret_cast(static_cast(&UploadBuffer)) ); - if(FAILED(hr)) + hr = pd3d12Device->CreateCommittedResource(&UploadHeapProps, D3D12_HEAP_FLAG_NONE, + &D3D12BuffDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, __uuidof(UploadBuffer), + reinterpret_cast(static_cast(&UploadBuffer))); + if (FAILED(hr)) LOG_ERROR_AND_THROW("Failed to create uload buffer"); - void* DestAddress = nullptr; - hr = UploadBuffer->Map(0, nullptr, &DestAddress); - if(FAILED(hr)) + void* DestAddress = nullptr; + + hr = UploadBuffer->Map(0, nullptr, &DestAddress); + if (FAILED(hr)) LOG_ERROR_AND_THROW("Failed to map uload buffer"); - memcpy(DestAddress, pBuffData->pData, pBuffData->DataSize); - UploadBuffer->Unmap(0, nullptr); + memcpy(DestAddress, pBuffData->pData, pBuffData->DataSize); + UploadBuffer->Unmap(0, nullptr); auto InitContext = pRenderDeviceD3D12->AllocateCommandContext(); - // copy data to the intermediate upload heap and then schedule a copy from the upload heap to the default buffer + // copy data to the intermediate upload heap and then schedule a copy from the upload heap to the default buffer VERIFY_EXPR(CheckState(RESOURCE_STATE_COPY_DEST)); // We MUST NOT call TransitionResource() from here, because - // it will call AddRef() and potentially Release(), while + // it will call AddRef() and potentially Release(), while // the object is not constructed yet - InitContext->CopyResource(m_pd3d12Resource, UploadBuffer); + InitContext->CopyResource(m_pd3d12Resource, UploadBuffer); // Command list fence should only be signaled when submitting cmd list // from the immediate context, otherwise the basic requirement will be violated // as in the scenario below // See http://diligentgraphics.com/diligent-engine/architecture/d3d12/managing-resource-lifetimes/ - // + // // Signaled Fence | Immediate Context | InitContext | // | | | // N | Draw(ResourceX) | | @@ -198,7 +204,7 @@ BufferD3D12Impl :: BufferD3D12Impl(IReferenceCounters* pRefCounters, // | was added to the delete queue | | // | with value N | | Uint32 QueueIndex = 0; - pRenderDeviceD3D12->CloseAndExecuteTransientCommandContext(QueueIndex, std::move(InitContext)); + pRenderDeviceD3D12->CloseAndExecuteTransientCommandContext(QueueIndex, std::move(InitContext)); // Add reference to the object to the release queue to keep it alive // until copy operation is complete. This must be done after @@ -221,8 +227,8 @@ static BufferDesc BufferDescFromD3D12Resource(BufferDesc BuffDesc, ID3D12Resourc auto D3D12BuffDesc = pd3d12Buffer->GetDesc(); VERIFY(D3D12BuffDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER, "D3D12 resource is not a buffer"); - VERIFY(BuffDesc.uiSizeInBytes == 0 || BuffDesc.uiSizeInBytes == D3D12BuffDesc.Width, "Buffer size specified by the BufferDesc (", BuffDesc.uiSizeInBytes,") does not match d3d12 resource size (", D3D12BuffDesc.Width, ")" ); - BuffDesc.uiSizeInBytes = static_cast( D3D12BuffDesc.Width ); + VERIFY(BuffDesc.uiSizeInBytes == 0 || BuffDesc.uiSizeInBytes == D3D12BuffDesc.Width, "Buffer size specified by the BufferDesc (", BuffDesc.uiSizeInBytes, ") does not match d3d12 resource size (", D3D12BuffDesc.Width, ")"); + BuffDesc.uiSizeInBytes = static_cast(D3D12BuffDesc.Width); if (D3D12BuffDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) { @@ -231,19 +237,18 @@ static BufferDesc BufferDescFromD3D12Resource(BufferDesc BuffDesc, ID3D12Resourc } if (D3D12BuffDesc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) { - VERIFY( !(BuffDesc.BindFlags & BIND_SHADER_RESOURCE), "BIND_SHADER_RESOURCE flag is specified by the BufferDesc, while d3d12 resource was created with D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE flag"); + VERIFY(!(BuffDesc.BindFlags & BIND_SHADER_RESOURCE), "BIND_SHADER_RESOURCE flag is specified by the BufferDesc, while d3d12 resource was created with D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE flag"); BuffDesc.BindFlags &= ~BIND_SHADER_RESOURCE; } - if( (BuffDesc.BindFlags & BIND_UNORDERED_ACCESS) || (BuffDesc.BindFlags & BIND_SHADER_RESOURCE) ) + if ((BuffDesc.BindFlags & BIND_UNORDERED_ACCESS) || (BuffDesc.BindFlags & BIND_SHADER_RESOURCE)) { - if(BuffDesc.Mode == BUFFER_MODE_STRUCTURED || BuffDesc.Mode == BUFFER_MODE_FORMATTED) + if (BuffDesc.Mode == BUFFER_MODE_STRUCTURED || BuffDesc.Mode == BUFFER_MODE_FORMATTED) { VERIFY(BuffDesc.ElementByteStride != 0, "Element byte stride cannot be 0 for a structured or a formatted buffer"); } - else if(BuffDesc.Mode == BUFFER_MODE_RAW) + else if (BuffDesc.Mode == BUFFER_MODE_RAW) { - } else { @@ -254,12 +259,13 @@ static BufferDesc BufferDescFromD3D12Resource(BufferDesc BuffDesc, ID3D12Resourc return BuffDesc; } -BufferD3D12Impl :: BufferD3D12Impl(IReferenceCounters* pRefCounters, - FixedBlockMemoryAllocator& BuffViewObjMemAllocator, - RenderDeviceD3D12Impl* pRenderDeviceD3D12, - const BufferDesc& BuffDesc, - RESOURCE_STATE InitialState, - ID3D12Resource* pd3d12Buffer) : +BufferD3D12Impl::BufferD3D12Impl(IReferenceCounters* pRefCounters, + FixedBlockMemoryAllocator& BuffViewObjMemAllocator, + RenderDeviceD3D12Impl* pRenderDeviceD3D12, + const BufferDesc& BuffDesc, + RESOURCE_STATE InitialState, + ID3D12Resource* pd3d12Buffer) : + // clang-format off TBufferBase { pRefCounters, @@ -274,6 +280,7 @@ BufferD3D12Impl :: BufferD3D12Impl(IReferenceCounters* pRefCounters, D3D12DynamicAllocation{}, STD_ALLOCATOR_RAW_MEM(D3D12DynamicAllocation, GetRawAllocator(), "Allocator for vector") } +// clang-format on { m_pd3d12Resource = pd3d12Buffer; SetState(InitialState); @@ -284,96 +291,94 @@ BufferD3D12Impl :: BufferD3D12Impl(IReferenceCounters* pRefCounters, CreateCBV(m_CBVDescriptorAllocation.GetCpuHandle()); } } -BufferD3D12Impl :: ~BufferD3D12Impl() +BufferD3D12Impl::~BufferD3D12Impl() { // D3D12 object can only be destroyed when it is no longer used by the GPU - auto *pDeviceD3D12Impl = ValidatedCast(GetDevice()); + auto* pDeviceD3D12Impl = ValidatedCast(GetDevice()); pDeviceD3D12Impl->SafeReleaseDeviceObject(std::move(m_pd3d12Resource), m_Desc.CommandQueueMask); } -IMPLEMENT_QUERY_INTERFACE( BufferD3D12Impl, IID_BufferD3D12, TBufferBase ) +IMPLEMENT_QUERY_INTERFACE(BufferD3D12Impl, IID_BufferD3D12, TBufferBase) -void BufferD3D12Impl::CreateViewInternal( const BufferViewDesc& OrigViewDesc, IBufferView** ppView, bool bIsDefaultView ) +void BufferD3D12Impl::CreateViewInternal(const BufferViewDesc& OrigViewDesc, IBufferView** ppView, bool bIsDefaultView) { - VERIFY( ppView != nullptr, "Null pointer provided" ); - if( !ppView )return; - VERIFY( *ppView == nullptr, "Overwriting reference to existing object may cause memory leaks" ); + VERIFY(ppView != nullptr, "Null pointer provided"); + if (!ppView) return; + VERIFY(*ppView == nullptr, "Overwriting reference to existing object may cause memory leaks"); *ppView = nullptr; try { - auto *pDeviceD3D12Impl = ValidatedCast(GetDevice()); - auto &BuffViewAllocator = pDeviceD3D12Impl->GetBuffViewObjAllocator(); - VERIFY( &BuffViewAllocator == &m_dbgBuffViewAllocator, "Buff view allocator does not match allocator provided at buffer initialization" ); + auto* pDeviceD3D12Impl = ValidatedCast(GetDevice()); + auto& BuffViewAllocator = pDeviceD3D12Impl->GetBuffViewObjAllocator(); + VERIFY(&BuffViewAllocator == &m_dbgBuffViewAllocator, "Buff view allocator does not match allocator provided at buffer initialization"); BufferViewDesc ViewDesc = OrigViewDesc; - if( ViewDesc.ViewType == BUFFER_VIEW_UNORDERED_ACCESS ) + if (ViewDesc.ViewType == BUFFER_VIEW_UNORDERED_ACCESS) { auto UAVHandleAlloc = pDeviceD3D12Impl->AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - CreateUAV( ViewDesc, UAVHandleAlloc.GetCpuHandle() ); - *ppView = NEW_RC_OBJ(BuffViewAllocator, "BufferViewD3D12Impl instance", BufferViewD3D12Impl, bIsDefaultView ? this : nullptr) - (GetDevice(), ViewDesc, this, std::move(UAVHandleAlloc), bIsDefaultView ); + CreateUAV(ViewDesc, UAVHandleAlloc.GetCpuHandle()); + *ppView = NEW_RC_OBJ(BuffViewAllocator, "BufferViewD3D12Impl instance", BufferViewD3D12Impl, bIsDefaultView ? this : nullptr)(GetDevice(), ViewDesc, this, std::move(UAVHandleAlloc), bIsDefaultView); } - else if( ViewDesc.ViewType == BUFFER_VIEW_SHADER_RESOURCE ) + else if (ViewDesc.ViewType == BUFFER_VIEW_SHADER_RESOURCE) { - auto SRVHandleAlloc = pDeviceD3D12Impl->AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - CreateSRV( ViewDesc, SRVHandleAlloc.GetCpuHandle() ); - *ppView = NEW_RC_OBJ(BuffViewAllocator, "BufferViewD3D12Impl instance", BufferViewD3D12Impl, bIsDefaultView ? this : nullptr) - (GetDevice(), ViewDesc, this, std::move(SRVHandleAlloc), bIsDefaultView ); + auto SRVHandleAlloc = pDeviceD3D12Impl->AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + CreateSRV(ViewDesc, SRVHandleAlloc.GetCpuHandle()); + *ppView = NEW_RC_OBJ(BuffViewAllocator, "BufferViewD3D12Impl instance", BufferViewD3D12Impl, bIsDefaultView ? this : nullptr)(GetDevice(), ViewDesc, this, std::move(SRVHandleAlloc), bIsDefaultView); } - if( !bIsDefaultView && *ppView ) + if (!bIsDefaultView && *ppView) (*ppView)->AddRef(); } - catch( const std::runtime_error & ) + catch (const std::runtime_error&) { - const auto *ViewTypeName = GetBufferViewTypeLiteralName(OrigViewDesc.ViewType); - LOG_ERROR("Failed to create view \"", OrigViewDesc.Name ? OrigViewDesc.Name : "", "\" (", ViewTypeName, ") for buffer \"", m_Desc.Name, "\"" ); + const auto* ViewTypeName = GetBufferViewTypeLiteralName(OrigViewDesc.ViewType); + LOG_ERROR("Failed to create view \"", OrigViewDesc.Name ? OrigViewDesc.Name : "", "\" (", ViewTypeName, ") for buffer \"", m_Desc.Name, "\""); } } -void BufferD3D12Impl::CreateUAV( BufferViewDesc& UAVDesc, D3D12_CPU_DESCRIPTOR_HANDLE UAVDescriptor ) +void BufferD3D12Impl::CreateUAV(BufferViewDesc& UAVDesc, D3D12_CPU_DESCRIPTOR_HANDLE UAVDescriptor) { - CorrectBufferViewDesc( UAVDesc ); + CorrectBufferViewDesc(UAVDesc); D3D12_UNORDERED_ACCESS_VIEW_DESC D3D12_UAVDesc; BufferViewDesc_to_D3D12_UAV_DESC(m_Desc, UAVDesc, D3D12_UAVDesc); - auto *pDeviceD3D12 = static_cast(GetDevice())->GetD3D12Device(); - pDeviceD3D12->CreateUnorderedAccessView( m_pd3d12Resource, nullptr, &D3D12_UAVDesc, UAVDescriptor ); + auto* pDeviceD3D12 = static_cast(GetDevice())->GetD3D12Device(); + pDeviceD3D12->CreateUnorderedAccessView(m_pd3d12Resource, nullptr, &D3D12_UAVDesc, UAVDescriptor); } -void BufferD3D12Impl::CreateSRV( struct BufferViewDesc& SRVDesc, D3D12_CPU_DESCRIPTOR_HANDLE SRVDescriptor ) +void BufferD3D12Impl::CreateSRV(struct BufferViewDesc& SRVDesc, D3D12_CPU_DESCRIPTOR_HANDLE SRVDescriptor) { - CorrectBufferViewDesc( SRVDesc ); + CorrectBufferViewDesc(SRVDesc); D3D12_SHADER_RESOURCE_VIEW_DESC D3D12_SRVDesc; BufferViewDesc_to_D3D12_SRV_DESC(m_Desc, SRVDesc, D3D12_SRVDesc); - auto *pDeviceD3D12 = static_cast(GetDevice())->GetD3D12Device(); - pDeviceD3D12->CreateShaderResourceView( m_pd3d12Resource, &D3D12_SRVDesc, SRVDescriptor ); + auto* pDeviceD3D12 = static_cast(GetDevice())->GetD3D12Device(); + pDeviceD3D12->CreateShaderResourceView(m_pd3d12Resource, &D3D12_SRVDesc, SRVDescriptor); } void BufferD3D12Impl::CreateCBV(D3D12_CPU_DESCRIPTOR_HANDLE CBVDescriptor) { D3D12_CONSTANT_BUFFER_VIEW_DESC D3D12_CBVDesc; D3D12_CBVDesc.BufferLocation = m_pd3d12Resource->GetGPUVirtualAddress(); - D3D12_CBVDesc.SizeInBytes = m_Desc.uiSizeInBytes; + D3D12_CBVDesc.SizeInBytes = m_Desc.uiSizeInBytes; - auto *pDeviceD3D12 = static_cast(GetDevice())->GetD3D12Device(); - pDeviceD3D12->CreateConstantBufferView( &D3D12_CBVDesc, CBVDescriptor ); + auto* pDeviceD3D12 = static_cast(GetDevice())->GetD3D12Device(); + pDeviceD3D12->CreateConstantBufferView(&D3D12_CBVDesc, CBVDescriptor); } ID3D12Resource* BufferD3D12Impl::GetD3D12Buffer(size_t& DataStartByteOffset, IDeviceContext* pContext) -{ +{ auto* pd3d12Resource = GetD3D12Resource(); - if(pd3d12Resource != nullptr) + if (pd3d12Resource != nullptr) { - VERIFY(m_Desc.Usage != USAGE_DYNAMIC || (m_Desc.BindFlags | (BIND_SHADER_RESOURCE|BIND_UNORDERED_ACCESS)) != 0, "Expected non-dynamic buffer or a buffer with SRV or UAV bind flags"); + VERIFY(m_Desc.Usage != USAGE_DYNAMIC || (m_Desc.BindFlags | (BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS)) != 0, "Expected non-dynamic buffer or a buffer with SRV or UAV bind flags"); DataStartByteOffset = 0; - return pd3d12Resource; + return pd3d12Resource; } else { @@ -382,17 +387,17 @@ ID3D12Resource* BufferD3D12Impl::GetD3D12Buffer(size_t& DataStartByteOffset, IDe #ifdef DEVELOPMENT DvpVerifyDynamicAllocation(pCtxD3D12); #endif - auto ContextId = pCtxD3D12->GetContextId(); + auto ContextId = pCtxD3D12->GetContextId(); DataStartByteOffset = m_DynamicData[ContextId].Offset; return m_DynamicData[ContextId].pBuffer; } } #ifdef DEVELOPMENT -void BufferD3D12Impl::DvpVerifyDynamicAllocation(DeviceContextD3D12Impl* pCtx)const +void BufferD3D12Impl::DvpVerifyDynamicAllocation(DeviceContextD3D12Impl* pCtx) const { - auto ContextId = pCtx->GetContextId(); - auto CurrentFrame = pCtx->GetCurrentFrameNumber(); + auto ContextId = pCtx->GetContextId(); + auto CurrentFrame = pCtx->GetCurrentFrameNumber(); DEV_CHECK_ERR(m_DynamicData[ContextId].GPUAddress != 0, "Dynamic buffer '", m_Desc.Name, "' has not been mapped before its first use. Context Id: ", ContextId, ". Note: memory for dynamic buffers is allocated when a buffer is mapped."); DEV_CHECK_ERR(m_DynamicData[ContextId].DvpCtxFrameNumber == static_cast(CurrentFrame), "Dynamic allocation of dynamic buffer '", m_Desc.Name, "' in frame ", CurrentFrame, " is out-of-date. Note: contents of all dynamic resources is discarded at the end of every frame. A buffer must be mapped before its first use in any frame."); VERIFY(GetState() == RESOURCE_STATE_GENERIC_READ, "Dynamic buffers are expected to always be in RESOURCE_STATE_GENERIC_READ state"); @@ -404,9 +409,9 @@ void BufferD3D12Impl::SetD3D12ResourceState(D3D12_RESOURCE_STATES state) SetState(D3D12ResourceStatesToResourceStateFlags(state)); } -D3D12_RESOURCE_STATES BufferD3D12Impl::GetD3D12ResourceState()const +D3D12_RESOURCE_STATES BufferD3D12Impl::GetD3D12ResourceState() const { return ResourceStateFlagsToD3D12ResourceStates(GetState()); } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/BufferViewD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/BufferViewD3D12Impl.cpp index 32dd5d89..ee8bf052 100644 --- a/Graphics/GraphicsEngineD3D12/src/BufferViewD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/BufferViewD3D12Impl.cpp @@ -27,12 +27,13 @@ namespace Diligent { -BufferViewD3D12Impl::BufferViewD3D12Impl( IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pDevice, - const BufferViewDesc& ViewDesc, - IBuffer* pBuffer, - DescriptorHeapAllocation&& HandleAlloc, - bool bIsDefaultView ) : +BufferViewD3D12Impl::BufferViewD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl* pDevice, + const BufferViewDesc& ViewDesc, + IBuffer* pBuffer, + DescriptorHeapAllocation&& HandleAlloc, + bool bIsDefaultView) : + // clang-format off TBufferViewBase { pRefCounters, @@ -42,9 +43,10 @@ BufferViewD3D12Impl::BufferViewD3D12Impl( IReferenceCounters* pRefCounter bIsDefaultView }, m_DescriptorHandle{std::move(HandleAlloc)} +// clang-format on { } -IMPLEMENT_QUERY_INTERFACE( BufferViewD3D12Impl, IID_BufferViewD3D12, TBufferViewBase ) +IMPLEMENT_QUERY_INTERFACE(BufferViewD3D12Impl, IID_BufferViewD3D12, TBufferViewBase) -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/CommandContext.cpp b/Graphics/GraphicsEngineD3D12/src/CommandContext.cpp index 4d327ecd..666d538e 100644 --- a/Graphics/GraphicsEngineD3D12/src/CommandContext.cpp +++ b/Graphics/GraphicsEngineD3D12/src/CommandContext.cpp @@ -33,41 +33,43 @@ namespace Diligent { -CommandContext::CommandContext( CommandListManager& CmdListManager) : +CommandContext::CommandContext(CommandListManager& CmdListManager) : + // clang-format off m_pCurGraphicsRootSignature {nullptr}, m_pCurPipelineState {nullptr}, m_pCurComputeRootSignature {nullptr}, m_PendingResourceBarriers {STD_ALLOCATOR_RAW_MEM(D3D12_RESOURCE_BARRIER, GetRawAllocator(), "Allocator for vector")} +// clang-format on { m_PendingResourceBarriers.reserve(MaxPendingBarriers); CmdListManager.CreateNewCommandList(&m_pCommandList, &m_pCurrentAllocator); } -CommandContext::~CommandContext( void ) +CommandContext::~CommandContext(void) { DEV_CHECK_ERR(m_pCurrentAllocator == nullptr, "Command allocator must be released prior to destroying the command context"); } -void CommandContext::Reset( CommandListManager& CmdListManager ) +void CommandContext::Reset(CommandListManager& CmdListManager) { - // We only call Reset() on previously freed contexts. The command list persists, but we need to - // request a new allocator - VERIFY_EXPR(m_pCommandList != nullptr); - if( !m_pCurrentAllocator ) + // We only call Reset() on previously freed contexts. The command list persists, but we need to + // request a new allocator + VERIFY_EXPR(m_pCommandList != nullptr); + if (!m_pCurrentAllocator) { CmdListManager.RequestAllocator(&m_pCurrentAllocator); - // Unlike ID3D12CommandAllocator::Reset, ID3D12GraphicsCommandList::Reset can be called while the - // command list is still being executed. A typical pattern is to submit a command list and then + // Unlike ID3D12CommandAllocator::Reset, ID3D12GraphicsCommandList::Reset can be called while the + // command list is still being executed. A typical pattern is to submit a command list and then // immediately reset it to reuse the allocated memory for another command list. m_pCommandList->Reset(m_pCurrentAllocator, nullptr); } - m_pCurPipelineState = nullptr; - m_pCurGraphicsRootSignature = nullptr; - m_pCurComputeRootSignature = nullptr; - m_PendingResourceBarriers.clear(); + m_pCurPipelineState = nullptr; + m_pCurGraphicsRootSignature = nullptr; + m_pCurComputeRootSignature = nullptr; + m_PendingResourceBarriers.clear(); m_BoundDescriptorHeaps = ShaderDescriptorHeaps(); - + m_DynamicGPUDescriptorAllocators = nullptr; m_PrimitiveTopology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED; @@ -78,22 +80,22 @@ void CommandContext::Reset( CommandListManager& CmdListManager ) ID3D12GraphicsCommandList* CommandContext::Close(CComPtr& pAllocator) { - FlushResourceBarriers(); + FlushResourceBarriers(); - //if (m_ID.length() > 0) - // EngineProfiling::EndBlock(this); + //if (m_ID.length() > 0) + // EngineProfiling::EndBlock(this); - VERIFY_EXPR(m_pCurrentAllocator != nullptr); - auto hr = m_pCommandList->Close(); + VERIFY_EXPR(m_pCurrentAllocator != nullptr); + auto hr = m_pCommandList->Close(); DEV_CHECK_ERR(SUCCEEDED(hr), "Failed to close the command list"); - + pAllocator = std::move(m_pCurrentAllocator); return m_pCommandList; } void CommandContext::TransitionResource(ITextureD3D12* pTexture, RESOURCE_STATE NewState) { - VERIFY_EXPR( pTexture != nullptr ); + VERIFY_EXPR(pTexture != nullptr); auto* pTexD3D12 = ValidatedCast(pTexture); VERIFY(pTexD3D12->IsInKnownState(), "Texture state can't be unknown"); StateTransitionDesc TextureBarrier(pTexture, RESOURCE_STATE_UNKNOWN, NewState, true); @@ -102,7 +104,7 @@ void CommandContext::TransitionResource(ITextureD3D12* pTexture, RESOURCE_STATE void CommandContext::TransitionResource(IBufferD3D12* pBuffer, RESOURCE_STATE NewState) { - VERIFY_EXPR( pBuffer != nullptr ); + VERIFY_EXPR(pBuffer != nullptr); auto* pBuffD3D12 = ValidatedCast(pBuffer); VERIFY(pBuffD3D12->IsInKnownState(), "Buffer state can't be unknown"); StateTransitionDesc BufferBarrier(pBuffer, RESOURCE_STATE_UNKNOWN, NewState, true); @@ -112,17 +114,17 @@ void CommandContext::TransitionResource(IBufferD3D12* pBuffer, RESOURCE_STATE Ne void CommandContext::InsertUAVBarrier(ID3D12Resource* pd3d12Resource) { m_PendingResourceBarriers.emplace_back(); - D3D12_RESOURCE_BARRIER& BarrierDesc = m_PendingResourceBarriers.back(); + D3D12_RESOURCE_BARRIER& BarrierDesc = m_PendingResourceBarriers.back(); // UAV barrier indicates that all UAV accesses (reads or writes) to a particular resource // must complete before any future UAV accesses (read or write) can begin. - BarrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; - BarrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - BarrierDesc.UAV.pResource = pd3d12Resource; + BarrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + BarrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + BarrierDesc.UAV.pResource = pd3d12Resource; } static D3D12_RESOURCE_BARRIER_FLAGS TransitionTypeToD3D12ResourceBarrierFlag(STATE_TRANSITION_TYPE TransitionType) { - switch(TransitionType) + switch (TransitionType) { case STATE_TRANSITION_TYPE_IMMEDIATE: return D3D12_RESOURCE_BARRIER_FLAG_NONE; @@ -141,8 +143,8 @@ static D3D12_RESOURCE_BARRIER_FLAGS TransitionTypeToD3D12ResourceBarrierFlag(STA void CommandContext::TransitionResource(const StateTransitionDesc& Barrier) { - DEV_CHECK_ERR( (Barrier.pTexture != nullptr) ^ (Barrier.pBuffer != nullptr), "Exactly one of pTexture or pBuffer must not be null"); - + DEV_CHECK_ERR((Barrier.pTexture != nullptr) ^ (Barrier.pBuffer != nullptr), "Exactly one of pTexture or pBuffer must not be null"); + DEV_CHECK_ERR(Barrier.NewState != RESOURCE_STATE_UNKNOWN, "New resource state can't be unknown"); RESOURCE_STATE OldState = RESOURCE_STATE_UNKNOWN; ID3D12Resource* pd3d12Resource = nullptr; @@ -151,24 +153,24 @@ void CommandContext::TransitionResource(const StateTransitionDesc& Barrier) if (Barrier.pTexture) { pTextureD3D12Impl = ValidatedCast(Barrier.pTexture); - pd3d12Resource = pTextureD3D12Impl->GetD3D12Resource(); - OldState = pTextureD3D12Impl->GetState(); + pd3d12Resource = pTextureD3D12Impl->GetD3D12Resource(); + OldState = pTextureD3D12Impl->GetState(); } else { VERIFY_EXPR(Barrier.pBuffer != nullptr); pBufferD3D12Impl = ValidatedCast(Barrier.pBuffer); - pd3d12Resource = pBufferD3D12Impl->GetD3D12Resource(); - OldState = pBufferD3D12Impl->GetState(); + pd3d12Resource = pBufferD3D12Impl->GetD3D12Resource(); + OldState = pBufferD3D12Impl->GetState(); #ifdef DEVELOPMENT - // Dynamic buffers wtih no SRV/UAV bind flags are suballocated in - // the upload heap when Map() is called and must always be in + // Dynamic buffers wtih no SRV/UAV bind flags are suballocated in + // the upload heap when Map() is called and must always be in // D3D12_RESOURCE_STATE_GENERIC_READ state - if (pBufferD3D12Impl->GetDesc().Usage == USAGE_DYNAMIC && (pBufferD3D12Impl->GetDesc().BindFlags & (BIND_SHADER_RESOURCE|BIND_UNORDERED_ACCESS)) == 0) + if (pBufferD3D12Impl->GetDesc().Usage == USAGE_DYNAMIC && (pBufferD3D12Impl->GetDesc().BindFlags & (BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS)) == 0) { DEV_CHECK_ERR(pBufferD3D12Impl->GetState() == RESOURCE_STATE_GENERIC_READ, "Dynamic buffers that cannot be bound as SRV or UAV are expected to always be in D3D12_RESOURCE_STATE_GENERIC_READ state"); - VERIFY( (Barrier.NewState & RESOURCE_STATE_GENERIC_READ) == Barrier.NewState, "Dynamic buffers can only transition to one of RESOURCE_STATE_GENERIC_READ states"); + VERIFY((Barrier.NewState & RESOURCE_STATE_GENERIC_READ) == Barrier.NewState, "Dynamic buffers can only transition to one of RESOURCE_STATE_GENERIC_READ states"); } #endif } @@ -183,7 +185,7 @@ void CommandContext::TransitionResource(const StateTransitionDesc& Barrier) DEV_CHECK_ERR(Barrier.OldState == RESOURCE_STATE_UNKNOWN || Barrier.OldState == OldState, "Resource state is known (", GetResourceStateString(OldState), ") and does not match the OldState (", GetResourceStateString(Barrier.OldState), ") specified in the resource barrier. Set OldState member to " - "RESOURCE_STATE_UNKNOWN to make the engine use current resource state"); + "RESOURCE_STATE_UNKNOWN to make the engine use current resource state"); } // Check if required state is already set @@ -191,19 +193,19 @@ void CommandContext::TransitionResource(const StateTransitionDesc& Barrier) { auto NewState = Barrier.NewState; // If both old state and new state are read-only states, combine the two - if( (OldState & RESOURCE_STATE_GENERIC_READ) == OldState && - (NewState & RESOURCE_STATE_GENERIC_READ) == NewState ) + if ((OldState & RESOURCE_STATE_GENERIC_READ) == OldState && + (NewState & RESOURCE_STATE_GENERIC_READ) == NewState) NewState = static_cast(OldState | NewState); - D3D12_RESOURCE_BARRIER BarrierDesc; - BarrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - BarrierDesc.Flags = TransitionTypeToD3D12ResourceBarrierFlag(Barrier.TransitionType); - BarrierDesc.Transition.pResource = pd3d12Resource; - BarrierDesc.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + D3D12_RESOURCE_BARRIER BarrierDesc; + BarrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + BarrierDesc.Flags = TransitionTypeToD3D12ResourceBarrierFlag(Barrier.TransitionType); + BarrierDesc.Transition.pResource = pd3d12Resource; + BarrierDesc.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; BarrierDesc.Transition.StateBefore = ResourceStateFlagsToD3D12ResourceStates(OldState); BarrierDesc.Transition.StateAfter = ResourceStateFlagsToD3D12ResourceStates(NewState); - // Note that RESOURCE_STATE_UNDEFINED != RESOURCE_STATE_PRESENT, but + // Note that RESOURCE_STATE_UNDEFINED != RESOURCE_STATE_PRESENT, but // D3D12_RESOURCE_STATE_COMMON == D3D12_RESOURCE_STATE_PRESENT if (BarrierDesc.Transition.StateBefore != BarrierDesc.Transition.StateAfter) { @@ -212,12 +214,12 @@ void CommandContext::TransitionResource(const StateTransitionDesc& Barrier) const auto& TexDesc = pTextureD3D12Impl->GetDesc(); VERIFY(Barrier.FirstMipLevel < TexDesc.MipLevels, "First mip level is out of range"); VERIFY(Barrier.MipLevelsCount == StateTransitionDesc::RemainingMipLevels || Barrier.FirstMipLevel + Barrier.MipLevelsCount <= TexDesc.MipLevels, - "Invalid mip level range "); + "Invalid mip level range"); VERIFY(Barrier.FirstArraySlice < TexDesc.ArraySize, "First array slice is out of range"); VERIFY(Barrier.ArraySliceCount == StateTransitionDesc::RemainingArraySlices || Barrier.FirstArraySlice + Barrier.ArraySliceCount <= TexDesc.ArraySize, - "Invalid array slice range "); + "Invalid array slice range"); - if (Barrier.FirstMipLevel == 0 && (Barrier.MipLevelsCount == StateTransitionDesc::RemainingMipLevels || Barrier.MipLevelsCount == TexDesc.MipLevels) && + if (Barrier.FirstMipLevel == 0 && (Barrier.MipLevelsCount == StateTransitionDesc::RemainingMipLevels || Barrier.MipLevelsCount == TexDesc.MipLevels) && Barrier.FirstArraySlice == 0 && (Barrier.ArraySliceCount == StateTransitionDesc::RemainingArraySlices || Barrier.ArraySliceCount == TexDesc.ArraySize)) { BarrierDesc.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; @@ -225,11 +227,11 @@ void CommandContext::TransitionResource(const StateTransitionDesc& Barrier) } else { - Uint32 EndMip = Barrier.MipLevelsCount == StateTransitionDesc::RemainingMipLevels ? TexDesc.MipLevels : Barrier.FirstMipLevel + Barrier.MipLevelsCount; + Uint32 EndMip = Barrier.MipLevelsCount == StateTransitionDesc::RemainingMipLevels ? TexDesc.MipLevels : Barrier.FirstMipLevel + Barrier.MipLevelsCount; Uint32 EndSlice = Barrier.ArraySliceCount == StateTransitionDesc::RemainingArraySlices ? TexDesc.ArraySize : Barrier.FirstArraySlice + Barrier.ArraySliceCount; - for(Uint32 mip = Barrier.FirstMipLevel; mip < EndMip; ++mip) + for (Uint32 mip = Barrier.FirstMipLevel; mip < EndMip; ++mip) { - for(Uint32 slice = Barrier.FirstArraySlice; slice < EndSlice; ++slice) + for (Uint32 slice = Barrier.FirstArraySlice; slice < EndSlice; ++slice) { BarrierDesc.Transition.Subresource = D3D12CalcSubresource(mip, slice, 0, TexDesc.MipLevels, TexDesc.ArraySize); m_PendingResourceBarriers.emplace_back(BarrierDesc); @@ -246,7 +248,8 @@ void CommandContext::TransitionResource(const StateTransitionDesc& Barrier) if (pTextureD3D12Impl) { - VERIFY(!Barrier.UpdateResourceState || (Barrier.TransitionType == STATE_TRANSITION_TYPE_IMMEDIATE || Barrier.TransitionType == STATE_TRANSITION_TYPE_END), "Texture state can't be updated in begin-split barrier"); + VERIFY(!Barrier.UpdateResourceState || (Barrier.TransitionType == STATE_TRANSITION_TYPE_IMMEDIATE || Barrier.TransitionType == STATE_TRANSITION_TYPE_END), + "Texture state can't be updated in begin-split barrier"); if (Barrier.UpdateResourceState) { pTextureD3D12Impl->SetState(NewState); @@ -256,14 +259,17 @@ void CommandContext::TransitionResource(const StateTransitionDesc& Barrier) { VERIFY_EXPR(pBufferD3D12Impl); - VERIFY(!Barrier.UpdateResourceState || (Barrier.TransitionType == STATE_TRANSITION_TYPE_IMMEDIATE || Barrier.TransitionType == STATE_TRANSITION_TYPE_END), "Buffer state can't be updated in begin-split barrier"); + VERIFY(!Barrier.UpdateResourceState || (Barrier.TransitionType == STATE_TRANSITION_TYPE_IMMEDIATE || Barrier.TransitionType == STATE_TRANSITION_TYPE_END), + "Buffer state can't be updated in begin-split barrier"); if (Barrier.UpdateResourceState) { pBufferD3D12Impl->SetState(NewState); } - if (pBufferD3D12Impl->GetDesc().Usage == USAGE_DYNAMIC && (pBufferD3D12Impl->GetDesc().BindFlags & (BIND_SHADER_RESOURCE|BIND_UNORDERED_ACCESS)) == 0) - VERIFY(pBufferD3D12Impl->GetState() == RESOURCE_STATE_GENERIC_READ, "Dynamic buffers without SRV/UAV bind flag are expected to never transition from RESOURCE_STATE_GENERIC_READ state"); + if (pBufferD3D12Impl->GetDesc().Usage == USAGE_DYNAMIC && (pBufferD3D12Impl->GetDesc().BindFlags & (BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS)) == 0) + VERIFY(pBufferD3D12Impl->GetState() == RESOURCE_STATE_GENERIC_READ, + "Dynamic buffers without SRV/UAV bind flag are expected to never " + "transition from RESOURCE_STATE_GENERIC_READ state"); } } @@ -273,22 +279,22 @@ void CommandContext::TransitionResource(const StateTransitionDesc& Barrier) InsertUAVBarrier(pd3d12Resource); } - if (m_PendingResourceBarriers.size() >= MaxPendingBarriers) + if (m_PendingResourceBarriers.size() >= MaxPendingBarriers) FlushResourceBarriers(); } void CommandContext::InsertAliasBarrier(D3D12ResourceBase& Before, D3D12ResourceBase& After, bool FlushImmediate) { m_PendingResourceBarriers.emplace_back(); - D3D12_RESOURCE_BARRIER& BarrierDesc = m_PendingResourceBarriers.back(); + D3D12_RESOURCE_BARRIER& BarrierDesc = m_PendingResourceBarriers.back(); - BarrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; - BarrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - BarrierDesc.Aliasing.pResourceBefore = Before.GetD3D12Resource(); - BarrierDesc.Aliasing.pResourceAfter = After.GetD3D12Resource(); + BarrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; + BarrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + BarrierDesc.Aliasing.pResourceBefore = Before.GetD3D12Resource(); + BarrierDesc.Aliasing.pResourceAfter = After.GetD3D12Resource(); - if (FlushImmediate) + if (FlushImmediate) FlushResourceBarriers(); } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/CommandListManager.cpp b/Graphics/GraphicsEngineD3D12/src/CommandListManager.cpp index 764a3c23..c39f77fd 100644 --- a/Graphics/GraphicsEngineD3D12/src/CommandListManager.cpp +++ b/Graphics/GraphicsEngineD3D12/src/CommandListManager.cpp @@ -28,9 +28,11 @@ namespace Diligent { -CommandListManager::CommandListManager(RenderDeviceD3D12Impl& DeviceD3D12Impl) : +CommandListManager::CommandListManager(RenderDeviceD3D12Impl& DeviceD3D12Impl) : + // clang-format off m_DeviceD3D12Impl{DeviceD3D12Impl}, m_FreeAllocators {STD_ALLOCATOR_RAW_MEM(CComPtr, GetRawAllocator(), "Allocator for vector>")} +// clang-format on { } @@ -40,56 +42,57 @@ CommandListManager::~CommandListManager() LOG_INFO_MESSAGE("Command list manager: created ", m_FreeAllocators.size(), " allocators"); } -void CommandListManager::CreateNewCommandList( ID3D12GraphicsCommandList** List, ID3D12CommandAllocator** Allocator ) +void CommandListManager::CreateNewCommandList(ID3D12GraphicsCommandList** List, ID3D12CommandAllocator** Allocator) { - RequestAllocator(Allocator); + RequestAllocator(Allocator); auto* pd3d12Device = m_DeviceD3D12Impl.GetD3D12Device(); - auto hr = pd3d12Device->CreateCommandList(1, D3D12_COMMAND_LIST_TYPE_DIRECT, *Allocator, nullptr, __uuidof(*List), reinterpret_cast(List) ); + auto hr = pd3d12Device->CreateCommandList(1, D3D12_COMMAND_LIST_TYPE_DIRECT, *Allocator, nullptr, __uuidof(*List), reinterpret_cast(List)); VERIFY(SUCCEEDED(hr), "Failed to create command list"); - (*List)->SetName(L"CommandList"); + (*List)->SetName(L"CommandList"); } void CommandListManager::RequestAllocator(ID3D12CommandAllocator** ppAllocator) { - std::lock_guard LockGuard(m_AllocatorMutex); + std::lock_guard LockGuard(m_AllocatorMutex); - VERIFY( (*ppAllocator) == nullptr, "Allocator pointer is not null" ); + VERIFY((*ppAllocator) == nullptr, "Allocator pointer is not null"); (*ppAllocator) = nullptr; if (!m_FreeAllocators.empty()) - { - *ppAllocator = m_FreeAllocators.back().Detach(); - auto hr = (*ppAllocator)->Reset(); + { + *ppAllocator = m_FreeAllocators.back().Detach(); + auto hr = (*ppAllocator)->Reset(); DEV_CHECK_ERR(SUCCEEDED(hr), "Failed to reset command allocator"); - m_FreeAllocators.pop_back(); - } + m_FreeAllocators.pop_back(); + } - // If no allocators were ready to be reused, create a new one - if ((*ppAllocator) == nullptr) - { + // If no allocators were ready to be reused, create a new one + if ((*ppAllocator) == nullptr) + { auto* pd3d12Device = m_DeviceD3D12Impl.GetD3D12Device(); - auto hr = pd3d12Device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(*ppAllocator), reinterpret_cast(ppAllocator)); + auto hr = pd3d12Device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(*ppAllocator), reinterpret_cast(ppAllocator)); VERIFY(SUCCEEDED(hr), "Failed to create command allocator"); - wchar_t AllocatorName[32]; - swprintf(AllocatorName, _countof(AllocatorName), L"Cmd list allocator %ld", Atomics::AtomicIncrement(m_NumAllocators)-1); - (*ppAllocator)->SetName(AllocatorName); - } + wchar_t AllocatorName[32]; + swprintf(AllocatorName, _countof(AllocatorName), L"Cmd list allocator %ld", Atomics::AtomicIncrement(m_NumAllocators) - 1); + (*ppAllocator)->SetName(AllocatorName); + } #ifdef DEVELOPMENT Atomics::AtomicIncrement(m_AllocatorCounter); #endif } -void CommandListManager::ReleaseAllocator( CComPtr&& Allocator, Uint32 CmdQueue, Uint64 FenceValue ) +void CommandListManager::ReleaseAllocator(CComPtr&& Allocator, Uint32 CmdQueue, Uint64 FenceValue) { struct StaleAllocator { CComPtr Allocator; CommandListManager* Mgr; + // clang-format off StaleAllocator(CComPtr&& _Allocator, CommandListManager& _Mgr)noexcept : - Allocator (std::move(_Allocator)), - Mgr (&_Mgr) + Allocator {std::move(_Allocator)}, + Mgr {&_Mgr } { } @@ -98,28 +101,29 @@ void CommandListManager::ReleaseAllocator( CComPtr&& All StaleAllocator& operator= ( StaleAllocator&&) = delete; StaleAllocator(StaleAllocator&& rhs)noexcept : - Allocator (std::move(rhs.Allocator)), - Mgr (rhs.Mgr) + Allocator {std::move(rhs.Allocator)}, + Mgr {rhs.Mgr } { rhs.Mgr = nullptr; } + // clang-format on ~StaleAllocator() { if (Mgr != nullptr) - Mgr->FreeAllocator( std::move(Allocator) ); + Mgr->FreeAllocator(std::move(Allocator)); } }; m_DeviceD3D12Impl.GetReleaseQueue(CmdQueue).DiscardResource(StaleAllocator{std::move(Allocator), *this}, FenceValue); } -void CommandListManager::FreeAllocator( CComPtr&& Allocator ) +void CommandListManager::FreeAllocator(CComPtr&& Allocator) { - std::lock_guard LockGuard(m_AllocatorMutex); - m_FreeAllocators.emplace_back( std::move(Allocator) ); + std::lock_guard LockGuard(m_AllocatorMutex); + m_FreeAllocators.emplace_back(std::move(Allocator)); #ifdef DEVELOPMENT Atomics::AtomicDecrement(m_AllocatorCounter); #endif } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/CommandQueueD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/CommandQueueD3D12Impl.cpp index 129475c6..cd39c11a 100644 --- a/Graphics/GraphicsEngineD3D12/src/CommandQueueD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/CommandQueueD3D12Impl.cpp @@ -27,14 +27,16 @@ namespace Diligent { -CommandQueueD3D12Impl::CommandQueueD3D12Impl(IReferenceCounters* pRefCounters, - ID3D12CommandQueue* pd3d12NativeCmdQueue, - ID3D12Fence* pd3d12Fence) : - TBase{pRefCounters}, - m_pd3d12CmdQueue {pd3d12NativeCmdQueue}, - m_d3d12Fence {pd3d12Fence }, - m_NextFenceValue {1 }, - m_WaitForGPUEventHandle{CreateEvent(nullptr, false, false, nullptr)} +CommandQueueD3D12Impl::CommandQueueD3D12Impl(IReferenceCounters* pRefCounters, + ID3D12CommandQueue* pd3d12NativeCmdQueue, + ID3D12Fence* pd3d12Fence) : + // clang-format off + TBase{pRefCounters}, + m_pd3d12CmdQueue {pd3d12NativeCmdQueue}, + m_d3d12Fence {pd3d12Fence }, + m_NextFenceValue {1 }, + m_WaitForGPUEventHandle{CreateEvent(nullptr, false, false, nullptr)} +// clang-format on { VERIFY_EXPR(m_WaitForGPUEventHandle != INVALID_HANDLE_VALUE); m_d3d12Fence->Signal(0); @@ -45,7 +47,7 @@ CommandQueueD3D12Impl::~CommandQueueD3D12Impl() CloseHandle(m_WaitForGPUEventHandle); } -IMPLEMENT_QUERY_INTERFACE( CommandQueueD3D12Impl, IID_CommandQueueD3D12, TBase ) +IMPLEMENT_QUERY_INTERFACE(CommandQueueD3D12Impl, IID_CommandQueueD3D12, TBase) Uint64 CommandQueueD3D12Impl::Submit(ID3D12GraphicsCommandList* commandList) { @@ -57,13 +59,13 @@ Uint64 CommandQueueD3D12Impl::Submit(ID3D12GraphicsCommandList* commandList) if (commandList != nullptr) { - ID3D12CommandList *const ppCmdLists[] = {commandList}; - m_pd3d12CmdQueue->ExecuteCommandLists(1, ppCmdLists); + ID3D12CommandList* const ppCmdLists[] = {commandList}; + m_pd3d12CmdQueue->ExecuteCommandLists(1, ppCmdLists); } // Signal the fence. This must be done atomically with command list submission. m_pd3d12CmdQueue->Signal(m_d3d12Fence, FenceValue); - + return FenceValue; } @@ -75,7 +77,7 @@ Uint64 CommandQueueD3D12Impl::WaitForIdle() Atomics::AtomicIncrement(m_NextFenceValue); m_pd3d12CmdQueue->Signal(m_d3d12Fence, LastSignaledFenceValue); - + if (GetCompletedFenceValue() < LastSignaledFenceValue) { m_d3d12Fence->SetEventOnCompletion(LastSignaledFenceValue, m_WaitForGPUEventHandle); @@ -88,7 +90,7 @@ Uint64 CommandQueueD3D12Impl::WaitForIdle() Uint64 CommandQueueD3D12Impl::GetCompletedFenceValue() { auto CompletedFenceValue = m_d3d12Fence->GetCompletedValue(); - if(CompletedFenceValue > m_LastCompletedFenceValue) + if (CompletedFenceValue > m_LastCompletedFenceValue) m_LastCompletedFenceValue = CompletedFenceValue; return m_LastCompletedFenceValue; } @@ -99,4 +101,4 @@ void CommandQueueD3D12Impl::SignalFence(ID3D12Fence* pFence, Uint64 Value) m_pd3d12CmdQueue->Signal(pFence, Value); } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/D3D12DynamicHeap.cpp b/Graphics/GraphicsEngineD3D12/src/D3D12DynamicHeap.cpp index 041a170d..8ef02a34 100644 --- a/Graphics/GraphicsEngineD3D12/src/D3D12DynamicHeap.cpp +++ b/Graphics/GraphicsEngineD3D12/src/D3D12DynamicHeap.cpp @@ -30,57 +30,57 @@ namespace Diligent D3D12DynamicPage::D3D12DynamicPage(ID3D12Device* pd3d12Device, Uint64 Size) { - D3D12_HEAP_PROPERTIES HeapProps; - HeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; - HeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; - HeapProps.CreationNodeMask = 1; - HeapProps.VisibleNodeMask = 1; - - D3D12_RESOURCE_DESC ResourceDesc; - ResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - ResourceDesc.Alignment = 0; - ResourceDesc.Height = 1; - ResourceDesc.DepthOrArraySize = 1; - ResourceDesc.MipLevels = 1; - ResourceDesc.Format = DXGI_FORMAT_UNKNOWN; - ResourceDesc.SampleDesc.Count = 1; - ResourceDesc.SampleDesc.Quality = 0; - ResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - - D3D12_RESOURCE_STATES DefaultUsage = D3D12_RESOURCE_STATE_GENERIC_READ; - HeapProps.Type = D3D12_HEAP_TYPE_UPLOAD; - ResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE; - DefaultUsage = D3D12_RESOURCE_STATE_GENERIC_READ; - ResourceDesc.Width = Size; - - auto hr = pd3d12Device->CreateCommittedResource(&HeapProps, D3D12_HEAP_FLAG_NONE, &ResourceDesc, - DefaultUsage, nullptr, __uuidof(m_pd3d12Buffer), reinterpret_cast(static_cast(&m_pd3d12Buffer)) ); - if(FAILED(hr)) + D3D12_HEAP_PROPERTIES HeapProps; + HeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; + HeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; + HeapProps.CreationNodeMask = 1; + HeapProps.VisibleNodeMask = 1; + + D3D12_RESOURCE_DESC ResourceDesc; + ResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + ResourceDesc.Alignment = 0; + ResourceDesc.Height = 1; + ResourceDesc.DepthOrArraySize = 1; + ResourceDesc.MipLevels = 1; + ResourceDesc.Format = DXGI_FORMAT_UNKNOWN; + ResourceDesc.SampleDesc.Count = 1; + ResourceDesc.SampleDesc.Quality = 0; + ResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + + D3D12_RESOURCE_STATES DefaultUsage = D3D12_RESOURCE_STATE_GENERIC_READ; + HeapProps.Type = D3D12_HEAP_TYPE_UPLOAD; + ResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE; + DefaultUsage = D3D12_RESOURCE_STATE_GENERIC_READ; + ResourceDesc.Width = Size; + + auto hr = pd3d12Device->CreateCommittedResource(&HeapProps, D3D12_HEAP_FLAG_NONE, &ResourceDesc, + DefaultUsage, nullptr, __uuidof(m_pd3d12Buffer), reinterpret_cast(static_cast(&m_pd3d12Buffer))); + if (FAILED(hr)) { LOG_D3D_ERROR(hr, "Failed to create dynamic page"); return; } - m_pd3d12Buffer->SetName(L"Dynamic memory page"); - + m_pd3d12Buffer->SetName(L"Dynamic memory page"); + m_GPUVirtualAddress = m_pd3d12Buffer->GetGPUVirtualAddress(); - - m_pd3d12Buffer->Map(0, nullptr, &m_CPUVirtualAddress); - LOG_INFO_MESSAGE("Created dynamic memory page. Size: ", FormatMemorySize(Size,2), "; GPU virtual address 0x", std::hex, m_GPUVirtualAddress); + m_pd3d12Buffer->Map(0, nullptr, &m_CPUVirtualAddress); + + LOG_INFO_MESSAGE("Created dynamic memory page. Size: ", FormatMemorySize(Size, 2), "; GPU virtual address 0x", std::hex, m_GPUVirtualAddress); } -D3D12DynamicMemoryManager::D3D12DynamicMemoryManager(IMemoryAllocator& Allocator, +D3D12DynamicMemoryManager::D3D12DynamicMemoryManager(IMemoryAllocator& Allocator, RenderDeviceD3D12Impl& DeviceD3D12Impl, Uint32 NumPagesToReserve, - Uint64 PageSize) : - m_DeviceD3D12Impl(DeviceD3D12Impl), - m_AvailablePages(STD_ALLOCATOR_RAW_MEM(AvailablePagesMapElemType, Allocator, "Allocator for multimap")) + Uint64 PageSize) : + m_DeviceD3D12Impl{DeviceD3D12Impl}, + m_AvailablePages{STD_ALLOCATOR_RAW_MEM(AvailablePagesMapElemType, Allocator, "Allocator for multimap")} { - for(Uint32 i=0; i < NumPagesToReserve; ++i) + for (Uint32 i = 0; i < NumPagesToReserve; ++i) { D3D12DynamicPage Page(m_DeviceD3D12Impl.GetD3D12Device(), PageSize); - auto Size = Page.GetSize(); + auto Size = Page.GetSize(); m_AvailablePages.emplace(Size, std::move(Page)); } } @@ -112,9 +112,10 @@ void D3D12DynamicMemoryManager::ReleasePages(std::vector& Page D3D12DynamicPage Page; D3D12DynamicMemoryManager* Mgr; + // clang-format off StalePage(D3D12DynamicPage&& _Page, D3D12DynamicMemoryManager& _Mgr)noexcept : - Page (std::move(_Page)), - Mgr (&_Mgr) + Page {std::move(_Page)}, + Mgr {&_Mgr} { } @@ -123,11 +124,12 @@ void D3D12DynamicMemoryManager::ReleasePages(std::vector& Page StalePage& operator= ( StalePage&&) = delete; StalePage(StalePage&& rhs)noexcept : - Page (std::move(rhs.Page)), - Mgr (rhs.Mgr) + Page {std::move(rhs.Page)}, + Mgr {rhs.Mgr} { rhs.Mgr = nullptr; } + // clang-format on ~StalePage() { @@ -142,7 +144,7 @@ void D3D12DynamicMemoryManager::ReleasePages(std::vector& Page } } }; - for(auto& Page : Pages) + for (auto& Page : Pages) { m_DeviceD3D12Impl.SafeReleaseDeviceObject(StalePage{std::move(Page), *this}, QueueMask); } @@ -152,11 +154,12 @@ void D3D12DynamicMemoryManager::Destroy() { DEV_CHECK_ERR(m_AllocatedPageCounter == 0, m_AllocatedPageCounter, " page(s) have not been returned to the manager."); Uint64 TotalAllocatedSize = 0; - for(const auto& Page : m_AvailablePages) + for (const auto& Page : m_AvailablePages) TotalAllocatedSize += Page.second.GetSize(); LOG_INFO_MESSAGE("Dynamic memory manager usage stats:\n" - " Total allocated memory: ", FormatMemorySize(TotalAllocatedSize, 2)); + " Total allocated memory: ", + FormatMemorySize(TotalAllocatedSize, 2)); m_AvailablePages.clear(); } @@ -171,16 +174,17 @@ D3D12DynamicMemoryManager::~D3D12DynamicMemoryManager() D3D12DynamicHeap::~D3D12DynamicHeap() { VERIFY(m_AllocatedPages.empty(), "Allocated pages have not been released which indicates FinishFrame() has not been called"); - + auto PeakAllocatedPages = m_PeakAllocatedSize / m_PageSize; - LOG_INFO_MESSAGE(m_HeapName, " usage stats:\n" - " Peak used/aligned/allocated size: ", - FormatMemorySize(m_PeakUsedSize, 2, m_PeakAlignedSize), " / ", - FormatMemorySize(m_PeakAlignedSize, 2, m_PeakAlignedSize), " / ", - FormatMemorySize(m_PeakAllocatedSize, 2, m_PeakAllocatedSize), - " (", PeakAllocatedPages, (PeakAllocatedPages == 1 ? " page)" : " pages)"), - ". Peak efficiency (used/aligned): ", std::fixed, std::setprecision(1), static_cast(m_PeakUsedSize) / static_cast(std::max(m_PeakAlignedSize, Uint64{1})) * 100.0, '%', - ". Peak utilization (used/allocated): ", std::fixed, std::setprecision(1), static_cast(m_PeakUsedSize) / static_cast(std::max(m_PeakAllocatedSize, Uint64{1})) * 100.0, '%'); + LOG_INFO_MESSAGE(m_HeapName, + " usage stats:\n" + " Peak used/aligned/allocated size: ", + FormatMemorySize(m_PeakUsedSize, 2, m_PeakAlignedSize), " / ", + FormatMemorySize(m_PeakAlignedSize, 2, m_PeakAlignedSize), " / ", + FormatMemorySize(m_PeakAllocatedSize, 2, m_PeakAllocatedSize), + " (", PeakAllocatedPages, (PeakAllocatedPages == 1 ? " page)" : " pages)"), + ". Peak efficiency (used/aligned): ", std::fixed, std::setprecision(1), static_cast(m_PeakUsedSize) / static_cast(std::max(m_PeakAlignedSize, Uint64{1})) * 100.0, '%', + ". Peak utilization (used/allocated): ", std::fixed, std::setprecision(1), static_cast(m_PeakUsedSize) / static_cast(std::max(m_PeakAllocatedSize, Uint64{1})) * 100.0, '%'); } D3D12DynamicAllocation D3D12DynamicHeap::Allocate(Uint64 SizeInBytes, Uint64 Alignment, Uint64 DvpCtxFrameNumber) @@ -191,7 +195,7 @@ D3D12DynamicAllocation D3D12DynamicHeap::Allocate(Uint64 SizeInBytes, Uint64 Ali if (m_CurrOffset == InvalidOffset || SizeInBytes + (Align(m_CurrOffset, Alignment) - m_CurrOffset) > m_AvailableSize) { auto NewPageSize = m_PageSize; - while(NewPageSize < SizeInBytes) + while (NewPageSize < SizeInBytes) NewPageSize *= 2; auto NewPage = m_GlobalDynamicMemMgr.AllocatePage(NewPageSize); @@ -199,9 +203,9 @@ D3D12DynamicAllocation D3D12DynamicHeap::Allocate(Uint64 SizeInBytes, Uint64 Ali { m_CurrOffset = 0; m_AvailableSize = NewPage.GetSize(); - + m_CurrAllocatedSize += m_AvailableSize; - m_PeakAllocatedSize = std::max(m_PeakAllocatedSize, m_CurrAllocatedSize); + m_PeakAllocatedSize = std::max(m_PeakAllocatedSize, m_CurrAllocatedSize); m_AllocatedPages.emplace_back(std::move(NewPage)); } @@ -210,29 +214,31 @@ D3D12DynamicAllocation D3D12DynamicHeap::Allocate(Uint64 SizeInBytes, Uint64 Ali if (m_CurrOffset != InvalidOffset && SizeInBytes + (Align(m_CurrOffset, Alignment) - m_CurrOffset) <= m_AvailableSize) { auto AlignedOffset = Align(m_CurrOffset, Alignment); - auto AdjustedSize = SizeInBytes + (AlignedOffset - m_CurrOffset); + auto AdjustedSize = SizeInBytes + (AlignedOffset - m_CurrOffset); VERIFY_EXPR(AdjustedSize <= m_AvailableSize); m_AvailableSize -= AdjustedSize; - m_CurrOffset += AdjustedSize; - + m_CurrOffset += AdjustedSize; + m_CurrUsedSize += SizeInBytes; - m_PeakUsedSize = std::max(m_PeakUsedSize, m_CurrUsedSize); + m_PeakUsedSize = std::max(m_PeakUsedSize, m_CurrUsedSize); m_CurrAlignedSize += AdjustedSize; - m_PeakAlignedSize = std::max(m_PeakAlignedSize, m_CurrAlignedSize); - + m_PeakAlignedSize = std::max(m_PeakAlignedSize, m_CurrAlignedSize); + auto& CurrPage = m_AllocatedPages.back(); + // clang-format off return D3D12DynamicAllocation - { + { CurrPage.GetD3D12Buffer(), AlignedOffset, SizeInBytes, CurrPage.GetCPUAddress(AlignedOffset), CurrPage.GetGPUAddress(AlignedOffset) #ifdef DEVELOPMENT - , DvpCtxFrameNumber + , DvpCtxFrameNumber #endif }; + // clang-format on } else return D3D12DynamicAllocation{}; @@ -250,4 +256,4 @@ void D3D12DynamicHeap::ReleaseAllocatedPages(Uint64 QueueMask) m_CurrAlignedSize = 0; } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/D3D12TypeConversions.cpp b/Graphics/GraphicsEngineD3D12/src/D3D12TypeConversions.cpp index 29bd8f18..cde4daf9 100644 --- a/Graphics/GraphicsEngineD3D12/src/D3D12TypeConversions.cpp +++ b/Graphics/GraphicsEngineD3D12/src/D3D12TypeConversions.cpp @@ -51,33 +51,36 @@ D3D12_TEXTURE_ADDRESS_MODE TexAddressModeToD3D12AddressMode(TEXTURE_ADDRESS_MODE return TexAddressModeToD3DAddressMode(Mode); } -void DepthStencilStateDesc_To_D3D12_DEPTH_STENCIL_DESC(const DepthStencilStateDesc& DepthStencilDesc, D3D12_DEPTH_STENCIL_DESC& d3d12DSSDesc) +void DepthStencilStateDesc_To_D3D12_DEPTH_STENCIL_DESC(const DepthStencilStateDesc& DepthStencilDesc, + D3D12_DEPTH_STENCIL_DESC& d3d12DSSDesc) { DepthStencilStateDesc_To_D3D_DEPTH_STENCIL_DESC(DepthStencilDesc, d3d12DSSDesc); } -void RasterizerStateDesc_To_D3D12_RASTERIZER_DESC(const RasterizerStateDesc& RasterizerDesc, D3D12_RASTERIZER_DESC& d3d12RSDesc) +void RasterizerStateDesc_To_D3D12_RASTERIZER_DESC(const RasterizerStateDesc& RasterizerDesc, + D3D12_RASTERIZER_DESC& d3d12RSDesc) { RasterizerStateDesc_To_D3D_RASTERIZER_DESC(RasterizerDesc, d3d12RSDesc); - // The sample count that is forced while UAV rendering or rasterizing. - // Valid values are 0, 1, 2, 4, 8, and optionally 16. 0 indicates that + // The sample count that is forced while UAV rendering or rasterizing. + // Valid values are 0, 1, 2, 4, 8, and optionally 16. 0 indicates that // the sample count is not forced. - d3d12RSDesc.ForcedSampleCount = 0; + d3d12RSDesc.ForcedSampleCount = 0; - d3d12RSDesc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; + d3d12RSDesc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; } -D3D12_LOGIC_OP LogicOperationToD3D12LogicOp( LOGIC_OPERATION lo ) +D3D12_LOGIC_OP LogicOperationToD3D12LogicOp(LOGIC_OPERATION lo) { // Note that this code is safe for multithreaded environments since // bIsInit is set to true only AFTER the entire map is initialized. - static bool bIsInit = false; + static bool bIsInit = false; static D3D12_LOGIC_OP D3D12LogicOp[LOGIC_OP_NUM_OPERATIONS] = {}; - if( !bIsInit ) + if (!bIsInit) { + // clang-format off // In a multithreaded environment, several threads can potentially enter // this block. This is not a problem since they will just initialize the // memory with the same values more than once @@ -97,18 +100,19 @@ D3D12_LOGIC_OP LogicOperationToD3D12LogicOp( LOGIC_OPERATION lo ) D3D12LogicOp[ D3D12_LOGIC_OP_AND_INVERTED ] = D3D12_LOGIC_OP_AND_INVERTED; D3D12LogicOp[ D3D12_LOGIC_OP_OR_REVERSE ] = D3D12_LOGIC_OP_OR_REVERSE; D3D12LogicOp[ D3D12_LOGIC_OP_OR_INVERTED ] = D3D12_LOGIC_OP_OR_INVERTED; - + // clang-format on + bIsInit = true; } - if( lo >= LOGIC_OP_CLEAR && lo < LOGIC_OP_NUM_OPERATIONS ) + if (lo >= LOGIC_OP_CLEAR && lo < LOGIC_OP_NUM_OPERATIONS) { auto d3dlo = D3D12LogicOp[lo]; return d3dlo; } else { - UNEXPECTED("Incorrect blend factor (", lo, ")" ); - return static_cast( 0 ); + UNEXPECTED("Incorrect blend factor (", lo, ")"); + return static_cast(0); } } @@ -117,19 +121,19 @@ void BlendStateDesc_To_D3D12_BLEND_DESC(const BlendStateDesc& BSDesc, D3D12_BLEN { BlendStateDescToD3DBlendDesc(BSDesc, d3d12BlendDesc); - for( int i = 0; i < 8; ++i ) + for (int i = 0; i < 8; ++i) { const auto& SrcRTDesc = BSDesc.RenderTargets[i]; - auto &DstRTDesc = d3d12BlendDesc.RenderTarget[i]; + auto& DstRTDesc = d3d12BlendDesc.RenderTarget[i]; // The following members only present in D3D_RENDER_TARGET_BLEND_DESC DstRTDesc.LogicOpEnable = SrcRTDesc.LogicOperationEnable ? TRUE : FALSE; - DstRTDesc.LogicOp = LogicOperationToD3D12LogicOp(SrcRTDesc.LogicOp); + DstRTDesc.LogicOp = LogicOperationToD3D12LogicOp(SrcRTDesc.LogicOp); } } -void LayoutElements_To_D3D12_INPUT_ELEMENT_DESCs(const InputLayoutDesc& InputLayout, - std::vector >& d3d12InputElements) +void LayoutElements_To_D3D12_INPUT_ELEMENT_DESCs(const InputLayoutDesc& InputLayout, + std::vector>& d3d12InputElements) { LayoutElements_To_D3D_INPUT_ELEMENT_DESCs(InputLayout, d3d12InputElements); } @@ -141,7 +145,9 @@ D3D12_PRIMITIVE_TOPOLOGY TopologyToD3D12Topology(PRIMITIVE_TOPOLOGY Topology) -void TextureViewDesc_to_D3D12_SRV_DESC(const TextureViewDesc& SRVDesc, D3D12_SHADER_RESOURCE_VIEW_DESC &D3D12SRVDesc, Uint32 SampleCount) +void TextureViewDesc_to_D3D12_SRV_DESC(const TextureViewDesc& SRVDesc, + D3D12_SHADER_RESOURCE_VIEW_DESC& D3D12SRVDesc, + Uint32 SampleCount) { TextureViewDesc_to_D3D_SRV_DESC(SRVDesc, D3D12SRVDesc, SampleCount); D3D12SRVDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; @@ -149,156 +155,165 @@ void TextureViewDesc_to_D3D12_SRV_DESC(const TextureViewDesc& SRVDesc, D3D12_SHA { case RESOURCE_DIM_TEX_1D: D3D12SRVDesc.Texture1D.ResourceMinLODClamp = 0; - break; + break; case RESOURCE_DIM_TEX_1D_ARRAY: D3D12SRVDesc.Texture1DArray.ResourceMinLODClamp = 0; - break; + break; case RESOURCE_DIM_TEX_2D: - if( SampleCount > 1 ) + if (SampleCount > 1) { } else { - D3D12SRVDesc.Texture2D.PlaneSlice = 0; + D3D12SRVDesc.Texture2D.PlaneSlice = 0; D3D12SRVDesc.Texture2D.ResourceMinLODClamp = 0; } - break; + break; case RESOURCE_DIM_TEX_2D_ARRAY: - if( SampleCount > 1 ) + if (SampleCount > 1) { } else { - D3D12SRVDesc.Texture2DArray.PlaneSlice = 0; + D3D12SRVDesc.Texture2DArray.PlaneSlice = 0; D3D12SRVDesc.Texture2DArray.ResourceMinLODClamp = 0; } - break; + break; case RESOURCE_DIM_TEX_3D: D3D12SRVDesc.Texture3D.ResourceMinLODClamp = 0; - break; + break; case RESOURCE_DIM_TEX_CUBE: D3D12SRVDesc.TextureCube.ResourceMinLODClamp = 0; - break; + break; case RESOURCE_DIM_TEX_CUBE_ARRAY: D3D12SRVDesc.TextureCubeArray.ResourceMinLODClamp = 0; - break; + break; default: - UNEXPECTED( "Unexpected view type" ); + UNEXPECTED("Unexpected view type"); } } -void TextureViewDesc_to_D3D12_RTV_DESC(const TextureViewDesc& RTVDesc, D3D12_RENDER_TARGET_VIEW_DESC& D3D12RTVDesc, Uint32 SampleCount) +void TextureViewDesc_to_D3D12_RTV_DESC(const TextureViewDesc& RTVDesc, + D3D12_RENDER_TARGET_VIEW_DESC& D3D12RTVDesc, + Uint32 SampleCount) { TextureViewDesc_to_D3D_RTV_DESC(RTVDesc, D3D12RTVDesc, SampleCount); switch (RTVDesc.TextureDim) { case RESOURCE_DIM_TEX_1D: - break; + break; case RESOURCE_DIM_TEX_1D_ARRAY: - break; + break; case RESOURCE_DIM_TEX_2D: - if( SampleCount > 1 ) + if (SampleCount > 1) { } else { D3D12RTVDesc.Texture2D.PlaneSlice = 0; } - break; + break; case RESOURCE_DIM_TEX_2D_ARRAY: - if( SampleCount > 1 ) + if (SampleCount > 1) { } else { D3D12RTVDesc.Texture2DArray.PlaneSlice = 0; } - break; + break; case RESOURCE_DIM_TEX_3D: - break; + break; default: - UNEXPECTED( "Unexpected view type" ); + UNEXPECTED("Unexpected view type"); } } -void TextureViewDesc_to_D3D12_DSV_DESC(const TextureViewDesc& DSVDesc, D3D12_DEPTH_STENCIL_VIEW_DESC& D3D12DSVDesc, Uint32 SampleCount) +void TextureViewDesc_to_D3D12_DSV_DESC(const TextureViewDesc& DSVDesc, + D3D12_DEPTH_STENCIL_VIEW_DESC& D3D12DSVDesc, + Uint32 SampleCount) { TextureViewDesc_to_D3D_DSV_DESC(DSVDesc, D3D12DSVDesc, SampleCount); D3D12DSVDesc.Flags = D3D12_DSV_FLAG_NONE; } -void TextureViewDesc_to_D3D12_UAV_DESC(const TextureViewDesc& UAVDesc, D3D12_UNORDERED_ACCESS_VIEW_DESC& D3D12UAVDesc) +void TextureViewDesc_to_D3D12_UAV_DESC(const TextureViewDesc& UAVDesc, + D3D12_UNORDERED_ACCESS_VIEW_DESC& D3D12UAVDesc) { TextureViewDesc_to_D3D_UAV_DESC(UAVDesc, D3D12UAVDesc); switch (UAVDesc.TextureDim) { case RESOURCE_DIM_TEX_1D: - break; + break; case RESOURCE_DIM_TEX_1D_ARRAY: - break; + break; case RESOURCE_DIM_TEX_2D: D3D12UAVDesc.Texture2D.PlaneSlice = 0; - break; + break; case RESOURCE_DIM_TEX_2D_ARRAY: D3D12UAVDesc.Texture2DArray.PlaneSlice = 0; - break; + break; case RESOURCE_DIM_TEX_3D: - break; + break; default: - UNEXPECTED( "Unexpected view type" ); + UNEXPECTED("Unexpected view type"); } } -void BufferViewDesc_to_D3D12_SRV_DESC(const BufferDesc &BuffDesc, const BufferViewDesc& SRVDesc, D3D12_SHADER_RESOURCE_VIEW_DESC& D3D12SRVDesc) +void BufferViewDesc_to_D3D12_SRV_DESC(const BufferDesc& BuffDesc, + const BufferViewDesc& SRVDesc, + D3D12_SHADER_RESOURCE_VIEW_DESC& D3D12SRVDesc) { BufferViewDesc_to_D3D_SRV_DESC(BuffDesc, SRVDesc, D3D12SRVDesc); D3D12SRVDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; if (BuffDesc.Mode == BUFFER_MODE_RAW && SRVDesc.Format.ValueType == VT_UNDEFINED) { D3D12SRVDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; - D3D12SRVDesc.Format = DXGI_FORMAT_R32_TYPELESS; + D3D12SRVDesc.Format = DXGI_FORMAT_R32_TYPELESS; } else D3D12SRVDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; VERIFY_EXPR(BuffDesc.BindFlags & BIND_SHADER_RESOURCE); if (BuffDesc.Mode == BUFFER_MODE_STRUCTURED) - D3D12SRVDesc.Buffer.StructureByteStride = BuffDesc.ElementByteStride; + D3D12SRVDesc.Buffer.StructureByteStride = BuffDesc.ElementByteStride; } -void BufferViewDesc_to_D3D12_UAV_DESC(const BufferDesc& BuffDesc, const BufferViewDesc& UAVDesc, D3D12_UNORDERED_ACCESS_VIEW_DESC& D3D12UAVDesc) +void BufferViewDesc_to_D3D12_UAV_DESC(const BufferDesc& BuffDesc, + const BufferViewDesc& UAVDesc, + D3D12_UNORDERED_ACCESS_VIEW_DESC& D3D12UAVDesc) { BufferViewDesc_to_D3D_UAV_DESC(BuffDesc, UAVDesc, D3D12UAVDesc); VERIFY_EXPR(BuffDesc.BindFlags & BIND_UNORDERED_ACCESS); if (BuffDesc.Mode == BUFFER_MODE_STRUCTURED) - D3D12UAVDesc.Buffer.StructureByteStride = BuffDesc.ElementByteStride; + D3D12UAVDesc.Buffer.StructureByteStride = BuffDesc.ElementByteStride; } D3D12_STATIC_BORDER_COLOR BorderColorToD3D12StaticBorderColor(const Float32 BorderColor[]) { D3D12_STATIC_BORDER_COLOR StaticBorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK; - if(BorderColor[0] == 0 && BorderColor[1] == 0 && BorderColor[2] == 0 && BorderColor[3] == 0) + if (BorderColor[0] == 0 && BorderColor[1] == 0 && BorderColor[2] == 0 && BorderColor[3] == 0) StaticBorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; - else if(BorderColor[0] == 0 && BorderColor[1] == 0 && BorderColor[2] == 0 && BorderColor[3] == 1) + else if (BorderColor[0] == 0 && BorderColor[1] == 0 && BorderColor[2] == 0 && BorderColor[3] == 1) StaticBorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK; - else if(BorderColor[0] == 1 && BorderColor[1] == 1 && BorderColor[2] == 1 && BorderColor[3] == 1) + else if (BorderColor[0] == 1 && BorderColor[1] == 1 && BorderColor[2] == 1 && BorderColor[3] == 1) StaticBorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE; else { @@ -311,9 +326,10 @@ D3D12_STATIC_BORDER_COLOR BorderColorToD3D12StaticBorderColor(const Float32 Bord static D3D12_RESOURCE_STATES ResourceStateFlagToD3D12ResourceState(RESOURCE_STATE StateFlag) { static_assert(RESOURCE_STATE_MAX_BIT == 0x8000, "This function must be updated to handle new resource state flag"); - VERIFY((StateFlag & (StateFlag-1)) == 0, "Only single bit must be set"); - switch(StateFlag) + VERIFY((StateFlag & (StateFlag - 1)) == 0, "Only single bit must be set"); + switch (StateFlag) { + // clang-format off case RESOURCE_STATE_UNDEFINED: return D3D12_RESOURCE_STATE_COMMON; case RESOURCE_STATE_VERTEX_BUFFER: return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER; case RESOURCE_STATE_CONSTANT_BUFFER: return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER; @@ -330,6 +346,7 @@ static D3D12_RESOURCE_STATES ResourceStateFlagToD3D12ResourceState(RESOURCE_STAT case RESOURCE_STATE_RESOLVE_DEST: return D3D12_RESOURCE_STATE_RESOLVE_DEST; case RESOURCE_STATE_RESOLVE_SOURCE: return D3D12_RESOURCE_STATE_RESOLVE_SOURCE; case RESOURCE_STATE_PRESENT: return D3D12_RESOURCE_STATE_PRESENT; + // clang-format on default: UNEXPECTED("Unexpected resource state flag"); return static_cast(0); @@ -341,35 +358,35 @@ class StateFlagBitPosToD3D12ResourceState public: StateFlagBitPosToD3D12ResourceState() { - static_assert( (1 << MaxFlagBitPos) == RESOURCE_STATE_MAX_BIT, "This function must be updated to handle new resource state flag"); - for (Uint32 bit=0; bit <= MaxFlagBitPos; ++bit) + static_assert((1 << MaxFlagBitPos) == RESOURCE_STATE_MAX_BIT, "This function must be updated to handle new resource state flag"); + for (Uint32 bit = 0; bit <= MaxFlagBitPos; ++bit) { - FlagBitPosToResStateMap[bit] = ResourceStateFlagToD3D12ResourceState(static_cast(1<(1 << bit)); } } - D3D12_RESOURCE_STATES operator()(Uint32 BitPos)const + D3D12_RESOURCE_STATES operator()(Uint32 BitPos) const { VERIFY(BitPos <= MaxFlagBitPos, "Resource state flag bit position (", BitPos, ") exceeds max bit position (", MaxFlagBitPos, ")"); return FlagBitPosToResStateMap[BitPos]; } private: - static constexpr Uint32 MaxFlagBitPos = 15; + static constexpr Uint32 MaxFlagBitPos = 15; std::array FlagBitPosToResStateMap; }; D3D12_RESOURCE_STATES ResourceStateFlagsToD3D12ResourceStates(RESOURCE_STATE StateFlags) { - VERIFY(StateFlags < (RESOURCE_STATE_MAX_BIT<<1), "Resource state flags are out of range"); + VERIFY(StateFlags < (RESOURCE_STATE_MAX_BIT << 1), "Resource state flags are out of range"); static const StateFlagBitPosToD3D12ResourceState BitPosToD3D12ResState; - D3D12_RESOURCE_STATES D3D12ResourceStates = static_cast(0); - Uint32 Bits = StateFlags; - while(Bits != 0) + D3D12_RESOURCE_STATES D3D12ResourceStates = static_cast(0); + Uint32 Bits = StateFlags; + while (Bits != 0) { auto lsb = PlatformMisc::GetLSB(Bits); D3D12ResourceStates |= BitPosToD3D12ResState(lsb); - Bits &= ~(1<(RESOURCE_STATE_VERTEX_BUFFER | RESOURCE_STATE_CONSTANT_BUFFER); @@ -397,6 +415,7 @@ static RESOURCE_STATE D3D12ResourceStateToResourceStateFlags(D3D12_RESOURCE_STAT case D3D12_RESOURCE_STATE_COPY_SOURCE: return RESOURCE_STATE_COPY_SOURCE; case D3D12_RESOURCE_STATE_RESOLVE_DEST: return RESOURCE_STATE_RESOLVE_DEST; case D3D12_RESOURCE_STATE_RESOLVE_SOURCE: return RESOURCE_STATE_RESOLVE_SOURCE; + // clang-format on default: UNEXPECTED("Unexpected D3D12 resource state"); return RESOURCE_STATE_UNKNOWN; @@ -409,20 +428,20 @@ class D3D12StateFlagBitPosToResourceState public: D3D12StateFlagBitPosToResourceState() { - for (Uint32 bit=0; bit <= MaxFlagBitPos; ++bit) + for (Uint32 bit = 0; bit <= MaxFlagBitPos; ++bit) { - FlagBitPosToResStateMap[bit] = D3D12ResourceStateToResourceStateFlags(static_cast(1<(1 << bit)); } } - RESOURCE_STATE operator()(Uint32 BitPos)const + RESOURCE_STATE operator()(Uint32 BitPos) const { VERIFY(BitPos <= MaxFlagBitPos, "Resource state flag bit position (", BitPos, ") exceeds max bit position (", MaxFlagBitPos, ")"); return FlagBitPosToResStateMap[BitPos]; } private: - static constexpr Uint32 MaxFlagBitPos = 13; + static constexpr Uint32 MaxFlagBitPos = 13; std::array FlagBitPosToResStateMap; }; @@ -432,15 +451,16 @@ RESOURCE_STATE D3D12ResourceStatesToResourceStateFlags(D3D12_RESOURCE_STATES Sta return RESOURCE_STATE_PRESENT; static const D3D12StateFlagBitPosToResourceState BitPosToResState; + Uint32 ResourceStates = 0; - Uint32 Bits = StateFlags; - while(Bits != 0) + Uint32 Bits = StateFlags; + while (Bits != 0) { auto lsb = PlatformMisc::GetLSB(Bits); ResourceStates |= BitPosToResState(lsb); - Bits &= ~(1<(ResourceStates); } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/D3D12Utils.cpp b/Graphics/GraphicsEngineD3D12/src/D3D12Utils.cpp index ccf4f290..7f289e54 100644 --- a/Graphics/GraphicsEngineD3D12/src/D3D12Utils.cpp +++ b/Graphics/GraphicsEngineD3D12/src/D3D12Utils.cpp @@ -26,20 +26,22 @@ namespace Diligent { - const Char* GetD3D12DescriptorHeapTypeLiteralName(D3D12_DESCRIPTOR_HEAP_TYPE Type) +const Char* GetD3D12DescriptorHeapTypeLiteralName(D3D12_DESCRIPTOR_HEAP_TYPE Type) +{ + static bool bIsInitialized = false; + static const Char* HeapTypeNames[D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES]; + if (!bIsInitialized) { - static bool bIsInitialized = false; - static const Char* HeapTypeNames[D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES]; - if (!bIsInitialized) - { - HeapTypeNames[D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV] = "D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV"; - HeapTypeNames[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER] = "D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER"; - HeapTypeNames[D3D12_DESCRIPTOR_HEAP_TYPE_RTV] = "D3D12_DESCRIPTOR_HEAP_TYPE_RTV"; - HeapTypeNames[D3D12_DESCRIPTOR_HEAP_TYPE_DSV] = "D3D12_DESCRIPTOR_HEAP_TYPE_DSV"; + // clang-format off + HeapTypeNames[D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV] = "D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV"; + HeapTypeNames[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER] = "D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER"; + HeapTypeNames[D3D12_DESCRIPTOR_HEAP_TYPE_RTV] = "D3D12_DESCRIPTOR_HEAP_TYPE_RTV"; + HeapTypeNames[D3D12_DESCRIPTOR_HEAP_TYPE_DSV] = "D3D12_DESCRIPTOR_HEAP_TYPE_DSV"; + // clang-format on - bIsInitialized = true; - } - VERIFY_EXPR(Type >= 0 && Type < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES); - return HeapTypeNames[Type]; + bIsInitialized = true; } + VERIFY_EXPR(Type >= 0 && Type < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES); + return HeapTypeNames[Type]; } +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/DescriptorHeap.cpp b/Graphics/GraphicsEngineD3D12/src/DescriptorHeap.cpp index c16e75a2..a2671346 100644 --- a/Graphics/GraphicsEngineD3D12/src/DescriptorHeap.cpp +++ b/Graphics/GraphicsEngineD3D12/src/DescriptorHeap.cpp @@ -30,11 +30,12 @@ namespace Diligent { // Creates a new descriptor heap and reference the entire heap -DescriptorHeapAllocationManager::DescriptorHeapAllocationManager(IMemoryAllocator& Allocator, +DescriptorHeapAllocationManager::DescriptorHeapAllocationManager(IMemoryAllocator& Allocator, RenderDeviceD3D12Impl& DeviceD3D12Impl, IDescriptorAllocator& ParentAllocator, size_t ThisManagerId, - const D3D12_DESCRIPTOR_HEAP_DESC& HeapDesc) : + const D3D12_DESCRIPTOR_HEAP_DESC& HeapDesc) : + // clang-format off m_ParentAllocator {ParentAllocator}, m_DeviceD3D12Impl {DeviceD3D12Impl}, m_ThisManagerId {ThisManagerId }, @@ -42,6 +43,7 @@ DescriptorHeapAllocationManager::DescriptorHeapAllocationManager(IMemoryAllocato m_DescriptorSize {DeviceD3D12Impl.GetD3D12Device()->GetDescriptorHandleIncrementSize(m_HeapDesc.Type)}, m_NumDescriptorsInAllocation {HeapDesc.NumDescriptors}, m_FreeBlockManager {HeapDesc.NumDescriptors, Allocator} +// clang-format on { auto pDevice = DeviceD3D12Impl.GetD3D12Device(); @@ -50,19 +52,20 @@ DescriptorHeapAllocationManager::DescriptorHeapAllocationManager(IMemoryAllocato pDevice->CreateDescriptorHeap(&m_HeapDesc, __uuidof(m_pd3d12DescriptorHeap), reinterpret_cast(static_cast(&m_pd3d12DescriptorHeap))); m_FirstCPUHandle = m_pd3d12DescriptorHeap->GetCPUDescriptorHandleForHeapStart(); - if(m_HeapDesc.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) + if (m_HeapDesc.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) m_FirstGPUHandle = m_pd3d12DescriptorHeap->GetGPUDescriptorHandleForHeapStart(); } // Uses subrange of descriptors in the existing D3D12 descriptor heap // that starts at offset FirstDescriptor and uses NumDescriptors descriptors -DescriptorHeapAllocationManager::DescriptorHeapAllocationManager(IMemoryAllocator& Allocator, +DescriptorHeapAllocationManager::DescriptorHeapAllocationManager(IMemoryAllocator& Allocator, RenderDeviceD3D12Impl& DeviceD3D12Impl, IDescriptorAllocator& ParentAllocator, size_t ThisManagerId, ID3D12DescriptorHeap* pd3d12DescriptorHeap, Uint32 FirstDescriptor, - Uint32 NumDescriptors): + Uint32 NumDescriptors) : + // clang-format off m_ParentAllocator {ParentAllocator}, m_DeviceD3D12Impl {DeviceD3D12Impl}, m_ThisManagerId {ThisManagerId }, @@ -71,6 +74,7 @@ DescriptorHeapAllocationManager::DescriptorHeapAllocationManager(IMemoryAllocato m_NumDescriptorsInAllocation {NumDescriptors}, m_FreeBlockManager {NumDescriptors, Allocator}, m_pd3d12DescriptorHeap {pd3d12DescriptorHeap} +// clang-format on { m_FirstCPUHandle = pd3d12DescriptorHeap->GetCPUDescriptorHandleForHeapStart(); m_FirstCPUHandle.ptr += m_DescriptorSize * FirstDescriptor; @@ -125,15 +129,15 @@ DescriptorHeapAllocation DescriptorHeapAllocationManager::Allocate(uint32_t Coun void DescriptorHeapAllocationManager::FreeAllocation(DescriptorHeapAllocation&& Allocation) { VERIFY(Allocation.GetAllocationManagerId() == m_ThisManagerId, "Invalid descriptor heap manager Id"); - + if (Allocation.IsNull()) return; std::lock_guard LockGuard(m_FreeBlockManagerMutex); - auto DescriptorOffset = (Allocation.GetCpuHandle().ptr - m_FirstCPUHandle.ptr) / m_DescriptorSize; + auto DescriptorOffset = (Allocation.GetCpuHandle().ptr - m_FirstCPUHandle.ptr) / m_DescriptorSize; // Methods of VariableSizeAllocationsManager class are not thread safe! m_FreeBlockManager.Free(DescriptorOffset, Allocation.GetNumHandles()); - + // Clear the allocation Allocation.Reset(); #ifdef DEVELOPMENT @@ -150,7 +154,8 @@ CPUDescriptorHeap::CPUDescriptorHeap(IMemoryAllocator& Allocator, RenderDeviceD3D12Impl& DeviceD3D12Impl, Uint32 NumDescriptorsInHeap, D3D12_DESCRIPTOR_HEAP_TYPE Type, - D3D12_DESCRIPTOR_HEAP_FLAGS Flags) : + D3D12_DESCRIPTOR_HEAP_FLAGS Flags) : + // clang-format off m_MemAllocator {Allocator }, m_DeviceD3D12Impl{DeviceD3D12Impl}, m_HeapPool {STD_ALLOCATOR_RAW_MEM(DescriptorHeapAllocationManager, GetRawAllocator(), "Allocator for vector")}, @@ -163,6 +168,7 @@ CPUDescriptorHeap::CPUDescriptorHeap(IMemoryAllocator& Allocator, 1 // NodeMask }, m_DescriptorSize{DeviceD3D12Impl.GetD3D12Device()->GetDescriptorHandleIncrementSize(Type)} +// clang-format on { // Create one pool m_HeapPool.emplace_back(m_MemAllocator, m_DeviceD3D12Impl, *this, 0, m_HeapDesc); @@ -171,8 +177,8 @@ CPUDescriptorHeap::CPUDescriptorHeap(IMemoryAllocator& Allocator, CPUDescriptorHeap::~CPUDescriptorHeap() { - DEV_CHECK_ERR(m_CurrentSize == 0, "Not all allocations released" ); - + DEV_CHECK_ERR(m_CurrentSize == 0, "Not all allocations released"); + DEV_CHECK_ERR(m_AvailableHeaps.size() == m_HeapPool.size(), "Not all descriptor heap pools are released"); Uint32 TotalDescriptors = 0; for (auto& Heap : m_HeapPool) @@ -183,13 +189,14 @@ CPUDescriptorHeap::~CPUDescriptorHeap() LOG_INFO_MESSAGE(std::setw(38), std::left, GetD3D12DescriptorHeapTypeLiteralName(m_HeapDesc.Type), " CPU heap allocated pool count: ", m_HeapPool.size(), ". Max descriptors: ", m_MaxSize, '/', TotalDescriptors, - " (", std::fixed, std::setprecision(2), m_MaxSize*100.0 / std::max(TotalDescriptors, 1u), "%)."); + " (", std::fixed, std::setprecision(2), m_MaxSize * 100.0 / std::max(TotalDescriptors, 1u), "%)."); } #ifdef DEVELOPMENT int32_t CPUDescriptorHeap::DvpGetTotalAllocationCount() { int32_t AllocationCount = 0; + std::lock_guard LockGuard(m_HeapPoolMutex); for (auto& Heap : m_HeapPool) AllocationCount += Heap.DvpGetAllocationsCounter(); @@ -197,7 +204,7 @@ int32_t CPUDescriptorHeap::DvpGetTotalAllocationCount() } #endif -DescriptorHeapAllocation CPUDescriptorHeap::Allocate( uint32_t Count ) +DescriptorHeapAllocation CPUDescriptorHeap::Allocate(uint32_t Count) { std::lock_guard LockGuard(m_HeapPoolMutex); // Note that every DescriptorHeapAllocationManager object instance is itslef @@ -206,7 +213,7 @@ DescriptorHeapAllocation CPUDescriptorHeap::Allocate( uint32_t Count ) DescriptorHeapAllocation Allocation; // Go through all descriptor heap managers that have free descriptors auto AvailableHeapIt = m_AvailableHeaps.begin(); - while( AvailableHeapIt != m_AvailableHeaps.end() ) + while (AvailableHeapIt != m_AvailableHeaps.end()) { auto NextIt = AvailableHeapIt; ++NextIt; @@ -223,20 +230,20 @@ DescriptorHeapAllocation CPUDescriptorHeap::Allocate( uint32_t Count ) AvailableHeapIt = NextIt; } - // If there were no available descriptor heap managers or no manager was able + // If there were no available descriptor heap managers or no manager was able // to suffice the allocation request, create a new manager if (Allocation.IsNull()) { // Make sure the heap is large enough to accomodate the requested number of descriptors - if(Count > m_HeapDesc.NumDescriptors) + if (Count > m_HeapDesc.NumDescriptors) { - LOG_INFO_MESSAGE("Number of requested CPU descriptors handles (", Count, ") exceeds the descriptor heap size (", m_HeapDesc.NumDescriptors,"). Increasing the number of descriptors in the heap"); + LOG_INFO_MESSAGE("Number of requested CPU descriptors handles (", Count, ") exceeds the descriptor heap size (", m_HeapDesc.NumDescriptors, "). Increasing the number of descriptors in the heap"); } m_HeapDesc.NumDescriptors = std::max(m_HeapDesc.NumDescriptors, static_cast(Count)); // Create a new descriptor heap manager. Note that this constructor creates a new D3D12 descriptor // heap and references the entire heap. Pool index is used as manager ID m_HeapPool.emplace_back(m_MemAllocator, m_DeviceD3D12Impl, *this, m_HeapPool.size(), m_HeapDesc); - auto NewHeapIt = m_AvailableHeaps.insert(m_HeapPool.size()-1); + auto NewHeapIt = m_AvailableHeaps.insert(m_HeapPool.size() - 1); VERIFY_EXPR(NewHeapIt.second); // Use the new manager to allocate descriptor handles @@ -257,9 +264,10 @@ void CPUDescriptorHeap::Free(DescriptorHeapAllocation&& Allocation, Uint64 CmdQu DescriptorHeapAllocation Allocation; CPUDescriptorHeap* Heap; + // clang-format off StaleAllocation(DescriptorHeapAllocation&& _Allocation, CPUDescriptorHeap& _Heap)noexcept : - Allocation(std::move(_Allocation)), - Heap (&_Heap) + Allocation{std::move(_Allocation)}, + Heap {&_Heap } { } @@ -268,11 +276,12 @@ void CPUDescriptorHeap::Free(DescriptorHeapAllocation&& Allocation, Uint64 CmdQu StaleAllocation& operator= ( StaleAllocation&&) = delete; StaleAllocation(StaleAllocation&& rhs)noexcept : - Allocation (std::move(rhs.Allocation)), - Heap (rhs.Heap) + Allocation {std::move(rhs.Allocation)}, + Heap {rhs.Heap } { rhs.Heap = nullptr; } + // clang-format on ~StaleAllocation() { @@ -286,7 +295,7 @@ void CPUDescriptorHeap::Free(DescriptorHeapAllocation&& Allocation, Uint64 CmdQu void CPUDescriptorHeap::FreeAllocation(DescriptorHeapAllocation&& Allocation) { std::lock_guard LockGuard(m_HeapPoolMutex); - auto ManagerId = Allocation.GetAllocationManagerId(); + auto ManagerId = Allocation.GetAllocationManagerId(); m_CurrentSize -= static_cast(Allocation.GetNumHandles()); m_HeapPool[ManagerId].FreeAllocation(std::move(Allocation)); // Return the manager to the pool of available managers @@ -296,12 +305,13 @@ void CPUDescriptorHeap::FreeAllocation(DescriptorHeapAllocation&& Allocation) -GPUDescriptorHeap::GPUDescriptorHeap(IMemoryAllocator& Allocator, - RenderDeviceD3D12Impl& Device, - Uint32 NumDescriptorsInHeap, +GPUDescriptorHeap::GPUDescriptorHeap(IMemoryAllocator& Allocator, + RenderDeviceD3D12Impl& Device, + Uint32 NumDescriptorsInHeap, Uint32 NumDynamicDescriptors, - D3D12_DESCRIPTOR_HEAP_TYPE Type, + D3D12_DESCRIPTOR_HEAP_TYPE Type, D3D12_DESCRIPTOR_HEAP_FLAGS Flags) : + // clang-format off m_DeviceD3D12Impl{Device}, m_HeapDesc { @@ -322,6 +332,7 @@ GPUDescriptorHeap::GPUDescriptorHeap(IMemoryAllocator& Allocator, m_DescriptorSize {Device.GetD3D12Device()->GetDescriptorHandleIncrementSize(Type)}, m_HeapAllocationManager {Allocator, Device, *this, 0, m_pd3d12DescriptorHeap, 0, NumDescriptorsInHeap}, m_DynamicAllocationsManager{Allocator, Device, *this, 1, m_pd3d12DescriptorHeap, NumDescriptorsInHeap, NumDynamicDescriptors} +// clang-format on { } @@ -332,7 +343,7 @@ GPUDescriptorHeap::~GPUDescriptorHeap() auto MaxStaticSize = m_HeapAllocationManager.GetMaxAllocatedSize(); auto MaxDynamicSize = m_DynamicAllocationsManager.GetMaxAllocatedSize(); - LOG_INFO_MESSAGE(std::setw(38), std::left, GetD3D12DescriptorHeapTypeLiteralName(m_HeapDesc.Type), " GPU heap max allocated size (static|dynamic): ", + LOG_INFO_MESSAGE(std::setw(38), std::left, GetD3D12DescriptorHeapTypeLiteralName(m_HeapDesc.Type), " GPU heap max allocated size (static|dynamic): ", MaxStaticSize, '/', TotalStaticSize, " (", std::fixed, std::setprecision(2), MaxStaticSize * 100.0 / TotalStaticSize, "%) | ", MaxDynamicSize, '/', TotalDynamicSize, " (", std::fixed, std::setprecision(2), MaxDynamicSize * 100.0 / TotalDynamicSize, "%)."); } @@ -344,9 +355,10 @@ void GPUDescriptorHeap::Free(DescriptorHeapAllocation&& Allocation, Uint64 CmdQu DescriptorHeapAllocation Allocation; GPUDescriptorHeap* Heap; + // clang-format off StaleAllocation(DescriptorHeapAllocation&& _Allocation, GPUDescriptorHeap& _Heap)noexcept : - Allocation(std::move(_Allocation)), - Heap (&_Heap) + Allocation{std::move(_Allocation)}, + Heap {&_Heap } { } @@ -355,11 +367,12 @@ void GPUDescriptorHeap::Free(DescriptorHeapAllocation&& Allocation, Uint64 CmdQu StaleAllocation& operator= ( StaleAllocation&&) = delete; StaleAllocation(StaleAllocation&& rhs)noexcept : - Allocation (std::move(rhs.Allocation)), - Heap (rhs.Heap) + Allocation{std::move(rhs.Allocation)}, + Heap {rhs.Heap } { rhs.Heap = nullptr; } + // clang-format on ~StaleAllocation() { @@ -387,10 +400,12 @@ DynamicSuballocationsManager::DynamicSuballocationsManager(IMemoryAllocator& Al GPUDescriptorHeap& ParentGPUHeap, Uint32 DynamicChunkSize, String ManagerName) : - m_ParentGPUHeap(ParentGPUHeap), - m_DynamicChunkSize(DynamicChunkSize), - m_Suballocations(STD_ALLOCATOR_RAW_MEM(DescriptorHeapAllocation, GetRawAllocator(), "Allocator for vector")), - m_ManagerName(std::move(ManagerName)) + // clang-format off + m_ParentGPUHeap {ParentGPUHeap }, + m_DynamicChunkSize{DynamicChunkSize}, + m_Suballocations {STD_ALLOCATOR_RAW_MEM(DescriptorHeapAllocation, GetRawAllocator(), "Allocator for vector")}, + m_ManagerName {std::move(ManagerName)} +// clang-format on { } @@ -403,9 +418,9 @@ DynamicSuballocationsManager::~DynamicSuballocationsManager() void DynamicSuballocationsManager::ReleaseAllocations(Uint64 CmdQueueMask) { // Clear the list and dispose all allocated chunks of GPU descriptor heap. - // The chunks will be added to release queues and eventually returned to the + // The chunks will be added to release queues and eventually returned to the // parent GPU heap. - for(auto& Allocation : m_Suballocations) + for (auto& Allocation : m_Suballocations) { m_ParentGPUHeap.Free(std::move(Allocation), CmdQueueMask); } @@ -420,11 +435,11 @@ DescriptorHeapAllocation DynamicSuballocationsManager::Allocate(Uint32 Count) // be called through device context from single thread only // Check if there are no chunks or the last chunk does not have enough space - if( m_Suballocations.empty() || - m_CurrentSuballocationOffset + Count > m_Suballocations.back().GetNumHandles() ) + if (m_Suballocations.empty() || + m_CurrentSuballocationOffset + Count > m_Suballocations.back().GetNumHandles()) { // Request a new chunk from the parent GPU descriptor heap - auto SuballocationSize = std::max(m_DynamicChunkSize, Count); + auto SuballocationSize = std::max(m_DynamicChunkSize, Count); auto NewDynamicSubAllocation = m_ParentGPUHeap.AllocateDynamic(SuballocationSize); if (NewDynamicSubAllocation.IsNull()) { @@ -435,25 +450,25 @@ DescriptorHeapAllocation DynamicSuballocationsManager::Allocate(Uint32 Count) m_CurrentSuballocationOffset = 0; m_CurrSuballocationsTotalSize += SuballocationSize; - m_PeakSuballocationsTotalSize = std::max(m_PeakSuballocationsTotalSize, m_CurrSuballocationsTotalSize); + m_PeakSuballocationsTotalSize = std::max(m_PeakSuballocationsTotalSize, m_CurrSuballocationsTotalSize); } // Perform suballocation from the last chunk auto& CurrentSuballocation = m_Suballocations.back(); - + auto ManagerId = CurrentSuballocation.GetAllocationManagerId(); VERIFY(ManagerId < std::numeric_limits::max(), "ManagerID exceed allowed limit"); - DescriptorHeapAllocation Allocation( *this, - CurrentSuballocation.GetDescriptorHeap(), - CurrentSuballocation.GetCpuHandle(m_CurrentSuballocationOffset), - CurrentSuballocation.GetGpuHandle(m_CurrentSuballocationOffset), - Count, - static_cast(ManagerId) ); + DescriptorHeapAllocation Allocation(*this, + CurrentSuballocation.GetDescriptorHeap(), + CurrentSuballocation.GetCpuHandle(m_CurrentSuballocationOffset), + CurrentSuballocation.GetGpuHandle(m_CurrentSuballocationOffset), + Count, + static_cast(ManagerId)); m_CurrentSuballocationOffset += Count; - m_CurrDescriptorCount += Count; - m_PeakDescriptorCount = std::max(m_PeakDescriptorCount, m_CurrDescriptorCount); + m_CurrDescriptorCount += Count; + m_PeakDescriptorCount = std::max(m_PeakDescriptorCount, m_CurrDescriptorCount); return Allocation; } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/DeviceContextD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/DeviceContextD3D12Impl.cpp index c15eea8e..cef3b54c 100644 --- a/Graphics/GraphicsEngineD3D12/src/DeviceContextD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/DeviceContextD3D12Impl.cpp @@ -40,1762 +40,1783 @@ namespace Diligent { - static std::string GetContextObjectName(const char* Object, bool bIsDeferred, Uint32 ContextId) - { - std::stringstream ss; - ss << Object; - if (bIsDeferred) - ss << " of deferred context #" << ContextId; - else - ss << " of immediate context"; - return ss.str(); - } +static std::string GetContextObjectName(const char* Object, bool bIsDeferred, Uint32 ContextId) +{ + std::stringstream ss; + ss << Object; + if (bIsDeferred) + ss << " of deferred context #" << ContextId; + else + ss << " of immediate context"; + return ss.str(); +} - DeviceContextD3D12Impl::DeviceContextD3D12Impl(IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pDeviceD3D12Impl, - bool bIsDeferred, - const EngineD3D12CreateInfo& EngineCI, - Uint32 ContextId, - Uint32 CommandQueueId) : - TDeviceContextBase - { - pRefCounters, - pDeviceD3D12Impl, - ContextId, - CommandQueueId, - bIsDeferred ? std::numeric_limits::max() : EngineCI.NumCommandsToFlushCmdList, - bIsDeferred - }, - m_DynamicHeap +DeviceContextD3D12Impl::DeviceContextD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl* pDeviceD3D12Impl, + bool bIsDeferred, + const EngineD3D12CreateInfo& EngineCI, + Uint32 ContextId, + Uint32 CommandQueueId) : + // clang-format off + TDeviceContextBase + { + pRefCounters, + pDeviceD3D12Impl, + ContextId, + CommandQueueId, + bIsDeferred ? std::numeric_limits::max() : EngineCI.NumCommandsToFlushCmdList, + bIsDeferred + }, + m_DynamicHeap + { + pDeviceD3D12Impl->GetDynamicMemoryManager(), + GetContextObjectName("Dynamic heap", bIsDeferred, ContextId), + EngineCI.DynamicHeapPageSize + }, + m_DynamicGPUDescriptorAllocator + { { - pDeviceD3D12Impl->GetDynamicMemoryManager(), - GetContextObjectName("Dynamic heap", bIsDeferred, ContextId), - EngineCI.DynamicHeapPageSize + GetRawAllocator(), + pDeviceD3D12Impl->GetGPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), + EngineCI.DynamicDescriptorAllocationChunkSize[D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV], + GetContextObjectName("CBV_SRV_UAV dynamic descriptor allocator", bIsDeferred, ContextId) }, - m_DynamicGPUDescriptorAllocator { - { - GetRawAllocator(), - pDeviceD3D12Impl->GetGPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), - EngineCI.DynamicDescriptorAllocationChunkSize[D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV], - GetContextObjectName("CBV_SRV_UAV dynamic descriptor allocator", bIsDeferred, ContextId) - }, - { - GetRawAllocator(), - pDeviceD3D12Impl->GetGPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER), - EngineCI.DynamicDescriptorAllocationChunkSize[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER], - GetContextObjectName("SAMPLER dynamic descriptor allocator", bIsDeferred, ContextId) - } - }, - m_CmdListAllocator{GetRawAllocator(), sizeof(CommandListD3D12Impl), 64} - { - RequestCommandContext(pDeviceD3D12Impl); + GetRawAllocator(), + pDeviceD3D12Impl->GetGPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER), + EngineCI.DynamicDescriptorAllocationChunkSize[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER], + GetContextObjectName("SAMPLER dynamic descriptor allocator", bIsDeferred, ContextId) + } + }, + m_CmdListAllocator{GetRawAllocator(), sizeof(CommandListD3D12Impl), 64} +// clang-format on +{ + RequestCommandContext(pDeviceD3D12Impl); - auto *pd3d12Device = pDeviceD3D12Impl->GetD3D12Device(); + auto* pd3d12Device = pDeviceD3D12Impl->GetD3D12Device(); - D3D12_COMMAND_SIGNATURE_DESC CmdSignatureDesc = {}; - D3D12_INDIRECT_ARGUMENT_DESC IndirectArg = {}; - CmdSignatureDesc.NodeMask = 0; - CmdSignatureDesc.NumArgumentDescs = 1; - CmdSignatureDesc.pArgumentDescs = &IndirectArg; + D3D12_COMMAND_SIGNATURE_DESC CmdSignatureDesc = {}; + D3D12_INDIRECT_ARGUMENT_DESC IndirectArg = {}; - CmdSignatureDesc.ByteStride = sizeof(UINT)*4; - IndirectArg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW; - auto hr = pd3d12Device->CreateCommandSignature(&CmdSignatureDesc, nullptr, __uuidof(m_pDrawIndirectSignature), reinterpret_cast(static_cast(&m_pDrawIndirectSignature)) ); - CHECK_D3D_RESULT_THROW(hr, "Failed to create indirect draw command signature"); + CmdSignatureDesc.NodeMask = 0; + CmdSignatureDesc.NumArgumentDescs = 1; + CmdSignatureDesc.pArgumentDescs = &IndirectArg; - CmdSignatureDesc.ByteStride = sizeof(UINT)*5; - IndirectArg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED; - hr = pd3d12Device->CreateCommandSignature(&CmdSignatureDesc, nullptr, __uuidof(m_pDrawIndexedIndirectSignature), reinterpret_cast(static_cast(&m_pDrawIndexedIndirectSignature)) ); - CHECK_D3D_RESULT_THROW(hr, "Failed to create draw indexed indirect command signature"); + CmdSignatureDesc.ByteStride = sizeof(UINT) * 4; + IndirectArg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW; + auto hr = pd3d12Device->CreateCommandSignature(&CmdSignatureDesc, nullptr, __uuidof(m_pDrawIndirectSignature), reinterpret_cast(static_cast(&m_pDrawIndirectSignature))); + CHECK_D3D_RESULT_THROW(hr, "Failed to create indirect draw command signature"); - CmdSignatureDesc.ByteStride = sizeof(UINT)*3; - IndirectArg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; - hr = pd3d12Device->CreateCommandSignature(&CmdSignatureDesc, nullptr, __uuidof(m_pDispatchIndirectSignature), reinterpret_cast(static_cast(&m_pDispatchIndirectSignature)) ); - CHECK_D3D_RESULT_THROW(hr, "Failed to create dispatch indirect command signature"); - } + CmdSignatureDesc.ByteStride = sizeof(UINT) * 5; + IndirectArg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED; + hr = pd3d12Device->CreateCommandSignature(&CmdSignatureDesc, nullptr, __uuidof(m_pDrawIndexedIndirectSignature), reinterpret_cast(static_cast(&m_pDrawIndexedIndirectSignature))); + CHECK_D3D_RESULT_THROW(hr, "Failed to create draw indexed indirect command signature"); - DeviceContextD3D12Impl::~DeviceContextD3D12Impl() - { - if (m_State.NumCommands != 0) - { - if (m_bIsDeferred) - { - LOG_ERROR_MESSAGE("There are outstanding commands in deferred context #", m_ContextId, " being destroyed, which indicates that FinishCommandList() has not been called." - " This may cause synchronization issues."); - } - else - { - LOG_ERROR_MESSAGE("There are outstanding commands in the immediate context being destroyed, which indicates the context has not been Flush()'ed.", - " This may cause synchronization issues."); - } - } + CmdSignatureDesc.ByteStride = sizeof(UINT) * 3; + IndirectArg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; + hr = pd3d12Device->CreateCommandSignature(&CmdSignatureDesc, nullptr, __uuidof(m_pDispatchIndirectSignature), reinterpret_cast(static_cast(&m_pDispatchIndirectSignature))); + CHECK_D3D_RESULT_THROW(hr, "Failed to create dispatch indirect command signature"); +} +DeviceContextD3D12Impl::~DeviceContextD3D12Impl() +{ + if (m_State.NumCommands != 0) + { if (m_bIsDeferred) { - if (m_CurrCmdCtx) - { - // The command context has never been executed, so it can be disposed without going through release queue - m_pDevice->DisposeCommandContext(std::move(m_CurrCmdCtx)); - } + LOG_ERROR_MESSAGE("There are outstanding commands in deferred context #", + m_ContextId, + " being destroyed, which indicates that FinishCommandList() has not been called." + " This may cause synchronization issues."); } else { - Flush(false); + LOG_ERROR_MESSAGE("There are outstanding commands in the immediate context being destroyed, " + "which indicates the context has not been Flush()'ed.", + " This may cause synchronization issues."); } + } - // For deferred contexts, m_SubmittedBuffersCmdQueueMask is reset to 0 after every call to FinishFrame(). - // In this case there are no resources to release, so there will be no issues. - FinishFrame(); - - // Note: as dynamic pages are returned to the global dynamic memory manager hosted by the render device, - // the dynamic heap can be destroyed before all pages are actually returned to the global manager. - DEV_CHECK_ERR(m_DynamicHeap.GetAllocatedPagesCount() == 0, "All dynamic pages must have been released by now."); - - for(size_t i=0; i < _countof(m_DynamicGPUDescriptorAllocator); ++i) + if (m_bIsDeferred) + { + if (m_CurrCmdCtx) { - // Note: as dynamic decriptor suballocations are returned to the global GPU descriptor heap that - // is hosted by the render device, the descriptor allocator can be destroyed before all suballocations - // are actually returned to the global heap. - DEV_CHECK_ERR(m_DynamicGPUDescriptorAllocator[i].GetSuballocationCount() == 0, "All dynamic suballocations must have been released"); + // The command context has never been executed, so it can be disposed without going through release queue + m_pDevice->DisposeCommandContext(std::move(m_CurrCmdCtx)); } } - - IMPLEMENT_QUERY_INTERFACE( DeviceContextD3D12Impl, IID_DeviceContextD3D12, TDeviceContextBase ) - - void DeviceContextD3D12Impl::SetPipelineState(IPipelineState* pPipelineState) + else { - auto* pPipelineStateD3D12 = ValidatedCast(pPipelineState); - if (PipelineStateD3D12Impl::IsSameObject(m_pPipelineState, pPipelineStateD3D12)) - return; + Flush(false); + } - // Never flush deferred context! - if (!m_bIsDeferred && m_State.NumCommands >= m_NumCommandsToFlush) - { - Flush(true); - } + // For deferred contexts, m_SubmittedBuffersCmdQueueMask is reset to 0 after every call to FinishFrame(). + // In this case there are no resources to release, so there will be no issues. + FinishFrame(); - const auto &PSODesc = pPipelineStateD3D12->GetDesc(); + // Note: as dynamic pages are returned to the global dynamic memory manager hosted by the render device, + // the dynamic heap can be destroyed before all pages are actually returned to the global manager. + DEV_CHECK_ERR(m_DynamicHeap.GetAllocatedPagesCount() == 0, "All dynamic pages must have been released by now."); - bool CommitStates = false; - bool CommitScissor = false; - if (!m_pPipelineState) - { - // If no pipeline state is bound, we are working with the fresh command - // list. We have to commit the states set in the context that are not - // committed by the draw command (render targets, viewports, scissor rects, etc.) - CommitStates = true; - } - else - { - const auto& OldPSODesc = m_pPipelineState->GetDesc(); - // Commit all graphics states when switching from compute pipeline - // This is necessary because if the command list had been flushed - // and the first PSO set on the command list was a compute pipeline, - // the states would otherwise never be committed (since m_pPipelineState != nullptr) - CommitStates = OldPSODesc.IsComputePipeline; - // We also need to update scissor rect if ScissorEnable state has changed - CommitScissor = OldPSODesc.GraphicsPipeline.RasterizerDesc.ScissorEnable != PSODesc.GraphicsPipeline.RasterizerDesc.ScissorEnable; - } + for (size_t i = 0; i < _countof(m_DynamicGPUDescriptorAllocator); ++i) + { + // Note: as dynamic decriptor suballocations are returned to the global GPU descriptor heap that + // is hosted by the render device, the descriptor allocator can be destroyed before all suballocations + // are actually returned to the global heap. + DEV_CHECK_ERR(m_DynamicGPUDescriptorAllocator[i].GetSuballocationCount() == 0, "All dynamic suballocations must have been released"); + } +} - TDeviceContextBase::SetPipelineState( pPipelineStateD3D12, 0 /*Dummy*/ ); +IMPLEMENT_QUERY_INTERFACE(DeviceContextD3D12Impl, IID_DeviceContextD3D12, TDeviceContextBase) - auto& CmdCtx = GetCmdContext(); - - auto* pd3d12PSO = pPipelineStateD3D12->GetD3D12PipelineState(); - if (PSODesc.IsComputePipeline) - { - CmdCtx.AsComputeContext().SetPipelineState(pd3d12PSO); - } - else - { - auto &GraphicsCtx = CmdCtx.AsGraphicsContext(); - GraphicsCtx.SetPipelineState(pd3d12PSO); +void DeviceContextD3D12Impl::SetPipelineState(IPipelineState* pPipelineState) +{ + auto* pPipelineStateD3D12 = ValidatedCast(pPipelineState); + if (PipelineStateD3D12Impl::IsSameObject(m_pPipelineState, pPipelineStateD3D12)) + return; - auto D3D12Topology = TopologyToD3D12Topology(PSODesc.GraphicsPipeline.PrimitiveTopology); - GraphicsCtx.SetPrimitiveTopology(D3D12Topology); + // Never flush deferred context! + if (!m_bIsDeferred && m_State.NumCommands >= m_NumCommandsToFlush) + { + Flush(true); + } - if(CommitStates) - { - GraphicsCtx.SetStencilRef(m_StencilRef); - GraphicsCtx.SetBlendFactor(m_BlendFactors); - CommitRenderTargets(RESOURCE_STATE_TRANSITION_MODE_VERIFY); - CommitViewports(); - } + const auto& PSODesc = pPipelineStateD3D12->GetDesc(); - if(CommitStates || CommitScissor) - { - CommitScissorRects(GraphicsCtx, PSODesc.GraphicsPipeline.RasterizerDesc.ScissorEnable); - } - } - m_State.pCommittedResourceCache = nullptr; - m_State.bRootViewsCommitted = false; + bool CommitStates = false; + bool CommitScissor = false; + if (!m_pPipelineState) + { + // If no pipeline state is bound, we are working with the fresh command + // list. We have to commit the states set in the context that are not + // committed by the draw command (render targets, viewports, scissor rects, etc.) + CommitStates = true; } - - void DeviceContextD3D12Impl::TransitionShaderResources(IPipelineState* pPipelineState, IShaderResourceBinding* pShaderResourceBinding) + else { - VERIFY_EXPR(pPipelineState != nullptr); - - auto& Ctx = GetCmdContext(); - auto* pPipelineStateD3D12 = ValidatedCast(pPipelineState); - PipelineStateD3D12Impl::CommitAndTransitionResourcesAttribs Attribs; - Attribs.CtxId = m_ContextId; - Attribs.pShaderResourceBinding = pShaderResourceBinding; - Attribs.CommitResources = false; - Attribs.TransitionResources = true; - Attribs.ValidateStates = false; - pPipelineStateD3D12->CommitAndTransitionShaderResources(this, Ctx, Attribs); + const auto& OldPSODesc = m_pPipelineState->GetDesc(); + // Commit all graphics states when switching from compute pipeline + // This is necessary because if the command list had been flushed + // and the first PSO set on the command list was a compute pipeline, + // the states would otherwise never be committed (since m_pPipelineState != nullptr) + CommitStates = OldPSODesc.IsComputePipeline; + // We also need to update scissor rect if ScissorEnable state has changed + CommitScissor = OldPSODesc.GraphicsPipeline.RasterizerDesc.ScissorEnable != PSODesc.GraphicsPipeline.RasterizerDesc.ScissorEnable; } - void DeviceContextD3D12Impl::CommitShaderResources(IShaderResourceBinding* pShaderResourceBinding, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) - { - if (!DeviceContextBase::CommitShaderResources(pShaderResourceBinding, StateTransitionMode, 0 /*Dummy*/)) - return; + TDeviceContextBase::SetPipelineState(pPipelineStateD3D12, 0 /*Dummy*/); - auto& Ctx = GetCmdContext(); - PipelineStateD3D12Impl::CommitAndTransitionResourcesAttribs Attribs; - Attribs.CtxId = m_ContextId; - Attribs.pShaderResourceBinding = pShaderResourceBinding; - Attribs.CommitResources = true; - Attribs.TransitionResources = StateTransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION; - Attribs.ValidateStates = StateTransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY; - m_State.pCommittedResourceCache = m_pPipelineState->CommitAndTransitionShaderResources(this, Ctx, Attribs); - m_State.bRootViewsCommitted = false; - } + auto& CmdCtx = GetCmdContext(); - void DeviceContextD3D12Impl::SetStencilRef(Uint32 StencilRef) + auto* pd3d12PSO = pPipelineStateD3D12->GetD3D12PipelineState(); + if (PSODesc.IsComputePipeline) + { + CmdCtx.AsComputeContext().SetPipelineState(pd3d12PSO); + } + else { - if (TDeviceContextBase::SetStencilRef(StencilRef, 0)) + auto& GraphicsCtx = CmdCtx.AsGraphicsContext(); + GraphicsCtx.SetPipelineState(pd3d12PSO); + + auto D3D12Topology = TopologyToD3D12Topology(PSODesc.GraphicsPipeline.PrimitiveTopology); + GraphicsCtx.SetPrimitiveTopology(D3D12Topology); + + if (CommitStates) { - GetCmdContext().AsGraphicsContext().SetStencilRef( m_StencilRef ); + GraphicsCtx.SetStencilRef(m_StencilRef); + GraphicsCtx.SetBlendFactor(m_BlendFactors); + CommitRenderTargets(RESOURCE_STATE_TRANSITION_MODE_VERIFY); + CommitViewports(); } - } - void DeviceContextD3D12Impl::SetBlendFactors(const float* pBlendFactors) - { - if (TDeviceContextBase::SetBlendFactors(pBlendFactors, 0)) + if (CommitStates || CommitScissor) { - GetCmdContext().AsGraphicsContext().SetBlendFactor( m_BlendFactors ); + CommitScissorRects(GraphicsCtx, PSODesc.GraphicsPipeline.RasterizerDesc.ScissorEnable); } } + m_State.pCommittedResourceCache = nullptr; + m_State.bRootViewsCommitted = false; +} + +void DeviceContextD3D12Impl::TransitionShaderResources(IPipelineState* pPipelineState, IShaderResourceBinding* pShaderResourceBinding) +{ + VERIFY_EXPR(pPipelineState != nullptr); + + auto& Ctx = GetCmdContext(); + + auto* pPipelineStateD3D12 = ValidatedCast(pPipelineState); + + PipelineStateD3D12Impl::CommitAndTransitionResourcesAttribs Attribs; + Attribs.CtxId = m_ContextId; + Attribs.pShaderResourceBinding = pShaderResourceBinding; + Attribs.CommitResources = false; + Attribs.TransitionResources = true; + Attribs.ValidateStates = false; + pPipelineStateD3D12->CommitAndTransitionShaderResources(this, Ctx, Attribs); +} + +void DeviceContextD3D12Impl::CommitShaderResources(IShaderResourceBinding* pShaderResourceBinding, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) +{ + if (!DeviceContextBase::CommitShaderResources(pShaderResourceBinding, StateTransitionMode, 0 /*Dummy*/)) + return; + + auto& Ctx = GetCmdContext(); + + PipelineStateD3D12Impl::CommitAndTransitionResourcesAttribs Attribs; + Attribs.CtxId = m_ContextId; + Attribs.pShaderResourceBinding = pShaderResourceBinding; + Attribs.CommitResources = true; + Attribs.TransitionResources = StateTransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION; + Attribs.ValidateStates = StateTransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY; + m_State.pCommittedResourceCache = m_pPipelineState->CommitAndTransitionShaderResources(this, Ctx, Attribs); + m_State.bRootViewsCommitted = false; +} + +void DeviceContextD3D12Impl::SetStencilRef(Uint32 StencilRef) +{ + if (TDeviceContextBase::SetStencilRef(StencilRef, 0)) + { + GetCmdContext().AsGraphicsContext().SetStencilRef(m_StencilRef); + } +} - void DeviceContextD3D12Impl::CommitD3D12IndexBuffer(GraphicsContext& GraphCtx, VALUE_TYPE IndexType) +void DeviceContextD3D12Impl::SetBlendFactors(const float* pBlendFactors) +{ + if (TDeviceContextBase::SetBlendFactors(pBlendFactors, 0)) { - VERIFY( m_pIndexBuffer != nullptr, "Index buffer is not set up for indexed draw command" ); + GetCmdContext().AsGraphicsContext().SetBlendFactor(m_BlendFactors); + } +} - D3D12_INDEX_BUFFER_VIEW IBView; - IBView.BufferLocation = m_pIndexBuffer->GetGPUAddress(m_ContextId, this) + m_IndexDataStartOffset; - if( IndexType == VT_UINT32 ) - IBView.Format = DXGI_FORMAT_R32_UINT; - else - { - DEV_CHECK_ERR( IndexType == VT_UINT16, "Unsupported index format. Only R16_UINT and R32_UINT are allowed."); - IBView.Format = DXGI_FORMAT_R16_UINT; - } - // Note that for a dynamic buffer, what we use here is the size of the buffer itself, not the upload heap buffer! - IBView.SizeInBytes = m_pIndexBuffer->GetDesc().uiSizeInBytes - m_IndexDataStartOffset; +void DeviceContextD3D12Impl::CommitD3D12IndexBuffer(GraphicsContext& GraphCtx, VALUE_TYPE IndexType) +{ + VERIFY(m_pIndexBuffer != nullptr, "Index buffer is not set up for indexed draw command"); + + D3D12_INDEX_BUFFER_VIEW IBView; + IBView.BufferLocation = m_pIndexBuffer->GetGPUAddress(m_ContextId, this) + m_IndexDataStartOffset; + if (IndexType == VT_UINT32) + IBView.Format = DXGI_FORMAT_R32_UINT; + else + { + DEV_CHECK_ERR(IndexType == VT_UINT16, "Unsupported index format. Only R16_UINT and R32_UINT are allowed."); + IBView.Format = DXGI_FORMAT_R16_UINT; + } + // Note that for a dynamic buffer, what we use here is the size of the buffer itself, not the upload heap buffer! + IBView.SizeInBytes = m_pIndexBuffer->GetDesc().uiSizeInBytes - m_IndexDataStartOffset; - // Device context keeps strong reference to bound index buffer. - // When the buffer is unbound, the reference to the D3D12 resource - // is added to the context. There is no need to add reference here - //auto &GraphicsCtx = GetCmdContext().AsGraphicsContext(); - //auto *pd3d12Resource = pBuffD3D12->GetD3D12Buffer(); - //GraphicsCtx.AddReferencedObject(pd3d12Resource); + // Device context keeps strong reference to bound index buffer. + // When the buffer is unbound, the reference to the D3D12 resource + // is added to the context. There is no need to add reference here + //auto &GraphicsCtx = GetCmdContext().AsGraphicsContext(); + //auto *pd3d12Resource = pBuffD3D12->GetD3D12Buffer(); + //GraphicsCtx.AddReferencedObject(pd3d12Resource); - bool IsDynamic = m_pIndexBuffer->GetDesc().Usage == USAGE_DYNAMIC; + bool IsDynamic = m_pIndexBuffer->GetDesc().Usage == USAGE_DYNAMIC; #ifdef DEVELOPMENT - if(IsDynamic) - m_pIndexBuffer->DvpVerifyDynamicAllocation(this); + if (IsDynamic) + m_pIndexBuffer->DvpVerifyDynamicAllocation(this); #endif - - size_t BuffDataStartByteOffset; - auto *pd3d12Buff = m_pIndexBuffer->GetD3D12Buffer(BuffDataStartByteOffset, this); - - if( IsDynamic || - m_State.CommittedD3D12IndexBuffer != pd3d12Buff || - m_State.CommittedIBFormat != IndexType || - m_State.CommittedD3D12IndexDataStartOffset != m_IndexDataStartOffset + BuffDataStartByteOffset) - { - m_State.CommittedD3D12IndexBuffer = pd3d12Buff; - m_State.CommittedIBFormat = IndexType; - m_State.CommittedD3D12IndexDataStartOffset = m_IndexDataStartOffset + static_cast(BuffDataStartByteOffset); - GraphCtx.SetIndexBuffer( IBView ); - } - - // GPU virtual address of a dynamic index buffer can change every time - // a draw command is invoked - m_State.bCommittedD3D12IBUpToDate = !IsDynamic; + + size_t BuffDataStartByteOffset; + auto* pd3d12Buff = m_pIndexBuffer->GetD3D12Buffer(BuffDataStartByteOffset, this); + + // clang-format off + if (IsDynamic || + m_State.CommittedD3D12IndexBuffer != pd3d12Buff || + m_State.CommittedIBFormat != IndexType || + m_State.CommittedD3D12IndexDataStartOffset != m_IndexDataStartOffset + BuffDataStartByteOffset) + // clang-format on + { + m_State.CommittedD3D12IndexBuffer = pd3d12Buff; + m_State.CommittedIBFormat = IndexType; + m_State.CommittedD3D12IndexDataStartOffset = m_IndexDataStartOffset + static_cast(BuffDataStartByteOffset); + GraphCtx.SetIndexBuffer(IBView); } - void DeviceContextD3D12Impl::CommitD3D12VertexBuffers(GraphicsContext& GraphCtx) + // GPU virtual address of a dynamic index buffer can change every time + // a draw command is invoked + m_State.bCommittedD3D12IBUpToDate = !IsDynamic; +} + +void DeviceContextD3D12Impl::CommitD3D12VertexBuffers(GraphicsContext& GraphCtx) +{ + // Do not initialize array with zeroes for performance reasons + D3D12_VERTEX_BUFFER_VIEW VBViews[MaxBufferSlots]; // = {} + VERIFY(m_NumVertexStreams <= MaxBufferSlots, "Too many buffers are being set"); + DEV_CHECK_ERR(m_NumVertexStreams >= m_pPipelineState->GetNumBufferSlotsUsed(), "Currently bound pipeline state '", m_pPipelineState->GetDesc().Name, "' expects ", m_pPipelineState->GetNumBufferSlotsUsed(), " input buffer slots, but only ", m_NumVertexStreams, " is bound"); + bool DynamicBufferPresent = false; + for (UINT Buff = 0; Buff < m_NumVertexStreams; ++Buff) { - // Do not initialize array with zeroes for performance reasons - D3D12_VERTEX_BUFFER_VIEW VBViews[MaxBufferSlots];// = {} - VERIFY( m_NumVertexStreams <= MaxBufferSlots, "Too many buffers are being set" ); - DEV_CHECK_ERR( m_NumVertexStreams >= m_pPipelineState->GetNumBufferSlotsUsed(), "Currently bound pipeline state '", m_pPipelineState->GetDesc().Name, "' expects ", m_pPipelineState->GetNumBufferSlotsUsed(), " input buffer slots, but only ", m_NumVertexStreams, " is bound"); - bool DynamicBufferPresent = false; - for( UINT Buff = 0; Buff < m_NumVertexStreams; ++Buff ) + auto& CurrStream = m_VertexStreams[Buff]; + auto& VBView = VBViews[Buff]; + if (auto* pBufferD3D12 = CurrStream.pBuffer.RawPtr()) { - auto& CurrStream = m_VertexStreams[Buff]; - auto& VBView = VBViews[Buff]; - if (auto* pBufferD3D12 = CurrStream.pBuffer.RawPtr()) + if (pBufferD3D12->GetDesc().Usage == USAGE_DYNAMIC) { - if (pBufferD3D12->GetDesc().Usage == USAGE_DYNAMIC) - { - DynamicBufferPresent = true; + DynamicBufferPresent = true; #ifdef DEVELOPMENT - pBufferD3D12->DvpVerifyDynamicAllocation(this); + pBufferD3D12->DvpVerifyDynamicAllocation(this); #endif - } + } - // Device context keeps strong references to all vertex buffers. - // When a buffer is unbound, a reference to D3D12 resource is added to the context, - // so there is no need to reference the resource here - //GraphicsCtx.AddReferencedObject(pd3d12Resource); + // Device context keeps strong references to all vertex buffers. + // When a buffer is unbound, a reference to D3D12 resource is added to the context, + // so there is no need to reference the resource here + //GraphicsCtx.AddReferencedObject(pd3d12Resource); - VBView.BufferLocation = pBufferD3D12->GetGPUAddress(m_ContextId, this) + CurrStream.Offset; - VBView.StrideInBytes = m_pPipelineState->GetBufferStride(Buff); - // Note that for a dynamic buffer, what we use here is the size of the buffer itself, not the upload heap buffer! - VBView.SizeInBytes = pBufferD3D12->GetDesc().uiSizeInBytes - CurrStream.Offset; - } - else - { - VBView = D3D12_VERTEX_BUFFER_VIEW{}; - } + VBView.BufferLocation = pBufferD3D12->GetGPUAddress(m_ContextId, this) + CurrStream.Offset; + VBView.StrideInBytes = m_pPipelineState->GetBufferStride(Buff); + // Note that for a dynamic buffer, what we use here is the size of the buffer itself, not the upload heap buffer! + VBView.SizeInBytes = pBufferD3D12->GetDesc().uiSizeInBytes - CurrStream.Offset; + } + else + { + VBView = D3D12_VERTEX_BUFFER_VIEW{}; } + } - GraphCtx.FlushResourceBarriers(); - GraphCtx.SetVertexBuffers( 0, m_NumVertexStreams, VBViews ); + GraphCtx.FlushResourceBarriers(); + GraphCtx.SetVertexBuffers(0, m_NumVertexStreams, VBViews); - // GPU virtual address of a dynamic vertex buffer can change every time - // a draw command is invoked - m_State.bCommittedD3D12VBsUpToDate = !DynamicBufferPresent; - } + // GPU virtual address of a dynamic vertex buffer can change every time + // a draw command is invoked + m_State.bCommittedD3D12VBsUpToDate = !DynamicBufferPresent; +} - void DeviceContextD3D12Impl::PrepareForDraw(GraphicsContext& GraphCtx, DRAW_FLAGS Flags) - { +void DeviceContextD3D12Impl::PrepareForDraw(GraphicsContext& GraphCtx, DRAW_FLAGS Flags) +{ #ifdef DEVELOPMENT - if ((Flags & DRAW_FLAG_VERIFY_RENDER_TARGETS) != 0) - DvpVerifyRenderTargets(); + if ((Flags & DRAW_FLAG_VERIFY_RENDER_TARGETS) != 0) + DvpVerifyRenderTargets(); #endif - if (!m_State.bCommittedD3D12VBsUpToDate && m_pPipelineState->GetNumBufferSlotsUsed() > 0) - { - CommitD3D12VertexBuffers(GraphCtx); - } + if (!m_State.bCommittedD3D12VBsUpToDate && m_pPipelineState->GetNumBufferSlotsUsed() > 0) + { + CommitD3D12VertexBuffers(GraphCtx); + } #ifdef DEVELOPMENT - if ((Flags & DRAW_FLAG_VERIFY_STATES) != 0) + if ((Flags & DRAW_FLAG_VERIFY_STATES) != 0) + { + for (Uint32 Buff = 0; Buff < m_NumVertexStreams; ++Buff) { - for( Uint32 Buff = 0; Buff < m_NumVertexStreams; ++Buff ) + const auto& CurrStream = m_VertexStreams[Buff]; + const auto* pBufferD3D12 = CurrStream.pBuffer.RawPtr(); + if (pBufferD3D12 != nullptr) { - const auto& CurrStream = m_VertexStreams[Buff]; - const auto* pBufferD3D12 = CurrStream.pBuffer.RawPtr(); - if (pBufferD3D12 != nullptr) - { - DvpVerifyBufferState(*pBufferD3D12, RESOURCE_STATE_VERTEX_BUFFER, "Using vertex buffers (DeviceContextD3D12Impl::Draw())"); - } + DvpVerifyBufferState(*pBufferD3D12, RESOURCE_STATE_VERTEX_BUFFER, "Using vertex buffers (DeviceContextD3D12Impl::Draw())"); } } + } #endif - GraphCtx.SetRootSignature( m_pPipelineState->GetD3D12RootSignature() ); + GraphCtx.SetRootSignature(m_pPipelineState->GetD3D12RootSignature()); - if (m_State.pCommittedResourceCache != nullptr) + if (m_State.pCommittedResourceCache != nullptr) + { + if (m_State.pCommittedResourceCache->GetNumDynamicCBsBound() > 0) { - if (m_State.pCommittedResourceCache->GetNumDynamicCBsBound() > 0) + if (!m_State.bRootViewsCommitted || (Flags & DRAW_FLAG_DYNAMIC_RESOURCE_BUFFERS_INTACT) == 0) { - if (!m_State.bRootViewsCommitted || (Flags & DRAW_FLAG_DYNAMIC_RESOURCE_BUFFERS_INTACT) == 0) - { - // Only process dynamic buffers. Non-dynamic buffers are committed by CommitShaderResources - m_pPipelineState->GetRootSignature(). - CommitRootViews(*m_State.pCommittedResourceCache, - GraphCtx, - false, // IsCompute - m_ContextId, - this, - true, // CommitViews - true, // ProcessDynamicBuffers - false, // ProcessNonDynamicBuffers - false, // TransitionStates - false // ValidateStates + // Only process dynamic buffers. Non-dynamic buffers are committed by CommitShaderResources + m_pPipelineState->GetRootSignature() + .CommitRootViews(*m_State.pCommittedResourceCache, + GraphCtx, + false, // IsCompute + m_ContextId, + this, + true, // CommitViews + true, // ProcessDynamicBuffers + false, // ProcessNonDynamicBuffers + false, // TransitionStates + false // ValidateStates ); - m_State.bRootViewsCommitted = true; - } + m_State.bRootViewsCommitted = true; } } + } #ifdef DEVELOPMENT - else - { - if (m_pPipelineState->ContainsShaderResources()) - LOG_ERROR_MESSAGE("Pipeline state '", m_pPipelineState->GetDesc().Name, "' contains shader resources, but IDeviceContext::CommitShaderResources() was not called with non-null SRB" ); - } -#endif + else + { + if (m_pPipelineState->ContainsShaderResources()) + LOG_ERROR_MESSAGE("Pipeline state '", m_pPipelineState->GetDesc().Name, "' contains shader resources, but IDeviceContext::CommitShaderResources() was not called with non-null SRB"); } +#endif +} - void DeviceContextD3D12Impl::PrepareForIndexedDraw(GraphicsContext& GraphCtx, DRAW_FLAGS Flags, VALUE_TYPE IndexType) +void DeviceContextD3D12Impl::PrepareForIndexedDraw(GraphicsContext& GraphCtx, DRAW_FLAGS Flags, VALUE_TYPE IndexType) +{ + PrepareForDraw(GraphCtx, Flags); + if (m_State.CommittedIBFormat != IndexType) + m_State.bCommittedD3D12IBUpToDate = false; + if (!m_State.bCommittedD3D12IBUpToDate) { - PrepareForDraw(GraphCtx, Flags); - if (m_State.CommittedIBFormat != IndexType) - m_State.bCommittedD3D12IBUpToDate = false; - if (!m_State.bCommittedD3D12IBUpToDate) - { - CommitD3D12IndexBuffer(GraphCtx, IndexType); - } + CommitD3D12IndexBuffer(GraphCtx, IndexType); + } #ifdef DEVELOPMENT - if ((Flags & DRAW_FLAG_VERIFY_STATES) != 0) - { - DvpVerifyBufferState(*m_pIndexBuffer, RESOURCE_STATE_INDEX_BUFFER, "Indexed draw (DeviceContextD3D12Impl::Draw())"); - } -#endif + if ((Flags & DRAW_FLAG_VERIFY_STATES) != 0) + { + DvpVerifyBufferState(*m_pIndexBuffer, RESOURCE_STATE_INDEX_BUFFER, "Indexed draw (DeviceContextD3D12Impl::Draw())"); } +#endif +} - void DeviceContextD3D12Impl::Draw(const DrawAttribs& Attribs) - { - if (!DvpVerifyDrawArguments(Attribs)) - return; +void DeviceContextD3D12Impl::Draw(const DrawAttribs& Attribs) +{ + if (!DvpVerifyDrawArguments(Attribs)) + return; - auto& GraphCtx = GetCmdContext().AsGraphicsContext(); - PrepareForDraw(GraphCtx, Attribs.Flags); - GraphCtx.Draw(Attribs.NumVertices, Attribs.NumInstances, Attribs.StartVertexLocation, Attribs.FirstInstanceLocation); - ++m_State.NumCommands; - } + auto& GraphCtx = GetCmdContext().AsGraphicsContext(); + PrepareForDraw(GraphCtx, Attribs.Flags); + GraphCtx.Draw(Attribs.NumVertices, Attribs.NumInstances, Attribs.StartVertexLocation, Attribs.FirstInstanceLocation); + ++m_State.NumCommands; +} - void DeviceContextD3D12Impl::DrawIndexed(const DrawIndexedAttribs& Attribs) - { - if (!DvpVerifyDrawIndexedArguments(Attribs)) - return; +void DeviceContextD3D12Impl::DrawIndexed(const DrawIndexedAttribs& Attribs) +{ + if (!DvpVerifyDrawIndexedArguments(Attribs)) + return; - auto& GraphCtx = GetCmdContext().AsGraphicsContext(); - PrepareForIndexedDraw(GraphCtx, Attribs.Flags, Attribs.IndexType); - GraphCtx.DrawIndexed(Attribs.NumIndices, Attribs.NumInstances, Attribs.FirstIndexLocation, Attribs.BaseVertex, Attribs.FirstInstanceLocation); - ++m_State.NumCommands; - } + auto& GraphCtx = GetCmdContext().AsGraphicsContext(); + PrepareForIndexedDraw(GraphCtx, Attribs.Flags, Attribs.IndexType); + GraphCtx.DrawIndexed(Attribs.NumIndices, Attribs.NumInstances, Attribs.FirstIndexLocation, Attribs.BaseVertex, Attribs.FirstInstanceLocation); + ++m_State.NumCommands; +} - void DeviceContextD3D12Impl::PrepareDrawIndirectBuffer(GraphicsContext& GraphCtx, - IBuffer* pAttribsBuffer, - RESOURCE_STATE_TRANSITION_MODE BufferStateTransitionMode, - ID3D12Resource*& pd3d12ArgsBuff, - size_t& BuffDataStartByteOffset) - { - DEV_CHECK_ERR(pAttribsBuffer != nullptr, "Indirect draw attribs buffer must not be null"); - - auto* pIndirectDrawAttribsD3D12 = ValidatedCast(pAttribsBuffer); +void DeviceContextD3D12Impl::PrepareDrawIndirectBuffer(GraphicsContext& GraphCtx, + IBuffer* pAttribsBuffer, + RESOURCE_STATE_TRANSITION_MODE BufferStateTransitionMode, + ID3D12Resource*& pd3d12ArgsBuff, + size_t& BuffDataStartByteOffset) +{ + DEV_CHECK_ERR(pAttribsBuffer != nullptr, "Indirect draw attribs buffer must not be null"); + + auto* pIndirectDrawAttribsD3D12 = ValidatedCast(pAttribsBuffer); #ifdef DEVELOPMENT - if (pIndirectDrawAttribsD3D12->GetDesc().Usage == USAGE_DYNAMIC) - pIndirectDrawAttribsD3D12->DvpVerifyDynamicAllocation(this); + if (pIndirectDrawAttribsD3D12->GetDesc().Usage == USAGE_DYNAMIC) + pIndirectDrawAttribsD3D12->DvpVerifyDynamicAllocation(this); #endif - TransitionOrVerifyBufferState(GraphCtx, *pIndirectDrawAttribsD3D12, BufferStateTransitionMode, - RESOURCE_STATE_INDIRECT_ARGUMENT, - "Indirect draw (DeviceContextD3D12Impl::PrepareDrawIndirectBuffer)"); + TransitionOrVerifyBufferState(GraphCtx, *pIndirectDrawAttribsD3D12, BufferStateTransitionMode, + RESOURCE_STATE_INDIRECT_ARGUMENT, + "Indirect draw (DeviceContextD3D12Impl::PrepareDrawIndirectBuffer)"); - pd3d12ArgsBuff = pIndirectDrawAttribsD3D12->GetD3D12Buffer(BuffDataStartByteOffset, this); - } + pd3d12ArgsBuff = pIndirectDrawAttribsD3D12->GetD3D12Buffer(BuffDataStartByteOffset, this); +} - void DeviceContextD3D12Impl::DrawIndirect(const DrawIndirectAttribs& Attribs, IBuffer* pAttribsBuffer) - { - if (!DvpVerifyDrawIndirectArguments(Attribs, pAttribsBuffer)) - return; +void DeviceContextD3D12Impl::DrawIndirect(const DrawIndirectAttribs& Attribs, IBuffer* pAttribsBuffer) +{ + if (!DvpVerifyDrawIndirectArguments(Attribs, pAttribsBuffer)) + return; - auto& GraphCtx = GetCmdContext().AsGraphicsContext(); - PrepareForDraw(GraphCtx, Attribs.Flags); + auto& GraphCtx = GetCmdContext().AsGraphicsContext(); + PrepareForDraw(GraphCtx, Attribs.Flags); - ID3D12Resource* pd3d12ArgsBuff; - size_t BuffDataStartByteOffset; - PrepareDrawIndirectBuffer(GraphCtx, pAttribsBuffer, Attribs.IndirectAttribsBufferStateTransitionMode, pd3d12ArgsBuff, BuffDataStartByteOffset); + ID3D12Resource* pd3d12ArgsBuff; + size_t BuffDataStartByteOffset; + PrepareDrawIndirectBuffer(GraphCtx, pAttribsBuffer, Attribs.IndirectAttribsBufferStateTransitionMode, pd3d12ArgsBuff, BuffDataStartByteOffset); - GraphCtx.ExecuteIndirect(m_pDrawIndirectSignature, pd3d12ArgsBuff, Attribs.IndirectDrawArgsOffset + BuffDataStartByteOffset); - ++m_State.NumCommands; - } + GraphCtx.ExecuteIndirect(m_pDrawIndirectSignature, pd3d12ArgsBuff, Attribs.IndirectDrawArgsOffset + BuffDataStartByteOffset); + ++m_State.NumCommands; +} - void DeviceContextD3D12Impl::DrawIndexedIndirect(const DrawIndexedIndirectAttribs& Attribs, IBuffer* pAttribsBuffer) - { - if (!DvpVerifyDrawIndexedIndirectArguments(Attribs, pAttribsBuffer)) - return; +void DeviceContextD3D12Impl::DrawIndexedIndirect(const DrawIndexedIndirectAttribs& Attribs, IBuffer* pAttribsBuffer) +{ + if (!DvpVerifyDrawIndexedIndirectArguments(Attribs, pAttribsBuffer)) + return; - auto& GraphCtx = GetCmdContext().AsGraphicsContext(); - PrepareForIndexedDraw(GraphCtx, Attribs.Flags, Attribs.IndexType); + auto& GraphCtx = GetCmdContext().AsGraphicsContext(); + PrepareForIndexedDraw(GraphCtx, Attribs.Flags, Attribs.IndexType); - ID3D12Resource* pd3d12ArgsBuff; - size_t BuffDataStartByteOffset; - PrepareDrawIndirectBuffer(GraphCtx, pAttribsBuffer, Attribs.IndirectAttribsBufferStateTransitionMode, pd3d12ArgsBuff, BuffDataStartByteOffset); + ID3D12Resource* pd3d12ArgsBuff; + size_t BuffDataStartByteOffset; + PrepareDrawIndirectBuffer(GraphCtx, pAttribsBuffer, Attribs.IndirectAttribsBufferStateTransitionMode, pd3d12ArgsBuff, BuffDataStartByteOffset); - GraphCtx.ExecuteIndirect(m_pDrawIndexedIndirectSignature, pd3d12ArgsBuff, Attribs.IndirectDrawArgsOffset + BuffDataStartByteOffset); - ++m_State.NumCommands; - } + GraphCtx.ExecuteIndirect(m_pDrawIndexedIndirectSignature, pd3d12ArgsBuff, Attribs.IndirectDrawArgsOffset + BuffDataStartByteOffset); + ++m_State.NumCommands; +} - void DeviceContextD3D12Impl::PrepareForDispatchCompute(ComputeContext& ComputeCtx) +void DeviceContextD3D12Impl::PrepareForDispatchCompute(ComputeContext& ComputeCtx) +{ + ComputeCtx.SetRootSignature(m_pPipelineState->GetD3D12RootSignature()); + if (m_State.pCommittedResourceCache != nullptr) { - ComputeCtx.SetRootSignature(m_pPipelineState->GetD3D12RootSignature()); - if (m_State.pCommittedResourceCache != nullptr) - { - if (m_State.pCommittedResourceCache->GetNumDynamicCBsBound() > 0) - { - // Only process dynamic buffers. Non-dynamic buffers are committed by CommitShaderResources - m_pPipelineState->GetRootSignature(). - CommitRootViews(*m_State.pCommittedResourceCache, - ComputeCtx, - true, // IsCompute - m_ContextId, - this, - true, // CommitViews - true, // ProcessDynamicBuffers - false, // ProcessNonDynamicBuffers - false, // TransitionStates - false // ValidateStates - ); - } + if (m_State.pCommittedResourceCache->GetNumDynamicCBsBound() > 0) + { + // Only process dynamic buffers. Non-dynamic buffers are committed by CommitShaderResources + m_pPipelineState->GetRootSignature() + .CommitRootViews(*m_State.pCommittedResourceCache, + ComputeCtx, + true, // IsCompute + m_ContextId, + this, + true, // CommitViews + true, // ProcessDynamicBuffers + false, // ProcessNonDynamicBuffers + false, // TransitionStates + false // ValidateStates + ); } + } #ifdef DEVELOPMENT - else - { - if (m_pPipelineState->ContainsShaderResources()) - LOG_ERROR_MESSAGE("Pipeline state '", m_pPipelineState->GetDesc().Name, "' contains shader resources, but IDeviceContext::CommitShaderResources() was not called with non-null SRB" ); - } -#endif + else + { + if (m_pPipelineState->ContainsShaderResources()) + LOG_ERROR_MESSAGE("Pipeline state '", m_pPipelineState->GetDesc().Name, "' contains shader resources, but IDeviceContext::CommitShaderResources() was not called with non-null SRB"); } +#endif +} - void DeviceContextD3D12Impl::DispatchCompute(const DispatchComputeAttribs& Attribs) - { - if (!DvpVerifyDispatchArguments(Attribs)) - return; +void DeviceContextD3D12Impl::DispatchCompute(const DispatchComputeAttribs& Attribs) +{ + if (!DvpVerifyDispatchArguments(Attribs)) + return; - auto& ComputeCtx = GetCmdContext().AsComputeContext(); - PrepareForDispatchCompute(ComputeCtx); - ComputeCtx.Dispatch(Attribs.ThreadGroupCountX, Attribs.ThreadGroupCountY, Attribs.ThreadGroupCountZ); - ++m_State.NumCommands; - } + auto& ComputeCtx = GetCmdContext().AsComputeContext(); + PrepareForDispatchCompute(ComputeCtx); + ComputeCtx.Dispatch(Attribs.ThreadGroupCountX, Attribs.ThreadGroupCountY, Attribs.ThreadGroupCountZ); + ++m_State.NumCommands; +} - void DeviceContextD3D12Impl::DispatchComputeIndirect(const DispatchComputeIndirectAttribs& Attribs, IBuffer* pAttribsBuffer) - { - if (!DvpVerifyDispatchIndirectArguments(Attribs, pAttribsBuffer)) - return; +void DeviceContextD3D12Impl::DispatchComputeIndirect(const DispatchComputeIndirectAttribs& Attribs, IBuffer* pAttribsBuffer) +{ + if (!DvpVerifyDispatchIndirectArguments(Attribs, pAttribsBuffer)) + return; - auto& ComputeCtx = GetCmdContext().AsComputeContext(); - PrepareForDispatchCompute(ComputeCtx); - - auto* pBufferD3D12 = ValidatedCast(pAttribsBuffer); + auto& ComputeCtx = GetCmdContext().AsComputeContext(); + PrepareForDispatchCompute(ComputeCtx); + + auto* pBufferD3D12 = ValidatedCast(pAttribsBuffer); #ifdef DEVELOPMENT - if(pBufferD3D12->GetDesc().Usage == USAGE_DYNAMIC) - pBufferD3D12->DvpVerifyDynamicAllocation(this); + if (pBufferD3D12->GetDesc().Usage == USAGE_DYNAMIC) + pBufferD3D12->DvpVerifyDynamicAllocation(this); #endif - TransitionOrVerifyBufferState(ComputeCtx, *pBufferD3D12, Attribs.IndirectAttribsBufferStateTransitionMode, - RESOURCE_STATE_INDIRECT_ARGUMENT, "Indirect dispatch (DeviceContextD3D12Impl::DispatchComputeIndirect)"); - size_t BuffDataStartByteOffset; - ID3D12Resource* pd3d12ArgsBuff = pBufferD3D12->GetD3D12Buffer(BuffDataStartByteOffset, this); - ComputeCtx.ExecuteIndirect(m_pDispatchIndirectSignature, pd3d12ArgsBuff, Attribs.DispatchArgsByteOffset + BuffDataStartByteOffset); - ++m_State.NumCommands; - } + TransitionOrVerifyBufferState(ComputeCtx, *pBufferD3D12, Attribs.IndirectAttribsBufferStateTransitionMode, + RESOURCE_STATE_INDIRECT_ARGUMENT, "Indirect dispatch (DeviceContextD3D12Impl::DispatchComputeIndirect)"); + size_t BuffDataStartByteOffset; + ID3D12Resource* pd3d12ArgsBuff = pBufferD3D12->GetD3D12Buffer(BuffDataStartByteOffset, this); + ComputeCtx.ExecuteIndirect(m_pDispatchIndirectSignature, pd3d12ArgsBuff, Attribs.DispatchArgsByteOffset + BuffDataStartByteOffset); + ++m_State.NumCommands; +} - void DeviceContextD3D12Impl::ClearDepthStencil(ITextureView* pView, - CLEAR_DEPTH_STENCIL_FLAGS ClearFlags, - float fDepth, - Uint8 Stencil, - RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) +void DeviceContextD3D12Impl::ClearDepthStencil(ITextureView* pView, + CLEAR_DEPTH_STENCIL_FLAGS ClearFlags, + float fDepth, + Uint8 Stencil, + RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) +{ + ITextureViewD3D12* pViewD3D12 = nullptr; + if (pView != nullptr) { - ITextureViewD3D12* pViewD3D12 = nullptr; - if (pView != nullptr) - { - pViewD3D12 = ValidatedCast(pView); + pViewD3D12 = ValidatedCast(pView); #ifdef _DEBUG - const auto& ViewDesc = pViewD3D12->GetDesc(); - VERIFY( ViewDesc.ViewType == TEXTURE_VIEW_DEPTH_STENCIL, "Incorrect view type: depth stencil is expected" ); + const auto& ViewDesc = pViewD3D12->GetDesc(); + VERIFY(ViewDesc.ViewType == TEXTURE_VIEW_DEPTH_STENCIL, "Incorrect view type: depth stencil is expected"); #endif - } - else + } + else + { + if (m_pSwapChain) { - if (m_pSwapChain) - { - pViewD3D12 = ValidatedCast(m_pSwapChain.RawPtr()->GetDepthBufferDSV()); - if (pViewD3D12 == nullptr) - { - LOG_WARNING_MESSAGE("Depth buffer is not initialized in the swap chain. Clear operation will be ignored."); - return; - } - } - else + pViewD3D12 = ValidatedCast(m_pSwapChain.RawPtr()->GetDepthBufferDSV()); + if (pViewD3D12 == nullptr) { - LOG_ERROR("Failed to clear default depth stencil buffer: swap chain is not initialized in the device context"); + LOG_WARNING_MESSAGE("Depth buffer is not initialized in the swap chain. Clear operation will be ignored."); return; } } + else + { + LOG_ERROR("Failed to clear default depth stencil buffer: swap chain is not initialized in the device context"); + return; + } + } - auto* pTextureD3D12 = ValidatedCast( pViewD3D12->GetTexture() ); - auto& CmdCtx = GetCmdContext(); - TransitionOrVerifyTextureState(CmdCtx, *pTextureD3D12, StateTransitionMode, RESOURCE_STATE_DEPTH_WRITE, "Clearing depth-stencil buffer (DeviceContextD3D12Impl::ClearDepthStencil)"); + auto* pTextureD3D12 = ValidatedCast(pViewD3D12->GetTexture()); + auto& CmdCtx = GetCmdContext(); + TransitionOrVerifyTextureState(CmdCtx, *pTextureD3D12, StateTransitionMode, RESOURCE_STATE_DEPTH_WRITE, "Clearing depth-stencil buffer (DeviceContextD3D12Impl::ClearDepthStencil)"); - D3D12_CLEAR_FLAGS d3d12ClearFlags = (D3D12_CLEAR_FLAGS)0; - if( ClearFlags & CLEAR_DEPTH_FLAG ) d3d12ClearFlags |= D3D12_CLEAR_FLAG_DEPTH; - if( ClearFlags & CLEAR_STENCIL_FLAG ) d3d12ClearFlags |= D3D12_CLEAR_FLAG_STENCIL; + D3D12_CLEAR_FLAGS d3d12ClearFlags = (D3D12_CLEAR_FLAGS)0; + if (ClearFlags & CLEAR_DEPTH_FLAG) d3d12ClearFlags |= D3D12_CLEAR_FLAG_DEPTH; + if (ClearFlags & CLEAR_STENCIL_FLAG) d3d12ClearFlags |= D3D12_CLEAR_FLAG_STENCIL; - // The full extent of the resource view is always cleared. - // Viewport and scissor settings are not applied?? - GetCmdContext().AsGraphicsContext().ClearDepthStencil( pViewD3D12->GetCPUDescriptorHandle(), d3d12ClearFlags, fDepth, Stencil ); - ++m_State.NumCommands; - } + // The full extent of the resource view is always cleared. + // Viewport and scissor settings are not applied?? + GetCmdContext().AsGraphicsContext().ClearDepthStencil(pViewD3D12->GetCPUDescriptorHandle(), d3d12ClearFlags, fDepth, Stencil); + ++m_State.NumCommands; +} - void DeviceContextD3D12Impl::ClearRenderTarget( ITextureView* pView, const float* RGBA, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode ) +void DeviceContextD3D12Impl::ClearRenderTarget(ITextureView* pView, const float* RGBA, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) +{ + ITextureViewD3D12* pViewD3D12 = nullptr; + if (pView != nullptr) { - ITextureViewD3D12* pViewD3D12 = nullptr; - if (pView != nullptr) - { #ifdef _DEBUG - const auto& ViewDesc = pView->GetDesc(); - VERIFY( ViewDesc.ViewType == TEXTURE_VIEW_RENDER_TARGET, "Incorrect view type: render target is expected" ); + const auto& ViewDesc = pView->GetDesc(); + VERIFY(ViewDesc.ViewType == TEXTURE_VIEW_RENDER_TARGET, "Incorrect view type: render target is expected"); #endif - pViewD3D12 = ValidatedCast(pView); + pViewD3D12 = ValidatedCast(pView); + } + else + { + if (m_pSwapChain) + { + pViewD3D12 = ValidatedCast(m_pSwapChain.RawPtr()->GetCurrentBackBufferRTV()); } else { - if (m_pSwapChain) - { - pViewD3D12 = ValidatedCast(m_pSwapChain.RawPtr()->GetCurrentBackBufferRTV()); - } - else - { - LOG_ERROR("Failed to clear default render target: swap chain is not initialized in the device context"); - return; - } + LOG_ERROR("Failed to clear default render target: swap chain is not initialized in the device context"); + return; } + } - static constexpr float Zero[4] = { 0.f, 0.f, 0.f, 0.f }; - if( RGBA == nullptr ) - RGBA = Zero; + static constexpr float Zero[4] = {0.f, 0.f, 0.f, 0.f}; + if (RGBA == nullptr) + RGBA = Zero; - auto* pTextureD3D12 = ValidatedCast( pViewD3D12->GetTexture() ); - auto& CmdCtx = GetCmdContext(); - TransitionOrVerifyTextureState(CmdCtx, *pTextureD3D12, StateTransitionMode, RESOURCE_STATE_RENDER_TARGET, "Clearing render target (DeviceContextD3D12Impl::ClearRenderTarget)"); + auto* pTextureD3D12 = ValidatedCast(pViewD3D12->GetTexture()); + auto& CmdCtx = GetCmdContext(); + TransitionOrVerifyTextureState(CmdCtx, *pTextureD3D12, StateTransitionMode, RESOURCE_STATE_RENDER_TARGET, "Clearing render target (DeviceContextD3D12Impl::ClearRenderTarget)"); - // The full extent of the resource view is always cleared. - // Viewport and scissor settings are not applied?? - CmdCtx.AsGraphicsContext().ClearRenderTarget( pViewD3D12->GetCPUDescriptorHandle(), RGBA ); - ++m_State.NumCommands; - } + // The full extent of the resource view is always cleared. + // Viewport and scissor settings are not applied?? + CmdCtx.AsGraphicsContext().ClearRenderTarget(pViewD3D12->GetCPUDescriptorHandle(), RGBA); + ++m_State.NumCommands; +} - void DeviceContextD3D12Impl::RequestCommandContext(RenderDeviceD3D12Impl* pDeviceD3D12Impl) - { - m_CurrCmdCtx = pDeviceD3D12Impl->AllocateCommandContext(); - m_CurrCmdCtx->SetDynamicGPUDescriptorAllocators(m_DynamicGPUDescriptorAllocator); - } +void DeviceContextD3D12Impl::RequestCommandContext(RenderDeviceD3D12Impl* pDeviceD3D12Impl) +{ + m_CurrCmdCtx = pDeviceD3D12Impl->AllocateCommandContext(); + m_CurrCmdCtx->SetDynamicGPUDescriptorAllocators(m_DynamicGPUDescriptorAllocator); +} - void DeviceContextD3D12Impl::Flush(bool RequestNewCmdCtx) +void DeviceContextD3D12Impl::Flush(bool RequestNewCmdCtx) +{ + if (m_CurrCmdCtx) { - if( m_CurrCmdCtx ) - { - VERIFY(!m_bIsDeferred, "Deferred contexts cannot execute command lists directly"); - if (m_State.NumCommands != 0) - { - m_CurrCmdCtx->FlushResourceBarriers(); - m_pDevice->CloseAndExecuteCommandContext(m_CommandQueueId, std::move(m_CurrCmdCtx), true, &m_PendingFences); - m_PendingFences.clear(); - } - else - m_pDevice->DisposeCommandContext(std::move(m_CurrCmdCtx)); - } - - // If there is no command list to submit, but there are pending fences, we need to signal them now - if (!m_PendingFences.empty()) + VERIFY(!m_bIsDeferred, "Deferred contexts cannot execute command lists directly"); + if (m_State.NumCommands != 0) { - m_pDevice->SignalFences(m_CommandQueueId, m_PendingFences); + m_CurrCmdCtx->FlushResourceBarriers(); + m_pDevice->CloseAndExecuteCommandContext(m_CommandQueueId, std::move(m_CurrCmdCtx), true, &m_PendingFences); m_PendingFences.clear(); } - - if(RequestNewCmdCtx) - RequestCommandContext(m_pDevice); - - m_State = State{}; - - // Setting pipeline state to null makes sure that render targets and other - // states will be restored in the command list next time a PSO is bound. - m_pPipelineState = nullptr; + else + m_pDevice->DisposeCommandContext(std::move(m_CurrCmdCtx)); } - void DeviceContextD3D12Impl::Flush() + // If there is no command list to submit, but there are pending fences, we need to signal them now + if (!m_PendingFences.empty()) { - if (m_bIsDeferred) - { - LOG_ERROR_MESSAGE("Flush() should only be called for immediate contexts"); - return; - } - - Flush(true); + m_pDevice->SignalFences(m_CommandQueueId, m_PendingFences); + m_PendingFences.clear(); } - void DeviceContextD3D12Impl::FinishFrame() - { -#ifdef _DEBUG - for(const auto& MappedBuffIt : m_DbgMappedBuffers) - { - const auto& BuffDesc = MappedBuffIt.first->GetDesc(); - if (BuffDesc.Usage == USAGE_DYNAMIC) - { - LOG_WARNING_MESSAGE("Dynamic buffer '", BuffDesc.Name, "' is still mapped when finishing the frame. The contents of the buffer and mapped address will become invalid"); - } - } -#endif - if (GetNumCommandsInCtx() != 0) - { - LOG_ERROR_MESSAGE(m_bIsDeferred ? - "There are outstanding commands in deferred device context #", m_ContextId, " when finishing the frame. This is an error and may cause unpredicted behaviour. Close all deferred contexts and execute them before finishing the frame" : - "There are outstanding commands in the immediate device context when finishing the frame. This is an error and may cause unpredicted behaviour. Call Flush() to submit all commands for execution before finishing the frame"); - } + if (RequestNewCmdCtx) + RequestCommandContext(m_pDevice); - VERIFY_EXPR(m_bIsDeferred || m_SubmittedBuffersCmdQueueMask == (Uint64{1}<GetDesc(); + if (BuffDesc.Usage == USAGE_DYNAMIC) { - auto& CmdCtx = GetCmdContext(); - TransitionOrVerifyBufferState(CmdCtx, *m_pIndexBuffer, StateTransitionMode, RESOURCE_STATE_INDEX_BUFFER, "Setting index buffer (DeviceContextD3D12Impl::SetIndexBuffer)"); + LOG_WARNING_MESSAGE("Dynamic buffer '", BuffDesc.Name, + "' is still mapped when finishing the frame. The contents of the buffer and " + "mapped address will become invalid"); } - m_State.bCommittedD3D12IBUpToDate = false; } - - void DeviceContextD3D12Impl::CommitViewports() +#endif + if (GetNumCommandsInCtx() != 0) { - static_assert(MaxViewports >= D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE, "MaxViewports constant must be greater than D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE"); - D3D12_VIEWPORT d3d12Viewports[MaxViewports]; // Do not waste time initializing array to zero - - for( Uint32 vp = 0; vp < m_NumViewports; ++vp ) + if (m_bIsDeferred) + { + LOG_ERROR_MESSAGE("There are outstanding commands in deferred device context #", + m_ContextId, + " when finishing the frame. This is an error and may cause unpredicted behaviour. " + "Close all deferred contexts and execute them before finishing the frame"); + } + else { - d3d12Viewports[vp].TopLeftX = m_Viewports[vp].TopLeftX; - d3d12Viewports[vp].TopLeftY = m_Viewports[vp].TopLeftY; - d3d12Viewports[vp].Width = m_Viewports[vp].Width; - d3d12Viewports[vp].Height = m_Viewports[vp].Height; - d3d12Viewports[vp].MinDepth = m_Viewports[vp].MinDepth; - d3d12Viewports[vp].MaxDepth = m_Viewports[vp].MaxDepth; + LOG_ERROR_MESSAGE("There are outstanding commands in the immediate device context when finishing the frame. " + "This is an error and may cause unpredicted behaviour. Call Flush() to submit all commands" + " for execution before finishing the frame"); } - // All viewports must be set atomically as one operation. - // Any viewports not defined by the call are disabled. - GetCmdContext().AsGraphicsContext().SetViewports( m_NumViewports, d3d12Viewports ); } - void DeviceContextD3D12Impl::SetViewports( Uint32 NumViewports, const Viewport* pViewports, Uint32 RTWidth, Uint32 RTHeight ) + VERIFY_EXPR(m_bIsDeferred || m_SubmittedBuffersCmdQueueMask == (Uint64{1} << m_CommandQueueId)); + + // Released pages are returned to the global dynamic memory manager hosted by render device. + m_DynamicHeap.ReleaseAllocatedPages(m_SubmittedBuffersCmdQueueMask); + + // Dynamic GPU descriptor allocations are returned to the global GPU descriptor heap + // hosted by the render device. + for (size_t i = 0; i < _countof(m_DynamicGPUDescriptorAllocator); ++i) + m_DynamicGPUDescriptorAllocator[i].ReleaseAllocations(m_SubmittedBuffersCmdQueueMask); + + EndFrame(); +} + +void DeviceContextD3D12Impl::SetVertexBuffers(Uint32 StartSlot, + Uint32 NumBuffersSet, + IBuffer** ppBuffers, + Uint32* pOffsets, + RESOURCE_STATE_TRANSITION_MODE StateTransitionMode, + SET_VERTEX_BUFFERS_FLAGS Flags) +{ + TDeviceContextBase::SetVertexBuffers(StartSlot, NumBuffersSet, ppBuffers, pOffsets, StateTransitionMode, Flags); + + auto& CmdCtx = GetCmdContext(); + for (Uint32 Buff = 0; Buff < m_NumVertexStreams; ++Buff) { - static_assert(MaxViewports >= D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE, "MaxViewports constant must be greater than D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE"); - TDeviceContextBase::SetViewports( NumViewports, pViewports, RTWidth, RTHeight ); - VERIFY( NumViewports == m_NumViewports, "Unexpected number of viewports" ); + auto& CurrStream = m_VertexStreams[Buff]; + if (auto* pBufferD3D12 = CurrStream.pBuffer.RawPtr()) + TransitionOrVerifyBufferState(CmdCtx, *pBufferD3D12, StateTransitionMode, RESOURCE_STATE_VERTEX_BUFFER, "Setting vertex buffers (DeviceContextD3D12Impl::SetVertexBuffers)"); + } + + m_State.bCommittedD3D12VBsUpToDate = false; +} + +void DeviceContextD3D12Impl::InvalidateState() +{ + if (m_State.NumCommands != 0) + LOG_WARNING_MESSAGE("Invalidating context that has outstanding commands in it. Call Flush() to submit commands for execution"); - CommitViewports(); + TDeviceContextBase::InvalidateState(); + m_State = State{}; +} + +void DeviceContextD3D12Impl::SetIndexBuffer(IBuffer* pIndexBuffer, Uint32 ByteOffset, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) +{ + TDeviceContextBase::SetIndexBuffer(pIndexBuffer, ByteOffset, StateTransitionMode); + if (m_pIndexBuffer) + { + auto& CmdCtx = GetCmdContext(); + TransitionOrVerifyBufferState(CmdCtx, *m_pIndexBuffer, StateTransitionMode, RESOURCE_STATE_INDEX_BUFFER, "Setting index buffer (DeviceContextD3D12Impl::SetIndexBuffer)"); } + m_State.bCommittedD3D12IBUpToDate = false; +} +void DeviceContextD3D12Impl::CommitViewports() +{ + static_assert(MaxViewports >= D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE, "MaxViewports constant must be greater than D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE"); + D3D12_VIEWPORT d3d12Viewports[MaxViewports]; // Do not waste time initializing array to zero - constexpr LONG MaxD3D12TexDim = D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION; - constexpr Uint32 MaxD3D12ScissorRects = D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; - static constexpr RECT MaxD3D12TexSizeRects[D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE] = + for (Uint32 vp = 0; vp < m_NumViewports; ++vp) { - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, + d3d12Viewports[vp].TopLeftX = m_Viewports[vp].TopLeftX; + d3d12Viewports[vp].TopLeftY = m_Viewports[vp].TopLeftY; + d3d12Viewports[vp].Width = m_Viewports[vp].Width; + d3d12Viewports[vp].Height = m_Viewports[vp].Height; + d3d12Viewports[vp].MinDepth = m_Viewports[vp].MinDepth; + d3d12Viewports[vp].MaxDepth = m_Viewports[vp].MaxDepth; + } + // All viewports must be set atomically as one operation. + // Any viewports not defined by the call are disabled. + GetCmdContext().AsGraphicsContext().SetViewports(m_NumViewports, d3d12Viewports); +} - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, +void DeviceContextD3D12Impl::SetViewports(Uint32 NumViewports, const Viewport* pViewports, Uint32 RTWidth, Uint32 RTHeight) +{ + static_assert(MaxViewports >= D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE, "MaxViewports constant must be greater than D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE"); + TDeviceContextBase::SetViewports(NumViewports, pViewports, RTWidth, RTHeight); + VERIFY(NumViewports == m_NumViewports, "Unexpected number of viewports"); - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, + CommitViewports(); +} - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, - { 0,0, MaxD3D12TexDim,MaxD3D12TexDim } - }; - void DeviceContextD3D12Impl::CommitScissorRects(GraphicsContext& GraphCtx, bool ScissorEnable) - { - if (ScissorEnable) - { - // Commit currently set scissor rectangles - D3D12_RECT d3d12ScissorRects[MaxD3D12ScissorRects]; // Do not waste time initializing array with zeroes - for (Uint32 sr = 0; sr < m_NumScissorRects; ++sr) - { - d3d12ScissorRects[sr].left = m_ScissorRects[sr].left; - d3d12ScissorRects[sr].top = m_ScissorRects[sr].top; - d3d12ScissorRects[sr].right = m_ScissorRects[sr].right; - d3d12ScissorRects[sr].bottom = m_ScissorRects[sr].bottom; - } - GraphCtx.SetScissorRects(m_NumScissorRects, d3d12ScissorRects); - } - else +constexpr LONG MaxD3D12TexDim = D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION; +constexpr Uint32 MaxD3D12ScissorRects = D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; +// clang-format off +static constexpr RECT MaxD3D12TexSizeRects[D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE] = +{ + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim}, + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim}, + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim}, + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim}, + + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim}, + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim}, + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim}, + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim}, + + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim}, + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim}, + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim}, + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim}, + + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim}, + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim}, + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim}, + {0, 0, MaxD3D12TexDim, MaxD3D12TexDim} +}; +// clang-format on + +void DeviceContextD3D12Impl::CommitScissorRects(GraphicsContext& GraphCtx, bool ScissorEnable) +{ + if (ScissorEnable) + { + // Commit currently set scissor rectangles + D3D12_RECT d3d12ScissorRects[MaxD3D12ScissorRects]; // Do not waste time initializing array with zeroes + for (Uint32 sr = 0; sr < m_NumScissorRects; ++sr) { - // Disable scissor rectangles - static_assert(_countof(MaxD3D12TexSizeRects) == MaxD3D12ScissorRects, "Unexpected array size"); - GraphCtx.SetScissorRects(MaxD3D12ScissorRects, MaxD3D12TexSizeRects); + d3d12ScissorRects[sr].left = m_ScissorRects[sr].left; + d3d12ScissorRects[sr].top = m_ScissorRects[sr].top; + d3d12ScissorRects[sr].right = m_ScissorRects[sr].right; + d3d12ScissorRects[sr].bottom = m_ScissorRects[sr].bottom; } + GraphCtx.SetScissorRects(m_NumScissorRects, d3d12ScissorRects); } - - void DeviceContextD3D12Impl::SetScissorRects( Uint32 NumRects, const Rect* pRects, Uint32 RTWidth, Uint32 RTHeight ) + else { - const Uint32 MaxScissorRects = D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; - VERIFY( NumRects < MaxScissorRects, "Too many scissor rects are being set" ); - NumRects = std::min( NumRects, MaxScissorRects ); + // Disable scissor rectangles + static_assert(_countof(MaxD3D12TexSizeRects) == MaxD3D12ScissorRects, "Unexpected array size"); + GraphCtx.SetScissorRects(MaxD3D12ScissorRects, MaxD3D12TexSizeRects); + } +} + +void DeviceContextD3D12Impl::SetScissorRects(Uint32 NumRects, const Rect* pRects, Uint32 RTWidth, Uint32 RTHeight) +{ + const Uint32 MaxScissorRects = D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; + VERIFY(NumRects < MaxScissorRects, "Too many scissor rects are being set"); + NumRects = std::min(NumRects, MaxScissorRects); - TDeviceContextBase::SetScissorRects(NumRects, pRects, RTWidth, RTHeight); + TDeviceContextBase::SetScissorRects(NumRects, pRects, RTWidth, RTHeight); - // Only commit scissor rects if scissor test is enabled in the rasterizer state. - // If scissor is currently disabled, or no PSO is bound, scissor rects will be committed by - // the SetPipelineState() when a PSO with enabled scissor test is set. - if( m_pPipelineState ) + // Only commit scissor rects if scissor test is enabled in the rasterizer state. + // If scissor is currently disabled, or no PSO is bound, scissor rects will be committed by + // the SetPipelineState() when a PSO with enabled scissor test is set. + if (m_pPipelineState) + { + const auto& PSODesc = m_pPipelineState->GetDesc(); + if (!PSODesc.IsComputePipeline && PSODesc.GraphicsPipeline.RasterizerDesc.ScissorEnable) { - const auto &PSODesc = m_pPipelineState->GetDesc(); - if(!PSODesc.IsComputePipeline && PSODesc.GraphicsPipeline.RasterizerDesc.ScissorEnable) - { - VERIFY(NumRects == m_NumScissorRects, "Unexpected number of scissor rects"); - auto& Ctx = GetCmdContext().AsGraphicsContext(); - CommitScissorRects(Ctx, true); - } + VERIFY(NumRects == m_NumScissorRects, "Unexpected number of scissor rects"); + auto& Ctx = GetCmdContext().AsGraphicsContext(); + CommitScissorRects(Ctx, true); } } +} - void DeviceContextD3D12Impl::CommitRenderTargets(RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) +void DeviceContextD3D12Impl::CommitRenderTargets(RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) +{ + const Uint32 MaxD3D12RTs = D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; + Uint32 NumRenderTargets = m_NumBoundRenderTargets; + VERIFY(NumRenderTargets <= MaxD3D12RTs, "D3D12 only allows 8 simultaneous render targets"); + NumRenderTargets = std::min(MaxD3D12RTs, NumRenderTargets); + + ITextureViewD3D12* ppRTVs[MaxD3D12RTs]; // Do not initialize with zeroes! + ITextureViewD3D12* pDSV = nullptr; + if (m_IsDefaultFramebufferBound) { - const Uint32 MaxD3D12RTs = D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; - Uint32 NumRenderTargets = m_NumBoundRenderTargets; - VERIFY( NumRenderTargets <= MaxD3D12RTs, "D3D12 only allows 8 simultaneous render targets" ); - NumRenderTargets = std::min( MaxD3D12RTs, NumRenderTargets ); - - ITextureViewD3D12* ppRTVs[MaxD3D12RTs]; // Do not initialize with zeroes! - ITextureViewD3D12* pDSV = nullptr; - if (m_IsDefaultFramebufferBound) + if (m_pSwapChain) { - if (m_pSwapChain) - { - NumRenderTargets = 1; - auto *pSwapChainD3D12 = m_pSwapChain.RawPtr(); - ppRTVs[0] = ValidatedCast(pSwapChainD3D12->GetCurrentBackBufferRTV()); - pDSV = ValidatedCast(pSwapChainD3D12->GetDepthBufferDSV()); - } - else - { - LOG_WARNING_MESSAGE("Failed to bind default render targets and depth-stencil buffer: swap chain is not initialized in the device context"); - return; - } + NumRenderTargets = 1; + auto* pSwapChainD3D12 = m_pSwapChain.RawPtr(); + ppRTVs[0] = ValidatedCast(pSwapChainD3D12->GetCurrentBackBufferRTV()); + pDSV = ValidatedCast(pSwapChainD3D12->GetDepthBufferDSV()); } else { - for( Uint32 rt = 0; rt < NumRenderTargets; ++rt ) - ppRTVs[rt] = m_pBoundRenderTargets[rt].RawPtr(); - pDSV = m_pBoundDepthStencil.RawPtr(); + LOG_WARNING_MESSAGE("Failed to bind default render targets and depth-stencil buffer: swap chain is not initialized in the device context"); + return; } + } + else + { + for (Uint32 rt = 0; rt < NumRenderTargets; ++rt) + ppRTVs[rt] = m_pBoundRenderTargets[rt].RawPtr(); + pDSV = m_pBoundDepthStencil.RawPtr(); + } - auto& CmdCtx = GetCmdContext(); - D3D12_CPU_DESCRIPTOR_HANDLE RTVHandles[8]; // Do not waste time initializing array to zero - D3D12_CPU_DESCRIPTOR_HANDLE DSVHandle = {}; - for (UINT i = 0; i < NumRenderTargets; ++i) - { - if (auto* pRTV = ppRTVs[i]) - { - auto* pTexture = ValidatedCast( pRTV->GetTexture() ); - TransitionOrVerifyTextureState(CmdCtx, *pTexture, StateTransitionMode, RESOURCE_STATE_RENDER_TARGET, "Setting render targets (DeviceContextD3D12Impl::CommitRenderTargets)"); - RTVHandles[i] = pRTV->GetCPUDescriptorHandle(); - VERIFY_EXPR(RTVHandles[i].ptr != 0); - } - } + auto& CmdCtx = GetCmdContext(); - if (pDSV) + D3D12_CPU_DESCRIPTOR_HANDLE RTVHandles[8]; // Do not waste time initializing array to zero + D3D12_CPU_DESCRIPTOR_HANDLE DSVHandle = {}; + for (UINT i = 0; i < NumRenderTargets; ++i) + { + if (auto* pRTV = ppRTVs[i]) { - auto* pTexture = ValidatedCast( pDSV->GetTexture() ); - //if (bReadOnlyDepth) - //{ - // TransitionResource(*pTexture, D3D12_RESOURCE_STATE_DEPTH_READ); - // m_pCommandList->OMSetRenderTargets( NumRTVs, RTVHandles, FALSE, &DSV->GetDSV_DepthReadOnly() ); - //} - //else - { - TransitionOrVerifyTextureState(CmdCtx, *pTexture, StateTransitionMode, RESOURCE_STATE_DEPTH_WRITE, "Setting depth-stencil buffer (DeviceContextD3D12Impl::CommitRenderTargets)"); - DSVHandle = pDSV->GetCPUDescriptorHandle(); - VERIFY_EXPR(DSVHandle.ptr != 0); - } + auto* pTexture = ValidatedCast(pRTV->GetTexture()); + TransitionOrVerifyTextureState(CmdCtx, *pTexture, StateTransitionMode, RESOURCE_STATE_RENDER_TARGET, "Setting render targets (DeviceContextD3D12Impl::CommitRenderTargets)"); + RTVHandles[i] = pRTV->GetCPUDescriptorHandle(); + VERIFY_EXPR(RTVHandles[i].ptr != 0); } - - VERIFY_EXPR(NumRenderTargets > 0 || DSVHandle.ptr != 0); - // No need to flush resource barriers as this is a CPU-side command - CmdCtx.AsGraphicsContext().GetCommandList()->OMSetRenderTargets( NumRenderTargets, RTVHandles, FALSE, DSVHandle.ptr != 0 ? &DSVHandle : nullptr ); } - void DeviceContextD3D12Impl::SetRenderTargets( Uint32 NumRenderTargets, - ITextureView* ppRenderTargets[], - ITextureView* pDepthStencil, - RESOURCE_STATE_TRANSITION_MODE StateTransitionMode ) + if (pDSV) { - if( TDeviceContextBase::SetRenderTargets( NumRenderTargets, ppRenderTargets, pDepthStencil ) ) - { - CommitRenderTargets(StateTransitionMode); - - // Set the viewport to match the render target size - SetViewports(1, nullptr, 0, 0); + auto* pTexture = ValidatedCast(pDSV->GetTexture()); + //if (bReadOnlyDepth) + //{ + // TransitionResource(*pTexture, D3D12_RESOURCE_STATE_DEPTH_READ); + // m_pCommandList->OMSetRenderTargets( NumRTVs, RTVHandles, FALSE, &DSV->GetDSV_DepthReadOnly() ); + //} + //else + { + TransitionOrVerifyTextureState(CmdCtx, *pTexture, StateTransitionMode, RESOURCE_STATE_DEPTH_WRITE, "Setting depth-stencil buffer (DeviceContextD3D12Impl::CommitRenderTargets)"); + DSVHandle = pDSV->GetCPUDescriptorHandle(); + VERIFY_EXPR(DSVHandle.ptr != 0); } } - - D3D12DynamicAllocation DeviceContextD3D12Impl::AllocateDynamicSpace(size_t NumBytes, size_t Alignment) - { - return m_DynamicHeap.Allocate(NumBytes, Alignment, m_ContextFrameNumber); - } - void DeviceContextD3D12Impl::UpdateBufferRegion(BufferD3D12Impl* pBuffD3D12, - D3D12DynamicAllocation& Allocation, - Uint64 DstOffset, - Uint64 NumBytes, - RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) - { - auto& CmdCtx = GetCmdContext(); - VERIFY_EXPR( static_cast(NumBytes) == NumBytes ); - TransitionOrVerifyBufferState(CmdCtx, *pBuffD3D12, StateTransitionMode, RESOURCE_STATE_COPY_DEST, "Updating buffer (DeviceContextD3D12Impl::UpdateBufferRegion)"); - size_t DstBuffDataStartByteOffset; - auto* pd3d12Buff = pBuffD3D12->GetD3D12Buffer(DstBuffDataStartByteOffset, this); - VERIFY(DstBuffDataStartByteOffset == 0, "Dst buffer must not be suballocated"); - CmdCtx.FlushResourceBarriers(); - CmdCtx.GetCommandList()->CopyBufferRegion( pd3d12Buff, DstOffset + DstBuffDataStartByteOffset, Allocation.pBuffer, Allocation.Offset, NumBytes); - ++m_State.NumCommands; - } - - void DeviceContextD3D12Impl::UpdateBuffer(IBuffer* pBuffer, - Uint32 Offset, - Uint32 Size, - const PVoid pData, + VERIFY_EXPR(NumRenderTargets > 0 || DSVHandle.ptr != 0); + // No need to flush resource barriers as this is a CPU-side command + CmdCtx.AsGraphicsContext().GetCommandList()->OMSetRenderTargets(NumRenderTargets, RTVHandles, FALSE, DSVHandle.ptr != 0 ? &DSVHandle : nullptr); +} + +void DeviceContextD3D12Impl::SetRenderTargets(Uint32 NumRenderTargets, + ITextureView* ppRenderTargets[], + ITextureView* pDepthStencil, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) +{ + if (TDeviceContextBase::SetRenderTargets(NumRenderTargets, ppRenderTargets, pDepthStencil)) { - TDeviceContextBase::UpdateBuffer(pBuffer, Offset, Size, pData, StateTransitionMode); + CommitRenderTargets(StateTransitionMode); - // We must use cmd context from the device context provided, otherwise there will - // be resource barrier issues in the cmd list in the device context - auto* pBuffD3D12 = ValidatedCast(pBuffer); - VERIFY(pBuffD3D12->GetDesc().Usage != USAGE_DYNAMIC, "Dynamic buffers must be updated via Map()"); - constexpr size_t DefaultAlginment = 16; - auto TmpSpace = m_DynamicHeap.Allocate(Size, DefaultAlginment, m_ContextFrameNumber); - memcpy(TmpSpace.CPUAddress, pData, Size); - UpdateBufferRegion(pBuffD3D12, TmpSpace, Offset, Size, StateTransitionMode); + // Set the viewport to match the render target size + SetViewports(1, nullptr, 0, 0); } +} - void DeviceContextD3D12Impl::CopyBuffer(IBuffer* pSrcBuffer, - Uint32 SrcOffset, - RESOURCE_STATE_TRANSITION_MODE SrcBufferTransitionMode, - IBuffer* pDstBuffer, - Uint32 DstOffset, - Uint32 Size, - RESOURCE_STATE_TRANSITION_MODE DstBufferTransitionMode) - { - TDeviceContextBase::CopyBuffer(pSrcBuffer, SrcOffset, SrcBufferTransitionMode, pDstBuffer, DstOffset, Size, DstBufferTransitionMode); +D3D12DynamicAllocation DeviceContextD3D12Impl::AllocateDynamicSpace(size_t NumBytes, size_t Alignment) +{ + return m_DynamicHeap.Allocate(NumBytes, Alignment, m_ContextFrameNumber); +} - auto* pSrcBuffD3D12 = ValidatedCast(pSrcBuffer); - auto* pDstBuffD3D12 = ValidatedCast(pDstBuffer); +void DeviceContextD3D12Impl::UpdateBufferRegion(BufferD3D12Impl* pBuffD3D12, + D3D12DynamicAllocation& Allocation, + Uint64 DstOffset, + Uint64 NumBytes, + RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) +{ + auto& CmdCtx = GetCmdContext(); + VERIFY_EXPR(static_cast(NumBytes) == NumBytes); + TransitionOrVerifyBufferState(CmdCtx, *pBuffD3D12, StateTransitionMode, RESOURCE_STATE_COPY_DEST, "Updating buffer (DeviceContextD3D12Impl::UpdateBufferRegion)"); + size_t DstBuffDataStartByteOffset; + auto* pd3d12Buff = pBuffD3D12->GetD3D12Buffer(DstBuffDataStartByteOffset, this); + VERIFY(DstBuffDataStartByteOffset == 0, "Dst buffer must not be suballocated"); + CmdCtx.FlushResourceBarriers(); + CmdCtx.GetCommandList()->CopyBufferRegion(pd3d12Buff, DstOffset + DstBuffDataStartByteOffset, Allocation.pBuffer, Allocation.Offset, NumBytes); + ++m_State.NumCommands; +} - VERIFY(pDstBuffD3D12->GetDesc().Usage != USAGE_DYNAMIC, "Dynamic buffers cannot be copy destinations"); +void DeviceContextD3D12Impl::UpdateBuffer(IBuffer* pBuffer, + Uint32 Offset, + Uint32 Size, + const PVoid pData, + RESOURCE_STATE_TRANSITION_MODE StateTransitionMode) +{ + TDeviceContextBase::UpdateBuffer(pBuffer, Offset, Size, pData, StateTransitionMode); + + // We must use cmd context from the device context provided, otherwise there will + // be resource barrier issues in the cmd list in the device context + auto* pBuffD3D12 = ValidatedCast(pBuffer); + VERIFY(pBuffD3D12->GetDesc().Usage != USAGE_DYNAMIC, "Dynamic buffers must be updated via Map()"); + constexpr size_t DefaultAlginment = 16; + auto TmpSpace = m_DynamicHeap.Allocate(Size, DefaultAlginment, m_ContextFrameNumber); + memcpy(TmpSpace.CPUAddress, pData, Size); + UpdateBufferRegion(pBuffD3D12, TmpSpace, Offset, Size, StateTransitionMode); +} - auto& CmdCtx = GetCmdContext(); - TransitionOrVerifyBufferState(CmdCtx, *pSrcBuffD3D12, SrcBufferTransitionMode, RESOURCE_STATE_COPY_SOURCE, "Using resource as copy source (DeviceContextD3D12Impl::CopyBuffer)"); - TransitionOrVerifyBufferState(CmdCtx, *pDstBuffD3D12, DstBufferTransitionMode, RESOURCE_STATE_COPY_DEST, "Using resource as copy destination (DeviceContextD3D12Impl::CopyBuffer)"); +void DeviceContextD3D12Impl::CopyBuffer(IBuffer* pSrcBuffer, + Uint32 SrcOffset, + RESOURCE_STATE_TRANSITION_MODE SrcBufferTransitionMode, + IBuffer* pDstBuffer, + Uint32 DstOffset, + Uint32 Size, + RESOURCE_STATE_TRANSITION_MODE DstBufferTransitionMode) +{ + TDeviceContextBase::CopyBuffer(pSrcBuffer, SrcOffset, SrcBufferTransitionMode, pDstBuffer, DstOffset, Size, DstBufferTransitionMode); - size_t DstDataStartByteOffset; - auto* pd3d12DstBuff = pDstBuffD3D12->GetD3D12Buffer(DstDataStartByteOffset, this); - VERIFY(DstDataStartByteOffset == 0, "Dst buffer must not be suballocated"); + auto* pSrcBuffD3D12 = ValidatedCast(pSrcBuffer); + auto* pDstBuffD3D12 = ValidatedCast(pDstBuffer); - size_t SrcDataStartByteOffset; - auto* pd3d12SrcBuff = pSrcBuffD3D12->GetD3D12Buffer(SrcDataStartByteOffset, this); - CmdCtx.FlushResourceBarriers(); - CmdCtx.GetCommandList()->CopyBufferRegion( pd3d12DstBuff, DstOffset + DstDataStartByteOffset, pd3d12SrcBuff, SrcOffset+SrcDataStartByteOffset, Size); - ++m_State.NumCommands; - } + VERIFY(pDstBuffD3D12->GetDesc().Usage != USAGE_DYNAMIC, "Dynamic buffers cannot be copy destinations"); - void DeviceContextD3D12Impl::MapBuffer(IBuffer* pBuffer, MAP_TYPE MapType, MAP_FLAGS MapFlags, PVoid& pMappedData) - { - TDeviceContextBase::MapBuffer(pBuffer, MapType, MapFlags, pMappedData); - auto* pBufferD3D12 = ValidatedCast(pBuffer); - const auto& BuffDesc = pBufferD3D12->GetDesc(); - auto* pd3d12Resource = pBufferD3D12->m_pd3d12Resource.p; + auto& CmdCtx = GetCmdContext(); + TransitionOrVerifyBufferState(CmdCtx, *pSrcBuffD3D12, SrcBufferTransitionMode, RESOURCE_STATE_COPY_SOURCE, "Using resource as copy source (DeviceContextD3D12Impl::CopyBuffer)"); + TransitionOrVerifyBufferState(CmdCtx, *pDstBuffD3D12, DstBufferTransitionMode, RESOURCE_STATE_COPY_DEST, "Using resource as copy destination (DeviceContextD3D12Impl::CopyBuffer)"); - if (MapType == MAP_READ) - { - LOG_WARNING_MESSAGE_ONCE("Mapping CPU buffer for reading on D3D12 currently requires flushing context and idling GPU"); - Flush(); - m_pDevice->IdleGPU(); - VERIFY(BuffDesc.Usage == USAGE_STAGING, "Buffer must be created as USAGE_STAGING to be mapped for reading"); - D3D12_RANGE MapRange; - MapRange.Begin = 0; - MapRange.End = BuffDesc.uiSizeInBytes; - pd3d12Resource->Map(0, &MapRange, &pMappedData); - } - else if(MapType == MAP_WRITE) + size_t DstDataStartByteOffset; + auto* pd3d12DstBuff = pDstBuffD3D12->GetD3D12Buffer(DstDataStartByteOffset, this); + VERIFY(DstDataStartByteOffset == 0, "Dst buffer must not be suballocated"); + + size_t SrcDataStartByteOffset; + auto* pd3d12SrcBuff = pSrcBuffD3D12->GetD3D12Buffer(SrcDataStartByteOffset, this); + CmdCtx.FlushResourceBarriers(); + CmdCtx.GetCommandList()->CopyBufferRegion(pd3d12DstBuff, DstOffset + DstDataStartByteOffset, pd3d12SrcBuff, SrcOffset + SrcDataStartByteOffset, Size); + ++m_State.NumCommands; +} + +void DeviceContextD3D12Impl::MapBuffer(IBuffer* pBuffer, MAP_TYPE MapType, MAP_FLAGS MapFlags, PVoid& pMappedData) +{ + TDeviceContextBase::MapBuffer(pBuffer, MapType, MapFlags, pMappedData); + auto* pBufferD3D12 = ValidatedCast(pBuffer); + const auto& BuffDesc = pBufferD3D12->GetDesc(); + auto* pd3d12Resource = pBufferD3D12->m_pd3d12Resource.p; + + if (MapType == MAP_READ) + { + LOG_WARNING_MESSAGE_ONCE("Mapping CPU buffer for reading on D3D12 currently requires flushing context and idling GPU"); + Flush(); + m_pDevice->IdleGPU(); + VERIFY(BuffDesc.Usage == USAGE_STAGING, "Buffer must be created as USAGE_STAGING to be mapped for reading"); + D3D12_RANGE MapRange; + MapRange.Begin = 0; + MapRange.End = BuffDesc.uiSizeInBytes; + pd3d12Resource->Map(0, &MapRange, &pMappedData); + } + else if (MapType == MAP_WRITE) + { + if (BuffDesc.Usage == USAGE_STAGING) { - if (BuffDesc.Usage == USAGE_STAGING) + VERIFY(pd3d12Resource != nullptr, "USAGE_STAGING buffer mapped for writing must intialize D3D12 resource"); + if (MapFlags & MAP_FLAG_DISCARD) { - VERIFY(pd3d12Resource != nullptr, "USAGE_STAGING buffer mapped for writing must intialize D3D12 resource"); - if (MapFlags & MAP_FLAG_DISCARD) - { - - } - pd3d12Resource->Map(0, nullptr, &pMappedData); } - else if (BuffDesc.Usage == USAGE_DYNAMIC) + pd3d12Resource->Map(0, nullptr, &pMappedData); + } + else if (BuffDesc.Usage == USAGE_DYNAMIC) + { + VERIFY((MapFlags & (MAP_FLAG_DISCARD | MAP_FLAG_DO_NOT_SYNCHRONIZE)) != 0, "D3D12 buffer must be mapped for writing with MAP_FLAG_DISCARD or MAP_FLAG_DO_NOT_SYNCHRONIZE flag"); + auto& DynamicData = pBufferD3D12->m_DynamicData[m_ContextId]; + if ((MapFlags & MAP_FLAG_DISCARD) != 0 || DynamicData.CPUAddress == nullptr) { - VERIFY( (MapFlags & (MAP_FLAG_DISCARD | MAP_FLAG_DO_NOT_SYNCHRONIZE)) != 0, "D3D12 buffer must be mapped for writing with MAP_FLAG_DISCARD or MAP_FLAG_DO_NOT_SYNCHRONIZE flag"); - auto& DynamicData = pBufferD3D12->m_DynamicData[m_ContextId]; - if ((MapFlags & MAP_FLAG_DISCARD) != 0 || DynamicData.CPUAddress == nullptr) - { - size_t Alignment = (BuffDesc.BindFlags & BIND_UNIFORM_BUFFER) ? D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT : 16; - DynamicData = AllocateDynamicSpace(BuffDesc.uiSizeInBytes, Alignment); - } - else - { - VERIFY_EXPR(MapFlags & MAP_FLAG_DO_NOT_SYNCHRONIZE); - // Reuse previously mapped region - } - pMappedData = DynamicData.CPUAddress; + size_t Alignment = (BuffDesc.BindFlags & BIND_UNIFORM_BUFFER) ? D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT : 16; + DynamicData = AllocateDynamicSpace(BuffDesc.uiSizeInBytes, Alignment); } else { - LOG_ERROR("Only USAGE_DYNAMIC and USAGE_STAGING D3D12 buffers can be mapped for writing"); + VERIFY_EXPR(MapFlags & MAP_FLAG_DO_NOT_SYNCHRONIZE); + // Reuse previously mapped region } - } - else if(MapType == MAP_READ_WRITE) - { - LOG_ERROR("MAP_READ_WRITE is not supported in D3D12"); + pMappedData = DynamicData.CPUAddress; } else { - LOG_ERROR("Only MAP_WRITE_DISCARD and MAP_READ are currently implemented in D3D12"); + LOG_ERROR("Only USAGE_DYNAMIC and USAGE_STAGING D3D12 buffers can be mapped for writing"); } } + else if (MapType == MAP_READ_WRITE) + { + LOG_ERROR("MAP_READ_WRITE is not supported in D3D12"); + } + else + { + LOG_ERROR("Only MAP_WRITE_DISCARD and MAP_READ are currently implemented in D3D12"); + } +} - void DeviceContextD3D12Impl::UnmapBuffer(IBuffer* pBuffer, MAP_TYPE MapType) +void DeviceContextD3D12Impl::UnmapBuffer(IBuffer* pBuffer, MAP_TYPE MapType) +{ + TDeviceContextBase::UnmapBuffer(pBuffer, MapType); + auto* pBufferD3D12 = ValidatedCast(pBuffer); + const auto& BuffDesc = pBufferD3D12->GetDesc(); + auto* pd3d12Resource = pBufferD3D12->m_pd3d12Resource.p; + if (MapType == MAP_READ) + { + D3D12_RANGE MapRange; + // It is valid to specify the CPU didn't write any data by passing a range where End is less than or equal to Begin. + MapRange.Begin = 1; + MapRange.End = 0; + pd3d12Resource->Unmap(0, &MapRange); + } + else if (MapType == MAP_WRITE) { - TDeviceContextBase::UnmapBuffer(pBuffer, MapType); - auto* pBufferD3D12 = ValidatedCast(pBuffer); - const auto& BuffDesc = pBufferD3D12->GetDesc(); - auto* pd3d12Resource = pBufferD3D12->m_pd3d12Resource.p; - if (MapType == MAP_READ ) + if (BuffDesc.Usage == USAGE_STAGING) { - D3D12_RANGE MapRange; - // It is valid to specify the CPU didn't write any data by passing a range where End is less than or equal to Begin. - MapRange.Begin = 1; - MapRange.End = 0; - pd3d12Resource->Unmap(0, &MapRange); + VERIFY(pd3d12Resource != nullptr, "USAGE_STAGING buffer mapped for writing must intialize D3D12 resource"); + pd3d12Resource->Unmap(0, nullptr); } - else if(MapType == MAP_WRITE) + else if (BuffDesc.Usage == USAGE_DYNAMIC) { - if (BuffDesc.Usage == USAGE_STAGING) + // Copy data into the resource + if (pd3d12Resource) { - VERIFY(pd3d12Resource != nullptr, "USAGE_STAGING buffer mapped for writing must intialize D3D12 resource"); - pd3d12Resource->Unmap(0, nullptr); - } - else if (BuffDesc.Usage == USAGE_DYNAMIC) - { - // Copy data into the resource - if (pd3d12Resource) - { - UpdateBufferRegion(pBufferD3D12, pBufferD3D12->m_DynamicData[m_ContextId], 0, BuffDesc.uiSizeInBytes, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); - } + UpdateBufferRegion(pBufferD3D12, pBufferD3D12->m_DynamicData[m_ContextId], 0, BuffDesc.uiSizeInBytes, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); } } } +} - void DeviceContextD3D12Impl::UpdateTexture(ITexture* pTexture, - Uint32 MipLevel, - Uint32 Slice, - const Box& DstBox, - const TextureSubResData& SubresData, - RESOURCE_STATE_TRANSITION_MODE SrcBufferTransitionMode, - RESOURCE_STATE_TRANSITION_MODE TextureTransitionMode) +void DeviceContextD3D12Impl::UpdateTexture(ITexture* pTexture, + Uint32 MipLevel, + Uint32 Slice, + const Box& DstBox, + const TextureSubResData& SubresData, + RESOURCE_STATE_TRANSITION_MODE SrcBufferTransitionMode, + RESOURCE_STATE_TRANSITION_MODE TextureTransitionMode) +{ + TDeviceContextBase::UpdateTexture(pTexture, MipLevel, Slice, DstBox, SubresData, SrcBufferTransitionMode, TextureTransitionMode); + + auto* pTexD3D12 = ValidatedCast(pTexture); + const auto& Desc = pTexD3D12->GetDesc(); + // OpenGL backend uses UpdateData() to initialize textures, so we can't check the usage in ValidateUpdateTextureParams() + DEV_CHECK_ERR(Desc.Usage == USAGE_DEFAULT, "Only USAGE_DEFAULT textures should be updated with UpdateData()"); + + Box BlockAlignedBox; + const auto& FmtAttribs = GetTextureFormatAttribs(Desc.Format); + const Box* pBox = nullptr; + if (FmtAttribs.ComponentType == COMPONENT_TYPE_COMPRESSED) { - TDeviceContextBase::UpdateTexture( pTexture, MipLevel, Slice, DstBox, SubresData, SrcBufferTransitionMode, TextureTransitionMode ); + // Align update region by the compressed block size - auto* pTexD3D12 = ValidatedCast(pTexture); - const auto& Desc = pTexD3D12->GetDesc(); - // OpenGL backend uses UpdateData() to initialize textures, so we can't check the usage in ValidateUpdateTextureParams() - DEV_CHECK_ERR( Desc.Usage == USAGE_DEFAULT, "Only USAGE_DEFAULT textures should be updated with UpdateData()" ); + VERIFY((DstBox.MinX % FmtAttribs.BlockWidth) == 0, "Update region min X coordinate (", DstBox.MinX, ") must be multiple of a compressed block width (", Uint32{FmtAttribs.BlockWidth}, ")"); + BlockAlignedBox.MinX = DstBox.MinX; + VERIFY((FmtAttribs.BlockWidth & (FmtAttribs.BlockWidth - 1)) == 0, "Compressed block width (", Uint32{FmtAttribs.BlockWidth}, ") is expected to be power of 2"); + BlockAlignedBox.MaxX = (DstBox.MaxX + FmtAttribs.BlockWidth - 1) & ~(FmtAttribs.BlockWidth - 1); - Box BlockAlignedBox; - const auto& FmtAttribs = GetTextureFormatAttribs(Desc.Format); - const Box* pBox = nullptr; - if (FmtAttribs.ComponentType == COMPONENT_TYPE_COMPRESSED) - { - // Align update region by the compressed block size - - VERIFY( (DstBox.MinX % FmtAttribs.BlockWidth) == 0, "Update region min X coordinate (", DstBox.MinX, ") must be multiple of a compressed block width (", Uint32{FmtAttribs.BlockWidth}, ")"); - BlockAlignedBox.MinX = DstBox.MinX; - VERIFY( (FmtAttribs.BlockWidth & (FmtAttribs.BlockWidth-1)) == 0, "Compressed block width (", Uint32{FmtAttribs.BlockWidth}, ") is expected to be power of 2"); - BlockAlignedBox.MaxX = (DstBox.MaxX + FmtAttribs.BlockWidth-1) & ~(FmtAttribs.BlockWidth-1); - - VERIFY( (DstBox.MinY % FmtAttribs.BlockHeight) == 0, "Update region min Y coordinate (", DstBox.MinY, ") must be multiple of a compressed block height (", Uint32{FmtAttribs.BlockHeight}, ")"); - BlockAlignedBox.MinY = DstBox.MinY; - VERIFY( (FmtAttribs.BlockHeight & (FmtAttribs.BlockHeight-1)) == 0, "Compressed block height (", Uint32{FmtAttribs.BlockHeight}, ") is expected to be power of 2"); - BlockAlignedBox.MaxY = (DstBox.MaxY + FmtAttribs.BlockHeight-1) & ~(FmtAttribs.BlockHeight-1); - - BlockAlignedBox.MinZ = DstBox.MinZ; - BlockAlignedBox.MaxZ = DstBox.MaxZ; - - pBox = &BlockAlignedBox; - } - else - { - pBox = &DstBox; - } - auto DstSubResIndex = D3D12CalcSubresource(MipLevel, Slice, 0, Desc.MipLevels, Desc.ArraySize); - if (SubresData.pSrcBuffer == nullptr) - { - UpdateTextureRegion(SubresData.pData, SubresData.Stride, SubresData.DepthStride, - *pTexD3D12, DstSubResIndex, *pBox, TextureTransitionMode); - } - else - { - CopyTextureRegion(SubresData.pSrcBuffer, 0, SubresData.Stride, SubresData.DepthStride, - *pTexD3D12, DstSubResIndex, *pBox, - SrcBufferTransitionMode, TextureTransitionMode); - } + VERIFY((DstBox.MinY % FmtAttribs.BlockHeight) == 0, "Update region min Y coordinate (", DstBox.MinY, ") must be multiple of a compressed block height (", Uint32{FmtAttribs.BlockHeight}, ")"); + BlockAlignedBox.MinY = DstBox.MinY; + VERIFY((FmtAttribs.BlockHeight & (FmtAttribs.BlockHeight - 1)) == 0, "Compressed block height (", Uint32{FmtAttribs.BlockHeight}, ") is expected to be power of 2"); + BlockAlignedBox.MaxY = (DstBox.MaxY + FmtAttribs.BlockHeight - 1) & ~(FmtAttribs.BlockHeight - 1); + + BlockAlignedBox.MinZ = DstBox.MinZ; + BlockAlignedBox.MaxZ = DstBox.MaxZ; + + pBox = &BlockAlignedBox; + } + else + { + pBox = &DstBox; + } + auto DstSubResIndex = D3D12CalcSubresource(MipLevel, Slice, 0, Desc.MipLevels, Desc.ArraySize); + if (SubresData.pSrcBuffer == nullptr) + { + UpdateTextureRegion(SubresData.pData, SubresData.Stride, SubresData.DepthStride, + *pTexD3D12, DstSubResIndex, *pBox, TextureTransitionMode); } + else + { + CopyTextureRegion(SubresData.pSrcBuffer, 0, SubresData.Stride, SubresData.DepthStride, + *pTexD3D12, DstSubResIndex, *pBox, + SrcBufferTransitionMode, TextureTransitionMode); + } +} - void DeviceContextD3D12Impl::CopyTexture(const CopyTextureAttribs& CopyAttribs) +void DeviceContextD3D12Impl::CopyTexture(const CopyTextureAttribs& CopyAttribs) +{ + TDeviceContextBase::CopyTexture(CopyAttribs); + + auto* pSrcTexD3D12 = ValidatedCast(CopyAttribs.pSrcTexture); + auto* pDstTexD3D12 = ValidatedCast(CopyAttribs.pDstTexture); + const auto& SrcTexDesc = pSrcTexD3D12->GetDesc(); + const auto& DstTexDesc = pDstTexD3D12->GetDesc(); + + D3D12_BOX D3D12SrcBox, *pD3D12SrcBox = nullptr; + if (const auto* pSrcBox = CopyAttribs.pSrcBox) { - TDeviceContextBase::CopyTexture( CopyAttribs ); + D3D12SrcBox.left = pSrcBox->MinX; + D3D12SrcBox.right = pSrcBox->MaxX; + D3D12SrcBox.top = pSrcBox->MinY; + D3D12SrcBox.bottom = pSrcBox->MaxY; + D3D12SrcBox.front = pSrcBox->MinZ; + D3D12SrcBox.back = pSrcBox->MaxZ; + pD3D12SrcBox = &D3D12SrcBox; + } - auto* pSrcTexD3D12 = ValidatedCast( CopyAttribs.pSrcTexture ); - auto* pDstTexD3D12 = ValidatedCast( CopyAttribs.pDstTexture ); - const auto& SrcTexDesc = pSrcTexD3D12->GetDesc(); - const auto& DstTexDesc = pDstTexD3D12->GetDesc(); + auto DstSubResIndex = D3D12CalcSubresource(CopyAttribs.DstMipLevel, CopyAttribs.DstSlice, 0, DstTexDesc.MipLevels, DstTexDesc.ArraySize); + auto SrcSubResIndex = D3D12CalcSubresource(CopyAttribs.SrcMipLevel, CopyAttribs.SrcSlice, 0, SrcTexDesc.MipLevels, SrcTexDesc.ArraySize); + CopyTextureRegion(pSrcTexD3D12, SrcSubResIndex, pD3D12SrcBox, CopyAttribs.SrcTextureTransitionMode, + pDstTexD3D12, DstSubResIndex, CopyAttribs.DstX, CopyAttribs.DstY, CopyAttribs.DstZ, + CopyAttribs.DstTextureTransitionMode); +} - D3D12_BOX D3D12SrcBox, *pD3D12SrcBox = nullptr; - if (const auto* pSrcBox = CopyAttribs.pSrcBox) - { - D3D12SrcBox.left = pSrcBox->MinX; - D3D12SrcBox.right = pSrcBox->MaxX; - D3D12SrcBox.top = pSrcBox->MinY; - D3D12SrcBox.bottom = pSrcBox->MaxY; - D3D12SrcBox.front = pSrcBox->MinZ; - D3D12SrcBox.back = pSrcBox->MaxZ; - pD3D12SrcBox = &D3D12SrcBox; - } +void DeviceContextD3D12Impl::CopyTextureRegion(TextureD3D12Impl* pSrcTexture, + Uint32 SrcSubResIndex, + const D3D12_BOX* pD3D12SrcBox, + RESOURCE_STATE_TRANSITION_MODE SrcTextureTransitionMode, + TextureD3D12Impl* pDstTexture, + Uint32 DstSubResIndex, + Uint32 DstX, + Uint32 DstY, + Uint32 DstZ, + RESOURCE_STATE_TRANSITION_MODE DstTextureTransitionMode) +{ + auto& CmdCtx = GetCmdContext(); + if (pSrcTexture->GetDesc().Usage == USAGE_STAGING) + { + DEV_CHECK_ERR((pSrcTexture->GetDesc().CPUAccessFlags & CPU_ACCESS_WRITE) != 0, "Source staging texture must be created with CPU_ACCESS_WRITE flag"); + DEV_CHECK_ERR(pSrcTexture->GetState() == RESOURCE_STATE_GENERIC_READ || !pSrcTexture->IsInKnownState(), "Staging texture must always be in RESOURCE_STATE_GENERIC_READ state"); + } + TransitionOrVerifyTextureState(CmdCtx, *pSrcTexture, SrcTextureTransitionMode, RESOURCE_STATE_COPY_SOURCE, "Using resource as copy source (DeviceContextD3D12Impl::CopyTextureRegion)"); - auto DstSubResIndex = D3D12CalcSubresource(CopyAttribs.DstMipLevel, CopyAttribs.DstSlice, 0, DstTexDesc.MipLevels, DstTexDesc.ArraySize); - auto SrcSubResIndex = D3D12CalcSubresource(CopyAttribs.SrcMipLevel, CopyAttribs.SrcSlice, 0, SrcTexDesc.MipLevels, SrcTexDesc.ArraySize); - CopyTextureRegion(pSrcTexD3D12, SrcSubResIndex, pD3D12SrcBox, CopyAttribs.SrcTextureTransitionMode, - pDstTexD3D12, DstSubResIndex, CopyAttribs.DstX, CopyAttribs.DstY, CopyAttribs.DstZ, - CopyAttribs.DstTextureTransitionMode); + if (pDstTexture->GetDesc().Usage == USAGE_STAGING) + { + DEV_CHECK_ERR((pDstTexture->GetDesc().CPUAccessFlags & CPU_ACCESS_READ) != 0, "Destination staging texture must be created with CPU_ACCESS_READ flag"); + DEV_CHECK_ERR(pDstTexture->GetState() == RESOURCE_STATE_COPY_DEST || !pDstTexture->IsInKnownState(), "Staging texture must always be in RESOURCE_STATE_COPY_DEST state"); } + TransitionOrVerifyTextureState(CmdCtx, *pDstTexture, DstTextureTransitionMode, RESOURCE_STATE_COPY_DEST, "Using resource as copy destination (DeviceContextD3D12Impl::CopyTextureRegion)"); + + D3D12_TEXTURE_COPY_LOCATION DstLocation = {}, SrcLocation = {}; - void DeviceContextD3D12Impl::CopyTextureRegion(TextureD3D12Impl* pSrcTexture, - Uint32 SrcSubResIndex, - const D3D12_BOX* pD3D12SrcBox, - RESOURCE_STATE_TRANSITION_MODE SrcTextureTransitionMode, - TextureD3D12Impl* pDstTexture, - Uint32 DstSubResIndex, - Uint32 DstX, - Uint32 DstY, - Uint32 DstZ, - RESOURCE_STATE_TRANSITION_MODE DstTextureTransitionMode) + SrcLocation.pResource = pSrcTexture->GetD3D12Resource(); + if (pSrcTexture->GetDesc().Usage == USAGE_STAGING) { - auto& CmdCtx = GetCmdContext(); - if (pSrcTexture->GetDesc().Usage == USAGE_STAGING) - { - DEV_CHECK_ERR((pSrcTexture->GetDesc().CPUAccessFlags & CPU_ACCESS_WRITE) != 0, "Source staging texture must be created with CPU_ACCESS_WRITE flag"); - DEV_CHECK_ERR(pSrcTexture->GetState() == RESOURCE_STATE_GENERIC_READ || !pSrcTexture->IsInKnownState(), "Staging texture must always be in RESOURCE_STATE_GENERIC_READ state"); - } - TransitionOrVerifyTextureState(CmdCtx, *pSrcTexture, SrcTextureTransitionMode, RESOURCE_STATE_COPY_SOURCE, "Using resource as copy source (DeviceContextD3D12Impl::CopyTextureRegion)"); + SrcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + SrcLocation.PlacedFootprint = pSrcTexture->GetStagingFootprint(SrcSubResIndex); + } + else + { + SrcLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + SrcLocation.SubresourceIndex = SrcSubResIndex; + } - if (pDstTexture->GetDesc().Usage == USAGE_STAGING) - { - DEV_CHECK_ERR((pDstTexture->GetDesc().CPUAccessFlags & CPU_ACCESS_READ) != 0, "Destination staging texture must be created with CPU_ACCESS_READ flag"); - DEV_CHECK_ERR(pDstTexture->GetState() == RESOURCE_STATE_COPY_DEST || !pDstTexture->IsInKnownState(), "Staging texture must always be in RESOURCE_STATE_COPY_DEST state"); - } - TransitionOrVerifyTextureState(CmdCtx, *pDstTexture, DstTextureTransitionMode, RESOURCE_STATE_COPY_DEST, "Using resource as copy destination (DeviceContextD3D12Impl::CopyTextureRegion)"); + DstLocation.pResource = pDstTexture->GetD3D12Resource(); + if (pDstTexture->GetDesc().Usage == USAGE_STAGING) + { + DstLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + DstLocation.PlacedFootprint = pDstTexture->GetStagingFootprint(DstSubResIndex); + } + else + { + DstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + DstLocation.SubresourceIndex = DstSubResIndex; + } - D3D12_TEXTURE_COPY_LOCATION DstLocation = {}, SrcLocation = {}; + CmdCtx.FlushResourceBarriers(); + CmdCtx.GetCommandList()->CopyTextureRegion(&DstLocation, DstX, DstY, DstZ, &SrcLocation, pD3D12SrcBox); + ++m_State.NumCommands; +} - SrcLocation.pResource = pSrcTexture->GetD3D12Resource(); - if (pSrcTexture->GetDesc().Usage == USAGE_STAGING) - { - SrcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - SrcLocation.PlacedFootprint = pSrcTexture->GetStagingFootprint(SrcSubResIndex); - } - else - { - SrcLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - SrcLocation.SubresourceIndex = SrcSubResIndex; - } - - DstLocation.pResource = pDstTexture->GetD3D12Resource(); - if (pDstTexture->GetDesc().Usage == USAGE_STAGING) - { - DstLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - DstLocation.PlacedFootprint = pDstTexture->GetStagingFootprint(DstSubResIndex); - } - else - { - DstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - DstLocation.SubresourceIndex = DstSubResIndex; - } - - CmdCtx.FlushResourceBarriers(); - CmdCtx.GetCommandList()->CopyTextureRegion( &DstLocation, DstX, DstY, DstZ, &SrcLocation, pD3D12SrcBox); - ++m_State.NumCommands; - } - - void DeviceContextD3D12Impl::CopyTextureRegion(ID3D12Resource* pd3d12Buffer, - Uint32 SrcOffset, - Uint32 SrcStride, - Uint32 SrcDepthStride, - Uint32 BufferSize, - TextureD3D12Impl& TextureD3D12, - Uint32 DstSubResIndex, - const Box& DstBox, - RESOURCE_STATE_TRANSITION_MODE TextureTransitionMode) - { - const auto& TexDesc = TextureD3D12.GetDesc(); - auto& CmdCtx = GetCmdContext(); - auto* pCmdList = CmdCtx.GetCommandList(); - bool StateTransitionRequired = false; - if (TextureTransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION) - { - StateTransitionRequired = TextureD3D12.IsInKnownState() && !TextureD3D12.CheckState(RESOURCE_STATE_COPY_DEST); - } +void DeviceContextD3D12Impl::CopyTextureRegion(ID3D12Resource* pd3d12Buffer, + Uint32 SrcOffset, + Uint32 SrcStride, + Uint32 SrcDepthStride, + Uint32 BufferSize, + TextureD3D12Impl& TextureD3D12, + Uint32 DstSubResIndex, + const Box& DstBox, + RESOURCE_STATE_TRANSITION_MODE TextureTransitionMode) +{ + const auto& TexDesc = TextureD3D12.GetDesc(); + auto& CmdCtx = GetCmdContext(); + auto* pCmdList = CmdCtx.GetCommandList(); + bool StateTransitionRequired = false; + if (TextureTransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION) + { + StateTransitionRequired = TextureD3D12.IsInKnownState() && !TextureD3D12.CheckState(RESOURCE_STATE_COPY_DEST); + } #ifdef DEVELOPMENT - else if (TextureTransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY) - { - DvpVerifyTextureState(TextureD3D12, RESOURCE_STATE_COPY_DEST, "Using texture as copy destination (DeviceContextD3D12Impl::CopyTextureRegion)"); - } + else if (TextureTransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY) + { + DvpVerifyTextureState(TextureD3D12, RESOURCE_STATE_COPY_DEST, "Using texture as copy destination (DeviceContextD3D12Impl::CopyTextureRegion)"); + } #endif - D3D12_RESOURCE_BARRIER BarrierDesc; - if (StateTransitionRequired) - { - BarrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - BarrierDesc.Transition.pResource = TextureD3D12.GetD3D12Resource(); - BarrierDesc.Transition.Subresource = DstSubResIndex; - BarrierDesc.Transition.StateBefore = ResourceStateFlagsToD3D12ResourceStates(TextureD3D12.GetState()); - BarrierDesc.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; - BarrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - pCmdList->ResourceBarrier(1, &BarrierDesc); - } + D3D12_RESOURCE_BARRIER BarrierDesc; + if (StateTransitionRequired) + { + BarrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + BarrierDesc.Transition.pResource = TextureD3D12.GetD3D12Resource(); + BarrierDesc.Transition.Subresource = DstSubResIndex; + BarrierDesc.Transition.StateBefore = ResourceStateFlagsToD3D12ResourceStates(TextureD3D12.GetState()); + BarrierDesc.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; + BarrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + pCmdList->ResourceBarrier(1, &BarrierDesc); + } - D3D12_TEXTURE_COPY_LOCATION DstLocation; - DstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - DstLocation.pResource = TextureD3D12.GetD3D12Resource(); - DstLocation.SubresourceIndex = static_cast(DstSubResIndex); + D3D12_TEXTURE_COPY_LOCATION DstLocation; + DstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + DstLocation.pResource = TextureD3D12.GetD3D12Resource(); + DstLocation.SubresourceIndex = static_cast(DstSubResIndex); - D3D12_TEXTURE_COPY_LOCATION SrcLocation; - SrcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - SrcLocation.pResource = pd3d12Buffer; - D3D12_PLACED_SUBRESOURCE_FOOTPRINT &Footpring = SrcLocation.PlacedFootprint; - Footpring.Offset = SrcOffset; - Footpring.Footprint.Width = static_cast(DstBox.MaxX - DstBox.MinX); - Footpring.Footprint.Height = static_cast(DstBox.MaxY - DstBox.MinY); - Footpring.Footprint.Depth = static_cast(DstBox.MaxZ - DstBox.MinZ); // Depth cannot be 0 - Footpring.Footprint.Format = TexFormatToDXGI_Format(TexDesc.Format); + D3D12_TEXTURE_COPY_LOCATION SrcLocation; + SrcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + SrcLocation.pResource = pd3d12Buffer; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT& Footpring = SrcLocation.PlacedFootprint; + Footpring.Offset = SrcOffset; + Footpring.Footprint.Width = static_cast(DstBox.MaxX - DstBox.MinX); + Footpring.Footprint.Height = static_cast(DstBox.MaxY - DstBox.MinY); + Footpring.Footprint.Depth = static_cast(DstBox.MaxZ - DstBox.MinZ); // Depth cannot be 0 + Footpring.Footprint.Format = TexFormatToDXGI_Format(TexDesc.Format); - Footpring.Footprint.RowPitch = static_cast(SrcStride); + Footpring.Footprint.RowPitch = static_cast(SrcStride); #ifdef _DEBUG - { - const auto& FmtAttribs = GetTextureFormatAttribs(TexDesc.Format); - const Uint32 RowCount = std::max((Footpring.Footprint.Height/FmtAttribs.BlockHeight), 1u); - VERIFY(BufferSize >= Footpring.Footprint.RowPitch * RowCount * Footpring.Footprint.Depth, "Buffer is not large enough"); - VERIFY(Footpring.Footprint.Depth == 1 || static_cast(SrcDepthStride) == Footpring.Footprint.RowPitch * RowCount, "Depth stride must be equal to the size of 2D plane"); - } + { + const auto& FmtAttribs = GetTextureFormatAttribs(TexDesc.Format); + const Uint32 RowCount = std::max((Footpring.Footprint.Height / FmtAttribs.BlockHeight), 1u); + VERIFY(BufferSize >= Footpring.Footprint.RowPitch * RowCount * Footpring.Footprint.Depth, "Buffer is not large enough"); + VERIFY(Footpring.Footprint.Depth == 1 || static_cast(SrcDepthStride) == Footpring.Footprint.RowPitch * RowCount, "Depth stride must be equal to the size of 2D plane"); + } #endif - D3D12_BOX D3D12SrcBox; - D3D12SrcBox.left = 0; - D3D12SrcBox.right = Footpring.Footprint.Width; - D3D12SrcBox.top = 0; - D3D12SrcBox.bottom = Footpring.Footprint.Height; - D3D12SrcBox.front = 0; - D3D12SrcBox.back = Footpring.Footprint.Depth; - CmdCtx.GetCommandList()->CopyTextureRegion( &DstLocation, - static_cast( DstBox.MinX ), - static_cast( DstBox.MinY ), - static_cast( DstBox.MinZ ), - &SrcLocation, &D3D12SrcBox); - - ++m_State.NumCommands; - - if (StateTransitionRequired) - { - std::swap(BarrierDesc.Transition.StateBefore, BarrierDesc.Transition.StateAfter); - pCmdList->ResourceBarrier(1, &BarrierDesc); - } + D3D12_BOX D3D12SrcBox; + D3D12SrcBox.left = 0; + D3D12SrcBox.right = Footpring.Footprint.Width; + D3D12SrcBox.top = 0; + D3D12SrcBox.bottom = Footpring.Footprint.Height; + D3D12SrcBox.front = 0; + D3D12SrcBox.back = Footpring.Footprint.Depth; + CmdCtx.GetCommandList()->CopyTextureRegion(&DstLocation, + static_cast(DstBox.MinX), + static_cast(DstBox.MinY), + static_cast(DstBox.MinZ), + &SrcLocation, &D3D12SrcBox); + + ++m_State.NumCommands; + + if (StateTransitionRequired) + { + std::swap(BarrierDesc.Transition.StateBefore, BarrierDesc.Transition.StateAfter); + pCmdList->ResourceBarrier(1, &BarrierDesc); } +} - void DeviceContextD3D12Impl::CopyTextureRegion(IBuffer* pSrcBuffer, - Uint32 SrcOffset, - Uint32 SrcStride, - Uint32 SrcDepthStride, - class TextureD3D12Impl& TextureD3D12, - Uint32 DstSubResIndex, - const Box& DstBox, - RESOURCE_STATE_TRANSITION_MODE BufferTransitionMode, - RESOURCE_STATE_TRANSITION_MODE TextureTransitionMode) +void DeviceContextD3D12Impl::CopyTextureRegion(IBuffer* pSrcBuffer, + Uint32 SrcOffset, + Uint32 SrcStride, + Uint32 SrcDepthStride, + class TextureD3D12Impl& TextureD3D12, + Uint32 DstSubResIndex, + const Box& DstBox, + RESOURCE_STATE_TRANSITION_MODE BufferTransitionMode, + RESOURCE_STATE_TRANSITION_MODE TextureTransitionMode) +{ + auto* pBufferD3D12 = ValidatedCast(pSrcBuffer); + if (pBufferD3D12->GetDesc().Usage == USAGE_DYNAMIC) + DEV_CHECK_ERR(pBufferD3D12->GetState() == RESOURCE_STATE_GENERIC_READ, "Dynamic buffer is expected to always be in RESOURCE_STATE_GENERIC_READ state"); + else { - auto* pBufferD3D12 = ValidatedCast(pSrcBuffer); - if (pBufferD3D12->GetDesc().Usage == USAGE_DYNAMIC) - DEV_CHECK_ERR(pBufferD3D12->GetState() == RESOURCE_STATE_GENERIC_READ, "Dynamic buffer is expected to always be in RESOURCE_STATE_GENERIC_READ state"); - else - { - if (BufferTransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION) - { - if (pBufferD3D12->IsInKnownState() && pBufferD3D12->GetState() != RESOURCE_STATE_GENERIC_READ) - GetCmdContext().TransitionResource(pBufferD3D12, RESOURCE_STATE_GENERIC_READ); - } -#ifdef DEVELOPMENT - else if (BufferTransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY) - { - DvpVerifyBufferState(*pBufferD3D12, RESOURCE_STATE_COPY_SOURCE, "Using buffer as copy source (DeviceContextD3D12Impl::CopyTextureRegion)"); - } -#endif - } - GetCmdContext().FlushResourceBarriers(); - size_t DataStartByteOffset = 0; - auto* pd3d12Buffer = pBufferD3D12->GetD3D12Buffer(DataStartByteOffset, this); - CopyTextureRegion(pd3d12Buffer, static_cast(DataStartByteOffset) + SrcOffset, SrcStride, SrcDepthStride, - pBufferD3D12->GetDesc().uiSizeInBytes, TextureD3D12, DstSubResIndex, DstBox, TextureTransitionMode); - } - - DeviceContextD3D12Impl::TextureUploadSpace DeviceContextD3D12Impl::AllocateTextureUploadSpace(TEXTURE_FORMAT TexFmt, - const Box& Region) - { - TextureUploadSpace UploadSpace; - VERIFY_EXPR(Region.MaxX > Region.MinX && Region.MaxY > Region.MinY && Region.MaxZ > Region.MinZ); - auto UpdateRegionWidth = Region.MaxX - Region.MinX; - auto UpdateRegionHeight = Region.MaxY - Region.MinY; - auto UpdateRegionDepth = Region.MaxZ - Region.MinZ; - const auto& FmtAttribs = GetTextureFormatAttribs(TexFmt); - if(FmtAttribs.ComponentType == COMPONENT_TYPE_COMPRESSED) + if (BufferTransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION) { - // Box must be aligned by the calling function - VERIFY_EXPR((UpdateRegionWidth % FmtAttribs.BlockWidth) == 0); - VERIFY_EXPR((UpdateRegionHeight % FmtAttribs.BlockHeight) == 0); - UploadSpace.RowSize = UpdateRegionWidth / Uint32{FmtAttribs.BlockWidth} * Uint32{FmtAttribs.ComponentSize}; - UploadSpace.RowCount = UpdateRegionHeight / FmtAttribs.BlockHeight; + if (pBufferD3D12->IsInKnownState() && pBufferD3D12->GetState() != RESOURCE_STATE_GENERIC_READ) + GetCmdContext().TransitionResource(pBufferD3D12, RESOURCE_STATE_GENERIC_READ); } - else +#ifdef DEVELOPMENT + else if (BufferTransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY) { - UploadSpace.RowSize = UpdateRegionWidth * Uint32{FmtAttribs.ComponentSize} * Uint32{FmtAttribs.NumComponents}; - UploadSpace.RowCount = UpdateRegionHeight; + DvpVerifyBufferState(*pBufferD3D12, RESOURCE_STATE_COPY_SOURCE, "Using buffer as copy source (DeviceContextD3D12Impl::CopyTextureRegion)"); } - // RowPitch must be a multiple of 256 (aka. D3D12_TEXTURE_DATA_PITCH_ALIGNMENT) - UploadSpace.Stride = (UploadSpace.RowSize + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT-1) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT-1); - UploadSpace.DepthStride = UploadSpace.RowCount * UploadSpace.Stride; - const auto MemorySize = UpdateRegionDepth * UploadSpace.DepthStride; - UploadSpace.Allocation = AllocateDynamicSpace(MemorySize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); - UploadSpace.AlignedOffset = (UploadSpace.Allocation.Offset + (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT-1)) & ~(D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT-1); - UploadSpace.Region = Region; - - return UploadSpace; - } - - void DeviceContextD3D12Impl::UpdateTextureRegion(const void* pSrcData, - Uint32 SrcStride, - Uint32 SrcDepthStride, - TextureD3D12Impl& TextureD3D12, - Uint32 DstSubResIndex, - const Box& DstBox, - RESOURCE_STATE_TRANSITION_MODE TextureTransitionMode) - { - const auto& TexDesc = TextureD3D12.GetDesc(); - auto UploadSpace = AllocateTextureUploadSpace(TexDesc.Format, DstBox); - auto UpdateRegionDepth = DstBox.MaxZ-DstBox.MinZ; +#endif + } + GetCmdContext().FlushResourceBarriers(); + size_t DataStartByteOffset = 0; + auto* pd3d12Buffer = pBufferD3D12->GetD3D12Buffer(DataStartByteOffset, this); + CopyTextureRegion(pd3d12Buffer, static_cast(DataStartByteOffset) + SrcOffset, SrcStride, SrcDepthStride, + pBufferD3D12->GetDesc().uiSizeInBytes, TextureD3D12, DstSubResIndex, DstBox, TextureTransitionMode); +} + +DeviceContextD3D12Impl::TextureUploadSpace DeviceContextD3D12Impl::AllocateTextureUploadSpace(TEXTURE_FORMAT TexFmt, + const Box& Region) +{ + TextureUploadSpace UploadSpace; + VERIFY_EXPR(Region.MaxX > Region.MinX && Region.MaxY > Region.MinY && Region.MaxZ > Region.MinZ); + auto UpdateRegionWidth = Region.MaxX - Region.MinX; + auto UpdateRegionHeight = Region.MaxY - Region.MinY; + auto UpdateRegionDepth = Region.MaxZ - Region.MinZ; + const auto& FmtAttribs = GetTextureFormatAttribs(TexFmt); + if (FmtAttribs.ComponentType == COMPONENT_TYPE_COMPRESSED) + { + // Box must be aligned by the calling function + VERIFY_EXPR((UpdateRegionWidth % FmtAttribs.BlockWidth) == 0); + VERIFY_EXPR((UpdateRegionHeight % FmtAttribs.BlockHeight) == 0); + UploadSpace.RowSize = UpdateRegionWidth / Uint32{FmtAttribs.BlockWidth} * Uint32{FmtAttribs.ComponentSize}; + UploadSpace.RowCount = UpdateRegionHeight / FmtAttribs.BlockHeight; + } + else + { + UploadSpace.RowSize = UpdateRegionWidth * Uint32{FmtAttribs.ComponentSize} * Uint32{FmtAttribs.NumComponents}; + UploadSpace.RowCount = UpdateRegionHeight; + } + // RowPitch must be a multiple of 256 (aka. D3D12_TEXTURE_DATA_PITCH_ALIGNMENT) + UploadSpace.Stride = (UploadSpace.RowSize + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1); + UploadSpace.DepthStride = UploadSpace.RowCount * UploadSpace.Stride; + const auto MemorySize = UpdateRegionDepth * UploadSpace.DepthStride; + UploadSpace.Allocation = AllocateDynamicSpace(MemorySize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); + UploadSpace.AlignedOffset = (UploadSpace.Allocation.Offset + (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT - 1)) & ~(D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT - 1); + UploadSpace.Region = Region; + + return UploadSpace; +} + +void DeviceContextD3D12Impl::UpdateTextureRegion(const void* pSrcData, + Uint32 SrcStride, + Uint32 SrcDepthStride, + TextureD3D12Impl& TextureD3D12, + Uint32 DstSubResIndex, + const Box& DstBox, + RESOURCE_STATE_TRANSITION_MODE TextureTransitionMode) +{ + const auto& TexDesc = TextureD3D12.GetDesc(); + auto UploadSpace = AllocateTextureUploadSpace(TexDesc.Format, DstBox); + auto UpdateRegionDepth = DstBox.MaxZ - DstBox.MinZ; #ifdef _DEBUG - { - VERIFY(SrcStride >= UploadSpace.RowSize, "Source data stride (", SrcStride, ") is below the image row size (", UploadSpace.RowSize, ")"); - const Uint32 PlaneSize = SrcStride * UploadSpace.RowCount; - VERIFY(UpdateRegionDepth == 1 || SrcDepthStride >= PlaneSize, "Source data depth stride (", SrcDepthStride, ") is below the image plane size (", PlaneSize, ")"); - } + { + VERIFY(SrcStride >= UploadSpace.RowSize, "Source data stride (", SrcStride, ") is below the image row size (", UploadSpace.RowSize, ")"); + const Uint32 PlaneSize = SrcStride * UploadSpace.RowCount; + VERIFY(UpdateRegionDepth == 1 || SrcDepthStride >= PlaneSize, "Source data depth stride (", SrcDepthStride, ") is below the image plane size (", PlaneSize, ")"); + } #endif - const auto AlignedOffset = UploadSpace.AlignedOffset; + const auto AlignedOffset = UploadSpace.AlignedOffset; - for(Uint32 DepthSlice = 0; DepthSlice < UpdateRegionDepth; ++DepthSlice) + for (Uint32 DepthSlice = 0; DepthSlice < UpdateRegionDepth; ++DepthSlice) + { + for (Uint32 row = 0; row < UploadSpace.RowCount; ++row) { - for(Uint32 row = 0; row < UploadSpace.RowCount; ++row) - { - const auto* pSrcPtr = - reinterpret_cast(pSrcData) - + row * SrcStride - + DepthSlice * SrcDepthStride; - auto* pDstPtr = - reinterpret_cast(UploadSpace.Allocation.CPUAddress) - + (AlignedOffset - UploadSpace.Allocation.Offset) - + row * UploadSpace.Stride - + DepthSlice * UploadSpace.DepthStride; - - memcpy(pDstPtr, pSrcPtr, UploadSpace.RowSize); - } + const auto* pSrcPtr = + reinterpret_cast(pSrcData) + row * SrcStride + DepthSlice * SrcDepthStride; + auto* pDstPtr = + reinterpret_cast(UploadSpace.Allocation.CPUAddress) + (AlignedOffset - UploadSpace.Allocation.Offset) + row * UploadSpace.Stride + DepthSlice * UploadSpace.DepthStride; + + memcpy(pDstPtr, pSrcPtr, UploadSpace.RowSize); } - CopyTextureRegion(UploadSpace.Allocation.pBuffer, - static_cast(AlignedOffset), - UploadSpace.Stride, - UploadSpace.DepthStride, - static_cast(UploadSpace.Allocation.Size - (AlignedOffset - UploadSpace.Allocation.Offset)), - TextureD3D12, - DstSubResIndex, - DstBox, - TextureTransitionMode); - } - - void DeviceContextD3D12Impl::MapTextureSubresource( ITexture* pTexture, - Uint32 MipLevel, - Uint32 ArraySlice, - MAP_TYPE MapType, - MAP_FLAGS MapFlags, - const Box* pMapRegion, - MappedTextureSubresource& MappedData ) - { - TDeviceContextBase::MapTextureSubresource(pTexture, MipLevel, ArraySlice, MapType, MapFlags, pMapRegion, MappedData); - - auto& TextureD3D12 = *ValidatedCast(pTexture); - const auto& TexDesc = TextureD3D12.GetDesc(); - auto Subres = D3D12CalcSubresource(MipLevel, ArraySlice, 0, TexDesc.MipLevels, TexDesc.ArraySize); - if (TexDesc.Usage == USAGE_DYNAMIC) - { - if (MapType != MAP_WRITE) - { - LOG_ERROR("USAGE_DEFAULT textures can only be mapped for writing"); - MappedData = MappedTextureSubresource{}; - return; - } + } + CopyTextureRegion(UploadSpace.Allocation.pBuffer, + static_cast(AlignedOffset), + UploadSpace.Stride, + UploadSpace.DepthStride, + static_cast(UploadSpace.Allocation.Size - (AlignedOffset - UploadSpace.Allocation.Offset)), + TextureD3D12, + DstSubResIndex, + DstBox, + TextureTransitionMode); +} - if( (MapFlags & (MAP_FLAG_DISCARD | MAP_FLAG_DO_NOT_SYNCHRONIZE)) != 0 ) - LOG_INFO_MESSAGE_ONCE("Mapping textures with flags MAP_FLAG_DISCARD or MAP_FLAG_DO_NOT_SYNCHRONIZE has no effect in D3D12 backend"); +void DeviceContextD3D12Impl::MapTextureSubresource(ITexture* pTexture, + Uint32 MipLevel, + Uint32 ArraySlice, + MAP_TYPE MapType, + MAP_FLAGS MapFlags, + const Box* pMapRegion, + MappedTextureSubresource& MappedData) +{ + TDeviceContextBase::MapTextureSubresource(pTexture, MipLevel, ArraySlice, MapType, MapFlags, pMapRegion, MappedData); - Box FullExtentBox; - if (pMapRegion == nullptr) - { - FullExtentBox.MaxX = std::max(TexDesc.Width >> MipLevel, 1u); - FullExtentBox.MaxY = std::max(TexDesc.Height >> MipLevel, 1u); - if (TexDesc.Type == RESOURCE_DIM_TEX_3D) - FullExtentBox.MaxZ = std::max(TexDesc.Depth >> MipLevel, 1u); - pMapRegion = &FullExtentBox; - } + auto& TextureD3D12 = *ValidatedCast(pTexture); + const auto& TexDesc = TextureD3D12.GetDesc(); + auto Subres = D3D12CalcSubresource(MipLevel, ArraySlice, 0, TexDesc.MipLevels, TexDesc.ArraySize); + if (TexDesc.Usage == USAGE_DYNAMIC) + { + if (MapType != MAP_WRITE) + { + LOG_ERROR("USAGE_DEFAULT textures can only be mapped for writing"); + MappedData = MappedTextureSubresource{}; + return; + } - auto UploadSpace = AllocateTextureUploadSpace(TexDesc.Format, *pMapRegion); - MappedData.pData = reinterpret_cast(UploadSpace.Allocation.CPUAddress) + (UploadSpace.AlignedOffset - UploadSpace.Allocation.Offset); - MappedData.Stride = UploadSpace.Stride; - MappedData.DepthStride = UploadSpace.DepthStride; + if ((MapFlags & (MAP_FLAG_DISCARD | MAP_FLAG_DO_NOT_SYNCHRONIZE)) != 0) + LOG_INFO_MESSAGE_ONCE("Mapping textures with flags MAP_FLAG_DISCARD or MAP_FLAG_DO_NOT_SYNCHRONIZE has no effect in D3D12 backend"); - auto it = m_MappedTextures.emplace(MappedTextureKey{&TextureD3D12, Subres}, std::move(UploadSpace)); - if(!it.second) - LOG_ERROR_MESSAGE("Mip level ", MipLevel, ", slice ", ArraySlice, " of texture '", TexDesc.Name, "' has already been mapped"); - } - else if (TexDesc.Usage == USAGE_STAGING) + Box FullExtentBox; + if (pMapRegion == nullptr) { - if( (MapFlags & MAP_FLAG_DO_NOT_SYNCHRONIZE) == 0 ) - { - LOG_WARNING_MESSAGE_ONCE("Mapping staging textures is never synchronized in D3D12 backend. " - "Application must use fences or other synchronization methods to explicitly synchronize " - "access and map texture with MAP_FLAG_DO_NOT_SYNCHRONIZE flag."); - } + FullExtentBox.MaxX = std::max(TexDesc.Width >> MipLevel, 1u); + FullExtentBox.MaxY = std::max(TexDesc.Height >> MipLevel, 1u); + if (TexDesc.Type == RESOURCE_DIM_TEX_3D) + FullExtentBox.MaxZ = std::max(TexDesc.Depth >> MipLevel, 1u); + pMapRegion = &FullExtentBox; + } - const auto& Footprint = TextureD3D12.GetStagingFootprint(Subres); - - // It is valid to specify the CPU won't read any data by passing a range where - // End is less than or equal to Begin. - // https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/nf-d3d12-id3d12resource-map - D3D12_RANGE InvalidateRange = {1,0}; - if (MapType == MAP_READ) - { - DEV_CHECK_ERR((TexDesc.CPUAccessFlags & CPU_ACCESS_READ), "Texture '", TexDesc.Name, "' was not created with CPU_ACCESS_READ flag and can't be mapped for reading"); - // Resources on D3D12_HEAP_TYPE_READBACK heaps do not support persistent map. - InvalidateRange.Begin = static_cast(Footprint.Offset); - const auto& NextFootprint = TextureD3D12.GetStagingFootprint(Subres+1); - InvalidateRange.End = static_cast(NextFootprint.Offset); - } - else if (MapType == MAP_WRITE) - { - DEV_CHECK_ERR((TexDesc.CPUAccessFlags & CPU_ACCESS_WRITE), "Texture '", TexDesc.Name, "' was not created with CPU_ACCESS_WRITE flag and can't be mapped for writing"); - } + auto UploadSpace = AllocateTextureUploadSpace(TexDesc.Format, *pMapRegion); + MappedData.pData = reinterpret_cast(UploadSpace.Allocation.CPUAddress) + (UploadSpace.AlignedOffset - UploadSpace.Allocation.Offset); + MappedData.Stride = UploadSpace.Stride; + MappedData.DepthStride = UploadSpace.DepthStride; - // Nested Map() calls are supported and are ref-counted. The first call to Map() allocates - // a CPU virtual address range for the resource. The last call to Unmap deallocates the CPU - // virtual address range. - - // Map() invalidates the CPU cache, when necessary, so that CPU reads to this address - // reflect any modifications made by the GPU. - void* pMappedDataPtr = nullptr; - TextureD3D12.GetD3D12Resource()->Map(0, &InvalidateRange, &pMappedDataPtr); - MappedData.pData = reinterpret_cast(pMappedDataPtr) + Footprint.Offset; - MappedData.Stride = static_cast(Footprint.Footprint.RowPitch); - const auto& FmtAttribs = GetTextureFormatAttribs(TexDesc.Format); - MappedData.DepthStride = static_cast(Footprint.Footprint.Height / FmtAttribs.BlockHeight * Footprint.Footprint.RowPitch); - } - else + auto it = m_MappedTextures.emplace(MappedTextureKey{&TextureD3D12, Subres}, std::move(UploadSpace)); + if (!it.second) + LOG_ERROR_MESSAGE("Mip level ", MipLevel, ", slice ", ArraySlice, " of texture '", TexDesc.Name, "' has already been mapped"); + } + else if (TexDesc.Usage == USAGE_STAGING) + { + if ((MapFlags & MAP_FLAG_DO_NOT_SYNCHRONIZE) == 0) { - UNSUPPORTED(GetUsageString(TexDesc.Usage), " textures cannot currently be mapped in D3D12 back-end"); + LOG_WARNING_MESSAGE_ONCE("Mapping staging textures is never synchronized in D3D12 backend. " + "Application must use fences or other synchronization methods to explicitly synchronize " + "access and map texture with MAP_FLAG_DO_NOT_SYNCHRONIZE flag."); } - } - void DeviceContextD3D12Impl::UnmapTextureSubresource(ITexture* pTexture, Uint32 MipLevel, Uint32 ArraySlice) - { - TDeviceContextBase::UnmapTextureSubresource( pTexture, MipLevel, ArraySlice); + const auto& Footprint = TextureD3D12.GetStagingFootprint(Subres); - TextureD3D12Impl& TextureD3D12 = *ValidatedCast(pTexture); - const auto& TexDesc = TextureD3D12.GetDesc(); - auto Subres = D3D12CalcSubresource(MipLevel, ArraySlice, 0, TexDesc.MipLevels, TexDesc.ArraySize); - if (TexDesc.Usage == USAGE_DYNAMIC) + // It is valid to specify the CPU won't read any data by passing a range where + // End is less than or equal to Begin. + // https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/nf-d3d12-id3d12resource-map + D3D12_RANGE InvalidateRange = {1, 0}; + if (MapType == MAP_READ) { - auto UploadSpaceIt = m_MappedTextures.find(MappedTextureKey{&TextureD3D12, Subres}); - if(UploadSpaceIt != m_MappedTextures.end()) - { - auto& UploadSpace = UploadSpaceIt->second; - CopyTextureRegion(UploadSpace.Allocation.pBuffer, - UploadSpace.AlignedOffset, - UploadSpace.Stride, - UploadSpace.DepthStride, - static_cast(UploadSpace.Allocation.Size - (UploadSpace.AlignedOffset - UploadSpace.Allocation.Offset)), - TextureD3D12, - Subres, - UploadSpace.Region, - RESOURCE_STATE_TRANSITION_MODE_TRANSITION); - m_MappedTextures.erase(UploadSpaceIt); - } - else - { - LOG_ERROR_MESSAGE("Failed to unmap mip level ", MipLevel, ", slice ", ArraySlice, " of texture '", TexDesc.Name, "'. The texture has either been unmapped already or has not been mapped"); - } + DEV_CHECK_ERR((TexDesc.CPUAccessFlags & CPU_ACCESS_READ), "Texture '", TexDesc.Name, "' was not created with CPU_ACCESS_READ flag and can't be mapped for reading"); + // Resources on D3D12_HEAP_TYPE_READBACK heaps do not support persistent map. + InvalidateRange.Begin = static_cast(Footprint.Offset); + const auto& NextFootprint = TextureD3D12.GetStagingFootprint(Subres + 1); + InvalidateRange.End = static_cast(NextFootprint.Offset); } - else if (TexDesc.Usage == USAGE_STAGING) + else if (MapType == MAP_WRITE) { - // It is valid to specify the CPU didn't write any data by passing a range where - // End is less than or equal to Begin. - // https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/nf-d3d12-id3d12resource-unmap - D3D12_RANGE FlushRange = {1, 0}; + DEV_CHECK_ERR((TexDesc.CPUAccessFlags & CPU_ACCESS_WRITE), "Texture '", TexDesc.Name, "' was not created with CPU_ACCESS_WRITE flag and can't be mapped for writing"); + } - if (TexDesc.CPUAccessFlags == CPU_ACCESS_WRITE) - { - const auto& Footprint = TextureD3D12.GetStagingFootprint(Subres); - const auto& NextFootprint = TextureD3D12.GetStagingFootprint(Subres+1); - FlushRange.Begin = static_cast(Footprint.Offset); - FlushRange.End = static_cast(NextFootprint.Offset); - } + // Nested Map() calls are supported and are ref-counted. The first call to Map() allocates + // a CPU virtual address range for the resource. The last call to Unmap deallocates the CPU + // virtual address range. - // Map and Unmap can be called by multiple threads safely. Nested Map calls are supported - // and are ref-counted. The first call to Map allocates a CPU virtual address range for the - // resource. The last call to Unmap deallocates the CPU virtual address range. + // Map() invalidates the CPU cache, when necessary, so that CPU reads to this address + // reflect any modifications made by the GPU. + void* pMappedDataPtr = nullptr; + TextureD3D12.GetD3D12Resource()->Map(0, &InvalidateRange, &pMappedDataPtr); + MappedData.pData = reinterpret_cast(pMappedDataPtr) + Footprint.Offset; + MappedData.Stride = static_cast(Footprint.Footprint.RowPitch); + const auto& FmtAttribs = GetTextureFormatAttribs(TexDesc.Format); + MappedData.DepthStride = static_cast(Footprint.Footprint.Height / FmtAttribs.BlockHeight * Footprint.Footprint.RowPitch); + } + else + { + UNSUPPORTED(GetUsageString(TexDesc.Usage), " textures cannot currently be mapped in D3D12 back-end"); + } +} - // Unmap() flushes the CPU cache, when necessary, so that GPU reads to this address reflect - // any modifications made by the CPU. - TextureD3D12.GetD3D12Resource()->Unmap(0, &FlushRange); +void DeviceContextD3D12Impl::UnmapTextureSubresource(ITexture* pTexture, Uint32 MipLevel, Uint32 ArraySlice) +{ + TDeviceContextBase::UnmapTextureSubresource(pTexture, MipLevel, ArraySlice); + + TextureD3D12Impl& TextureD3D12 = *ValidatedCast(pTexture); + const auto& TexDesc = TextureD3D12.GetDesc(); + auto Subres = D3D12CalcSubresource(MipLevel, ArraySlice, 0, TexDesc.MipLevels, TexDesc.ArraySize); + if (TexDesc.Usage == USAGE_DYNAMIC) + { + auto UploadSpaceIt = m_MappedTextures.find(MappedTextureKey{&TextureD3D12, Subres}); + if (UploadSpaceIt != m_MappedTextures.end()) + { + auto& UploadSpace = UploadSpaceIt->second; + CopyTextureRegion(UploadSpace.Allocation.pBuffer, + UploadSpace.AlignedOffset, + UploadSpace.Stride, + UploadSpace.DepthStride, + static_cast(UploadSpace.Allocation.Size - (UploadSpace.AlignedOffset - UploadSpace.Allocation.Offset)), + TextureD3D12, + Subres, + UploadSpace.Region, + RESOURCE_STATE_TRANSITION_MODE_TRANSITION); + m_MappedTextures.erase(UploadSpaceIt); } else { - UNSUPPORTED(GetUsageString(TexDesc.Usage), " textures cannot currently be mapped in D3D12 back-end"); + LOG_ERROR_MESSAGE("Failed to unmap mip level ", MipLevel, ", slice ", ArraySlice, " of texture '", TexDesc.Name, "'. The texture has either been unmapped already or has not been mapped"); } } + else if (TexDesc.Usage == USAGE_STAGING) + { + // It is valid to specify the CPU didn't write any data by passing a range where + // End is less than or equal to Begin. + // https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/nf-d3d12-id3d12resource-unmap + D3D12_RANGE FlushRange = {1, 0}; + + if (TexDesc.CPUAccessFlags == CPU_ACCESS_WRITE) + { + const auto& Footprint = TextureD3D12.GetStagingFootprint(Subres); + const auto& NextFootprint = TextureD3D12.GetStagingFootprint(Subres + 1); + FlushRange.Begin = static_cast(Footprint.Offset); + FlushRange.End = static_cast(NextFootprint.Offset); + } + // Map and Unmap can be called by multiple threads safely. Nested Map calls are supported + // and are ref-counted. The first call to Map allocates a CPU virtual address range for the + // resource. The last call to Unmap deallocates the CPU virtual address range. - void DeviceContextD3D12Impl::GenerateMips(ITextureView* pTexView) + // Unmap() flushes the CPU cache, when necessary, so that GPU reads to this address reflect + // any modifications made by the CPU. + TextureD3D12.GetD3D12Resource()->Unmap(0, &FlushRange); + } + else { - TDeviceContextBase::GenerateMips(pTexView); - auto& Ctx = GetCmdContext(); - const auto& MipsGenerator = m_pDevice->GetMipsGenerator(); - MipsGenerator.GenerateMips(m_pDevice->GetD3D12Device(), ValidatedCast(pTexView), Ctx); - ++m_State.NumCommands; + UNSUPPORTED(GetUsageString(TexDesc.Usage), " textures cannot currently be mapped in D3D12 back-end"); } +} - void DeviceContextD3D12Impl::FinishCommandList(ICommandList** ppCommandList) - { - CommandListD3D12Impl* pCmdListD3D12( NEW_RC_OBJ(m_CmdListAllocator, "CommandListD3D12Impl instance", CommandListD3D12Impl) - (m_pDevice, this, std::move(m_CurrCmdCtx)) ); - pCmdListD3D12->QueryInterface( IID_CommandList, reinterpret_cast(ppCommandList) ); - Flush(true); - InvalidateState(); - } +void DeviceContextD3D12Impl::GenerateMips(ITextureView* pTexView) +{ + TDeviceContextBase::GenerateMips(pTexView); - void DeviceContextD3D12Impl::ExecuteCommandList(ICommandList* pCommandList) - { - if (m_bIsDeferred) - { - LOG_ERROR_MESSAGE("Only immediate context can execute command list"); - return; - } - // First execute commands in this context - Flush(true); + auto& Ctx = GetCmdContext(); - InvalidateState(); + const auto& MipsGenerator = m_pDevice->GetMipsGenerator(); + MipsGenerator.GenerateMips(m_pDevice->GetD3D12Device(), ValidatedCast(pTexView), Ctx); + ++m_State.NumCommands; +} - CommandListD3D12Impl* pCmdListD3D12 = ValidatedCast(pCommandList); - VERIFY_EXPR(m_PendingFences.empty()); - RefCntAutoPtr pDeferredCtx; - auto CmdContext = pCmdListD3D12->Close(pDeferredCtx); - m_pDevice->CloseAndExecuteCommandContext(m_CommandQueueId, std::move(CmdContext), true, nullptr); - // Set the bit in the deferred context cmd queue mask corresponding to cmd queue of this context - pDeferredCtx->m_SubmittedBuffersCmdQueueMask |= Uint64{1} << m_CommandQueueId; - } +void DeviceContextD3D12Impl::FinishCommandList(ICommandList** ppCommandList) +{ + CommandListD3D12Impl* pCmdListD3D12(NEW_RC_OBJ(m_CmdListAllocator, "CommandListD3D12Impl instance", CommandListD3D12Impl)(m_pDevice, this, std::move(m_CurrCmdCtx))); + pCmdListD3D12->QueryInterface(IID_CommandList, reinterpret_cast(ppCommandList)); + Flush(true); - void DeviceContextD3D12Impl::SignalFence(IFence* pFence, Uint64 Value) - { - VERIFY(!m_bIsDeferred, "Fence can only be signaled from immediate context"); - m_PendingFences.emplace_back(Value, pFence); - } + InvalidateState(); +} - void DeviceContextD3D12Impl::WaitForFence(IFence* pFence, Uint64 Value, bool FlushContext) +void DeviceContextD3D12Impl::ExecuteCommandList(ICommandList* pCommandList) +{ + if (m_bIsDeferred) { - VERIFY(!m_bIsDeferred, "Fence can only be waited from immediate context"); - if (FlushContext) - Flush(); - auto* pFenceD3D12 = ValidatedCast(pFence); - pFenceD3D12->WaitForCompletion(Value); + LOG_ERROR_MESSAGE("Only immediate context can execute command list"); + return; } + // First execute commands in this context + Flush(true); + + InvalidateState(); + + CommandListD3D12Impl* pCmdListD3D12 = ValidatedCast(pCommandList); + VERIFY_EXPR(m_PendingFences.empty()); + RefCntAutoPtr pDeferredCtx; + auto CmdContext = pCmdListD3D12->Close(pDeferredCtx); + m_pDevice->CloseAndExecuteCommandContext(m_CommandQueueId, std::move(CmdContext), true, nullptr); + // Set the bit in the deferred context cmd queue mask corresponding to cmd queue of this context + pDeferredCtx->m_SubmittedBuffersCmdQueueMask |= Uint64{1} << m_CommandQueueId; +} - void DeviceContextD3D12Impl::WaitForIdle() - { - VERIFY(!m_bIsDeferred, "Only immediate contexts can be idled"); +void DeviceContextD3D12Impl::SignalFence(IFence* pFence, Uint64 Value) +{ + VERIFY(!m_bIsDeferred, "Fence can only be signaled from immediate context"); + m_PendingFences.emplace_back(Value, pFence); +} + +void DeviceContextD3D12Impl::WaitForFence(IFence* pFence, Uint64 Value, bool FlushContext) +{ + VERIFY(!m_bIsDeferred, "Fence can only be waited from immediate context"); + if (FlushContext) Flush(); - m_pDevice->IdleCommandQueue(m_CommandQueueId, true); - } + auto* pFenceD3D12 = ValidatedCast(pFence); + pFenceD3D12->WaitForCompletion(Value); +} - void DeviceContextD3D12Impl::TransitionResourceStates(Uint32 BarrierCount, StateTransitionDesc* pResourceBarriers) - { - auto& CmdCtx = GetCmdContext(); - for(Uint32 i = 0; i < BarrierCount; ++i) - { -#ifdef DEVELOPMENT - DvpVerifyStateTransitionDesc(pResourceBarriers[i]); -#endif - CmdCtx.TransitionResource(pResourceBarriers[i]); - } - } +void DeviceContextD3D12Impl::WaitForIdle() +{ + VERIFY(!m_bIsDeferred, "Only immediate contexts can be idled"); + Flush(); + m_pDevice->IdleCommandQueue(m_CommandQueueId, true); +} - void DeviceContextD3D12Impl::TransitionOrVerifyBufferState(CommandContext& CmdCtx, - BufferD3D12Impl& Buffer, - RESOURCE_STATE_TRANSITION_MODE TransitionMode, - RESOURCE_STATE RequiredState, - const char* OperationName) +void DeviceContextD3D12Impl::TransitionResourceStates(Uint32 BarrierCount, StateTransitionDesc* pResourceBarriers) +{ + auto& CmdCtx = GetCmdContext(); + for (Uint32 i = 0; i < BarrierCount; ++i) { - if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION) - { - if (Buffer.IsInKnownState() && !Buffer.CheckState(RequiredState)) - CmdCtx.TransitionResource(&Buffer, RequiredState); - } #ifdef DEVELOPMENT - else if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY) - { - DvpVerifyBufferState(Buffer, RequiredState, OperationName); - } + DvpVerifyStateTransitionDesc(pResourceBarriers[i]); #endif + CmdCtx.TransitionResource(pResourceBarriers[i]); } +} - void DeviceContextD3D12Impl::TransitionOrVerifyTextureState(CommandContext& CmdCtx, - TextureD3D12Impl& Texture, - RESOURCE_STATE_TRANSITION_MODE TransitionMode, - RESOURCE_STATE RequiredState, - const char* OperationName) +void DeviceContextD3D12Impl::TransitionOrVerifyBufferState(CommandContext& CmdCtx, + BufferD3D12Impl& Buffer, + RESOURCE_STATE_TRANSITION_MODE TransitionMode, + RESOURCE_STATE RequiredState, + const char* OperationName) +{ + if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION) { - if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION) - { - if (Texture.IsInKnownState() && !Texture.CheckState(RequiredState)) - CmdCtx.TransitionResource(&Texture, RequiredState); - } -#ifdef DEVELOPMENT - else if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY) - { - DvpVerifyTextureState(Texture, RequiredState, OperationName); - } -#endif + if (Buffer.IsInKnownState() && !Buffer.CheckState(RequiredState)) + CmdCtx.TransitionResource(&Buffer, RequiredState); } - - void DeviceContextD3D12Impl::TransitionTextureState(ITexture *pTexture, D3D12_RESOURCE_STATES State) +#ifdef DEVELOPMENT + else if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY) { - VERIFY_EXPR(pTexture != nullptr); - DEV_CHECK_ERR(pTexture->GetState() != RESOURCE_STATE_UNKNOWN, "Texture state is unknown"); - auto& CmdCtx = GetCmdContext(); - CmdCtx.TransitionResource(ValidatedCast(pTexture), D3D12ResourceStatesToResourceStateFlags(State)); + DvpVerifyBufferState(Buffer, RequiredState, OperationName); } +#endif +} - void DeviceContextD3D12Impl::TransitionBufferState(IBuffer *pBuffer, D3D12_RESOURCE_STATES State) +void DeviceContextD3D12Impl::TransitionOrVerifyTextureState(CommandContext& CmdCtx, + TextureD3D12Impl& Texture, + RESOURCE_STATE_TRANSITION_MODE TransitionMode, + RESOURCE_STATE RequiredState, + const char* OperationName) +{ + if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION) { - VERIFY_EXPR(pBuffer != nullptr); - DEV_CHECK_ERR(pBuffer->GetState() != RESOURCE_STATE_UNKNOWN, "Buffer state is unknown"); - auto& CmdCtx = GetCmdContext(); - CmdCtx.TransitionResource(ValidatedCast(pBuffer), D3D12ResourceStatesToResourceStateFlags(State)); + if (Texture.IsInKnownState() && !Texture.CheckState(RequiredState)) + CmdCtx.TransitionResource(&Texture, RequiredState); } - - ID3D12GraphicsCommandList* DeviceContextD3D12Impl::GetD3D12CommandList() +#ifdef DEVELOPMENT + else if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY) { - auto& CmdCtx = GetCmdContext(); - return CmdCtx.GetCommandList(); + DvpVerifyTextureState(Texture, RequiredState, OperationName); } +#endif +} - void DeviceContextD3D12Impl::ResolveTextureSubresource(ITexture* pSrcTexture, - ITexture* pDstTexture, - const ResolveTextureSubresourceAttribs& ResolveAttribs) - { - TDeviceContextBase::ResolveTextureSubresource(pSrcTexture, pDstTexture, ResolveAttribs); +void DeviceContextD3D12Impl::TransitionTextureState(ITexture* pTexture, D3D12_RESOURCE_STATES State) +{ + VERIFY_EXPR(pTexture != nullptr); + DEV_CHECK_ERR(pTexture->GetState() != RESOURCE_STATE_UNKNOWN, "Texture state is unknown"); + auto& CmdCtx = GetCmdContext(); + CmdCtx.TransitionResource(ValidatedCast(pTexture), D3D12ResourceStatesToResourceStateFlags(State)); +} + +void DeviceContextD3D12Impl::TransitionBufferState(IBuffer* pBuffer, D3D12_RESOURCE_STATES State) +{ + VERIFY_EXPR(pBuffer != nullptr); + DEV_CHECK_ERR(pBuffer->GetState() != RESOURCE_STATE_UNKNOWN, "Buffer state is unknown"); + auto& CmdCtx = GetCmdContext(); + CmdCtx.TransitionResource(ValidatedCast(pBuffer), D3D12ResourceStatesToResourceStateFlags(State)); +} + +ID3D12GraphicsCommandList* DeviceContextD3D12Impl::GetD3D12CommandList() +{ + auto& CmdCtx = GetCmdContext(); + return CmdCtx.GetCommandList(); +} - auto* pSrcTexD3D12 = ValidatedCast(pSrcTexture); - auto* pDstTexD3D12 = ValidatedCast(pDstTexture); - const auto& SrcTexDesc = pSrcTexD3D12->GetDesc(); - const auto& DstTexDesc = pDstTexD3D12->GetDesc(); +void DeviceContextD3D12Impl::ResolveTextureSubresource(ITexture* pSrcTexture, + ITexture* pDstTexture, + const ResolveTextureSubresourceAttribs& ResolveAttribs) +{ + TDeviceContextBase::ResolveTextureSubresource(pSrcTexture, pDstTexture, ResolveAttribs); - auto& CmdCtx = GetCmdContext(); - TransitionOrVerifyTextureState(CmdCtx, *pSrcTexD3D12, ResolveAttribs.SrcTextureTransitionMode, RESOURCE_STATE_RESOLVE_SOURCE, "Resolving multi-sampled texture (DeviceContextD3D12Impl::ResolveTextureSubresource)"); - TransitionOrVerifyTextureState(CmdCtx, *pDstTexD3D12, ResolveAttribs.DstTextureTransitionMode, RESOURCE_STATE_RESOLVE_DEST, "Resolving multi-sampled texture (DeviceContextD3D12Impl::ResolveTextureSubresource)"); + auto* pSrcTexD3D12 = ValidatedCast(pSrcTexture); + auto* pDstTexD3D12 = ValidatedCast(pDstTexture); + const auto& SrcTexDesc = pSrcTexD3D12->GetDesc(); + const auto& DstTexDesc = pDstTexD3D12->GetDesc(); - auto Format = ResolveAttribs.Format; - if (Format == TEX_FORMAT_UNKNOWN) + auto& CmdCtx = GetCmdContext(); + TransitionOrVerifyTextureState(CmdCtx, *pSrcTexD3D12, ResolveAttribs.SrcTextureTransitionMode, RESOURCE_STATE_RESOLVE_SOURCE, "Resolving multi-sampled texture (DeviceContextD3D12Impl::ResolveTextureSubresource)"); + TransitionOrVerifyTextureState(CmdCtx, *pDstTexD3D12, ResolveAttribs.DstTextureTransitionMode, RESOURCE_STATE_RESOLVE_DEST, "Resolving multi-sampled texture (DeviceContextD3D12Impl::ResolveTextureSubresource)"); + + auto Format = ResolveAttribs.Format; + if (Format == TEX_FORMAT_UNKNOWN) + { + const auto& SrcFmtAttribs = GetTextureFormatAttribs(SrcTexDesc.Format); + if (!SrcFmtAttribs.IsTypeless) { - const auto& SrcFmtAttribs = GetTextureFormatAttribs(SrcTexDesc.Format); - if (!SrcFmtAttribs.IsTypeless) - { - Format = SrcTexDesc.Format; - } - else - { - const auto& DstFmtAttribs = GetTextureFormatAttribs(DstTexDesc.Format); - DEV_CHECK_ERR(!DstFmtAttribs.IsTypeless, "Resolve operation format can't be typeless when both source and destination textures are typeless"); - Format = DstFmtAttribs.Format; - } + Format = SrcTexDesc.Format; + } + else + { + const auto& DstFmtAttribs = GetTextureFormatAttribs(DstTexDesc.Format); + DEV_CHECK_ERR(!DstFmtAttribs.IsTypeless, "Resolve operation format can't be typeless when both source and destination textures are typeless"); + Format = DstFmtAttribs.Format; } + } - auto DXGIFmt = TexFormatToDXGI_Format(Format); - auto SrcSubresIndex = D3D12CalcSubresource(ResolveAttribs.SrcMipLevel, ResolveAttribs.SrcSlice, 0, SrcTexDesc.MipLevels, SrcTexDesc.ArraySize); - auto DstSubresIndex = D3D12CalcSubresource(ResolveAttribs.DstMipLevel, ResolveAttribs.DstSlice, 0, DstTexDesc.MipLevels, DstTexDesc.ArraySize); + auto DXGIFmt = TexFormatToDXGI_Format(Format); + auto SrcSubresIndex = D3D12CalcSubresource(ResolveAttribs.SrcMipLevel, ResolveAttribs.SrcSlice, 0, SrcTexDesc.MipLevels, SrcTexDesc.ArraySize); + auto DstSubresIndex = D3D12CalcSubresource(ResolveAttribs.DstMipLevel, ResolveAttribs.DstSlice, 0, DstTexDesc.MipLevels, DstTexDesc.ArraySize); - CmdCtx.ResolveSubresource(pDstTexD3D12->GetD3D12Resource(), DstSubresIndex, pSrcTexD3D12->GetD3D12Resource(), SrcSubresIndex, DXGIFmt); - } + CmdCtx.ResolveSubresource(pDstTexD3D12->GetD3D12Resource(), DstSubresIndex, pSrcTexD3D12->GetD3D12Resource(), SrcSubresIndex, DXGIFmt); } +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/EngineFactoryD3D12.cpp b/Graphics/GraphicsEngineD3D12/src/EngineFactoryD3D12.cpp index 6b16a440..545da3d3 100644 --- a/Graphics/GraphicsEngineD3D12/src/EngineFactoryD3D12.cpp +++ b/Graphics/GraphicsEngineD3D12/src/EngineFactoryD3D12.cpp @@ -57,50 +57,50 @@ public: TBase{IID_EngineFactoryD3D12} {} - void CreateDeviceAndContextsD3D12(const EngineD3D12CreateInfo& EngineCI, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts)override final; + void CreateDeviceAndContextsD3D12(const EngineD3D12CreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts) override final; - void AttachToD3D12Device(void* pd3d12NativeDevice, + void AttachToD3D12Device(void* pd3d12NativeDevice, size_t CommandQueueCount, ICommandQueueD3D12** ppCommandQueues, - const EngineD3D12CreateInfo& EngineCI, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts)override final; - - void CreateSwapChainD3D12( IRenderDevice* pDevice, - IDeviceContext* pImmediateContext, - const SwapChainDesc& SwapChainDesc, - const FullScreenModeDesc& FSDesc, - void* pNativeWndHandle, - ISwapChain** ppSwapChain )override final; + const EngineD3D12CreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts) override final; + + void CreateSwapChainD3D12(IRenderDevice* pDevice, + IDeviceContext* pImmediateContext, + const SwapChainDesc& SwapChainDesc, + const FullScreenModeDesc& FSDesc, + void* pNativeWndHandle, + ISwapChain** ppSwapChain) override final; }; static void GetHardwareAdapter(IDXGIFactory2* pFactory, IDXGIAdapter1** ppAdapter, D3D_FEATURE_LEVEL FeatureLevel) { - CComPtr adapter; - *ppAdapter = nullptr; - - for (UINT adapterIndex = 0; DXGI_ERROR_NOT_FOUND != pFactory->EnumAdapters1(adapterIndex, &adapter); ++adapterIndex, adapter.Release()) - { - DXGI_ADAPTER_DESC1 desc; - adapter->GetDesc1(&desc); - - if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) - { - // Skip software devices - continue; - } - - // Check to see if the adapter supports Direct3D 12, but don't create the - // actual device yet. - if (SUCCEEDED(D3D12CreateDevice(adapter, FeatureLevel, _uuidof(ID3D12Device), nullptr))) - { - break; - } - } - - *ppAdapter = adapter.Detach(); + CComPtr adapter; + *ppAdapter = nullptr; + + for (UINT adapterIndex = 0; DXGI_ERROR_NOT_FOUND != pFactory->EnumAdapters1(adapterIndex, &adapter); ++adapterIndex, adapter.Release()) + { + DXGI_ADAPTER_DESC1 desc; + adapter->GetDesc1(&desc); + + if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) + { + // Skip software devices + continue; + } + + // Check to see if the adapter supports Direct3D 12, but don't create the + // actual device yet. + if (SUCCEEDED(D3D12CreateDevice(adapter, FeatureLevel, _uuidof(ID3D12Device), nullptr))) + { + break; + } + } + + *ppAdapter = adapter.Detach(); } void EngineFactoryD3D12Impl::CreateDeviceAndContextsD3D12(const EngineD3D12CreateInfo& EngineCI, @@ -113,23 +113,23 @@ void EngineFactoryD3D12Impl::CreateDeviceAndContextsD3D12(const EngineD3D12Creat if (EngineCI.DebugMessageCallback != nullptr) SetDebugMessageCallback(EngineCI.DebugMessageCallback); - VERIFY( ppDevice && ppContexts, "Null pointer provided" ); - if( !ppDevice || !ppContexts ) + VERIFY(ppDevice && ppContexts, "Null pointer provided"); + if (!ppDevice || !ppContexts) return; - for (Uint32 Type=D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; Type < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; ++Type) + for (Uint32 Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; Type < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; ++Type) { - auto CPUHeapAllocSize = EngineCI.CPUDescriptorHeapAllocationSize[Type]; - Uint32 MaxSize = 1 << 20; - if( CPUHeapAllocSize > 1 << 20 ) + auto CPUHeapAllocSize = EngineCI.CPUDescriptorHeapAllocationSize[Type]; + Uint32 MaxSize = 1 << 20; + if (CPUHeapAllocSize > 1 << 20) { - LOG_ERROR( "CPU Heap allocation size is too large (", CPUHeapAllocSize, "). Max allowed size is ", MaxSize ); + LOG_ERROR("CPU Heap allocation size is too large (", CPUHeapAllocSize, "). Max allowed size is ", MaxSize); return; } - if( (CPUHeapAllocSize % 16) != 0 ) + if ((CPUHeapAllocSize % 16) != 0) { - LOG_ERROR( "CPU Heap allocation size (", CPUHeapAllocSize, ") is expected to be multiple of 16" ); + LOG_ERROR("CPU Heap allocation size (", CPUHeapAllocSize, ") is expected to be multiple of 16"); return; } } @@ -138,16 +138,16 @@ void EngineFactoryD3D12Impl::CreateDeviceAndContextsD3D12(const EngineD3D12Creat memset(ppContexts, 0, sizeof(*ppContexts) * (1 + EngineCI.NumDeferredContexts)); RefCntAutoPtr pCmdQueueD3D12; - CComPtr d3d12Device; + CComPtr d3d12Device; try { - // Enable the D3D12 debug layer. + // Enable the D3D12 debug layer. if (EngineCI.EnableDebugLayer) - { - CComPtr debugController; - if (SUCCEEDED(D3D12GetDebugInterface(__uuidof(debugController), reinterpret_cast(static_cast(&debugController)) ))) - { - debugController->EnableDebugLayer(); + { + CComPtr debugController; + if (SUCCEEDED(D3D12GetDebugInterface(__uuidof(debugController), reinterpret_cast(static_cast(&debugController))))) + { + debugController->EnableDebugLayer(); //static_cast(debugController.p)->SetEnableSynchronizedCommandQueueValidation(FALSE); if (EngineCI.EnableGPUBasedValidation) { @@ -158,27 +158,28 @@ void EngineFactoryD3D12Impl::CreateDeviceAndContextsD3D12(const EngineD3D12Creat debugController1->SetEnableGPUBasedValidation(true); } } - } - } + } + } - CComPtr factory; - HRESULT hr = CreateDXGIFactory1(__uuidof(factory), reinterpret_cast(static_cast(&factory)) ); + CComPtr factory; + + HRESULT hr = CreateDXGIFactory1(__uuidof(factory), reinterpret_cast(static_cast(&factory))); CHECK_D3D_RESULT_THROW(hr, "Failed to create DXGI factory"); // Direct3D12 does not allow feature levels below 11.0 (D3D12CreateDevice fails to create a device). const auto MinimumFeatureLevel = EngineCI.MinimumFeatureLevel >= DIRECT3D_FEATURE_LEVEL_11_0 ? EngineCI.MinimumFeatureLevel : DIRECT3D_FEATURE_LEVEL_11_0; - CComPtr hardwareAdapter; - if(EngineCI.AdapterId == EngineD3D12CreateInfo::DefaultAdapterId) + CComPtr hardwareAdapter; + if (EngineCI.AdapterId == EngineD3D12CreateInfo::DefaultAdapterId) { - GetHardwareAdapter(factory, &hardwareAdapter, GetD3DFeatureLevel(MinimumFeatureLevel)); - if(hardwareAdapter == nullptr) + GetHardwareAdapter(factory, &hardwareAdapter, GetD3DFeatureLevel(MinimumFeatureLevel)); + if (hardwareAdapter == nullptr) LOG_ERROR_AND_THROW("No suitable hardware adapter found"); } else { auto Adapters = FindCompatibleAdapters(MinimumFeatureLevel); - if(EngineCI.AdapterId < Adapters.size()) + if (EngineCI.AdapterId < Adapters.size()) hardwareAdapter = Adapters[EngineCI.AdapterId]; else { @@ -193,28 +194,30 @@ void EngineFactoryD3D12Impl::CreateDeviceAndContextsD3D12(const EngineD3D12Creat } constexpr auto MaxFeatureLevel = DIRECT3D_FEATURE_LEVEL_12_1; - for (auto FeatureLevel = MaxFeatureLevel; FeatureLevel >= MinimumFeatureLevel; FeatureLevel = static_cast(Uint8{FeatureLevel}-1)) + for (auto FeatureLevel = MaxFeatureLevel; FeatureLevel >= MinimumFeatureLevel; FeatureLevel = static_cast(Uint8{FeatureLevel} - 1)) { auto d3dFeatureLevel = GetD3DFeatureLevel(FeatureLevel); - hr = D3D12CreateDevice(hardwareAdapter, d3dFeatureLevel, __uuidof(d3d12Device), reinterpret_cast(static_cast(&d3d12Device)) ); + + hr = D3D12CreateDevice(hardwareAdapter, d3dFeatureLevel, __uuidof(d3d12Device), reinterpret_cast(static_cast(&d3d12Device))); if (SUCCEEDED(hr)) { VERIFY_EXPR(d3d12Device); break; } } - if( FAILED(hr)) + if (FAILED(hr)) { LOG_WARNING_MESSAGE("Failed to create hardware device. Attempting to create WARP device"); - CComPtr warpAdapter; - hr = factory->EnumWarpAdapter( __uuidof(warpAdapter), reinterpret_cast(static_cast(&warpAdapter)) ); + CComPtr warpAdapter; + hr = factory->EnumWarpAdapter(__uuidof(warpAdapter), reinterpret_cast(static_cast(&warpAdapter))); CHECK_D3D_RESULT_THROW(hr, "Failed to enum warp adapter"); - for (auto FeatureLevel = MaxFeatureLevel; FeatureLevel >= MinimumFeatureLevel; FeatureLevel = static_cast(Uint8{FeatureLevel}-1)) + for (auto FeatureLevel = MaxFeatureLevel; FeatureLevel >= MinimumFeatureLevel; FeatureLevel = static_cast(Uint8{FeatureLevel} - 1)) { auto d3dFeatureLevel = GetD3DFeatureLevel(FeatureLevel); - hr = D3D12CreateDevice( warpAdapter, d3dFeatureLevel, __uuidof(d3d12Device), reinterpret_cast(static_cast(&d3d12Device)) ); + + hr = D3D12CreateDevice(warpAdapter, d3dFeatureLevel, __uuidof(d3d12Device), reinterpret_cast(static_cast(&d3d12Device))); if (SUCCEEDED(hr)) { VERIFY_EXPR(d3d12Device); @@ -226,31 +229,31 @@ void EngineFactoryD3D12Impl::CreateDeviceAndContextsD3D12(const EngineD3D12Creat if (EngineCI.EnableDebugLayer) { - CComPtr pInfoQueue; + CComPtr pInfoQueue; hr = d3d12Device->QueryInterface(__uuidof(pInfoQueue), reinterpret_cast(static_cast(&pInfoQueue))); - if( SUCCEEDED(hr) ) - { - // Suppress whole categories of messages - //D3D12_MESSAGE_CATEGORY Categories[] = {}; - - // Suppress messages based on their severity level - D3D12_MESSAGE_SEVERITY Severities[] = - { - D3D12_MESSAGE_SEVERITY_INFO - }; - - // Suppress individual messages by their ID - //D3D12_MESSAGE_ID DenyIds[] = {}; - - D3D12_INFO_QUEUE_FILTER NewFilter = {}; - //NewFilter.DenyList.NumCategories = _countof(Categories); - //NewFilter.DenyList.pCategoryList = Categories; - NewFilter.DenyList.NumSeverities = _countof(Severities); - NewFilter.DenyList.pSeverityList = Severities; - //NewFilter.DenyList.NumIDs = _countof(DenyIds); - //NewFilter.DenyList.pIDList = DenyIds; - - hr = pInfoQueue->PushStorageFilter(&NewFilter); + if (SUCCEEDED(hr)) + { + // Suppress whole categories of messages + //D3D12_MESSAGE_CATEGORY Categories[] = {}; + + // Suppress messages based on their severity level + D3D12_MESSAGE_SEVERITY Severities[] = + { + D3D12_MESSAGE_SEVERITY_INFO // + }; + + // Suppress individual messages by their ID + //D3D12_MESSAGE_ID DenyIds[] = {}; + + D3D12_INFO_QUEUE_FILTER NewFilter = {}; + //NewFilter.DenyList.NumCategories = _countof(Categories); + //NewFilter.DenyList.pCategoryList = Categories; + NewFilter.DenyList.NumSeverities = _countof(Severities); + NewFilter.DenyList.pSeverityList = Severities; + //NewFilter.DenyList.NumIDs = _countof(DenyIds); + //NewFilter.DenyList.pIDList = DenyIds; + + hr = pInfoQueue->PushStorageFilter(&NewFilter); VERIFY(SUCCEEDED(hr), "Failed to push storage filter"); if (EngineCI.BreakOnCorruption) @@ -261,21 +264,22 @@ void EngineFactoryD3D12Impl::CreateDeviceAndContextsD3D12(const EngineD3D12Creat if (EngineCI.BreakOnError) { - hr = pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true); + hr = pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true); VERIFY(SUCCEEDED(hr), "Failed to set break on error"); } } } #ifndef RELEASE - // Prevent the GPU from overclocking or underclocking to get consistent timings - //d3d12Device->SetStablePowerState(TRUE); + // Prevent the GPU from overclocking or underclocking to get consistent timings + //d3d12Device->SetStablePowerState(TRUE); #endif - // Describe and create the command queue. - D3D12_COMMAND_QUEUE_DESC queueDesc = {}; - queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; - queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + // Describe and create the command queue. + D3D12_COMMAND_QUEUE_DESC queueDesc = {}; + + queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; + queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; CComPtr pd3d12CmdQueue; hr = d3d12Device->CreateCommandQueue(&queueDesc, __uuidof(pd3d12CmdQueue), reinterpret_cast(static_cast(&pd3d12CmdQueue))); @@ -286,28 +290,28 @@ void EngineFactoryD3D12Impl::CreateDeviceAndContextsD3D12(const EngineD3D12Creat CComPtr pd3d12Fence; hr = d3d12Device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(pd3d12Fence), reinterpret_cast(static_cast(&pd3d12Fence))); CHECK_D3D_RESULT_THROW(hr, "Failed to create main command queue fence"); - d3d12Device->SetName(L"Main Command Queue fence"); + d3d12Device->SetName(L"Main Command Queue fence"); - auto &RawMemAllocator = GetRawAllocator(); - pCmdQueueD3D12 = NEW_RC_OBJ(RawMemAllocator, "CommandQueueD3D12 instance", CommandQueueD3D12Impl)(pd3d12CmdQueue, pd3d12Fence); + auto& RawMemAllocator = GetRawAllocator(); + pCmdQueueD3D12 = NEW_RC_OBJ(RawMemAllocator, "CommandQueueD3D12 instance", CommandQueueD3D12Impl)(pd3d12CmdQueue, pd3d12Fence); } - catch( const std::runtime_error & ) + catch (const std::runtime_error&) { - LOG_ERROR( "Failed to initialize D3D12 resources" ); + LOG_ERROR("Failed to initialize D3D12 resources"); return; } - + std::array CmdQueues = {pCmdQueueD3D12}; AttachToD3D12Device(d3d12Device, CmdQueues.size(), CmdQueues.data(), EngineCI, ppDevice, ppContexts); } -void EngineFactoryD3D12Impl::AttachToD3D12Device(void* pd3d12NativeDevice, +void EngineFactoryD3D12Impl::AttachToD3D12Device(void* pd3d12NativeDevice, size_t CommandQueueCount, ICommandQueueD3D12** ppCommandQueues, - const EngineD3D12CreateInfo& EngineCI, - IRenderDevice** ppDevice, + const EngineD3D12CreateInfo& EngineCI, + IRenderDevice** ppDevice, IDeviceContext** ppContexts) { if (EngineCI.APIVersion != DILIGENT_API_VERSION) @@ -316,8 +320,8 @@ void EngineFactoryD3D12Impl::AttachToD3D12Device(void* pd if (EngineCI.DebugMessageCallback != nullptr) SetDebugMessageCallback(EngineCI.DebugMessageCallback); - VERIFY( pd3d12NativeDevice && ppCommandQueues && ppDevice && ppContexts, "Null pointer provided" ); - if( !pd3d12NativeDevice || !ppCommandQueues || !ppDevice || !ppContexts ) + VERIFY(pd3d12NativeDevice && ppCommandQueues && ppDevice && ppContexts, "Null pointer provided"); + if (!pd3d12NativeDevice || !ppCommandQueues || !ppDevice || !ppContexts) return; *ppDevice = nullptr; @@ -326,65 +330,66 @@ void EngineFactoryD3D12Impl::AttachToD3D12Device(void* pd try { SetRawAllocator(EngineCI.pRawMemAllocator); - auto &RawMemAllocator = GetRawAllocator(); - auto d3d12Device = reinterpret_cast(pd3d12NativeDevice); - RenderDeviceD3D12Impl *pRenderDeviceD3D12( NEW_RC_OBJ(RawMemAllocator, "RenderDeviceD3D12Impl instance", RenderDeviceD3D12Impl)(RawMemAllocator, this, EngineCI, d3d12Device, CommandQueueCount, ppCommandQueues) ); - pRenderDeviceD3D12->QueryInterface(IID_RenderDevice, reinterpret_cast(ppDevice) ); + auto& RawMemAllocator = GetRawAllocator(); + auto d3d12Device = reinterpret_cast(pd3d12NativeDevice); - RefCntAutoPtr pImmediateCtxD3D12( NEW_RC_OBJ(RawMemAllocator, "DeviceContextD3D12Impl instance", DeviceContextD3D12Impl)(pRenderDeviceD3D12, false, EngineCI, 0, 0) ); + RenderDeviceD3D12Impl* pRenderDeviceD3D12(NEW_RC_OBJ(RawMemAllocator, "RenderDeviceD3D12Impl instance", RenderDeviceD3D12Impl)(RawMemAllocator, this, EngineCI, d3d12Device, CommandQueueCount, ppCommandQueues)); + pRenderDeviceD3D12->QueryInterface(IID_RenderDevice, reinterpret_cast(ppDevice)); + + RefCntAutoPtr pImmediateCtxD3D12(NEW_RC_OBJ(RawMemAllocator, "DeviceContextD3D12Impl instance", DeviceContextD3D12Impl)(pRenderDeviceD3D12, false, EngineCI, 0, 0)); // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceD3D12 will // keep a weak reference to the context - pImmediateCtxD3D12->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts) ); + pImmediateCtxD3D12->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts)); pRenderDeviceD3D12->SetImmediateContext(pImmediateCtxD3D12); for (Uint32 DeferredCtx = 0; DeferredCtx < EngineCI.NumDeferredContexts; ++DeferredCtx) { - RefCntAutoPtr pDeferredCtxD3D12( NEW_RC_OBJ(RawMemAllocator, "DeviceContextD3D12Impl instance", DeviceContextD3D12Impl)(pRenderDeviceD3D12, true, EngineCI, 1+DeferredCtx, 0) ); + RefCntAutoPtr pDeferredCtxD3D12(NEW_RC_OBJ(RawMemAllocator, "DeviceContextD3D12Impl instance", DeviceContextD3D12Impl)(pRenderDeviceD3D12, true, EngineCI, 1 + DeferredCtx, 0)); // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceD3D12 will // keep a weak reference to the context - pDeferredCtxD3D12->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts + 1 + DeferredCtx) ); + pDeferredCtxD3D12->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts + 1 + DeferredCtx)); pRenderDeviceD3D12->SetDeferredContext(DeferredCtx, pDeferredCtxD3D12); } } - catch( const std::runtime_error & ) + catch (const std::runtime_error&) { - if( *ppDevice ) + if (*ppDevice) { (*ppDevice)->Release(); *ppDevice = nullptr; } - for(Uint32 ctx=0; ctx < 1 + EngineCI.NumDeferredContexts; ++ctx) + for (Uint32 ctx = 0; ctx < 1 + EngineCI.NumDeferredContexts; ++ctx) { - if( ppContexts[ctx] != nullptr ) + if (ppContexts[ctx] != nullptr) { ppContexts[ctx]->Release(); ppContexts[ctx] = nullptr; } } - LOG_ERROR( "Failed to create device and contexts" ); + LOG_ERROR("Failed to create device and contexts"); } } -void EngineFactoryD3D12Impl::CreateSwapChainD3D12(IRenderDevice* pDevice, - IDeviceContext* pImmediateContext, - const SwapChainDesc& SCDesc, +void EngineFactoryD3D12Impl::CreateSwapChainD3D12(IRenderDevice* pDevice, + IDeviceContext* pImmediateContext, + const SwapChainDesc& SCDesc, const FullScreenModeDesc& FSDesc, - void* pNativeWndHandle, - ISwapChain** ppSwapChain ) + void* pNativeWndHandle, + ISwapChain** ppSwapChain) { - VERIFY( ppSwapChain, "Null pointer provided" ); - if( !ppSwapChain ) + VERIFY(ppSwapChain, "Null pointer provided"); + if (!ppSwapChain) return; *ppSwapChain = nullptr; try { - auto* pDeviceD3D12 = ValidatedCast( pDevice ); + auto* pDeviceD3D12 = ValidatedCast(pDevice); auto* pDeviceContextD3D12 = ValidatedCast(pImmediateContext); - auto& RawMemAllocator = GetRawAllocator(); + auto& RawMemAllocator = GetRawAllocator(); if (pDeviceContextD3D12->GetSwapChain() != nullptr && SCDesc.IsPrimary) { @@ -393,16 +398,16 @@ void EngineFactoryD3D12Impl::CreateSwapChainD3D12(IRenderDevice* pDev } auto* pSwapChainD3D12 = NEW_RC_OBJ(RawMemAllocator, "SwapChainD3D12Impl instance", SwapChainD3D12Impl)(SCDesc, FSDesc, pDeviceD3D12, pDeviceContextD3D12, pNativeWndHandle); - pSwapChainD3D12->QueryInterface( IID_SwapChain, reinterpret_cast(ppSwapChain) ); + pSwapChainD3D12->QueryInterface(IID_SwapChain, reinterpret_cast(ppSwapChain)); if (SCDesc.IsPrimary) { pDeviceContextD3D12->SetSwapChain(pSwapChainD3D12); // Bind default render target - pDeviceContextD3D12->SetRenderTargets( 0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); + pDeviceContextD3D12->SetRenderTargets(0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); // Set default viewport - pDeviceContextD3D12->SetViewports( 1, nullptr, 0, 0 ); - + pDeviceContextD3D12->SetViewports(1, nullptr, 0, 0); + auto NumDeferredCtx = pDeviceD3D12->GetNumDeferredContexts(); for (size_t ctx = 0; ctx < NumDeferredCtx; ++ctx) { @@ -412,21 +417,21 @@ void EngineFactoryD3D12Impl::CreateSwapChainD3D12(IRenderDevice* pDev pDeferredCtxD3D12->SetSwapChain(pSwapChainD3D12); // We cannot bind default render target here because // there is no guarantee that deferred context will be used - // in this frame. It is an error to bind + // in this frame. It is an error to bind // RTV of an inactive buffer in the swap chain } } } } - catch( const std::runtime_error& ) + catch (const std::runtime_error&) { - if( *ppSwapChain ) + if (*ppSwapChain) { (*ppSwapChain)->Release(); *ppSwapChain = nullptr; } - LOG_ERROR( "Failed to create the swap chain" ); + LOG_ERROR("Failed to create the swap chain"); } } @@ -443,8 +448,8 @@ void EngineFactoryD3D12Impl::CreateSwapChainD3D12(IRenderDevice* pDev /// void LoadGraphicsEngineD3D12(GetEngineFactoryD3D12Type& GetFactoryFunc) { - // This function is only required because DoxyGen refuses to generate documentation for a static function when SHOW_FILES==NO - #error This function must never be compiled; +// This function is only required because DoxyGen refuses to generate documentation for a static function when SHOW_FILES==NO +# error This function must never be compiled; } #endif @@ -454,4 +459,4 @@ IEngineFactoryD3D12* GetEngineFactoryD3D12() return EngineFactoryD3D12Impl::GetInstance(); } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/FenceD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/FenceD3D12Impl.cpp index 06a052c7..05bc654f 100644 --- a/Graphics/GraphicsEngineD3D12/src/FenceD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/FenceD3D12Impl.cpp @@ -30,35 +30,35 @@ #include "RenderDeviceD3D12Impl.h" namespace Diligent { - -FenceD3D12Impl :: FenceD3D12Impl(IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pDevice, - const FenceDesc& Desc) : + +FenceD3D12Impl::FenceD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl* pDevice, + const FenceDesc& Desc) : TFenceBase{pRefCounters, pDevice, Desc} { auto* pd3d12Device = ValidatedCast(pDevice)->GetD3D12Device(); - auto hr = pd3d12Device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(m_pd3d12Fence), reinterpret_cast(static_cast(&m_pd3d12Fence))); + auto hr = pd3d12Device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(m_pd3d12Fence), reinterpret_cast(static_cast(&m_pd3d12Fence))); CHECK_D3D_RESULT_THROW(hr, "Failed to create D3D12 fence"); } -FenceD3D12Impl :: ~FenceD3D12Impl() +FenceD3D12Impl::~FenceD3D12Impl() { } -Uint64 FenceD3D12Impl :: GetCompletedValue() +Uint64 FenceD3D12Impl::GetCompletedValue() { return m_pd3d12Fence->GetCompletedValue(); } -void FenceD3D12Impl :: Reset(Uint64 Value) +void FenceD3D12Impl::Reset(Uint64 Value) { m_pd3d12Fence->Signal(Value); } -void FenceD3D12Impl :: WaitForCompletion(Uint64 Value) +void FenceD3D12Impl::WaitForCompletion(Uint64 Value) { while (m_pd3d12Fence->GetCompletedValue() < Value) std::this_thread::yield(); } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/GenerateMips.cpp b/Graphics/GraphicsEngineD3D12/src/GenerateMips.cpp index f70d93f0..1d00fba6 100644 --- a/Graphics/GraphicsEngineD3D12/src/GenerateMips.cpp +++ b/Graphics/GraphicsEngineD3D12/src/GenerateMips.cpp @@ -34,7 +34,7 @@ // // Developed by Minigraph // -// Author: James Stanard +// Author: James Stanard // @@ -58,210 +58,215 @@ namespace Diligent { - GenerateMipsHelper::GenerateMipsHelper(ID3D12Device *pd3d12Device) +GenerateMipsHelper::GenerateMipsHelper(ID3D12Device* pd3d12Device) +{ + CD3DX12_ROOT_PARAMETER Params[3]; + Params[0].InitAsConstants(6, 0); + CD3DX12_DESCRIPTOR_RANGE SRVRange(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); + Params[1].InitAsDescriptorTable(1, &SRVRange); + CD3DX12_DESCRIPTOR_RANGE UAVRange(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 4, 0); + Params[2].InitAsDescriptorTable(1, &UAVRange); + CD3DX12_STATIC_SAMPLER_DESC SamplerLinearClampDesc( + 0, D3D12_FILTER_MIN_MAG_MIP_LINEAR, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP); + CD3DX12_ROOT_SIGNATURE_DESC RootSigDesc; + RootSigDesc.NumParameters = _countof(Params); + RootSigDesc.pParameters = Params; + RootSigDesc.NumStaticSamplers = 1; + RootSigDesc.pStaticSamplers = &SamplerLinearClampDesc; + RootSigDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + + CComPtr signature; + CComPtr error; + + HRESULT hr = D3D12SerializeRootSignature(&RootSigDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error); + + hr = pd3d12Device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), __uuidof(m_pGenerateMipsRS), reinterpret_cast(static_cast(&m_pGenerateMipsRS))); + CHECK_D3D_RESULT_THROW(hr, "Failed to create root signature for mipmap generation"); + + D3D12_COMPUTE_PIPELINE_STATE_DESC PSODesc = {}; + + PSODesc.pRootSignature = m_pGenerateMipsRS; + PSODesc.NodeMask = 0; + PSODesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; + +#define CreatePSO(PSO, ShaderByteCode) \ + PSODesc.CS.pShaderBytecode = ShaderByteCode; \ + PSODesc.CS.BytecodeLength = sizeof(ShaderByteCode); \ + hr = pd3d12Device->CreateComputePipelineState(&PSODesc, __uuidof(PSO), reinterpret_cast(static_cast(&PSO))); \ + CHECK_D3D_RESULT_THROW(hr, "Failed to create Pipeline state for mipmap generation"); \ + PSO->SetName(L"Generate mips PSO"); + + CreatePSO(m_pGenerateMipsLinearPSO[0], g_pGenerateMipsLinearCS); + CreatePSO(m_pGenerateMipsLinearPSO[1], g_pGenerateMipsLinearOddXCS); + CreatePSO(m_pGenerateMipsLinearPSO[2], g_pGenerateMipsLinearOddYCS); + CreatePSO(m_pGenerateMipsLinearPSO[3], g_pGenerateMipsLinearOddCS); + CreatePSO(m_pGenerateMipsGammaPSO[0], g_pGenerateMipsGammaCS); + CreatePSO(m_pGenerateMipsGammaPSO[1], g_pGenerateMipsGammaOddXCS); + CreatePSO(m_pGenerateMipsGammaPSO[2], g_pGenerateMipsGammaOddYCS); + CreatePSO(m_pGenerateMipsGammaPSO[3], g_pGenerateMipsGammaOddCS); +} + +void GenerateMipsHelper::GenerateMips(ID3D12Device* pd3d12Device, TextureViewD3D12Impl* pTexView, CommandContext& Ctx) const +{ + auto& ComputeCtx = Ctx.AsComputeContext(); + ComputeCtx.SetRootSignature(m_pGenerateMipsRS); + auto* pTexD3D12 = pTexView->GetTexture(); + const auto& TexDesc = pTexD3D12->GetDesc(); + const auto& ViewDesc = pTexView->GetDesc(); + + bool IsAllSlices = + (TexDesc.Type != RESOURCE_DIM_TEX_1D_ARRAY && + TexDesc.Type != RESOURCE_DIM_TEX_2D_ARRAY && + TexDesc.Type != RESOURCE_DIM_TEX_CUBE_ARRAY) || + TexDesc.ArraySize == ViewDesc.NumArraySlices; + bool IsAllMips = ViewDesc.NumMipLevels == TexDesc.MipLevels; + + auto SRVDescriptorHandle = pTexView->GetTexArraySRV(); + + if (!pTexD3D12->IsInKnownState()) { - CD3DX12_ROOT_PARAMETER Params[3]; - Params[0].InitAsConstants(6, 0); - CD3DX12_DESCRIPTOR_RANGE SRVRange(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); - Params[1].InitAsDescriptorTable(1, &SRVRange); - CD3DX12_DESCRIPTOR_RANGE UAVRange(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 4, 0); - Params[2].InitAsDescriptorTable(1, &UAVRange); - CD3DX12_STATIC_SAMPLER_DESC SamplerLinearClampDesc( - 0, D3D12_FILTER_MIN_MAG_MIP_LINEAR, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP); - CD3DX12_ROOT_SIGNATURE_DESC RootSigDesc; - RootSigDesc.NumParameters = _countof(Params); - RootSigDesc.pParameters = Params; - RootSigDesc.NumStaticSamplers = 1; - RootSigDesc.pStaticSamplers = &SamplerLinearClampDesc; - RootSigDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; - - CComPtr signature; - CComPtr error; - HRESULT hr = D3D12SerializeRootSignature(&RootSigDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error); - hr = pd3d12Device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), __uuidof(m_pGenerateMipsRS), reinterpret_cast( static_cast(&m_pGenerateMipsRS))); - CHECK_D3D_RESULT_THROW(hr, "Failed to create root signature for mipmap generation"); - - D3D12_COMPUTE_PIPELINE_STATE_DESC PSODesc = {}; - PSODesc.pRootSignature = m_pGenerateMipsRS; - PSODesc.NodeMask = 0; - PSODesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; - -#define CreatePSO(PSO, ShaderByteCode) \ - PSODesc.CS.pShaderBytecode = ShaderByteCode;\ - PSODesc.CS.BytecodeLength = sizeof(ShaderByteCode);\ - hr = pd3d12Device->CreateComputePipelineState(&PSODesc, __uuidof(PSO), reinterpret_cast( static_cast(&PSO))); \ - CHECK_D3D_RESULT_THROW(hr, "Failed to create Pipeline state for mipmap generation"); \ - PSO->SetName(L"Generate mips PSO"); - - CreatePSO(m_pGenerateMipsLinearPSO[0], g_pGenerateMipsLinearCS); - CreatePSO(m_pGenerateMipsLinearPSO[1], g_pGenerateMipsLinearOddXCS); - CreatePSO(m_pGenerateMipsLinearPSO[2], g_pGenerateMipsLinearOddYCS); - CreatePSO(m_pGenerateMipsLinearPSO[3], g_pGenerateMipsLinearOddCS); - CreatePSO(m_pGenerateMipsGammaPSO[0], g_pGenerateMipsGammaCS); - CreatePSO(m_pGenerateMipsGammaPSO[1], g_pGenerateMipsGammaOddXCS); - CreatePSO(m_pGenerateMipsGammaPSO[2], g_pGenerateMipsGammaOddYCS); - CreatePSO(m_pGenerateMipsGammaPSO[3], g_pGenerateMipsGammaOddCS); + LOG_ERROR_MESSAGE("Unable to generate mips for texture '", TexDesc.Name, "' because the texture state is unknown"); + return; } - void GenerateMipsHelper::GenerateMips(ID3D12Device* pd3d12Device, TextureViewD3D12Impl* pTexView, CommandContext& Ctx)const + if (pTexD3D12->GetState() == RESOURCE_STATE_UNDEFINED) { - auto& ComputeCtx = Ctx.AsComputeContext(); - ComputeCtx.SetRootSignature(m_pGenerateMipsRS); - auto* pTexD3D12 = pTexView->GetTexture(); - const auto& TexDesc = pTexD3D12->GetDesc(); - const auto& ViewDesc = pTexView->GetDesc(); - bool IsAllSlices = (TexDesc.Type != RESOURCE_DIM_TEX_1D_ARRAY && - TexDesc.Type != RESOURCE_DIM_TEX_2D_ARRAY && - TexDesc.Type != RESOURCE_DIM_TEX_CUBE_ARRAY) || - TexDesc.ArraySize == ViewDesc.NumArraySlices; - bool IsAllMips = ViewDesc.NumMipLevels == TexDesc.MipLevels; - - auto SRVDescriptorHandle = pTexView->GetTexArraySRV(); - - if (!pTexD3D12->IsInKnownState()) + // If texture state is undefined, transition it to shader resource state. + // We need all subresources to be in a defined state at the end of the procedure. + Ctx.TransitionResource(pTexD3D12, RESOURCE_STATE_SHADER_RESOURCE); + } + + const auto OriginalState = pTexD3D12->GetState(); + pTexD3D12->SetState(RESOURCE_STATE_UNKNOWN); // Switch to manual state management + + // If we are processing the entire texture, we will leave it in SHADER_RESOURCE layout. + // Otherwise we will transition affected subresources back to original layout. + const auto FinalState = (IsAllSlices && IsAllMips) ? RESOURCE_STATE_SHADER_RESOURCE : OriginalState; + + auto BottomMip = ViewDesc.NumMipLevels - 1; + for (uint32_t TopMip = 0; TopMip < BottomMip;) + { + uint32_t SrcWidth = std::max(TexDesc.Width >> (TopMip + ViewDesc.MostDetailedMip), 1u); + uint32_t SrcHeight = std::max(TexDesc.Height >> (TopMip + ViewDesc.MostDetailedMip), 1u); + uint32_t DstWidth = std::max(SrcWidth >> 1, 1u); + uint32_t DstHeight = std::max(SrcHeight >> 1, 1u); + + // Determine if the first downsample is more than 2:1. This happens whenever + // the source width or height is odd. + uint32_t NonPowerOfTwo = (SrcWidth & 1) | (SrcHeight & 1) << 1; + if (TexDesc.Format == TEX_FORMAT_RGBA8_UNORM_SRGB) + ComputeCtx.SetPipelineState(m_pGenerateMipsGammaPSO[NonPowerOfTwo]); + else + ComputeCtx.SetPipelineState(m_pGenerateMipsLinearPSO[NonPowerOfTwo]); + + // We can downsample up to four times, but if the ratio between levels is not + // exactly 2:1, we have to shift our blend weights, which gets complicated or + // expensive. Maybe we can update the code later to compute sample weights for + // each successive downsample. We use _BitScanForward to count number of zeros + // in the low bits. Zeros indicate we can divide by two without truncating. + uint32_t AdditionalMips; + _BitScanForward((unsigned long*)&AdditionalMips, DstWidth | DstHeight); + uint32_t NumMips = 1 + (AdditionalMips > 3 ? 3 : AdditionalMips); + if (TopMip + NumMips > BottomMip) + NumMips = BottomMip - TopMip; + + // These are clamped to 1 after computing additional mips because clamped + // dimensions should not limit us from downsampling multiple times. (E.g. + // 16x1 -> 8x1 -> 4x1 -> 2x1 -> 1x1.) + if (DstWidth == 0) + DstWidth = 1; + if (DstHeight == 0) + DstHeight = 1; + + D3D12_DESCRIPTOR_HEAP_TYPE HeapType = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + auto DescriptorAlloc = Ctx.AllocateDynamicGPUVisibleDescriptor(HeapType, 5); + + CommandContext::ShaderDescriptorHeaps Heaps{DescriptorAlloc.GetDescriptorHeap()}; + ComputeCtx.SetDescriptorHeaps(Heaps); + Ctx.GetCommandList()->SetComputeRootDescriptorTable(1, DescriptorAlloc.GetGpuHandle(0)); + Ctx.GetCommandList()->SetComputeRootDescriptorTable(2, DescriptorAlloc.GetGpuHandle(1)); + struct RootCBData { - LOG_ERROR_MESSAGE("Unable to generate mips for texture '", TexDesc.Name, "' because the texture state is unknown"); - return; + Uint32 SrcMipLevel; // Texture level of source mip + Uint32 NumMipLevels; // Number of OutMips to write: [1, 4] + Uint32 FirstArraySlice; + Uint32 Dummy; + float TexelSize[2]; // 1.0 / OutMip1.Dimensions + }; + RootCBData CBData{ + TopMip, // Mip levels are relateive to the view's most detailed mip + NumMips, + 0, // Array slices are relative to the view's first array slice + 0, + 1.0f / static_cast(DstWidth), 1.0f / static_cast(DstHeight)}; + + Ctx.GetCommandList()->SetComputeRoot32BitConstants(0, 6, &CBData, 0); + + // TODO: Shouldn't we transition top mip to shader resource state? + D3D12_CPU_DESCRIPTOR_HANDLE DstDescriptorRange = DescriptorAlloc.GetCpuHandle(); + const Uint32 MaxMipsHandledByCS = 4; // Max number of mip levels processed by one CS shader invocation + UINT DstRangeSize = 1 + MaxMipsHandledByCS; + D3D12_CPU_DESCRIPTOR_HANDLE SrcDescriptorRanges[5] = {}; + + SrcDescriptorRanges[0] = SRVDescriptorHandle; + UINT SrcRangeSizes[5] = {1, 1, 1, 1, 1}; + // On Resource Binding Tier 2 hardware, all descriptor tables of type CBV and UAV declared in the set + // Root Signature must be populated and initialized, even if the shaders do not need the descriptor. + // So we must populate all 4 slots even though we may actually process less than 4 mip levels + // Copy top mip level UAV descriptor handle to all unused slots + for (Uint32 u = 0; u < MaxMipsHandledByCS; ++u) + SrcDescriptorRanges[1 + u] = pTexView->GetMipLevelUAV(TopMip + std::min(u + 1, NumMips)); + + pd3d12Device->CopyDescriptors(1, &DstDescriptorRange, &DstRangeSize, 1 + MaxMipsHandledByCS, SrcDescriptorRanges, SrcRangeSizes, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + + // Transition top mip level to the shader resource state + StateTransitionDesc SrcMipBarrier{pTexD3D12, TopMip == 0 ? OriginalState : RESOURCE_STATE_UNORDERED_ACCESS, RESOURCE_STATE_SHADER_RESOURCE, false}; + if (SrcMipBarrier.OldState != SrcMipBarrier.NewState) + { + SrcMipBarrier.FirstMipLevel = ViewDesc.MostDetailedMip + TopMip; + SrcMipBarrier.MipLevelsCount = 1; + SrcMipBarrier.FirstArraySlice = ViewDesc.FirstArraySlice; + SrcMipBarrier.ArraySliceCount = ViewDesc.NumArraySlices; + Ctx.TransitionResource(SrcMipBarrier); } - - if (pTexD3D12->GetState() == RESOURCE_STATE_UNDEFINED) + + // Transition dst mip levels to UAV state + StateTransitionDesc DstMipsBarrier{pTexD3D12, OriginalState, RESOURCE_STATE_UNORDERED_ACCESS, false}; + if (DstMipsBarrier.OldState != DstMipsBarrier.NewState) { - // If texture state is undefined, transition it to shader resource state. - // We need all subresources to be in a defined state at the end of the procedure. - Ctx.TransitionResource(pTexD3D12, RESOURCE_STATE_SHADER_RESOURCE); + DstMipsBarrier.FirstMipLevel = ViewDesc.MostDetailedMip + TopMip + 1; + DstMipsBarrier.MipLevelsCount = NumMips; + DstMipsBarrier.FirstArraySlice = ViewDesc.FirstArraySlice; + DstMipsBarrier.ArraySliceCount = ViewDesc.NumArraySlices; + Ctx.TransitionResource(DstMipsBarrier); } - const auto OriginalState = pTexD3D12->GetState(); - pTexD3D12->SetState(RESOURCE_STATE_UNKNOWN); // Switch to manual state management - - // If we are processing the entire texture, we will leave it in SHADER_RESOURCE layout. - // Otherwise we will transition affected subresources back to original layout. - const auto FinalState = (IsAllSlices && IsAllMips) ? RESOURCE_STATE_SHADER_RESOURCE : OriginalState; + ComputeCtx.Dispatch((DstWidth + 7) / 8, (DstHeight + 7) / 8, ViewDesc.NumArraySlices); - auto BottomMip = ViewDesc.NumMipLevels - 1; - for (uint32_t TopMip = 0; TopMip < BottomMip; ) + // Transition the lowest level back to original layout or leave it in RESOURCE_STATE_SHADER_RESOURCE + // if all subresources are processed + if (SrcMipBarrier.NewState != FinalState) { - uint32_t SrcWidth = std::max(TexDesc.Width >> (TopMip + ViewDesc.MostDetailedMip), 1u); - uint32_t SrcHeight = std::max(TexDesc.Height >> (TopMip + ViewDesc.MostDetailedMip), 1u); - uint32_t DstWidth = std::max(SrcWidth >> 1, 1u); - uint32_t DstHeight = std::max(SrcHeight >> 1, 1u); - - // Determine if the first downsample is more than 2:1. This happens whenever - // the source width or height is odd. - uint32_t NonPowerOfTwo = (SrcWidth & 1) | (SrcHeight & 1) << 1; - if (TexDesc.Format == TEX_FORMAT_RGBA8_UNORM_SRGB) - ComputeCtx.SetPipelineState(m_pGenerateMipsGammaPSO[NonPowerOfTwo]); - else - ComputeCtx.SetPipelineState(m_pGenerateMipsLinearPSO[NonPowerOfTwo]); - - // We can downsample up to four times, but if the ratio between levels is not - // exactly 2:1, we have to shift our blend weights, which gets complicated or - // expensive. Maybe we can update the code later to compute sample weights for - // each successive downsample. We use _BitScanForward to count number of zeros - // in the low bits. Zeros indicate we can divide by two without truncating. - uint32_t AdditionalMips; - _BitScanForward((unsigned long*)&AdditionalMips, DstWidth | DstHeight); - uint32_t NumMips = 1 + (AdditionalMips > 3 ? 3 : AdditionalMips); - if (TopMip + NumMips > BottomMip) - NumMips = BottomMip - TopMip; - - // These are clamped to 1 after computing additional mips because clamped - // dimensions should not limit us from downsampling multiple times. (E.g. - // 16x1 -> 8x1 -> 4x1 -> 2x1 -> 1x1.) - if (DstWidth == 0) - DstWidth = 1; - if (DstHeight == 0) - DstHeight = 1; - - D3D12_DESCRIPTOR_HEAP_TYPE HeapType = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; - auto DescriptorAlloc = Ctx.AllocateDynamicGPUVisibleDescriptor(HeapType, 5); - CommandContext::ShaderDescriptorHeaps Heaps(DescriptorAlloc.GetDescriptorHeap()); - ComputeCtx.SetDescriptorHeaps(Heaps); - Ctx.GetCommandList()->SetComputeRootDescriptorTable(1, DescriptorAlloc.GetGpuHandle(0)); - Ctx.GetCommandList()->SetComputeRootDescriptorTable(2, DescriptorAlloc.GetGpuHandle(1)); - struct RootCBData - { - Uint32 SrcMipLevel; // Texture level of source mip - Uint32 NumMipLevels; // Number of OutMips to write: [1, 4] - Uint32 FirstArraySlice; - Uint32 Dummy; - float TexelSize[2]; // 1.0 / OutMip1.Dimensions - }; - RootCBData CBData - { - TopMip, // Mip levels are relateive to the view's most detailed mip - NumMips, - 0, // Array slices are relative to the view's first array slice - 0, - 1.0f / static_cast(DstWidth), 1.0f / static_cast(DstHeight) - }; - - Ctx.GetCommandList()->SetComputeRoot32BitConstants(0, 6, &CBData, 0); - - // TODO: Shouldn't we transition top mip to shader resource state? - D3D12_CPU_DESCRIPTOR_HANDLE DstDescriptorRange = DescriptorAlloc.GetCpuHandle(); - const Uint32 MaxMipsHandledByCS = 4; // Max number of mip levels processed by one CS shader invocation - UINT DstRangeSize = 1 + MaxMipsHandledByCS; - D3D12_CPU_DESCRIPTOR_HANDLE SrcDescriptorRanges[5] = {}; - SrcDescriptorRanges[0] = SRVDescriptorHandle; - UINT SrcRangeSizes[5] = { 1,1,1,1,1 }; - // On Resource Binding Tier 2 hardware, all descriptor tables of type CBV and UAV declared in the set - // Root Signature must be populated and initialized, even if the shaders do not need the descriptor. - // So we must populate all 4 slots even though we may actually process less than 4 mip levels - // Copy top mip level UAV descriptor handle to all unused slots - for (Uint32 u = 0; u < MaxMipsHandledByCS; ++u) - SrcDescriptorRanges[1 + u] = pTexView->GetMipLevelUAV(TopMip + std::min(u + 1, NumMips)); - - pd3d12Device->CopyDescriptors(1, &DstDescriptorRange, &DstRangeSize, 1 + MaxMipsHandledByCS, SrcDescriptorRanges, SrcRangeSizes, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - - // Transition top mip level to the shader resource state - StateTransitionDesc SrcMipBarrier{pTexD3D12, TopMip == 0 ? OriginalState : RESOURCE_STATE_UNORDERED_ACCESS, RESOURCE_STATE_SHADER_RESOURCE, false}; - if (SrcMipBarrier.OldState != SrcMipBarrier.NewState) - { - SrcMipBarrier.FirstMipLevel = ViewDesc.MostDetailedMip + TopMip; - SrcMipBarrier.MipLevelsCount = 1; - SrcMipBarrier.FirstArraySlice = ViewDesc.FirstArraySlice; - SrcMipBarrier.ArraySliceCount = ViewDesc.NumArraySlices; - Ctx.TransitionResource(SrcMipBarrier); - } - - // Transition dst mip levels to UAV state - StateTransitionDesc DstMipsBarrier{pTexD3D12, OriginalState, RESOURCE_STATE_UNORDERED_ACCESS, false}; - if (DstMipsBarrier.OldState != DstMipsBarrier.NewState) - { - DstMipsBarrier.FirstMipLevel = ViewDesc.MostDetailedMip + TopMip + 1; - DstMipsBarrier.MipLevelsCount = NumMips; - DstMipsBarrier.FirstArraySlice = ViewDesc.FirstArraySlice; - DstMipsBarrier.ArraySliceCount = ViewDesc.NumArraySlices; - Ctx.TransitionResource(DstMipsBarrier); - } - - ComputeCtx.Dispatch((DstWidth + 7) / 8, (DstHeight + 7) / 8, ViewDesc.NumArraySlices); - - // Transition the lowest level back to original layout or leave it in RESOURCE_STATE_SHADER_RESOURCE - // if all subresources are processed - if (SrcMipBarrier.NewState != FinalState) - { - SrcMipBarrier.OldState = SrcMipBarrier.NewState; - SrcMipBarrier.NewState = FinalState; - Ctx.TransitionResource(SrcMipBarrier); - } - - if (DstMipsBarrier.NewState != FinalState) - { - DstMipsBarrier.OldState = DstMipsBarrier.NewState; - DstMipsBarrier.NewState = FinalState; - // Do not transition the bottom level if we have more mips to process - if (TopMip + NumMips < BottomMip) - --DstMipsBarrier.MipLevelsCount; - if (DstMipsBarrier.MipLevelsCount > 0) - Ctx.TransitionResource(DstMipsBarrier); - } - - TopMip += NumMips; + SrcMipBarrier.OldState = SrcMipBarrier.NewState; + SrcMipBarrier.NewState = FinalState; + Ctx.TransitionResource(SrcMipBarrier); } - // Set state - pTexD3D12->SetState(FinalState); + if (DstMipsBarrier.NewState != FinalState) + { + DstMipsBarrier.OldState = DstMipsBarrier.NewState; + DstMipsBarrier.NewState = FinalState; + // Do not transition the bottom level if we have more mips to process + if (TopMip + NumMips < BottomMip) + --DstMipsBarrier.MipLevelsCount; + if (DstMipsBarrier.MipLevelsCount > 0) + Ctx.TransitionResource(DstMipsBarrier); + } + + TopMip += NumMips; } + + // Set state + pTexD3D12->SetState(FinalState); } +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp index 1a0f2186..731af7bb 100644 --- a/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp @@ -42,16 +42,18 @@ class PrimitiveTopology_To_D3D12_PRIMITIVE_TOPOLOGY_TYPE public: PrimitiveTopology_To_D3D12_PRIMITIVE_TOPOLOGY_TYPE() { + // clang-format off m_Map[PRIMITIVE_TOPOLOGY_UNDEFINED] = D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED; m_Map[PRIMITIVE_TOPOLOGY_TRIANGLE_LIST] = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; m_Map[PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP] = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; m_Map[PRIMITIVE_TOPOLOGY_POINT_LIST] = D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT; m_Map[PRIMITIVE_TOPOLOGY_LINE_LIST] = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE; - for(int t = static_cast(PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST); t < static_cast(PRIMITIVE_TOPOLOGY_NUM_TOPOLOGIES); ++t) + // clang-format on + for (int t = static_cast(PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST); t < static_cast(PRIMITIVE_TOPOLOGY_NUM_TOPOLOGIES); ++t) m_Map[t] = D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH; } - - D3D12_PRIMITIVE_TOPOLOGY_TYPE operator[](PRIMITIVE_TOPOLOGY Topology)const + + D3D12_PRIMITIVE_TOPOLOGY_TYPE operator[](PRIMITIVE_TOPOLOGY Topology) const { return m_Map[static_cast(Topology)]; } @@ -60,29 +62,29 @@ private: std::array m_Map; }; -PipelineStateD3D12Impl :: PipelineStateD3D12Impl(IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pDeviceD3D12, - const PipelineStateDesc& PipelineDesc) : +PipelineStateD3D12Impl ::PipelineStateD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl* pDeviceD3D12, + const PipelineStateDesc& PipelineDesc) : TPipelineStateBase{pRefCounters, pDeviceD3D12, PipelineDesc}, - m_SRBMemAllocator {GetRawAllocator()} + m_SRBMemAllocator{GetRawAllocator()} { - auto pd3d12Device = pDeviceD3D12->GetD3D12Device(); + auto pd3d12Device = pDeviceD3D12->GetD3D12Device(); const auto& ResourceLayout = m_Desc.ResourceLayout; m_RootSig.AllocateStaticSamplers(ResourceLayout); { auto& ShaderResLayoutAllocator = GetRawAllocator(); - m_pShaderResourceLayouts = ALLOCATE(ShaderResLayoutAllocator, "Raw memory for ShaderResourceLayoutD3D12", ShaderResourceLayoutD3D12, m_NumShaders * 2); + m_pShaderResourceLayouts = ALLOCATE(ShaderResLayoutAllocator, "Raw memory for ShaderResourceLayoutD3D12", ShaderResourceLayoutD3D12, m_NumShaders * 2); } { auto& ShaderResCacheAllocator = GetRawAllocator(); - m_pStaticResourceCaches = ALLOCATE(ShaderResCacheAllocator, "Raw memory for ShaderResourceCacheD3D12", ShaderResourceCacheD3D12, m_NumShaders); + m_pStaticResourceCaches = ALLOCATE(ShaderResCacheAllocator, "Raw memory for ShaderResourceCacheD3D12", ShaderResourceCacheD3D12, m_NumShaders); } { auto& ShaderVarMgrAllocator = GetRawAllocator(); - m_pStaticVarManagers = ALLOCATE(ShaderVarMgrAllocator, "Raw memory for ShaderVariableManagerD3D12", ShaderVariableManagerD3D12, m_NumShaders); + m_pStaticVarManagers = ALLOCATE(ShaderVarMgrAllocator, "Raw memory for ShaderVariableManagerD3D12", ShaderVariableManagerD3D12, m_NumShaders); } #ifdef DEVELOPMENT @@ -91,21 +93,22 @@ PipelineStateD3D12Impl :: PipelineStateD3D12Impl(IReferenceCounters* pRefCo for (Uint32 s = 0; s < m_NumShaders; ++s) { const auto* pShader = GetShader(s); - pResources[s] = &(*pShader->GetShaderResources()); + pResources[s] = &(*pShader->GetShaderResources()); } ShaderResources::DvpVerifyResourceLayout(ResourceLayout, pResources, m_NumShaders); } #endif - for (Uint32 s=0; s < m_NumShaders; ++s) + for (Uint32 s = 0; s < m_NumShaders; ++s) { auto* pShaderD3D12 = GetShader(s); - auto ShaderType = pShaderD3D12->GetDesc().ShaderType; - auto ShaderInd = GetShaderTypeIndex(ShaderType); + auto ShaderType = pShaderD3D12->GetDesc().ShaderType; + auto ShaderInd = GetShaderTypeIndex(ShaderType); + m_ResourceLayoutIndex[ShaderInd] = static_cast(s); - - new (m_pShaderResourceLayouts+s) - ShaderResourceLayoutD3D12 + + new (m_pShaderResourceLayouts + s) + ShaderResourceLayoutD3D12 // { *this, pDeviceD3D12->GetD3D12Device(), @@ -115,14 +118,14 @@ PipelineStateD3D12Impl :: PipelineStateD3D12Impl(IReferenceCounters* pRefCo nullptr, 0, nullptr, - &m_RootSig + &m_RootSig // }; - new (m_pStaticResourceCaches+s) ShaderResourceCacheD3D12{ShaderResourceCacheD3D12::DbgCacheContentType::StaticShaderResources}; + new (m_pStaticResourceCaches + s) ShaderResourceCacheD3D12{ShaderResourceCacheD3D12::DbgCacheContentType::StaticShaderResources}; const SHADER_RESOURCE_VARIABLE_TYPE StaticVarType[] = {SHADER_RESOURCE_VARIABLE_TYPE_STATIC}; new (m_pShaderResourceLayouts + m_NumShaders + s) - ShaderResourceLayoutD3D12 + ShaderResourceLayoutD3D12 // { *this, pDeviceD3D12->GetD3D12Device(), @@ -131,19 +134,19 @@ PipelineStateD3D12Impl :: PipelineStateD3D12Impl(IReferenceCounters* pRefCo GetRawAllocator(), StaticVarType, _countof(StaticVarType), - m_pStaticResourceCaches+s, - nullptr + m_pStaticResourceCaches + s, + nullptr // }; - new (m_pStaticVarManagers+s) - ShaderVariableManagerD3D12 + new (m_pStaticVarManagers + s) + ShaderVariableManagerD3D12 // { *this, GetStaticShaderResLayout(s), GetRawAllocator(), nullptr, 0, - GetStaticShaderResCache(s) + GetStaticShaderResCache(s) // }; } m_RootSig.Finalize(pd3d12Device); @@ -152,79 +155,86 @@ PipelineStateD3D12Impl :: PipelineStateD3D12Impl(IReferenceCounters* pRefCo { auto& ComputePipeline = PipelineDesc.ComputePipeline; - if( ComputePipeline.pCS == nullptr ) + if (ComputePipeline.pCS == nullptr) LOG_ERROR_AND_THROW("Compute shader is not set in the pipeline desc"); D3D12_COMPUTE_PIPELINE_STATE_DESC d3d12PSODesc = {}; + d3d12PSODesc.pRootSignature = nullptr; - - auto* pByteCode = ValidatedCast(ComputePipeline.pCS)->GetShaderByteCode(); + + auto* pByteCode = ValidatedCast(ComputePipeline.pCS)->GetShaderByteCode(); d3d12PSODesc.CS.pShaderBytecode = pByteCode->GetBufferPointer(); - d3d12PSODesc.CS.BytecodeLength = pByteCode->GetBufferSize(); + d3d12PSODesc.CS.BytecodeLength = pByteCode->GetBufferSize(); - // For single GPU operation, set this to zero. If there are multiple GPU nodes, - // set bits to identify the nodes (the device's physical adapters) for which the - // graphics pipeline state is to apply. Each bit in the mask corresponds to a single node. + // For single GPU operation, set this to zero. If there are multiple GPU nodes, + // set bits to identify the nodes (the device's physical adapters) for which the + // graphics pipeline state is to apply. Each bit in the mask corresponds to a single node. d3d12PSODesc.NodeMask = 0; - d3d12PSODesc.CachedPSO.pCachedBlob = nullptr; + d3d12PSODesc.CachedPSO.pCachedBlob = nullptr; d3d12PSODesc.CachedPSO.CachedBlobSizeInBytes = 0; - + // The only valid bit is D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG, which can only be set on WARP devices. d3d12PSODesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; d3d12PSODesc.pRootSignature = m_RootSig.GetD3D12RootSignature(); - HRESULT hr = pd3d12Device->CreateComputePipelineState(&d3d12PSODesc, __uuidof(ID3D12PipelineState), reinterpret_cast( static_cast(&m_pd3d12PSO)) ); - if(FAILED(hr)) + HRESULT hr = pd3d12Device->CreateComputePipelineState(&d3d12PSODesc, __uuidof(ID3D12PipelineState), reinterpret_cast(static_cast(&m_pd3d12PSO))); + if (FAILED(hr)) LOG_ERROR_AND_THROW("Failed to create pipeline state"); } else { const auto& GraphicsPipeline = PipelineDesc.GraphicsPipeline; + D3D12_GRAPHICS_PIPELINE_STATE_DESC d3d12PSODesc = {}; - - for (Uint32 s=0; s < m_NumShaders; ++s) + + for (Uint32 s = 0; s < m_NumShaders; ++s) { auto* pShaderD3D12 = GetShader(s); - auto ShaderType = pShaderD3D12->GetDesc().ShaderType; - D3D12_SHADER_BYTECODE *pd3d12ShaderBytecode = nullptr; - switch(ShaderType) + auto ShaderType = pShaderD3D12->GetDesc().ShaderType; + + D3D12_SHADER_BYTECODE* pd3d12ShaderBytecode = nullptr; + switch (ShaderType) { + // clang-format off case SHADER_TYPE_VERTEX: pd3d12ShaderBytecode = &d3d12PSODesc.VS; break; case SHADER_TYPE_PIXEL: pd3d12ShaderBytecode = &d3d12PSODesc.PS; break; case SHADER_TYPE_GEOMETRY: pd3d12ShaderBytecode = &d3d12PSODesc.GS; break; case SHADER_TYPE_HULL: pd3d12ShaderBytecode = &d3d12PSODesc.HS; break; case SHADER_TYPE_DOMAIN: pd3d12ShaderBytecode = &d3d12PSODesc.DS; break; + // clang-format on default: UNEXPECTED("Unexpected shader type"); } auto* pByteCode = pShaderD3D12->GetShaderByteCode(); + pd3d12ShaderBytecode->pShaderBytecode = pByteCode->GetBufferPointer(); pd3d12ShaderBytecode->BytecodeLength = pByteCode->GetBufferSize(); } d3d12PSODesc.pRootSignature = m_RootSig.GetD3D12RootSignature(); - + memset(&d3d12PSODesc.StreamOutput, 0, sizeof(d3d12PSODesc.StreamOutput)); BlendStateDesc_To_D3D12_BLEND_DESC(GraphicsPipeline.BlendDesc, d3d12PSODesc.BlendState); // The sample mask for the blend state. d3d12PSODesc.SampleMask = GraphicsPipeline.SampleMask; - + RasterizerStateDesc_To_D3D12_RASTERIZER_DESC(GraphicsPipeline.RasterizerDesc, d3d12PSODesc.RasterizerState); DepthStencilStateDesc_To_D3D12_DEPTH_STENCIL_DESC(GraphicsPipeline.DepthStencilDesc, d3d12PSODesc.DepthStencilState); - std::vector> d312InputElements( STD_ALLOCATOR_RAW_MEM(D3D12_INPUT_ELEMENT_DESC, GetRawAllocator(), "Allocator for vector") ); + std::vector> d312InputElements{STD_ALLOCATOR_RAW_MEM(D3D12_INPUT_ELEMENT_DESC, GetRawAllocator(), "Allocator for vector")}; + const auto& InputLayout = m_Desc.GraphicsPipeline.InputLayout; - if (InputLayout.NumElements > 0) + if (InputLayout.NumElements > 0) { LayoutElements_To_D3D12_INPUT_ELEMENT_DESCs(InputLayout, d312InputElements); - d3d12PSODesc.InputLayout.NumElements = static_cast(d312InputElements.size()); + d3d12PSODesc.InputLayout.NumElements = static_cast(d312InputElements.size()); d3d12PSODesc.InputLayout.pInputElementDescs = d312InputElements.data(); } else { - d3d12PSODesc.InputLayout.NumElements = 0; + d3d12PSODesc.InputLayout.NumElements = 0; d3d12PSODesc.InputLayout.pInputElementDescs = nullptr; } @@ -239,22 +249,22 @@ PipelineStateD3D12Impl :: PipelineStateD3D12Impl(IReferenceCounters* pRefCo d3d12PSODesc.RTVFormats[rt] = TexFormatToDXGI_Format(GraphicsPipeline.RTVFormats[rt]); d3d12PSODesc.DSVFormat = TexFormatToDXGI_Format(GraphicsPipeline.DSVFormat); - d3d12PSODesc.SampleDesc.Count = GraphicsPipeline.SmplDesc.Count; + d3d12PSODesc.SampleDesc.Count = GraphicsPipeline.SmplDesc.Count; d3d12PSODesc.SampleDesc.Quality = GraphicsPipeline.SmplDesc.Quality; - // For single GPU operation, set this to zero. If there are multiple GPU nodes, - // set bits to identify the nodes (the device's physical adapters) for which the - // graphics pipeline state is to apply. Each bit in the mask corresponds to a single node. + // For single GPU operation, set this to zero. If there are multiple GPU nodes, + // set bits to identify the nodes (the device's physical adapters) for which the + // graphics pipeline state is to apply. Each bit in the mask corresponds to a single node. d3d12PSODesc.NodeMask = 0; - d3d12PSODesc.CachedPSO.pCachedBlob = nullptr; + d3d12PSODesc.CachedPSO.pCachedBlob = nullptr; d3d12PSODesc.CachedPSO.CachedBlobSizeInBytes = 0; // The only valid bit is D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG, which can only be set on WARP devices. d3d12PSODesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; - HRESULT hr = pd3d12Device->CreateGraphicsPipelineState(&d3d12PSODesc, __uuidof(ID3D12PipelineState), reinterpret_cast( static_cast(&m_pd3d12PSO)) ); - if(FAILED(hr)) + HRESULT hr = pd3d12Device->CreateGraphicsPipelineState(&d3d12PSODesc, __uuidof(ID3D12PipelineState), reinterpret_cast(static_cast(&m_pd3d12PSO))); + if (FAILED(hr)) LOG_ERROR_AND_THROW("Failed to create pipeline state"); } @@ -267,13 +277,14 @@ PipelineStateD3D12Impl :: PipelineStateD3D12Impl(IReferenceCounters* pRefCo m_RootSig.GetD3D12RootSignature()->SetName(WidenString(RootSignatureDesc).c_str()); } - if(PipelineDesc.SRBAllocationGranularity > 1) + if (PipelineDesc.SRBAllocationGranularity > 1) { std::array ShaderVarMgrDataSizes = {}; for (Uint32 s = 0; s < m_NumShaders; ++s) { - std::array AllowedVarTypes = { SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC }; - Uint32 NumVariablesUnused = 0; + std::array AllowedVarTypes = {SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; + Uint32 NumVariablesUnused = 0; + ShaderVarMgrDataSizes[s] = ShaderVariableManagerD3D12::GetRequiredMemorySize(m_pShaderResourceLayouts[s], AllowedVarTypes.data(), static_cast(AllowedVarTypes.size()), NumVariablesUnused); } @@ -287,13 +298,13 @@ PipelineStateD3D12Impl :: PipelineStateD3D12Impl(IReferenceCounters* pRefCo PipelineStateD3D12Impl::~PipelineStateD3D12Impl() { auto& ShaderResLayoutAllocator = GetRawAllocator(); - for(Uint32 s = 0; s < m_NumShaders; ++s) + for (Uint32 s = 0; s < m_NumShaders; ++s) { m_pStaticVarManagers[s].Destroy(GetRawAllocator()); m_pStaticVarManagers[s].~ShaderVariableManagerD3D12(); - m_pStaticResourceCaches [s].~ShaderResourceCacheD3D12(); + m_pStaticResourceCaches[s].~ShaderResourceCacheD3D12(); m_pShaderResourceLayouts[s].~ShaderResourceLayoutD3D12(); - m_pShaderResourceLayouts[m_NumShaders+s].~ShaderResourceLayoutD3D12(); + m_pShaderResourceLayouts[m_NumShaders + s].~ShaderResourceLayoutD3D12(); } ShaderResLayoutAllocator.Free(m_pStaticVarManagers); ShaderResLayoutAllocator.Free(m_pStaticResourceCaches); @@ -303,26 +314,26 @@ PipelineStateD3D12Impl::~PipelineStateD3D12Impl() m_pDevice->SafeReleaseDeviceObject(std::move(m_pd3d12PSO), m_Desc.CommandQueueMask); } -IMPLEMENT_QUERY_INTERFACE( PipelineStateD3D12Impl, IID_PipelineStateD3D12, TPipelineStateBase ) +IMPLEMENT_QUERY_INTERFACE(PipelineStateD3D12Impl, IID_PipelineStateD3D12, TPipelineStateBase) -void PipelineStateD3D12Impl::CreateShaderResourceBinding(IShaderResourceBinding** ppShaderResourceBinding, bool InitStaticResources ) +void PipelineStateD3D12Impl::CreateShaderResourceBinding(IShaderResourceBinding** ppShaderResourceBinding, bool InitStaticResources) { - auto& SRBAllocator = m_pDevice->GetSRBAllocator(); - auto pResBindingD3D12 = NEW_RC_OBJ(SRBAllocator, "ShaderResourceBindingD3D12Impl instance", ShaderResourceBindingD3D12Impl)(this, false); + auto& SRBAllocator = m_pDevice->GetSRBAllocator(); + auto pResBindingD3D12 = NEW_RC_OBJ(SRBAllocator, "ShaderResourceBindingD3D12Impl instance", ShaderResourceBindingD3D12Impl)(this, false); if (InitStaticResources) pResBindingD3D12->InitializeStaticResources(nullptr); pResBindingD3D12->QueryInterface(IID_ShaderResourceBinding, reinterpret_cast(ppShaderResourceBinding)); } -bool PipelineStateD3D12Impl::IsCompatibleWith(const IPipelineState* pPSO)const +bool PipelineStateD3D12Impl::IsCompatibleWith(const IPipelineState* pPSO) const { VERIFY_EXPR(pPSO != nullptr); if (pPSO == this) return true; - const PipelineStateD3D12Impl *pPSOD3D12 = ValidatedCast(pPSO); + const PipelineStateD3D12Impl* pPSOD3D12 = ValidatedCast(pPSO); if (m_ShaderResourceLayoutHash != pPSOD3D12->m_ShaderResourceLayoutHash) return false; @@ -334,7 +345,7 @@ bool PipelineStateD3D12Impl::IsCompatibleWith(const IPipelineState* pPSO)const if (m_NumShaders != pPSOD3D12->m_NumShaders) IsCompatibleShaders = false; - if(IsCompatibleShaders) + if (IsCompatibleShaders) { for (Uint32 s = 0; s < m_NumShaders; ++s) { @@ -345,8 +356,8 @@ bool PipelineStateD3D12Impl::IsCompatibleWith(const IPipelineState* pPSO)const IsCompatibleShaders = false; break; } - const ShaderResourcesD3D12 *pRes0 = pShader0->GetShaderResources().get(); - const ShaderResourcesD3D12 *pRes1 = pShader1->GetShaderResources().get(); + const ShaderResourcesD3D12* pRes0 = pShader0->GetShaderResources().get(); + const ShaderResourcesD3D12* pRes1 = pShader1->GetShaderResources().get(); if (!pRes0->IsCompatibleWith(*pRes1)) { IsCompatibleShaders = false; @@ -355,17 +366,17 @@ bool PipelineStateD3D12Impl::IsCompatibleWith(const IPipelineState* pPSO)const } } - if(IsCompatibleShaders) + if (IsCompatibleShaders) VERIFY(IsSameRootSignature, "Compatible shaders must have same root signatures"); } #endif - + return IsSameRootSignature; } ShaderResourceCacheD3D12* PipelineStateD3D12Impl::CommitAndTransitionShaderResources(class DeviceContextD3D12Impl* pDeviceCtx, class CommandContext& CmdCtx, - CommitAndTransitionResourcesAttribs& Attrib)const + CommitAndTransitionResourcesAttribs& Attrib) const { #ifdef DEVELOPMENT if (Attrib.pShaderResourceBinding == nullptr && ContainsShaderResources()) @@ -380,10 +391,10 @@ ShaderResourceCacheD3D12* PipelineStateD3D12Impl::CommitAndTransitionShaderResou { if (Attrib.CommitResources) { - if(m_Desc.IsComputePipeline) - CmdCtx.AsComputeContext().SetRootSignature( GetD3D12RootSignature() ); + if (m_Desc.IsComputePipeline) + CmdCtx.AsComputeContext().SetRootSignature(GetD3D12RootSignature()); else - CmdCtx.AsGraphicsContext().SetRootSignature( GetD3D12RootSignature() ); + CmdCtx.AsGraphicsContext().SetRootSignature(GetD3D12RootSignature()); } return nullptr; } @@ -396,24 +407,25 @@ ShaderResourceCacheD3D12* PipelineStateD3D12Impl::CommitAndTransitionShaderResou } - if( (m_RootSig.GetTotalSrvCbvUavSlots(SHADER_RESOURCE_VARIABLE_TYPE_STATIC) != 0 || - m_RootSig.GetTotalRootViews(SHADER_RESOURCE_VARIABLE_TYPE_STATIC) != 0) && !pResBindingD3D12Impl->StaticResourcesInitialized() ) + if ((m_RootSig.GetTotalSrvCbvUavSlots(SHADER_RESOURCE_VARIABLE_TYPE_STATIC) != 0 || + m_RootSig.GetTotalRootViews(SHADER_RESOURCE_VARIABLE_TYPE_STATIC) != 0) && + !pResBindingD3D12Impl->StaticResourcesInitialized()) { - LOG_ERROR_MESSAGE("Static resources have not been initialized in the shader resource binding object being committed for PSO '", m_Desc.Name,"'. Please call IShaderResourceBinding::InitializeStaticResources()."); + LOG_ERROR_MESSAGE("Static resources have not been initialized in the shader resource binding object being committed for PSO '", m_Desc.Name, "'. Please call IShaderResourceBinding::InitializeStaticResources()."); } pResBindingD3D12Impl->dvpVerifyResourceBindings(this); #endif auto& ResourceCache = pResBindingD3D12Impl->GetResourceCache(); - if(Attrib.CommitResources) + if (Attrib.CommitResources) { - if(m_Desc.IsComputePipeline) - CmdCtx.AsComputeContext().SetRootSignature( GetD3D12RootSignature() ); + if (m_Desc.IsComputePipeline) + CmdCtx.AsComputeContext().SetRootSignature(GetD3D12RootSignature()); else - CmdCtx.AsGraphicsContext().SetRootSignature( GetD3D12RootSignature() ); + CmdCtx.AsGraphicsContext().SetRootSignature(GetD3D12RootSignature()); - if(Attrib.TransitionResources) + if (Attrib.TransitionResources) { (m_RootSig.*m_RootSig.TransitionAndCommitDescriptorHandles)(m_pDevice, ResourceCache, CmdCtx, m_Desc.IsComputePipeline, Attrib.ValidateStates); } @@ -434,23 +446,22 @@ ShaderResourceCacheD3D12* PipelineStateD3D12Impl::CommitAndTransitionShaderResou m_Desc.IsComputePipeline, Attrib.CtxId, pDeviceCtx, - Attrib.CommitResources, // CommitViews - false, // ProcessDynamicBuffers - true, // ProcessNonDynamicBuffers + Attrib.CommitResources, // CommitViews + false, // ProcessDynamicBuffers + true, // ProcessNonDynamicBuffers Attrib.TransitionResources, - Attrib.ValidateStates - ); + Attrib.ValidateStates); return &ResourceCache; } -bool PipelineStateD3D12Impl::ContainsShaderResources()const +bool PipelineStateD3D12Impl::ContainsShaderResources() const { - for(auto VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType+1)) + for (auto VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType + 1)) { - if (m_RootSig.GetTotalSrvCbvUavSlots(VarType) != 0 || - m_RootSig.GetTotalRootViews (VarType) != 0) + if (m_RootSig.GetTotalSrvCbvUavSlots(VarType) != 0 || + m_RootSig.GetTotalRootViews(VarType) != 0) return true; } return false; @@ -458,7 +469,7 @@ bool PipelineStateD3D12Impl::ContainsShaderResources()const void PipelineStateD3D12Impl::BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags) { - for (Uint32 s=0; s < m_NumShaders; ++s) + for (Uint32 s = 0; s < m_NumShaders; ++s) { auto ShaderType = GetStaticShaderResLayout(s).GetShaderType(); if ((ShaderFlags & ShaderType) != 0) @@ -493,4 +504,4 @@ IShaderResourceVariable* PipelineStateD3D12Impl::GetStaticVariableByIndex(SHADER return m_pStaticVarManagers[LayoutInd].GetVariable(Index); } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/RenderDeviceD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/RenderDeviceD3D12Impl.cpp index c517f634..3b9d9907 100644 --- a/Graphics/GraphicsEngineD3D12/src/RenderDeviceD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/RenderDeviceD3D12Impl.cpp @@ -37,31 +37,33 @@ namespace Diligent { -D3D_FEATURE_LEVEL RenderDeviceD3D12Impl :: GetD3DFeatureLevel() const +D3D_FEATURE_LEVEL RenderDeviceD3D12Impl ::GetD3DFeatureLevel() const { - D3D_FEATURE_LEVEL FeatureLevels[] = - { - D3D_FEATURE_LEVEL_12_1, - D3D_FEATURE_LEVEL_12_0, - D3D_FEATURE_LEVEL_11_1, - D3D_FEATURE_LEVEL_11_0, - D3D_FEATURE_LEVEL_10_1, - D3D_FEATURE_LEVEL_10_0 - }; + D3D_FEATURE_LEVEL FeatureLevels[] = + { + D3D_FEATURE_LEVEL_12_1, + D3D_FEATURE_LEVEL_12_0, + D3D_FEATURE_LEVEL_11_1, + D3D_FEATURE_LEVEL_11_0, + D3D_FEATURE_LEVEL_10_1, + D3D_FEATURE_LEVEL_10_0 // + }; D3D12_FEATURE_DATA_FEATURE_LEVELS FeatureLevelsData = {}; + FeatureLevelsData.pFeatureLevelsRequested = FeatureLevels; FeatureLevelsData.NumFeatureLevels = _countof(FeatureLevels); m_pd3d12Device->CheckFeatureSupport(D3D12_FEATURE_FEATURE_LEVELS, &FeatureLevelsData, sizeof(FeatureLevelsData)); return FeatureLevelsData.MaxSupportedFeatureLevel; } -RenderDeviceD3D12Impl :: RenderDeviceD3D12Impl(IReferenceCounters* pRefCounters, - IMemoryAllocator& RawMemAllocator, - IEngineFactory* pEngineFactory, - const EngineD3D12CreateInfo& EngineCI, - ID3D12Device* pd3d12Device, - size_t CommandQueueCount, - ICommandQueueD3D12** ppCmdQueues) : +RenderDeviceD3D12Impl ::RenderDeviceD3D12Impl(IReferenceCounters* pRefCounters, + IMemoryAllocator& RawMemAllocator, + IEngineFactory* pEngineFactory, + const EngineD3D12CreateInfo& EngineCI, + ID3D12Device* pd3d12Device, + size_t CommandQueueCount, + ICommandQueueD3D12** ppCmdQueues) : + // clang-format off TRenderDeviceBase { pRefCounters, @@ -101,29 +103,30 @@ RenderDeviceD3D12Impl :: RenderDeviceD3D12Impl(IReferenceCounters* pRe m_ContextPool {STD_ALLOCATOR_RAW_MEM(PooledCommandContext, GetRawAllocator(), "Allocator for vector")}, m_DynamicMemoryManager{GetRawAllocator(), *this, EngineCI.NumDynamicHeapPagesToReserve, EngineCI.DynamicHeapPageSize}, m_MipsGenerator {pd3d12Device} +// clang-format on { m_DeviceCaps.DevType = DeviceType::D3D12; - auto FeatureLevel = GetD3DFeatureLevel(); + auto FeatureLevel = GetD3DFeatureLevel(); switch (FeatureLevel) { case D3D_FEATURE_LEVEL_12_0: case D3D_FEATURE_LEVEL_12_1: - m_DeviceCaps.MajorVersion = 12; - m_DeviceCaps.MinorVersion = FeatureLevel == D3D_FEATURE_LEVEL_12_1 ? 1 : 0; + m_DeviceCaps.MajorVersion = 12; + m_DeviceCaps.MinorVersion = FeatureLevel == D3D_FEATURE_LEVEL_12_1 ? 1 : 0; m_DeviceCaps.bBindlessSupported = true; - break; + break; case D3D_FEATURE_LEVEL_11_0: case D3D_FEATURE_LEVEL_11_1: m_DeviceCaps.MajorVersion = 11; m_DeviceCaps.MinorVersion = FeatureLevel == D3D_FEATURE_LEVEL_11_1 ? 1 : 0; - break; - + break; + case D3D_FEATURE_LEVEL_10_0: case D3D_FEATURE_LEVEL_10_1: m_DeviceCaps.MajorVersion = 10; m_DeviceCaps.MinorVersion = FeatureLevel == D3D_FEATURE_LEVEL_10_1 ? 1 : 0; - break; + break; default: UNEXPECTED("Unexpected D3D feature level"); @@ -144,11 +147,11 @@ RenderDeviceD3D12Impl::~RenderDeviceD3D12Impl() ReleaseStaleResources(true); #ifdef DEVELOPMENT - for (auto i=0; i < _countof(m_CPUDescriptorHeaps); ++i) + for (auto i = 0; i < _countof(m_CPUDescriptorHeaps); ++i) { DEV_CHECK_ERR(m_CPUDescriptorHeaps[i].DvpGetTotalAllocationCount() == 0, "All CPU descriptor heap allocations must be released"); } - for (auto i=0; i < _countof(m_GPUDescriptorHeaps); ++i) + for (auto i = 0; i < _countof(m_GPUDescriptorHeaps); ++i) { DEV_CHECK_ERR(m_GPUDescriptorHeaps[i].DvpGetTotalAllocationCount() == 0, "All GPU descriptor heap allocations must be released"); } @@ -159,13 +162,13 @@ RenderDeviceD3D12Impl::~RenderDeviceD3D12Impl() DEV_CHECK_ERR(m_CmdListManager.GetAllocatorCounter() == 0, "All allocators must have been returned to the manager at this point."); DEV_CHECK_ERR(m_AllocatedCtxCounter == 0, "All contexts must have been released."); - m_ContextPool.clear(); + m_ContextPool.clear(); DestroyCommandQueues(); } void RenderDeviceD3D12Impl::DisposeCommandContext(PooledCommandContext&& Ctx) { - CComPtr pAllocator; + CComPtr pAllocator; Ctx->Close(pAllocator); // Since allocator has not been used, we cmd list manager can put it directly into the free allocator list m_CmdListManager.FreeAllocator(std::move(pAllocator)); @@ -174,7 +177,7 @@ void RenderDeviceD3D12Impl::DisposeCommandContext(PooledCommandContext&& Ctx) void RenderDeviceD3D12Impl::FreeCommandContext(PooledCommandContext&& Ctx) { - std::lock_guard LockGuard(m_ContextPoolMutex); + std::lock_guard LockGuard(m_ContextPoolMutex); m_ContextPool.emplace_back(std::move(Ctx)); #ifdef DEVELOPMENT Atomics::AtomicDecrement(m_AllocatedCtxCounter); @@ -184,30 +187,29 @@ void RenderDeviceD3D12Impl::FreeCommandContext(PooledCommandContext&& Ctx) void RenderDeviceD3D12Impl::CloseAndExecuteTransientCommandContext(Uint32 CommandQueueIndex, PooledCommandContext&& Ctx) { CComPtr pAllocator; - ID3D12GraphicsCommandList* pCmdList = Ctx->Close(pAllocator); - Uint64 FenceValue = 0; + ID3D12GraphicsCommandList* pCmdList = Ctx->Close(pAllocator); + Uint64 FenceValue = 0; // Execute command list directly through the queue to avoid interference with command list numbers in the queue - LockCmdQueueAndRun(CommandQueueIndex, - [&](ICommandQueueD3D12* pCmdQueue) - { - FenceValue = pCmdQueue->Submit(pCmdList); - } - ); - m_CmdListManager.ReleaseAllocator(std::move(pAllocator), CommandQueueIndex, FenceValue); + LockCmdQueueAndRun(CommandQueueIndex, + [&](ICommandQueueD3D12* pCmdQueue) // + { + FenceValue = pCmdQueue->Submit(pCmdList); + }); + m_CmdListManager.ReleaseAllocator(std::move(pAllocator), CommandQueueIndex, FenceValue); FreeCommandContext(std::move(Ctx)); } -Uint64 RenderDeviceD3D12Impl::CloseAndExecuteCommandContext(Uint32 QueueIndex, PooledCommandContext&& Ctx, bool DiscardStaleObjects, std::vector > >* pSignalFences) +Uint64 RenderDeviceD3D12Impl::CloseAndExecuteCommandContext(Uint32 QueueIndex, PooledCommandContext&& Ctx, bool DiscardStaleObjects, std::vector>>* pSignalFences) { CComPtr pAllocator; - ID3D12GraphicsCommandList* pCmdList = Ctx->Close(pAllocator); + ID3D12GraphicsCommandList* pCmdList = Ctx->Close(pAllocator); Uint64 FenceValue = 0; { - // Stale objects should only be discarded when submitting cmd list from + // Stale objects should only be discarded when submitting cmd list from // the immediate context, otherwise the basic requirement may be violated // as in the following scenario - // + // // Signaled | | // Fence Value | Immediate Context | InitContext | // | | | @@ -223,12 +225,12 @@ Uint64 RenderDeviceD3D12Impl::CloseAndExecuteCommandContext(Uint32 QueueIndex, P // | was added to the delete queue | | // | with number N | | auto SubmittedCmdBuffInfo = TRenderDeviceBase::SubmitCommandBuffer(QueueIndex, pCmdList, true); - FenceValue = SubmittedCmdBuffInfo.FenceValue; + FenceValue = SubmittedCmdBuffInfo.FenceValue; if (pSignalFences != nullptr) SignalFences(QueueIndex, *pSignalFences); } - m_CmdListManager.ReleaseAllocator(std::move(pAllocator), QueueIndex, FenceValue); + m_CmdListManager.ReleaseAllocator(std::move(pAllocator), QueueIndex, FenceValue); FreeCommandContext(std::move(Ctx)); PurgeReleaseQueue(QueueIndex); @@ -236,25 +238,25 @@ Uint64 RenderDeviceD3D12Impl::CloseAndExecuteCommandContext(Uint32 QueueIndex, P return FenceValue; } -void RenderDeviceD3D12Impl::SignalFences(Uint32 QueueIndex, std::vector > >& SignalFences) +void RenderDeviceD3D12Impl::SignalFences(Uint32 QueueIndex, std::vector>>& SignalFences) { for (auto& val_fence : SignalFences) { auto* pFenceD3D12Impl = val_fence.second.RawPtr(); - auto* pd3d12Fence = pFenceD3D12Impl->GetD3D12Fence(); + auto* pd3d12Fence = pFenceD3D12Impl->GetD3D12Fence(); m_CommandQueues[QueueIndex].CmdQueue->SignalFence(pd3d12Fence, val_fence.first); } } -void RenderDeviceD3D12Impl::IdleGPU() -{ +void RenderDeviceD3D12Impl::IdleGPU() +{ IdleAllCommandQueues(true); ReleaseStaleResources(); } void RenderDeviceD3D12Impl::FlushStaleResources(Uint32 CmdQueueIndex) { - // Submit empty command list to the queue. This will effectively signal the fence and + // Submit empty command list to the queue. This will effectively signal the fence and // discard all resources ID3D12GraphicsCommandList* pNullCmdList = nullptr; TRenderDeviceBase::SubmitCommandBuffer(CmdQueueIndex, pNullCmdList, true); @@ -269,7 +271,7 @@ void RenderDeviceD3D12Impl::ReleaseStaleResources(bool ForceRelease) RenderDeviceD3D12Impl::PooledCommandContext RenderDeviceD3D12Impl::AllocateCommandContext(const Char* ID) { { - std::lock_guard LockGuard(m_ContextPoolMutex); + std::lock_guard LockGuard(m_ContextPoolMutex); if (!m_ContextPool.empty()) { PooledCommandContext Ctx = std::move(m_ContextPool.back()); @@ -284,8 +286,8 @@ RenderDeviceD3D12Impl::PooledCommandContext RenderDeviceD3D12Impl::AllocateComma } auto& CmdCtxAllocator = GetRawAllocator(); - auto* pRawMem = ALLOCATE(CmdCtxAllocator, "CommandContext instance", CommandContext, 1); - auto pCtx = new (pRawMem) CommandContext(m_CmdListManager); + auto* pRawMem = ALLOCATE(CmdCtxAllocator, "CommandContext instance", CommandContext, 1); + auto pCtx = new (pRawMem) CommandContext(m_CmdListManager); pCtx->SetID(ID); #ifdef DEVELOPMENT Atomics::AtomicIncrement(m_AllocatedCtxCounter); @@ -294,14 +296,15 @@ RenderDeviceD3D12Impl::PooledCommandContext RenderDeviceD3D12Impl::AllocateComma } -void RenderDeviceD3D12Impl::TestTextureFormat( TEXTURE_FORMAT TexFormat ) +void RenderDeviceD3D12Impl::TestTextureFormat(TEXTURE_FORMAT TexFormat) { - auto &TexFormatInfo = m_TextureFormatsInfo[TexFormat]; - VERIFY( TexFormatInfo.Supported, "Texture format is not supported" ); + auto& TexFormatInfo = m_TextureFormatsInfo[TexFormat]; + VERIFY(TexFormatInfo.Supported, "Texture format is not supported"); auto DXGIFormat = TexFormatToDXGI_Format(TexFormat); D3D12_FEATURE_DATA_FORMAT_SUPPORT FormatSupport = {DXGIFormat}; + auto hr = m_pd3d12Device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &FormatSupport, sizeof(FormatSupport)); if (FAILED(hr)) { @@ -309,161 +312,154 @@ void RenderDeviceD3D12Impl::TestTextureFormat( TEXTURE_FORMAT TexFormat ) return; } + // clang-format off TexFormatInfo.Filterable = ((FormatSupport.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE) != 0) || ((FormatSupport.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE_COMPARISON) != 0); TexFormatInfo.ColorRenderable = (FormatSupport.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET) != 0; TexFormatInfo.DepthRenderable = (FormatSupport.Support1 & D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL) != 0; - TexFormatInfo.Tex1DFmt = (FormatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE1D) != 0; - TexFormatInfo.Tex2DFmt = (FormatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D) != 0; - TexFormatInfo.Tex3DFmt = (FormatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE3D) != 0; + TexFormatInfo.Tex1DFmt = (FormatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE1D) != 0; + TexFormatInfo.Tex2DFmt = (FormatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D) != 0; + TexFormatInfo.Tex3DFmt = (FormatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE3D) != 0; TexFormatInfo.TexCubeFmt = (FormatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURECUBE) != 0; + // clang-format on TexFormatInfo.SampleCounts = 0x0; - for(Uint32 SampleCount = 1; SampleCount <= D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT; SampleCount *= 2) + for (Uint32 SampleCount = 1; SampleCount <= D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT; SampleCount *= 2) { D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS QualityLevels = {DXGIFormat, SampleCount}; + hr = m_pd3d12Device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &QualityLevels, sizeof(QualityLevels)); - if(SUCCEEDED(hr) && QualityLevels.NumQualityLevels > 0) + if (SUCCEEDED(hr) && QualityLevels.NumQualityLevels > 0) TexFormatInfo.SampleCounts |= SampleCount; } } -IMPLEMENT_QUERY_INTERFACE( RenderDeviceD3D12Impl, IID_RenderDeviceD3D12, TRenderDeviceBase ) +IMPLEMENT_QUERY_INTERFACE(RenderDeviceD3D12Impl, IID_RenderDeviceD3D12, TRenderDeviceBase) void RenderDeviceD3D12Impl::CreatePipelineState(const PipelineStateDesc& PipelineDesc, IPipelineState** ppPipelineState) { - CreateDeviceObject("Pipeline State", PipelineDesc, ppPipelineState, - [&]() - { - PipelineStateD3D12Impl *pPipelineStateD3D12( NEW_RC_OBJ(m_PSOAllocator, "PipelineStateD3D12Impl instance", PipelineStateD3D12Impl)(this, PipelineDesc ) ); - pPipelineStateD3D12->QueryInterface( IID_PipelineState, reinterpret_cast(ppPipelineState) ); - OnCreateDeviceObject( pPipelineStateD3D12 ); - } - ); + CreateDeviceObject("Pipeline State", PipelineDesc, ppPipelineState, + [&]() // + { + PipelineStateD3D12Impl* pPipelineStateD3D12(NEW_RC_OBJ(m_PSOAllocator, "PipelineStateD3D12Impl instance", PipelineStateD3D12Impl)(this, PipelineDesc)); + pPipelineStateD3D12->QueryInterface(IID_PipelineState, reinterpret_cast(ppPipelineState)); + OnCreateDeviceObject(pPipelineStateD3D12); + }); } -void RenderDeviceD3D12Impl :: CreateBufferFromD3DResource(ID3D12Resource* pd3d12Buffer, const BufferDesc& BuffDesc, RESOURCE_STATE InitialState, IBuffer** ppBuffer) +void RenderDeviceD3D12Impl ::CreateBufferFromD3DResource(ID3D12Resource* pd3d12Buffer, const BufferDesc& BuffDesc, RESOURCE_STATE InitialState, IBuffer** ppBuffer) { - CreateDeviceObject("buffer", BuffDesc, ppBuffer, - [&]() - { - BufferD3D12Impl *pBufferD3D12( NEW_RC_OBJ(m_BufObjAllocator, "BufferD3D12Impl instance", BufferD3D12Impl)(m_BuffViewObjAllocator, this, BuffDesc, InitialState, pd3d12Buffer ) ); - pBufferD3D12->QueryInterface( IID_Buffer, reinterpret_cast(ppBuffer) ); - pBufferD3D12->CreateDefaultViews(); - OnCreateDeviceObject( pBufferD3D12 ); - } - ); + CreateDeviceObject("buffer", BuffDesc, ppBuffer, + [&]() // + { + BufferD3D12Impl* pBufferD3D12(NEW_RC_OBJ(m_BufObjAllocator, "BufferD3D12Impl instance", BufferD3D12Impl)(m_BuffViewObjAllocator, this, BuffDesc, InitialState, pd3d12Buffer)); + pBufferD3D12->QueryInterface(IID_Buffer, reinterpret_cast(ppBuffer)); + pBufferD3D12->CreateDefaultViews(); + OnCreateDeviceObject(pBufferD3D12); + }); } -void RenderDeviceD3D12Impl :: CreateBuffer(const BufferDesc& BuffDesc, const BufferData* pBuffData, IBuffer** ppBuffer) +void RenderDeviceD3D12Impl ::CreateBuffer(const BufferDesc& BuffDesc, const BufferData* pBuffData, IBuffer** ppBuffer) { - CreateDeviceObject("buffer", BuffDesc, ppBuffer, - [&]() - { - BufferD3D12Impl *pBufferD3D12( NEW_RC_OBJ(m_BufObjAllocator, "BufferD3D12Impl instance", BufferD3D12Impl)(m_BuffViewObjAllocator, this, BuffDesc, pBuffData ) ); - pBufferD3D12->QueryInterface( IID_Buffer, reinterpret_cast(ppBuffer) ); - pBufferD3D12->CreateDefaultViews(); - OnCreateDeviceObject( pBufferD3D12 ); - } - ); + CreateDeviceObject("buffer", BuffDesc, ppBuffer, + [&]() // + { + BufferD3D12Impl* pBufferD3D12(NEW_RC_OBJ(m_BufObjAllocator, "BufferD3D12Impl instance", BufferD3D12Impl)(m_BuffViewObjAllocator, this, BuffDesc, pBuffData)); + pBufferD3D12->QueryInterface(IID_Buffer, reinterpret_cast(ppBuffer)); + pBufferD3D12->CreateDefaultViews(); + OnCreateDeviceObject(pBufferD3D12); + }); } -void RenderDeviceD3D12Impl :: CreateShader(const ShaderCreateInfo& ShaderCI, IShader** ppShader) +void RenderDeviceD3D12Impl ::CreateShader(const ShaderCreateInfo& ShaderCI, IShader** ppShader) { - CreateDeviceObject( "shader", ShaderCI.Desc, ppShader, - [&]() - { - ShaderD3D12Impl *pShaderD3D12( NEW_RC_OBJ(m_ShaderObjAllocator, "ShaderD3D12Impl instance", ShaderD3D12Impl)(this, ShaderCI ) ); - pShaderD3D12->QueryInterface( IID_Shader, reinterpret_cast(ppShader) ); - - OnCreateDeviceObject( pShaderD3D12 ); - } - ); + CreateDeviceObject("shader", ShaderCI.Desc, ppShader, + [&]() // + { + ShaderD3D12Impl* pShaderD3D12(NEW_RC_OBJ(m_ShaderObjAllocator, "ShaderD3D12Impl instance", ShaderD3D12Impl)(this, ShaderCI)); + pShaderD3D12->QueryInterface(IID_Shader, reinterpret_cast(ppShader)); + + OnCreateDeviceObject(pShaderD3D12); + }); } void RenderDeviceD3D12Impl::CreateTextureFromD3DResource(ID3D12Resource* pd3d12Texture, RESOURCE_STATE InitialState, ITexture** ppTexture) { TextureDesc TexDesc; TexDesc.Name = "Texture from d3d12 resource"; - CreateDeviceObject( "texture", TexDesc, ppTexture, - [&]() - { - TextureD3D12Impl *pTextureD3D12 = NEW_RC_OBJ(m_TexObjAllocator, "TextureD3D12Impl instance", TextureD3D12Impl)(m_TexViewObjAllocator, this, TexDesc, InitialState, pd3d12Texture); - - pTextureD3D12->QueryInterface( IID_Texture, reinterpret_cast(ppTexture) ); - pTextureD3D12->CreateDefaultViews(); - OnCreateDeviceObject( pTextureD3D12 ); - } - ); + CreateDeviceObject("texture", TexDesc, ppTexture, + [&]() // + { + TextureD3D12Impl* pTextureD3D12 = NEW_RC_OBJ(m_TexObjAllocator, "TextureD3D12Impl instance", TextureD3D12Impl)(m_TexViewObjAllocator, this, TexDesc, InitialState, pd3d12Texture); + + pTextureD3D12->QueryInterface(IID_Texture, reinterpret_cast(ppTexture)); + pTextureD3D12->CreateDefaultViews(); + OnCreateDeviceObject(pTextureD3D12); + }); } void RenderDeviceD3D12Impl::CreateTexture(const TextureDesc& TexDesc, ID3D12Resource* pd3d12Texture, RESOURCE_STATE InitialState, TextureD3D12Impl** ppTexture) { - CreateDeviceObject( "texture", TexDesc, ppTexture, - [&]() - { - TextureD3D12Impl* pTextureD3D12 = NEW_RC_OBJ(m_TexObjAllocator, "TextureD3D12Impl instance", TextureD3D12Impl)(m_TexViewObjAllocator, this, TexDesc, InitialState, pd3d12Texture); - pTextureD3D12->QueryInterface( IID_TextureD3D12, reinterpret_cast(ppTexture) ); - } - ); + CreateDeviceObject("texture", TexDesc, ppTexture, + [&]() // + { + TextureD3D12Impl* pTextureD3D12 = NEW_RC_OBJ(m_TexObjAllocator, "TextureD3D12Impl instance", TextureD3D12Impl)(m_TexViewObjAllocator, this, TexDesc, InitialState, pd3d12Texture); + pTextureD3D12->QueryInterface(IID_TextureD3D12, reinterpret_cast(ppTexture)); + }); } -void RenderDeviceD3D12Impl :: CreateTexture(const TextureDesc& TexDesc, const TextureData* pData, ITexture** ppTexture) +void RenderDeviceD3D12Impl ::CreateTexture(const TextureDesc& TexDesc, const TextureData* pData, ITexture** ppTexture) { - CreateDeviceObject( "texture", TexDesc, ppTexture, - [&]() - { - TextureD3D12Impl* pTextureD3D12 = NEW_RC_OBJ(m_TexObjAllocator, "TextureD3D12Impl instance", TextureD3D12Impl)(m_TexViewObjAllocator, this, TexDesc, pData ); - - pTextureD3D12->QueryInterface( IID_Texture, reinterpret_cast(ppTexture) ); - pTextureD3D12->CreateDefaultViews(); - OnCreateDeviceObject( pTextureD3D12 ); - } - ); + CreateDeviceObject("texture", TexDesc, ppTexture, + [&]() // + { + TextureD3D12Impl* pTextureD3D12 = NEW_RC_OBJ(m_TexObjAllocator, "TextureD3D12Impl instance", TextureD3D12Impl)(m_TexViewObjAllocator, this, TexDesc, pData); + + pTextureD3D12->QueryInterface(IID_Texture, reinterpret_cast(ppTexture)); + pTextureD3D12->CreateDefaultViews(); + OnCreateDeviceObject(pTextureD3D12); + }); } -void RenderDeviceD3D12Impl :: CreateSampler(const SamplerDesc& SamplerDesc, ISampler** ppSampler) +void RenderDeviceD3D12Impl ::CreateSampler(const SamplerDesc& SamplerDesc, ISampler** ppSampler) { - CreateDeviceObject( "sampler", SamplerDesc, ppSampler, - [&]() - { - m_SamplersRegistry.Find( SamplerDesc, reinterpret_cast(ppSampler) ); - if( *ppSampler == nullptr ) - { - SamplerD3D12Impl *pSamplerD3D12( NEW_RC_OBJ(m_SamplerObjAllocator, "SamplerD3D12Impl instance", SamplerD3D12Impl)(this, SamplerDesc ) ); - pSamplerD3D12->QueryInterface( IID_Sampler, reinterpret_cast(ppSampler) ); - OnCreateDeviceObject( pSamplerD3D12 ); - m_SamplersRegistry.Add( SamplerDesc, *ppSampler ); - } - } - ); + CreateDeviceObject("sampler", SamplerDesc, ppSampler, + [&]() // + { + m_SamplersRegistry.Find(SamplerDesc, reinterpret_cast(ppSampler)); + if (*ppSampler == nullptr) + { + SamplerD3D12Impl* pSamplerD3D12(NEW_RC_OBJ(m_SamplerObjAllocator, "SamplerD3D12Impl instance", SamplerD3D12Impl)(this, SamplerDesc)); + pSamplerD3D12->QueryInterface(IID_Sampler, reinterpret_cast(ppSampler)); + OnCreateDeviceObject(pSamplerD3D12); + m_SamplersRegistry.Add(SamplerDesc, *ppSampler); + } + }); } void RenderDeviceD3D12Impl::CreateFence(const FenceDesc& Desc, IFence** ppFence) { - CreateDeviceObject( "Fence", Desc, ppFence, - [&]() - { - FenceD3D12Impl* pFenceD3D12( NEW_RC_OBJ(m_FenceAllocator, "FenceD3D12Impl instance", FenceD3D12Impl) - (this, Desc) ); - pFenceD3D12->QueryInterface( IID_Fence, reinterpret_cast(ppFence) ); - OnCreateDeviceObject( pFenceD3D12 ); - } - ); + CreateDeviceObject("Fence", Desc, ppFence, + [&]() // + { + FenceD3D12Impl* pFenceD3D12(NEW_RC_OBJ(m_FenceAllocator, "FenceD3D12Impl instance", FenceD3D12Impl)(this, Desc)); + pFenceD3D12->QueryInterface(IID_Fence, reinterpret_cast(ppFence)); + OnCreateDeviceObject(pFenceD3D12); + }); } -DescriptorHeapAllocation RenderDeviceD3D12Impl :: AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT Count /*= 1*/) +DescriptorHeapAllocation RenderDeviceD3D12Impl ::AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT Count /*= 1*/) { VERIFY(Type >= D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && Type < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES, "Invalid heap type"); return m_CPUDescriptorHeaps[Type].Allocate(Count); } -DescriptorHeapAllocation RenderDeviceD3D12Impl :: AllocateGPUDescriptors(D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT Count /*= 1*/) +DescriptorHeapAllocation RenderDeviceD3D12Impl ::AllocateGPUDescriptors(D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT Count /*= 1*/) { VERIFY(Type >= D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && Type <= D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, "Invalid heap type"); return m_GPUDescriptorHeaps[Type].Allocate(Count); } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/RootSignature.cpp b/Graphics/GraphicsEngineD3D12/src/RootSignature.cpp index 147fd72e..d96194ce 100644 --- a/Graphics/GraphicsEngineD3D12/src/RootSignature.cpp +++ b/Graphics/GraphicsEngineD3D12/src/RootSignature.cpp @@ -35,16 +35,16 @@ namespace Diligent { -RootSignature::RootParamsManager::RootParamsManager(IMemoryAllocator &MemAllocator): +RootSignature::RootParamsManager::RootParamsManager(IMemoryAllocator& MemAllocator) : m_MemAllocator{MemAllocator}, m_pMemory{nullptr, STDDeleter(MemAllocator)} {} size_t RootSignature::RootParamsManager::GetRequiredMemorySize(Uint32 NumExtraRootTables, Uint32 NumExtraRootViews, - Uint32 NumExtraDescriptorRanges)const + Uint32 NumExtraDescriptorRanges) const { - return sizeof(RootParameter) * (m_NumRootTables + NumExtraRootTables + m_NumRootViews + NumExtraRootViews) + sizeof(D3D12_DESCRIPTOR_RANGE) * (m_TotalDescriptorRanges + NumExtraDescriptorRanges); + return sizeof(RootParameter) * (m_NumRootTables + NumExtraRootTables + m_NumRootViews + NumExtraRootViews) + sizeof(D3D12_DESCRIPTOR_RANGE) * (m_TotalDescriptorRanges + NumExtraDescriptorRanges); } D3D12_DESCRIPTOR_RANGE* RootSignature::RootParamsManager::Extend(Uint32 NumExtraRootTables, @@ -52,29 +52,29 @@ D3D12_DESCRIPTOR_RANGE* RootSignature::RootParamsManager::Extend(Uint32 NumExtra Uint32 NumExtraDescriptorRanges, Uint32 RootTableToAddRanges) { - VERIFY(NumExtraRootTables > 0 || NumExtraRootViews > 0 || NumExtraDescriptorRanges > 0, "At least one root table, root view or descriptor range must be added" ); + VERIFY(NumExtraRootTables > 0 || NumExtraRootViews > 0 || NumExtraDescriptorRanges > 0, "At least one root table, root view or descriptor range must be added"); auto MemorySize = GetRequiredMemorySize(NumExtraRootTables, NumExtraRootViews, NumExtraDescriptorRanges); VERIFY_EXPR(MemorySize > 0); auto* pNewMemory = ALLOCATE_RAW(m_MemAllocator, "Memory buffer for root tables, root views & descriptor ranges", MemorySize); memset(pNewMemory, 0, MemorySize); // Note: this order is more efficient than views->tables->ranges - auto *pNewRootTables = reinterpret_cast(pNewMemory); - auto *pNewRootViews = pNewRootTables + (m_NumRootTables + NumExtraRootTables); - auto *pCurrDescriptorRangePtr = reinterpret_cast(pNewRootViews+m_NumRootViews+NumExtraRootViews); + auto* pNewRootTables = reinterpret_cast(pNewMemory); + auto* pNewRootViews = pNewRootTables + (m_NumRootTables + NumExtraRootTables); + auto* pCurrDescriptorRangePtr = reinterpret_cast(pNewRootViews + m_NumRootViews + NumExtraRootViews); // Copy existing root tables to new memory for (Uint32 rt = 0; rt < m_NumRootTables; ++rt) { - const auto& SrcTbl = GetRootTable(rt); - auto& D3D12SrcTbl = static_cast(SrcTbl).DescriptorTable; - auto NumRanges = D3D12SrcTbl.NumDescriptorRanges; - if(rt == RootTableToAddRanges) + const auto& SrcTbl = GetRootTable(rt); + auto& D3D12SrcTbl = static_cast(SrcTbl).DescriptorTable; + auto NumRanges = D3D12SrcTbl.NumDescriptorRanges; + if (rt == RootTableToAddRanges) { VERIFY(NumExtraRootTables == 0 || NumExtraRootTables == 1, "Up to one descriptor table can be extended at a time"); NumRanges += NumExtraDescriptorRanges; } - new(pNewRootTables + rt) RootParameter(SrcTbl, NumRanges, pCurrDescriptorRangePtr); + new (pNewRootTables + rt) RootParameter(SrcTbl, NumRanges, pCurrDescriptorRangePtr); pCurrDescriptorRangePtr += NumRanges; } @@ -82,7 +82,7 @@ D3D12_DESCRIPTOR_RANGE* RootSignature::RootParamsManager::Extend(Uint32 NumExtra for (Uint32 rv = 0; rv < m_NumRootViews; ++rv) { const auto& SrcView = GetRootView(rv); - new(pNewRootViews + rv) RootParameter(SrcView); + new (pNewRootViews + rv) RootParameter(SrcView); } m_pMemory.reset(pNewMemory); @@ -90,42 +90,42 @@ D3D12_DESCRIPTOR_RANGE* RootSignature::RootParamsManager::Extend(Uint32 NumExtra m_NumRootViews += NumExtraRootViews; m_TotalDescriptorRanges += NumExtraDescriptorRanges; m_pRootTables = m_NumRootTables != 0 ? pNewRootTables : nullptr; - m_pRootViews = m_NumRootViews != 0 ? pNewRootViews : nullptr; + m_pRootViews = m_NumRootViews != 0 ? pNewRootViews : nullptr; return pCurrDescriptorRangePtr; } -void RootSignature::RootParamsManager::AddRootView(D3D12_ROOT_PARAMETER_TYPE ParameterType, - Uint32 RootIndex, - UINT Register, - D3D12_SHADER_VISIBILITY Visibility, - SHADER_RESOURCE_VARIABLE_TYPE VarType) +void RootSignature::RootParamsManager::AddRootView(D3D12_ROOT_PARAMETER_TYPE ParameterType, + Uint32 RootIndex, + UINT Register, + D3D12_SHADER_VISIBILITY Visibility, + SHADER_RESOURCE_VARIABLE_TYPE VarType) { - auto *pRangePtr = Extend(0, 1, 0); + auto* pRangePtr = Extend(0, 1, 0); VERIFY_EXPR((char*)pRangePtr == (char*)m_pMemory.get() + GetRequiredMemorySize(0, 0, 0)); - new(m_pRootViews + m_NumRootViews-1) RootParameter(ParameterType, RootIndex, Register, 0u, Visibility, VarType); + new (m_pRootViews + m_NumRootViews - 1) RootParameter(ParameterType, RootIndex, Register, 0u, Visibility, VarType); } -void RootSignature::RootParamsManager::AddRootTable(Uint32 RootIndex, - D3D12_SHADER_VISIBILITY Visibility, - SHADER_RESOURCE_VARIABLE_TYPE VarType, - Uint32 NumRangesInNewTable) +void RootSignature::RootParamsManager::AddRootTable(Uint32 RootIndex, + D3D12_SHADER_VISIBILITY Visibility, + SHADER_RESOURCE_VARIABLE_TYPE VarType, + Uint32 NumRangesInNewTable) { - auto *pRangePtr = Extend(1, 0, NumRangesInNewTable); - VERIFY_EXPR( (char*)(pRangePtr + NumRangesInNewTable) == (char*)m_pMemory.get() + GetRequiredMemorySize(0, 0, 0)); - new(m_pRootTables + m_NumRootTables-1) RootParameter(D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, RootIndex, NumRangesInNewTable, pRangePtr, Visibility, VarType); + auto* pRangePtr = Extend(1, 0, NumRangesInNewTable); + VERIFY_EXPR((char*)(pRangePtr + NumRangesInNewTable) == (char*)m_pMemory.get() + GetRequiredMemorySize(0, 0, 0)); + new (m_pRootTables + m_NumRootTables - 1) RootParameter(D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, RootIndex, NumRangesInNewTable, pRangePtr, Visibility, VarType); } void RootSignature::RootParamsManager::AddDescriptorRanges(Uint32 RootTableInd, Uint32 NumExtraRanges) { - auto *pRangePtr = Extend(0, 0, NumExtraRanges, RootTableInd); - VERIFY_EXPR( (char*)pRangePtr == (char*)m_pMemory.get() + GetRequiredMemorySize(0, 0, 0)); + auto* pRangePtr = Extend(0, 0, NumExtraRanges, RootTableInd); + VERIFY_EXPR((char*)pRangePtr == (char*)m_pMemory.get() + GetRequiredMemorySize(0, 0, 0)); } -bool RootSignature::RootParamsManager::operator == (const RootParamsManager& RootParams)const +bool RootSignature::RootParamsManager::operator==(const RootParamsManager& RootParams) const { if (m_NumRootTables != RootParams.m_NumRootTables || - m_NumRootViews != RootParams.m_NumRootViews) + m_NumRootViews != RootParams.m_NumRootViews) return false; for (Uint32 rv = 0; rv < m_NumRootViews; ++rv) @@ -147,7 +147,7 @@ bool RootSignature::RootParamsManager::operator == (const RootParamsManager& Roo return true; } -size_t RootSignature::RootParamsManager::GetHash()const +size_t RootSignature::RootParamsManager::GetHash() const { size_t hash = ComputeHash(m_NumRootTables, m_NumRootViews); for (Uint32 rv = 0; rv < m_NumRootViews; ++rv) @@ -159,17 +159,18 @@ size_t RootSignature::RootParamsManager::GetHash()const return hash; } -RootSignature::RootSignature() : +RootSignature::RootSignature() : m_RootParams(GetRawAllocator()), m_MemAllocator(GetRawAllocator()), - m_StaticSamplers( STD_ALLOCATOR_RAW_MEM(StaticSamplerAttribs, GetRawAllocator(), "Allocator for vector") ) + m_StaticSamplers(STD_ALLOCATOR_RAW_MEM(StaticSamplerAttribs, GetRawAllocator(), "Allocator for vector")) { - for(size_t i=0; i < m_SrvCbvUavRootTablesMap.size(); ++i) + for (size_t i = 0; i < m_SrvCbvUavRootTablesMap.size(); ++i) m_SrvCbvUavRootTablesMap[i] = InvalidRootTableIndex; - for(size_t i=0; i < m_SamplerRootTablesMap.size(); ++i) + for (size_t i = 0; i < m_SamplerRootTablesMap.size(); ++i) m_SamplerRootTablesMap[i] = InvalidRootTableIndex; } +// clang-format off static D3D12_SHADER_VISIBILITY ShaderTypeInd2ShaderVisibilityMap[] { D3D12_SHADER_VISIBILITY_VERTEX, // 0 @@ -179,25 +180,29 @@ static D3D12_SHADER_VISIBILITY ShaderTypeInd2ShaderVisibilityMap[] D3D12_SHADER_VISIBILITY_DOMAIN, // 4 D3D12_SHADER_VISIBILITY_ALL // 5 }; +// clang-format on D3D12_SHADER_VISIBILITY GetShaderVisibility(SHADER_TYPE ShaderType) { - auto ShaderInd = GetShaderTypeIndex(ShaderType); + auto ShaderInd = GetShaderTypeIndex(ShaderType); auto ShaderVisibility = ShaderTypeInd2ShaderVisibilityMap[ShaderInd]; #ifdef _DEBUG switch (ShaderType) { + // clang-format off case SHADER_TYPE_VERTEX: VERIFY_EXPR(ShaderVisibility == D3D12_SHADER_VISIBILITY_VERTEX); break; case SHADER_TYPE_PIXEL: VERIFY_EXPR(ShaderVisibility == D3D12_SHADER_VISIBILITY_PIXEL); break; case SHADER_TYPE_GEOMETRY: VERIFY_EXPR(ShaderVisibility == D3D12_SHADER_VISIBILITY_GEOMETRY); break; case SHADER_TYPE_HULL: VERIFY_EXPR(ShaderVisibility == D3D12_SHADER_VISIBILITY_HULL); break; case SHADER_TYPE_DOMAIN: VERIFY_EXPR(ShaderVisibility == D3D12_SHADER_VISIBILITY_DOMAIN); break; case SHADER_TYPE_COMPUTE: VERIFY_EXPR(ShaderVisibility == D3D12_SHADER_VISIBILITY_ALL); break; + // clang-format on default: LOG_ERROR("Unknown shader type (", ShaderType, ")"); break; } #endif return ShaderVisibility; } +// clang-format off static SHADER_TYPE ShaderVisibility2ShaderTypeMap[] = { SHADER_TYPE_COMPUTE, // D3D12_SHADER_VISIBILITY_ALL = 0 @@ -207,19 +212,23 @@ static SHADER_TYPE ShaderVisibility2ShaderTypeMap[] = SHADER_TYPE_GEOMETRY, // D3D12_SHADER_VISIBILITY_GEOMETRY = 4 SHADER_TYPE_PIXEL // D3D12_SHADER_VISIBILITY_PIXEL = 5 }; +// clang-format on + SHADER_TYPE ShaderTypeFromShaderVisibility(D3D12_SHADER_VISIBILITY ShaderVisibility) { - VERIFY_EXPR(ShaderVisibility >= D3D12_SHADER_VISIBILITY_ALL && ShaderVisibility <= D3D12_SHADER_VISIBILITY_PIXEL ); + VERIFY_EXPR(ShaderVisibility >= D3D12_SHADER_VISIBILITY_ALL && ShaderVisibility <= D3D12_SHADER_VISIBILITY_PIXEL); auto ShaderType = ShaderVisibility2ShaderTypeMap[ShaderVisibility]; #ifdef _DEBUG switch (ShaderVisibility) { + // clang-format off case D3D12_SHADER_VISIBILITY_VERTEX: VERIFY_EXPR(ShaderType == SHADER_TYPE_VERTEX); break; case D3D12_SHADER_VISIBILITY_PIXEL: VERIFY_EXPR(ShaderType == SHADER_TYPE_PIXEL); break; case D3D12_SHADER_VISIBILITY_GEOMETRY: VERIFY_EXPR(ShaderType == SHADER_TYPE_GEOMETRY); break; case D3D12_SHADER_VISIBILITY_HULL: VERIFY_EXPR(ShaderType == SHADER_TYPE_HULL); break; case D3D12_SHADER_VISIBILITY_DOMAIN: VERIFY_EXPR(ShaderType == SHADER_TYPE_DOMAIN); break; case D3D12_SHADER_VISIBILITY_ALL: VERIFY_EXPR(ShaderType == SHADER_TYPE_COMPUTE); break; + // clang-format on default: LOG_ERROR("Unknown shader visibility (", ShaderVisibility, ")"); break; } #endif @@ -227,13 +236,15 @@ SHADER_TYPE ShaderTypeFromShaderVisibility(D3D12_SHADER_VISIBILITY ShaderVisibil } +// clang-format off static D3D12_DESCRIPTOR_HEAP_TYPE RangeType2HeapTypeMap[] { - D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, //D3D12_DESCRIPTOR_RANGE_TYPE_SRV = 0, - D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, //D3D12_DESCRIPTOR_RANGE_TYPE_UAV = ( D3D12_DESCRIPTOR_RANGE_TYPE_SRV + 1 ) , - D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, //D3D12_DESCRIPTOR_RANGE_TYPE_CBV = ( D3D12_DESCRIPTOR_RANGE_TYPE_UAV + 1 ) , - D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER //D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER = ( D3D12_DESCRIPTOR_RANGE_TYPE_CBV + 1 ) + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, //D3D12_DESCRIPTOR_RANGE_TYPE_SRV = 0 + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, //D3D12_DESCRIPTOR_RANGE_TYPE_UAV = ( D3D12_DESCRIPTOR_RANGE_TYPE_SRV + 1 ) + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, //D3D12_DESCRIPTOR_RANGE_TYPE_CBV = ( D3D12_DESCRIPTOR_RANGE_TYPE_UAV + 1 ) + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER //D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER = ( D3D12_DESCRIPTOR_RANGE_TYPE_CBV + 1 ) }; +// clang-format on D3D12_DESCRIPTOR_HEAP_TYPE HeapTypeFromRangeType(D3D12_DESCRIPTOR_RANGE_TYPE RangeType) { VERIFY_EXPR(RangeType >= D3D12_DESCRIPTOR_RANGE_TYPE_SRV && RangeType <= D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER); @@ -242,10 +253,12 @@ D3D12_DESCRIPTOR_HEAP_TYPE HeapTypeFromRangeType(D3D12_DESCRIPTOR_RANGE_TYPE Ran #ifdef _DEBUG switch (RangeType) { - case D3D12_DESCRIPTOR_RANGE_TYPE_CBV: VERIFY_EXPR(HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); break; - case D3D12_DESCRIPTOR_RANGE_TYPE_SRV: VERIFY_EXPR(HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); break; - case D3D12_DESCRIPTOR_RANGE_TYPE_UAV: VERIFY_EXPR(HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); break; - case D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER: VERIFY_EXPR(HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); break; + // clang-format off + case D3D12_DESCRIPTOR_RANGE_TYPE_CBV: VERIFY_EXPR(HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); break; + case D3D12_DESCRIPTOR_RANGE_TYPE_SRV: VERIFY_EXPR(HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); break; + case D3D12_DESCRIPTOR_RANGE_TYPE_UAV: VERIFY_EXPR(HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); break; + case D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER: VERIFY_EXPR(HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); break; + // clang-format on default: UNEXPECTED("Unexpected descriptor range type"); break; } #endif @@ -259,7 +272,7 @@ void RootSignature::InitStaticSampler(SHADER_TYPE ShaderType const D3DShaderResourceAttribs& SamplerAttribs) { auto ShaderVisibility = GetShaderVisibility(ShaderType); - auto SamplerFound = false; + auto SamplerFound = false; for (auto& StSmplr : m_StaticSamplers) { if (StSmplr.ShaderVisibility == ShaderVisibility && @@ -268,7 +281,7 @@ void RootSignature::InitStaticSampler(SHADER_TYPE ShaderType StSmplr.ShaderRegister = SamplerAttribs.BindPoint; StSmplr.ArraySize = SamplerAttribs.BindCount; StSmplr.RegisterSpace = 0; - SamplerFound = true; + SamplerFound = true; break; } } @@ -280,22 +293,22 @@ void RootSignature::InitStaticSampler(SHADER_TYPE ShaderType } // http://diligentgraphics.com/diligent-engine/architecture/d3d12/shader-resource-layout#Initializing-Shader-Resource-Layouts-and-Root-Signature-in-a-Pipeline-State-Object -void RootSignature::AllocateResourceSlot(SHADER_TYPE ShaderType, - const D3DShaderResourceAttribs& ShaderResAttribs, +void RootSignature::AllocateResourceSlot(SHADER_TYPE ShaderType, + const D3DShaderResourceAttribs& ShaderResAttribs, SHADER_RESOURCE_VARIABLE_TYPE VariableType, - D3D12_DESCRIPTOR_RANGE_TYPE RangeType, - Uint32& RootIndex, // Output parameter + D3D12_DESCRIPTOR_RANGE_TYPE RangeType, + Uint32& RootIndex, // Output parameter Uint32& OffsetFromTableStart // Output parameter - ) +) { - auto ShaderInd = GetShaderTypeIndex(ShaderType); + auto ShaderInd = GetShaderTypeIndex(ShaderType); auto ShaderVisibility = GetShaderVisibility(ShaderType); if (RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_CBV && ShaderResAttribs.BindCount == 1) { // Allocate single CBV directly in the root signature // Get the next available root index past all allocated tables and root views - RootIndex = m_RootParams.GetNumRootTables() + m_RootParams.GetNumRootViews(); + RootIndex = m_RootParams.GetNumRootTables() + m_RootParams.GetNumRootViews(); OffsetFromTableStart = 0; // Add new root view to existing root parameters @@ -305,17 +318,17 @@ void RootSignature::AllocateResourceSlot(SHADER_TYPE ShaderT { // Use the same table for static and mutable resources. Treat both as static auto RootTableType = (VariableType == SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) ? SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC : SHADER_RESOURCE_VARIABLE_TYPE_STATIC; - auto TableIndKey = ShaderInd * SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES + RootTableType; + auto TableIndKey = ShaderInd * SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES + RootTableType; // Get the table array index (this is not the root index!) - auto& RootTableArrayInd = (( RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER ) ? m_SamplerRootTablesMap : m_SrvCbvUavRootTablesMap)[ TableIndKey ]; + auto& RootTableArrayInd = ((RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER) ? m_SamplerRootTablesMap : m_SrvCbvUavRootTablesMap)[TableIndKey]; if (RootTableArrayInd == InvalidRootTableIndex) { // Root table has not been assigned to this combination yet // Get the next available root index past all allocated tables and root views - RootIndex = m_RootParams.GetNumRootTables() + m_RootParams.GetNumRootViews(); + RootIndex = m_RootParams.GetNumRootTables() + m_RootParams.GetNumRootViews(); VERIFY_EXPR(m_RootParams.GetNumRootTables() < 255); - RootTableArrayInd = static_cast( m_RootParams.GetNumRootTables() ); + RootTableArrayInd = static_cast(m_RootParams.GetNumRootTables()); // Add root table with one single-descriptor range m_RootParams.AddRootTable(RootIndex, ShaderVisibility, RootTableType, 1); } @@ -324,41 +337,41 @@ void RootSignature::AllocateResourceSlot(SHADER_TYPE ShaderT // Add a new single-descriptor range to the existing table at index RootTableArrayInd m_RootParams.AddDescriptorRanges(RootTableArrayInd, 1); } - + // Reference to either existing or just added table auto& CurrParam = m_RootParams.GetRootTable(RootTableArrayInd); - RootIndex = CurrParam.GetRootIndex(); + RootIndex = CurrParam.GetRootIndex(); const auto& d3d12RootParam = static_cast(CurrParam); - VERIFY( d3d12RootParam.ShaderVisibility == ShaderVisibility, "Shader visibility is not correct" ); - + VERIFY(d3d12RootParam.ShaderVisibility == ShaderVisibility, "Shader visibility is not correct"); + // Descriptors are tightly packed, so the next descriptor offset is the // current size of the table OffsetFromTableStart = CurrParam.GetDescriptorTableSize(); // New just added range is the last range in the descriptor table - Uint32 NewDescriptorRangeIndex = d3d12RootParam.DescriptorTable.NumDescriptorRanges-1; - CurrParam.SetDescriptorRange(NewDescriptorRangeIndex, + Uint32 NewDescriptorRangeIndex = d3d12RootParam.DescriptorTable.NumDescriptorRanges - 1; + CurrParam.SetDescriptorRange(NewDescriptorRangeIndex, RangeType, // Range type (CBV, SRV, UAV or SAMPLER) ShaderResAttribs.BindPoint, // Shader register ShaderResAttribs.BindCount, // Number of registers used (1 for non-array resources) 0, // Register space. Always 0 for now OffsetFromTableStart // Offset in descriptors from the table start - ); + ); } } #ifdef _DEBUG -void RootSignature::dbgVerifyRootParameters()const +void RootSignature::dbgVerifyRootParameters() const { Uint32 dbgTotalSrvCbvUavSlots = 0; - Uint32 dbgTotalSamplerSlots = 0; - for(Uint32 rt = 0; rt < m_RootParams.GetNumRootTables(); ++rt) + Uint32 dbgTotalSamplerSlots = 0; + for (Uint32 rt = 0; rt < m_RootParams.GetNumRootTables(); ++rt) { auto& RootTable = m_RootParams.GetRootTable(rt); - auto& Param = static_cast( RootTable ); + auto& Param = static_cast(RootTable); VERIFY(Param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, "Root parameter is expected to be a descriptor table"); auto& Table = Param.DescriptorTable; VERIFY(Table.NumDescriptorRanges > 0, "Descriptor table is expected to be non-empty"); @@ -367,11 +380,14 @@ void RootSignature::dbgVerifyRootParameters()const for (Uint32 r = 0; r < Table.NumDescriptorRanges; ++r) { const auto& range = Table.pDescriptorRanges[r]; - if(IsResourceTable) + if (IsResourceTable) { - VERIFY( range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV || - range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_CBV || - range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_UAV, "Resource type is expected to be SRV, CBV or UAV"); + // clang-format off + VERIFY(range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV || + range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_CBV || + range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + "Resource type is expected to be SRV, CBV or UAV"); + // clang-format on dbgTotalSrvCbvUavSlots += range.NumDescriptors; } else @@ -380,22 +396,23 @@ void RootSignature::dbgVerifyRootParameters()const dbgTotalSamplerSlots += range.NumDescriptors; } - if(r>0) + if (r > 0) { - VERIFY(Table.pDescriptorRanges[r].OffsetInDescriptorsFromTableStart == Table.pDescriptorRanges[r-1].OffsetInDescriptorsFromTableStart+Table.pDescriptorRanges[r-1].NumDescriptors, "Ranges in a descriptor table are expected to be consequtive"); + VERIFY(Table.pDescriptorRanges[r].OffsetInDescriptorsFromTableStart == Table.pDescriptorRanges[r - 1].OffsetInDescriptorsFromTableStart + Table.pDescriptorRanges[r - 1].NumDescriptors, "Ranges in a descriptor table are expected to be consequtive"); } } } Uint32 dbgTotalRootViews = 0; - for(Uint32 rv = 0; rv < m_RootParams.GetNumRootViews(); ++rv) + for (Uint32 rv = 0; rv < m_RootParams.GetNumRootViews(); ++rv) { auto& RootView = m_RootParams.GetRootView(rv); - auto& Param = static_cast( RootView ); + auto& Param = static_cast(RootView); VERIFY(Param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV, "Root parameter is expected to be a CBV"); ++dbgTotalRootViews; } + // clang-format off VERIFY(dbgTotalSrvCbvUavSlots == m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] + m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE] + @@ -408,6 +425,7 @@ void RootSignature::dbgVerifyRootParameters()const m_TotalRootViews[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] + m_TotalRootViews[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE] + m_TotalRootViews[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC], "Unexpected number of root views"); + // clang-format on } #endif @@ -416,13 +434,13 @@ void RootSignature::AllocateStaticSamplers(const PipelineResourceLayoutDesc& Res if (ResourceLayout.NumStaticSamplers > 0) { m_StaticSamplers.reserve(ResourceLayout.NumStaticSamplers); - for(Uint32 sam=0; sam < ResourceLayout.NumStaticSamplers; ++sam) + for (Uint32 sam = 0; sam < ResourceLayout.NumStaticSamplers; ++sam) { - const auto& StSamDesc = ResourceLayout.StaticSamplers[sam]; - Uint32 ShaderStages = StSamDesc.ShaderStages; + const auto& StSamDesc = ResourceLayout.StaticSamplers[sam]; + Uint32 ShaderStages = StSamDesc.ShaderStages; while (ShaderStages != 0) { - auto Stage = ShaderStages & ~(ShaderStages-1); + auto Stage = ShaderStages & ~(ShaderStages - 1); m_StaticSamplers.emplace_back(StSamDesc, GetShaderVisibility(static_cast(Stage))); ShaderStages &= ~Stage; } @@ -432,20 +450,20 @@ void RootSignature::AllocateStaticSamplers(const PipelineResourceLayoutDesc& Res void RootSignature::Finalize(ID3D12Device* pd3d12Device) { - for(Uint32 rt = 0; rt < m_RootParams.GetNumRootTables(); ++rt) + for (Uint32 rt = 0; rt < m_RootParams.GetNumRootTables(); ++rt) { - const auto& RootTbl = m_RootParams.GetRootTable(rt); + const auto& RootTbl = m_RootParams.GetRootTable(rt); const auto& d3d12RootParam = static_cast(RootTbl); VERIFY_EXPR(d3d12RootParam.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE); - + auto TableSize = RootTbl.GetDescriptorTableSize(); VERIFY(d3d12RootParam.DescriptorTable.NumDescriptorRanges > 0 && TableSize > 0, "Unexpected empty descriptor table"); auto IsSamplerTable = d3d12RootParam.DescriptorTable.pDescriptorRanges[0].RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER; - auto VarType = RootTbl.GetShaderVariableType(); + auto VarType = RootTbl.GetShaderVariableType(); (IsSamplerTable ? m_TotalSamplerSlots : m_TotalSrvCbvUavSlots)[VarType] += TableSize; } - for(Uint32 rv = 0; rv < m_RootParams.GetNumRootViews(); ++rv) + for (Uint32 rv = 0; rv < m_RootParams.GetNumRootViews(); ++rv) { const auto& RootView = m_RootParams.GetRootView(rv); ++m_TotalRootViews[RootView.GetShaderVariableType()]; @@ -457,45 +475,47 @@ void RootSignature::Finalize(ID3D12Device* pd3d12Device) D3D12_ROOT_SIGNATURE_DESC rootSignatureDesc; rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; - + auto TotalParams = m_RootParams.GetNumRootTables() + m_RootParams.GetNumRootViews(); - std::vector > D3D12Parameters( TotalParams, D3D12_ROOT_PARAMETER(), STD_ALLOCATOR_RAW_MEM(D3D12_ROOT_PARAMETER, GetRawAllocator(), "Allocator for vector") ); - for(Uint32 rt = 0; rt < m_RootParams.GetNumRootTables(); ++rt) + + std::vector> D3D12Parameters{TotalParams, D3D12_ROOT_PARAMETER(), STD_ALLOCATOR_RAW_MEM(D3D12_ROOT_PARAMETER, GetRawAllocator(), "Allocator for vector")}; + for (Uint32 rt = 0; rt < m_RootParams.GetNumRootTables(); ++rt) { - const auto& RootTable = m_RootParams.GetRootTable(rt); - const D3D12_ROOT_PARAMETER &SrcParam = RootTable; - VERIFY( SrcParam.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE && SrcParam.DescriptorTable.NumDescriptorRanges > 0, "Non-empty descriptor table is expected" ); + const auto& RootTable = m_RootParams.GetRootTable(rt); + const D3D12_ROOT_PARAMETER& SrcParam = RootTable; + VERIFY(SrcParam.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE && SrcParam.DescriptorTable.NumDescriptorRanges > 0, "Non-empty descriptor table is expected"); D3D12Parameters[RootTable.GetRootIndex()] = SrcParam; } - for(Uint32 rv = 0; rv < m_RootParams.GetNumRootViews(); ++rv) + for (Uint32 rv = 0; rv < m_RootParams.GetNumRootViews(); ++rv) { - const auto& RootView = m_RootParams.GetRootView(rv); - const D3D12_ROOT_PARAMETER &SrcParam = RootView; - VERIFY( SrcParam.ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV, "Root CBV is expected" ); + const auto& RootView = m_RootParams.GetRootView(rv); + const D3D12_ROOT_PARAMETER& SrcParam = RootView; + VERIFY(SrcParam.ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV, "Root CBV is expected"); D3D12Parameters[RootView.GetRootIndex()] = SrcParam; } rootSignatureDesc.NumParameters = static_cast(D3D12Parameters.size()); - rootSignatureDesc.pParameters = D3D12Parameters.size() ? D3D12Parameters.data() : nullptr; + rootSignatureDesc.pParameters = D3D12Parameters.size() ? D3D12Parameters.data() : nullptr; UINT TotalD3D12StaticSamplers = 0; - for(const auto& StSam : m_StaticSamplers) + for (const auto& StSam : m_StaticSamplers) TotalD3D12StaticSamplers += StSam.ArraySize; rootSignatureDesc.NumStaticSamplers = TotalD3D12StaticSamplers; - rootSignatureDesc.pStaticSamplers = nullptr; - std::vector > D3D12StaticSamplers( STD_ALLOCATOR_RAW_MEM(D3D12_STATIC_SAMPLER_DESC, GetRawAllocator(), "Allocator for vector") ); + rootSignatureDesc.pStaticSamplers = nullptr; + std::vector> D3D12StaticSamplers(STD_ALLOCATOR_RAW_MEM(D3D12_STATIC_SAMPLER_DESC, GetRawAllocator(), "Allocator for vector")); D3D12StaticSamplers.reserve(TotalD3D12StaticSamplers); - if ( !m_StaticSamplers.empty() ) + if (!m_StaticSamplers.empty()) { - for(size_t s=0; s < m_StaticSamplers.size(); ++s) + for (size_t s = 0; s < m_StaticSamplers.size(); ++s) { const auto& StSmplrDesc = m_StaticSamplers[s]; - const auto& SamDesc = StSmplrDesc.SamplerDesc.Desc; - for(UINT ArrInd = 0; ArrInd < StSmplrDesc.ArraySize; ++ArrInd) + const auto& SamDesc = StSmplrDesc.SamplerDesc.Desc; + for (UINT ArrInd = 0; ArrInd < StSmplrDesc.ArraySize; ++ArrInd) { D3D12StaticSamplers.emplace_back( - D3D12_STATIC_SAMPLER_DESC{ + D3D12_STATIC_SAMPLER_DESC // + { FilterTypeToD3D12Filter(SamDesc.MinFilter, SamDesc.MagFilter, SamDesc.MipFilter), TexAddressModeToD3D12AddressMode(SamDesc.AddressU), TexAddressModeToD3D12AddressMode(SamDesc.AddressV), @@ -508,61 +528,61 @@ void RootSignature::Finalize(ID3D12Device* pd3d12Device) SamDesc.MaxLOD, StSmplrDesc.ShaderRegister + ArrInd, StSmplrDesc.RegisterSpace, - StSmplrDesc.ShaderVisibility - } + StSmplrDesc.ShaderVisibility // + } // ); } } rootSignatureDesc.pStaticSamplers = D3D12StaticSamplers.data(); - + // Release static samplers array, we no longer need it - std::vector > EmptySamplers( STD_ALLOCATOR_RAW_MEM(StaticSamplerAttribs, GetRawAllocator(), "Allocator for vector") ); - m_StaticSamplers.swap( EmptySamplers ); + std::vector> EmptySamplers(STD_ALLOCATOR_RAW_MEM(StaticSamplerAttribs, GetRawAllocator(), "Allocator for vector")); + m_StaticSamplers.swap(EmptySamplers); VERIFY_EXPR(D3D12StaticSamplers.size() == TotalD3D12StaticSamplers); } - - CComPtr signature; - CComPtr error; - HRESULT hr = D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error); - hr = pd3d12Device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), __uuidof(m_pd3d12RootSignature), reinterpret_cast( static_cast(&m_pd3d12RootSignature))); + + CComPtr signature; + CComPtr error; + HRESULT hr = D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error); + hr = pd3d12Device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), __uuidof(m_pd3d12RootSignature), reinterpret_cast(static_cast(&m_pd3d12RootSignature))); CHECK_D3D_RESULT_THROW(hr, "Failed to create root signature"); bool bHasDynamicDescriptors = m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC] != 0 || m_TotalSamplerSlots[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC] != 0; - if(bHasDynamicDescriptors) + if (bHasDynamicDescriptors) { - CommitDescriptorHandles = &RootSignature::CommitDescriptorHandlesInternal_SMD; + CommitDescriptorHandles = &RootSignature::CommitDescriptorHandlesInternal_SMD; TransitionAndCommitDescriptorHandles = &RootSignature::CommitDescriptorHandlesInternal_SMD; } else { - CommitDescriptorHandles = &RootSignature::CommitDescriptorHandlesInternal_SM; + CommitDescriptorHandles = &RootSignature::CommitDescriptorHandlesInternal_SM; TransitionAndCommitDescriptorHandles = &RootSignature::CommitDescriptorHandlesInternal_SM; } } -size_t RootSignature::GetResourceCacheRequiredMemSize()const +size_t RootSignature::GetResourceCacheRequiredMemSize() const { auto CacheTableSizes = GetCacheTableSizes(); return ShaderResourceCacheD3D12::GetRequiredMemorySize(static_cast(CacheTableSizes.size()), CacheTableSizes.data()); } -std::vector > RootSignature::GetCacheTableSizes()const +std::vector> RootSignature::GetCacheTableSizes() const { // Get root table size for every root index // m_RootParams keeps root tables sorted by the array index, not the root index // Root views are treated as one-descriptor tables - std::vector > CacheTableSizes(m_RootParams.GetNumRootTables() + m_RootParams.GetNumRootViews(), 0, STD_ALLOCATOR_RAW_MEM(Uint32, GetRawAllocator(), "Allocator for vector") ); - for(Uint32 rt = 0; rt < m_RootParams.GetNumRootTables(); ++rt) + std::vector> CacheTableSizes(m_RootParams.GetNumRootTables() + m_RootParams.GetNumRootViews(), 0, STD_ALLOCATOR_RAW_MEM(Uint32, GetRawAllocator(), "Allocator for vector")); + for (Uint32 rt = 0; rt < m_RootParams.GetNumRootTables(); ++rt) { - auto& RootParam = m_RootParams.GetRootTable(rt); + auto& RootParam = m_RootParams.GetRootTable(rt); CacheTableSizes[RootParam.GetRootIndex()] = RootParam.GetDescriptorTableSize(); } - for(Uint32 rv = 0; rv < m_RootParams.GetNumRootViews(); ++rv) + for (Uint32 rv = 0; rv < m_RootParams.GetNumRootViews(); ++rv) { - auto& RootParam = m_RootParams.GetRootView(rv); + auto& RootParam = m_RootParams.GetRootView(rv); CacheTableSizes[RootParam.GetRootIndex()] = 1; } @@ -572,36 +592,39 @@ std::vector > RootSignature::GetCacheTableSiz //http://diligentgraphics.com/diligent-engine/architecture/d3d12/shader-resource-cache#Initializing-the-Cache-for-Shader-Resource-Binding-Object void RootSignature::InitResourceCache(RenderDeviceD3D12Impl* pDeviceD3D12Impl, ShaderResourceCacheD3D12& ResourceCache, - IMemoryAllocator& CacheMemAllocator)const + IMemoryAllocator& CacheMemAllocator) const { auto CacheTableSizes = GetCacheTableSizes(); - // Initialize resource cache to hold root tables + // Initialize resource cache to hold root tables ResourceCache.Initialize(CacheMemAllocator, static_cast(CacheTableSizes.size()), CacheTableSizes.data()); // Allocate space in GPU-visible descriptor heap for static and mutable variables only Uint32 TotalSrvCbvUavDescriptors = - m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] + - m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE]; + m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] + + m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE]; Uint32 TotalSamplerDescriptors = - m_TotalSamplerSlots[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] + - m_TotalSamplerSlots[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE]; + m_TotalSamplerSlots[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] + + m_TotalSamplerSlots[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE]; DescriptorHeapAllocation CbcSrvUavHeapSpace, SamplerHeapSpace; if (TotalSrvCbvUavDescriptors) { CbcSrvUavHeapSpace = pDeviceD3D12Impl->AllocateGPUDescriptors(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, TotalSrvCbvUavDescriptors); - DEV_CHECK_ERR(!CbcSrvUavHeapSpace.IsNull(), - "Failed to allocate ", TotalSrvCbvUavDescriptors, " GPU-visible CBV/SRV/UAV descriptor", (TotalSrvCbvUavDescriptors > 1 ? "s" : ""), ". " - "Consider increasing GPUDescriptorHeapSize[0] in EngineD3D12CreateInfo."); + DEV_CHECK_ERR(!CbcSrvUavHeapSpace.IsNull(), + "Failed to allocate ", TotalSrvCbvUavDescriptors, " GPU-visible CBV/SRV/UAV descriptor", + (TotalSrvCbvUavDescriptors > 1 ? "s" : ""), + ". Consider increasing GPUDescriptorHeapSize[0] in EngineD3D12CreateInfo."); } VERIFY_EXPR(TotalSrvCbvUavDescriptors == 0 && CbcSrvUavHeapSpace.IsNull() || CbcSrvUavHeapSpace.GetNumHandles() == TotalSrvCbvUavDescriptors); if (TotalSamplerDescriptors) { SamplerHeapSpace = pDeviceD3D12Impl->AllocateGPUDescriptors(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, TotalSamplerDescriptors); - DEV_CHECK_ERR(!SamplerHeapSpace.IsNull(), - "Failed to allocate ", TotalSamplerDescriptors, " GPU-visible Sampler descriptor", (TotalSamplerDescriptors > 1 ? "s" : ""), ". " - "Consider using static samplers in the Pipeline State Object or increasing GPUDescriptorHeapSize[1] in EngineD3D12CreateInfo."); + DEV_CHECK_ERR(!SamplerHeapSpace.IsNull(), + "Failed to allocate ", TotalSamplerDescriptors, " GPU-visible Sampler descriptor", + (TotalSamplerDescriptors > 1 ? "s" : ""), + ". Consider using static samplers in the Pipeline State Object or " + "increasing GPUDescriptorHeapSize[1] in EngineD3D12CreateInfo."); } VERIFY_EXPR(TotalSamplerDescriptors == 0 && SamplerHeapSpace.IsNull() || SamplerHeapSpace.GetNumHandles() == TotalSamplerDescriptors); @@ -610,32 +633,32 @@ void RootSignature::InitResourceCache(RenderDeviceD3D12Impl* pDeviceD3D12Impl // Root tables with dynamic resources as well as root views are not assigned space in GPU-visible allocation // (root views are simply not processed) Uint32 SrvCbvUavTblStartOffset = 0; - Uint32 SamplerTblStartOffset = 0; - for(Uint32 rt = 0; rt < m_RootParams.GetNumRootTables(); ++rt) + Uint32 SamplerTblStartOffset = 0; + for (Uint32 rt = 0; rt < m_RootParams.GetNumRootTables(); ++rt) { - auto& RootParam = m_RootParams.GetRootTable(rt); + auto& RootParam = m_RootParams.GetRootTable(rt); const auto& D3D12RootParam = static_cast(RootParam); - auto& RootTableCache = ResourceCache.GetRootTable(RootParam.GetRootIndex()); - + auto& RootTableCache = ResourceCache.GetRootTable(RootParam.GetRootIndex()); + SHADER_TYPE dbgShaderType = SHADER_TYPE_UNKNOWN; #ifdef _DEBUG dbgShaderType = ShaderTypeFromShaderVisibility(D3D12RootParam.ShaderVisibility); #endif - VERIFY_EXPR( D3D12RootParam.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE ); - + VERIFY_EXPR(D3D12RootParam.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE); + auto TableSize = RootParam.GetDescriptorTableSize(); VERIFY(TableSize > 0, "Unexpected empty descriptor table"); auto HeapType = HeapTypeFromRangeType(D3D12RootParam.DescriptorTable.pDescriptorRanges[0].RangeType); #ifdef _DEBUG - RootTableCache.SetDebugAttribs( TableSize, HeapType, dbgShaderType ); + RootTableCache.SetDebugAttribs(TableSize, HeapType, dbgShaderType); #endif // Space for dynamic variables is allocated at every draw call - if( RootParam.GetShaderVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC ) + if (RootParam.GetShaderVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) { - if( HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ) + if (HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { RootTableCache.m_TableStartOffset = SrvCbvUavTblStartOffset; SrvCbvUavTblStartOffset += TableSize; @@ -653,30 +676,29 @@ void RootSignature::InitResourceCache(RenderDeviceD3D12Impl* pDeviceD3D12Impl } #ifdef _DEBUG - for(Uint32 rv = 0; rv < m_RootParams.GetNumRootViews(); ++rv) + for (Uint32 rv = 0; rv < m_RootParams.GetNumRootViews(); ++rv) { - auto& RootParam = m_RootParams.GetRootView(rv); + auto& RootParam = m_RootParams.GetRootView(rv); const auto& D3D12RootParam = static_cast(RootParam); - auto& RootTableCache = ResourceCache.GetRootTable(RootParam.GetRootIndex()); + auto& RootTableCache = ResourceCache.GetRootTable(RootParam.GetRootIndex()); // Root views are not assigned valid table start offset VERIFY_EXPR(RootTableCache.m_TableStartOffset == ShaderResourceCacheD3D12::InvalidDescriptorOffset); - + SHADER_TYPE dbgShaderType = ShaderTypeFromShaderVisibility(D3D12RootParam.ShaderVisibility); VERIFY_EXPR(D3D12RootParam.ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV); - RootTableCache.SetDebugAttribs( 1, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, dbgShaderType ); + RootTableCache.SetDebugAttribs(1, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, dbgShaderType); } #endif - + VERIFY_EXPR(SrvCbvUavTblStartOffset == TotalSrvCbvUavDescriptors); VERIFY_EXPR(SamplerTblStartOffset == TotalSamplerDescriptors); ResourceCache.SetDescriptorHeapSpace(std::move(CbcSrvUavHeapSpace), std::move(SamplerHeapSpace)); } -__forceinline -void TransitionResource(CommandContext& Ctx, - ShaderResourceCacheD3D12::Resource& Res, - D3D12_DESCRIPTOR_RANGE_TYPE RangeType) +__forceinline void TransitionResource(CommandContext& Ctx, + ShaderResourceCacheD3D12::Resource& Res, + D3D12_DESCRIPTOR_RANGE_TYPE RangeType) { switch (Res.Type) { @@ -693,21 +715,21 @@ void TransitionResource(CommandContext& Ctx, case CachedResourceType::BufSRV: { VERIFY(RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV, "Unexpected descriptor range type"); - auto* pBuffViewD3D12 = Res.pObject.RawPtr(); + auto* pBuffViewD3D12 = Res.pObject.RawPtr(); auto* pBuffToTransition = pBuffViewD3D12->GetBuffer(); if (pBuffToTransition->IsInKnownState() && !pBuffToTransition->CheckState(RESOURCE_STATE_SHADER_RESOURCE)) - Ctx.TransitionResource(pBuffToTransition, RESOURCE_STATE_SHADER_RESOURCE ); + Ctx.TransitionResource(pBuffToTransition, RESOURCE_STATE_SHADER_RESOURCE); } break; case CachedResourceType::BufUAV: { VERIFY(RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_UAV, "Unexpected descriptor range type"); - auto* pBuffViewD3D12 = Res.pObject.RawPtr(); + auto* pBuffViewD3D12 = Res.pObject.RawPtr(); auto* pBuffToTransition = pBuffViewD3D12->GetBuffer(); if (pBuffToTransition->IsInKnownState()) { - // We must always call TransitionResource() even when the state is already + // We must always call TransitionResource() even when the state is already // RESOURCE_STATE_UNORDERED_ACCESS as in this case UAV barrier must be executed Ctx.TransitionResource(pBuffToTransition, RESOURCE_STATE_UNORDERED_ACCESS); } @@ -717,30 +739,30 @@ void TransitionResource(CommandContext& Ctx, case CachedResourceType::TexSRV: { VERIFY(RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV, "Unexpected descriptor range type"); - auto* pTexViewD3D12 = Res.pObject.RawPtr(); + auto* pTexViewD3D12 = Res.pObject.RawPtr(); auto* pTexToTransition = pTexViewD3D12->GetTexture(); if (pTexToTransition->IsInKnownState() && !pTexToTransition->CheckState(RESOURCE_STATE_SHADER_RESOURCE)) - Ctx.TransitionResource(pTexToTransition, RESOURCE_STATE_SHADER_RESOURCE ); + Ctx.TransitionResource(pTexToTransition, RESOURCE_STATE_SHADER_RESOURCE); } break; case CachedResourceType::TexUAV: { VERIFY(RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_UAV, "Unexpected descriptor range type"); - auto* pTexViewD3D12 = Res.pObject.RawPtr(); + auto* pTexViewD3D12 = Res.pObject.RawPtr(); auto* pTexToTransition = pTexViewD3D12->GetTexture(); if (pTexToTransition->IsInKnownState()) { - // We must always call TransitionResource() even when the state is already + // We must always call TransitionResource() even when the state is already // RESOURCE_STATE_UNORDERED_ACCESS as in this case UAV barrier must be executed - Ctx.TransitionResource(pTexToTransition, RESOURCE_STATE_UNORDERED_ACCESS ); + Ctx.TransitionResource(pTexToTransition, RESOURCE_STATE_UNORDERED_ACCESS); } } break; case CachedResourceType::Sampler: VERIFY(RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, "Unexpected descriptor range type"); - break; + break; default: // Resource not bound @@ -762,11 +784,13 @@ void RootSignature::DvpVerifyResourceState(const ShaderResourceCacheD3D12::Resou // Not using QueryInterface() for the sake of efficiency const auto* pBufferD3D12 = Res.pObject.RawPtr(); if (pBufferD3D12->IsInKnownState() && !pBufferD3D12->CheckState(RESOURCE_STATE_CONSTANT_BUFFER)) + { LOG_ERROR_MESSAGE("Buffer '", pBufferD3D12->GetDesc().Name, "' must be in RESOURCE_STATE_CONSTANT_BUFFER state. Actual state: ", - GetResourceStateString(pBufferD3D12->GetState()), - ". Call IDeviceContext::TransitionShaderResources(), use RESOURCE_STATE_TRANSITION_MODE_TRANSITION " - "when calling IDeviceContext::CommitShaderResources() or explicitly transition the buffer state " - "with IDeviceContext::TransitionResourceStates()." ); + GetResourceStateString(pBufferD3D12->GetState()), + ". Call IDeviceContext::TransitionShaderResources(), use RESOURCE_STATE_TRANSITION_MODE_TRANSITION " + "when calling IDeviceContext::CommitShaderResources() or explicitly transition the buffer state " + "with IDeviceContext::TransitionResourceStates()."); + } } break; @@ -774,13 +798,15 @@ void RootSignature::DvpVerifyResourceState(const ShaderResourceCacheD3D12::Resou { VERIFY(RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV, "Unexpected descriptor range type"); const auto* pBuffViewD3D12 = Res.pObject.RawPtr(); - const auto* pBufferD3D12 = pBuffViewD3D12->GetBuffer(); + const auto* pBufferD3D12 = pBuffViewD3D12->GetBuffer(); if (pBufferD3D12->IsInKnownState() && !pBufferD3D12->CheckState(RESOURCE_STATE_SHADER_RESOURCE)) + { LOG_ERROR_MESSAGE("Buffer '", pBufferD3D12->GetDesc().Name, "' must be in RESOURCE_STATE_SHADER_RESOURCE state. Actual state: ", - GetResourceStateString(pBufferD3D12->GetState()), - ". Call IDeviceContext::TransitionShaderResources(), use RESOURCE_STATE_TRANSITION_MODE_TRANSITION " - "when calling IDeviceContext::CommitShaderResources() or explicitly transition the buffer state " - "with IDeviceContext::TransitionResourceStates()." ); + GetResourceStateString(pBufferD3D12->GetState()), + ". Call IDeviceContext::TransitionShaderResources(), use RESOURCE_STATE_TRANSITION_MODE_TRANSITION " + "when calling IDeviceContext::CommitShaderResources() or explicitly transition the buffer state " + "with IDeviceContext::TransitionResourceStates()."); + } } break; @@ -788,13 +814,15 @@ void RootSignature::DvpVerifyResourceState(const ShaderResourceCacheD3D12::Resou { VERIFY(RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_UAV, "Unexpected descriptor range type"); const auto* pBuffViewD3D12 = Res.pObject.RawPtr(); - const auto* pBufferD3D12 = pBuffViewD3D12->GetBuffer(); + const auto* pBufferD3D12 = pBuffViewD3D12->GetBuffer(); if (pBufferD3D12->IsInKnownState() && !pBufferD3D12->CheckState(RESOURCE_STATE_UNORDERED_ACCESS)) + { LOG_ERROR_MESSAGE("Buffer '", pBufferD3D12->GetDesc().Name, "' must be in RESOURCE_STATE_UNORDERED_ACCESS state. Actual state: ", - GetResourceStateString(pBufferD3D12->GetState()), - ". Call IDeviceContext::TransitionShaderResources(), use RESOURCE_STATE_TRANSITION_MODE_TRANSITION " - "when calling IDeviceContext::CommitShaderResources() or explicitly transition the buffer state " - "with IDeviceContext::TransitionResourceStates()." ); + GetResourceStateString(pBufferD3D12->GetState()), + ". Call IDeviceContext::TransitionShaderResources(), use RESOURCE_STATE_TRANSITION_MODE_TRANSITION " + "when calling IDeviceContext::CommitShaderResources() or explicitly transition the buffer state " + "with IDeviceContext::TransitionResourceStates()."); + } } break; @@ -802,13 +830,15 @@ void RootSignature::DvpVerifyResourceState(const ShaderResourceCacheD3D12::Resou { VERIFY(RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV, "Unexpected descriptor range type"); const auto* pTexViewD3D12 = Res.pObject.RawPtr(); - const auto* pTexD3D12 = pTexViewD3D12->GetTexture(); + const auto* pTexD3D12 = pTexViewD3D12->GetTexture(); if (pTexD3D12->IsInKnownState() && !pTexD3D12->CheckState(RESOURCE_STATE_SHADER_RESOURCE)) + { LOG_ERROR_MESSAGE("Texture '", pTexD3D12->GetDesc().Name, "' must be in RESOURCE_STATE_SHADER_RESOURCE state. Actual state: ", - GetResourceStateString(pTexD3D12->GetState()), - ". Call IDeviceContext::TransitionShaderResources(), use RESOURCE_STATE_TRANSITION_MODE_TRANSITION " - "when calling IDeviceContext::CommitShaderResources() or explicitly transition the texture state " - "with IDeviceContext::TransitionResourceStates()." ); + GetResourceStateString(pTexD3D12->GetState()), + ". Call IDeviceContext::TransitionShaderResources(), use RESOURCE_STATE_TRANSITION_MODE_TRANSITION " + "when calling IDeviceContext::CommitShaderResources() or explicitly transition the texture state " + "with IDeviceContext::TransitionResourceStates()."); + } } break; @@ -816,19 +846,21 @@ void RootSignature::DvpVerifyResourceState(const ShaderResourceCacheD3D12::Resou { VERIFY(RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_UAV, "Unexpected descriptor range type"); const auto* pTexViewD3D12 = Res.pObject.RawPtr(); - const auto* pTexD3D12 = pTexViewD3D12->GetTexture(); + const auto* pTexD3D12 = pTexViewD3D12->GetTexture(); if (pTexD3D12->IsInKnownState() && !pTexD3D12->CheckState(RESOURCE_STATE_UNORDERED_ACCESS)) + { LOG_ERROR_MESSAGE("Texture '", pTexD3D12->GetDesc().Name, "' must be in RESOURCE_STATE_UNORDERED_ACCESS state. Actual state: ", - GetResourceStateString(pTexD3D12->GetState()), - ". Call IDeviceContext::TransitionShaderResources(), use RESOURCE_STATE_TRANSITION_MODE_TRANSITION " - "when calling IDeviceContext::CommitShaderResources() or explicitly transition the texture state " - "with IDeviceContext::TransitionResourceStates()." ); + GetResourceStateString(pTexD3D12->GetState()), + ". Call IDeviceContext::TransitionShaderResources(), use RESOURCE_STATE_TRANSITION_MODE_TRANSITION " + "when calling IDeviceContext::CommitShaderResources() or explicitly transition the texture state " + "with IDeviceContext::TransitionResourceStates()."); + } } break; case CachedResourceType::Sampler: VERIFY(RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, "Unexpected descriptor range type"); - break; + break; default: // Resource not bound @@ -838,21 +870,21 @@ void RootSignature::DvpVerifyResourceState(const ShaderResourceCacheD3D12::Resou } #endif // DEVELOPMENT -template -__forceinline void RootSignature::RootParamsManager::ProcessRootTables(TOperation Operation)const +template +__forceinline void RootSignature::RootParamsManager::ProcessRootTables(TOperation Operation) const { - for(Uint32 rt = 0; rt < m_NumRootTables; ++rt) + for (Uint32 rt = 0; rt < m_NumRootTables; ++rt) { - auto& RootTable = GetRootTable(rt); - auto RootInd = RootTable.GetRootIndex(); + auto& RootTable = GetRootTable(rt); + auto RootInd = RootTable.GetRootIndex(); const D3D12_ROOT_PARAMETER& D3D12Param = RootTable; VERIFY_EXPR(D3D12Param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE); auto& d3d12Table = D3D12Param.DescriptorTable; VERIFY(d3d12Table.NumDescriptorRanges > 0 && RootTable.GetDescriptorTableSize() > 0, "Unexepected empty descriptor table"); - bool IsResourceTable = d3d12Table.pDescriptorRanges[0].RangeType != D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER; - D3D12_DESCRIPTOR_HEAP_TYPE dbgHeapType = D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; + bool IsResourceTable = d3d12Table.pDescriptorRanges[0].RangeType != D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER; + D3D12_DESCRIPTOR_HEAP_TYPE dbgHeapType = D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; #ifdef _DEBUG dbgHeapType = IsResourceTable ? D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV : D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER; #endif @@ -860,11 +892,11 @@ __forceinline void RootSignature::RootParamsManager::ProcessRootTables(TOperatio } } -template -__forceinline void ProcessCachedTableResources(Uint32 RootInd, - const D3D12_ROOT_PARAMETER& D3D12Param, - ShaderResourceCacheD3D12& ResourceCache, - D3D12_DESCRIPTOR_HEAP_TYPE dbgHeapType, +template +__forceinline void ProcessCachedTableResources(Uint32 RootInd, + const D3D12_ROOT_PARAMETER& D3D12Param, + ShaderResourceCacheD3D12& ResourceCache, + D3D12_DESCRIPTOR_HEAP_TYPE dbgHeapType, TOperation Operation) { for (UINT r = 0; r < D3D12Param.DescriptorTable.NumDescriptorRanges; ++r) @@ -877,8 +909,8 @@ __forceinline void ProcessCachedTableResources(Uint32 RootI dbgShaderType = ShaderTypeFromShaderVisibility(D3D12Param.ShaderVisibility); VERIFY(dbgHeapType == HeapTypeFromRangeType(range.RangeType), "Mistmatch between descriptor heap type and descriptor range type"); #endif - auto OffsetFromTableStart = range.OffsetInDescriptorsFromTableStart + d; - auto& Res = ResourceCache.GetRootTable(RootInd).GetResource(OffsetFromTableStart, dbgHeapType, dbgShaderType); + auto OffsetFromTableStart = range.OffsetInDescriptorsFromTableStart + d; + auto& Res = ResourceCache.GetRootTable(RootInd).GetResource(OffsetFromTableStart, dbgHeapType, dbgShaderType); Operation(OffsetFromTableStart, range, Res); } @@ -886,35 +918,37 @@ __forceinline void ProcessCachedTableResources(Uint32 RootI } -template -void RootSignature::CommitDescriptorHandlesInternal_SMD(RenderDeviceD3D12Impl* pRenderDeviceD3D12, - ShaderResourceCacheD3D12& ResourceCache, - CommandContext& Ctx, +template +void RootSignature::CommitDescriptorHandlesInternal_SMD(RenderDeviceD3D12Impl* pRenderDeviceD3D12, + ShaderResourceCacheD3D12& ResourceCache, + CommandContext& Ctx, bool IsCompute, - bool ValidateStates)const + bool ValidateStates) const { - auto *pd3d12Device = pRenderDeviceD3D12->GetD3D12Device(); + auto* pd3d12Device = pRenderDeviceD3D12->GetD3D12Device(); Uint32 NumDynamicCbvSrvUavDescriptors = m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC]; - Uint32 NumDynamicSamplerDescriptors = m_TotalSamplerSlots [SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC]; + Uint32 NumDynamicSamplerDescriptors = m_TotalSamplerSlots[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC]; VERIFY_EXPR(NumDynamicCbvSrvUavDescriptors > 0 || NumDynamicSamplerDescriptors > 0); DescriptorHeapAllocation DynamicCbvSrvUavDescriptors, DynamicSamplerDescriptors; if (NumDynamicCbvSrvUavDescriptors > 0) { DynamicCbvSrvUavDescriptors = Ctx.AllocateDynamicGPUVisibleDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDynamicCbvSrvUavDescriptors); - DEV_CHECK_ERR(DynamicCbvSrvUavDescriptors.GetDescriptorHeap() != nullptr, - "Failed to allocate ", NumDynamicCbvSrvUavDescriptors, " dynamic GPU-visible CBV/SRV/UAV descriptor", (NumDynamicCbvSrvUavDescriptors > 1 ? "s" : ""), ". " - "Consider increasing GPUDescriptorHeapDynamicSize[0] in EngineD3D12CreateInfo " + DEV_CHECK_ERR(DynamicCbvSrvUavDescriptors.GetDescriptorHeap() != nullptr, + "Failed to allocate ", NumDynamicCbvSrvUavDescriptors, " dynamic GPU-visible CBV/SRV/UAV descriptor", + (NumDynamicCbvSrvUavDescriptors > 1 ? "s" : ""), + ". Consider increasing GPUDescriptorHeapDynamicSize[0] in EngineD3D12CreateInfo " "or optimizing dynamic resource utilization by using static or mutable shader resource variables instead."); } if (NumDynamicSamplerDescriptors > 0) { DynamicSamplerDescriptors = Ctx.AllocateDynamicGPUVisibleDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, NumDynamicSamplerDescriptors); - DEV_CHECK_ERR(DynamicSamplerDescriptors.GetDescriptorHeap() != nullptr, - "Failed to allocate ", NumDynamicSamplerDescriptors, " dynamic GPU-visible Sampler descriptor", (NumDynamicSamplerDescriptors > 1 ? "s" : ""), ". " - "Consider using static samplers in the Pipeline State Object, increasing GPUDescriptorHeapDynamicSize[1] in " + DEV_CHECK_ERR(DynamicSamplerDescriptors.GetDescriptorHeap() != nullptr, + "Failed to allocate ", NumDynamicSamplerDescriptors, " dynamic GPU-visible Sampler descriptor", + (NumDynamicSamplerDescriptors > 1 ? "s" : ""), + ". Consider using static samplers in the Pipeline State Object, increasing GPUDescriptorHeapDynamicSize[1] in " "EngineD3D12CreateInfo, or optimizing dynamic resource utilization by using static or mutable shader resource variables instead."); } @@ -926,62 +960,70 @@ void RootSignature::CommitDescriptorHandlesInternal_SMD(RenderDeviceD3D12Impl* Heaps.pSrvCbvUavHeap = DynamicCbvSrvUavDescriptors.GetDescriptorHeap(); if (NumDynamicCbvSrvUavDescriptors > 0) - VERIFY(DynamicCbvSrvUavDescriptors.GetDescriptorHeap() == Heaps.pSrvCbvUavHeap, "Inconsistent CbvSrvUav descriptor heaps" ); + VERIFY(DynamicCbvSrvUavDescriptors.GetDescriptorHeap() == Heaps.pSrvCbvUavHeap, "Inconsistent CbvSrvUav descriptor heaps"); if (NumDynamicSamplerDescriptors > 0) - VERIFY(DynamicSamplerDescriptors.GetDescriptorHeap() == Heaps.pSamplerHeap, "Inconsistent Sampler descriptor heaps" ); + VERIFY(DynamicSamplerDescriptors.GetDescriptorHeap() == Heaps.pSamplerHeap, "Inconsistent Sampler descriptor heaps"); if (Heaps) Ctx.SetDescriptorHeaps(Heaps); - // Offset to the beginning of the current dynamic CBV_SRV_UAV/SAMPLER table from + // Offset to the beginning of the current dynamic CBV_SRV_UAV/SAMPLER table from // the start of the allocation Uint32 DynamicCbvSrvUavTblOffset = 0; - Uint32 DynamicSamplerTblOffset = 0; + Uint32 DynamicSamplerTblOffset = 0; m_RootParams.ProcessRootTables( - [&](Uint32 RootInd, const RootParameter& RootTable, const D3D12_ROOT_PARAMETER& D3D12Param, bool IsResourceTable, D3D12_DESCRIPTOR_HEAP_TYPE dbgHeapType) + [&](Uint32 RootInd, + const RootParameter& RootTable, + const D3D12_ROOT_PARAMETER& D3D12Param, + bool IsResourceTable, + D3D12_DESCRIPTOR_HEAP_TYPE dbgHeapType) // { D3D12_GPU_DESCRIPTOR_HANDLE RootTableGPUDescriptorHandle; + bool IsDynamicTable = RootTable.GetShaderVariableType() == SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; if (IsDynamicTable) { - if( IsResourceTable ) + if (IsResourceTable) RootTableGPUDescriptorHandle = DynamicCbvSrvUavDescriptors.GetGpuHandle(DynamicCbvSrvUavTblOffset); else RootTableGPUDescriptorHandle = DynamicSamplerDescriptors.GetGpuHandle(DynamicSamplerTblOffset); } else { - RootTableGPUDescriptorHandle = IsResourceTable ? - ResourceCache.GetShaderVisibleTableGPUDescriptorHandle(RootInd) : + RootTableGPUDescriptorHandle = IsResourceTable ? + ResourceCache.GetShaderVisibleTableGPUDescriptorHandle(RootInd) : ResourceCache.GetShaderVisibleTableGPUDescriptorHandle(RootInd); VERIFY(RootTableGPUDescriptorHandle.ptr != 0, "Unexpected null GPU descriptor handle"); } - if(IsCompute) + if (IsCompute) Ctx.GetCommandList()->SetComputeRootDescriptorTable(RootInd, RootTableGPUDescriptorHandle); else Ctx.GetCommandList()->SetGraphicsRootDescriptorTable(RootInd, RootTableGPUDescriptorHandle); - ProcessCachedTableResources(RootInd, D3D12Param, ResourceCache, dbgHeapType, - [&](UINT OffsetFromTableStart, const D3D12_DESCRIPTOR_RANGE& range, ShaderResourceCacheD3D12::Resource& Res) + ProcessCachedTableResources( + RootInd, D3D12Param, ResourceCache, dbgHeapType, + [&](UINT OffsetFromTableStart, + const D3D12_DESCRIPTOR_RANGE& range, + ShaderResourceCacheD3D12::Resource& Res) // { - if(PerformResourceTransitions) + if (PerformResourceTransitions) { TransitionResource(Ctx, Res, range.RangeType); } #ifdef DEVELOPMENT - else if(ValidateStates) + else if (ValidateStates) { DvpVerifyResourceState(Res, range.RangeType); } #endif - if(IsDynamicTable) + if (IsDynamicTable) { if (IsResourceTable) { - VERIFY( DynamicCbvSrvUavTblOffset < NumDynamicCbvSrvUavDescriptors, "Not enough space in the descriptor heap allocation"); + VERIFY(DynamicCbvSrvUavTblOffset < NumDynamicCbvSrvUavDescriptors, "Not enough space in the descriptor heap allocation"); if (Res.CPUDescriptorHandle.ptr != 0) { @@ -998,7 +1040,7 @@ void RootSignature::CommitDescriptorHandlesInternal_SMD(RenderDeviceD3D12Impl* } else { - VERIFY( DynamicSamplerTblOffset < NumDynamicSamplerDescriptors, "Not enough space in the descriptor heap allocation"); + VERIFY(DynamicSamplerTblOffset < NumDynamicSamplerDescriptors, "Not enough space in the descriptor heap allocation"); if (Res.CPUDescriptorHandle.ptr != 0) { @@ -1010,39 +1052,38 @@ void RootSignature::CommitDescriptorHandlesInternal_SMD(RenderDeviceD3D12Impl* LOG_ERROR_MESSAGE("No valid sampler descriptor handle found for root parameter ", RootInd, ", descriptor slot ", OffsetFromTableStart); } #endif - + ++DynamicSamplerTblOffset; } } - } + } // ); - } + } // ); - - VERIFY_EXPR( DynamicCbvSrvUavTblOffset == NumDynamicCbvSrvUavDescriptors ); - VERIFY_EXPR( DynamicSamplerTblOffset == NumDynamicSamplerDescriptors ); + + VERIFY_EXPR(DynamicCbvSrvUavTblOffset == NumDynamicCbvSrvUavDescriptors); + VERIFY_EXPR(DynamicSamplerTblOffset == NumDynamicSamplerDescriptors); } -template -void RootSignature::CommitDescriptorHandlesInternal_SM(RenderDeviceD3D12Impl* pRenderDeviceD3D12, - ShaderResourceCacheD3D12& ResourceCache, - CommandContext& Ctx, +template +void RootSignature::CommitDescriptorHandlesInternal_SM(RenderDeviceD3D12Impl* pRenderDeviceD3D12, + ShaderResourceCacheD3D12& ResourceCache, + CommandContext& Ctx, bool IsCompute, - bool ValidateStates)const + bool ValidateStates) const { VERIFY_EXPR(m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC] == 0 && m_TotalSamplerSlots[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC] == 0); CommandContext::ShaderDescriptorHeaps Heaps(ResourceCache.GetSrvCbvUavDescriptorHeap(), ResourceCache.GetSamplerDescriptorHeap()); - if(Heaps) + if (Heaps) Ctx.SetDescriptorHeaps(Heaps); m_RootParams.ProcessRootTables( - [&](Uint32 RootInd, const RootParameter& RootTable, const D3D12_ROOT_PARAMETER& D3D12Param, bool IsResourceTable, D3D12_DESCRIPTOR_HEAP_TYPE dbgHeapType ) - { + [&](Uint32 RootInd, const RootParameter& RootTable, const D3D12_ROOT_PARAMETER& D3D12Param, bool IsResourceTable, D3D12_DESCRIPTOR_HEAP_TYPE dbgHeapType) { VERIFY(RootTable.GetShaderVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC, "Unexpected dynamic resource"); - D3D12_GPU_DESCRIPTOR_HANDLE RootTableGPUDescriptorHandle = IsResourceTable ? - ResourceCache.GetShaderVisibleTableGPUDescriptorHandle(RootInd) : + D3D12_GPU_DESCRIPTOR_HANDLE RootTableGPUDescriptorHandle = IsResourceTable ? + ResourceCache.GetShaderVisibleTableGPUDescriptorHandle(RootInd) : ResourceCache.GetShaderVisibleTableGPUDescriptorHandle(RootInd); VERIFY(RootTableGPUDescriptorHandle.ptr != 0, "Unexpected null GPU descriptor handle"); @@ -1051,45 +1092,58 @@ void RootSignature::CommitDescriptorHandlesInternal_SM(RenderDeviceD3D12Impl* else Ctx.GetCommandList()->SetGraphicsRootDescriptorTable(RootInd, RootTableGPUDescriptorHandle); - if(PerformResourceTransitions) + if (PerformResourceTransitions) { - ProcessCachedTableResources(RootInd, D3D12Param, ResourceCache, dbgHeapType, - [&](UINT OffsetFromTableStart, const D3D12_DESCRIPTOR_RANGE& range, ShaderResourceCacheD3D12::Resource& Res) + ProcessCachedTableResources( + RootInd, D3D12Param, ResourceCache, dbgHeapType, + [&](UINT OffsetFromTableStart, + const D3D12_DESCRIPTOR_RANGE& range, + ShaderResourceCacheD3D12::Resource& Res) // { TransitionResource(Ctx, Res, range.RangeType); - } + } // ); } #ifdef DEVELOPMENT - else if(ValidateStates) + else if (ValidateStates) { - ProcessCachedTableResources(RootInd, D3D12Param, ResourceCache, dbgHeapType, - [&](UINT OffsetFromTableStart, const D3D12_DESCRIPTOR_RANGE& range, const ShaderResourceCacheD3D12::Resource &Res) + ProcessCachedTableResources( + RootInd, D3D12Param, ResourceCache, dbgHeapType, + [&](UINT OffsetFromTableStart, + const D3D12_DESCRIPTOR_RANGE& range, + const ShaderResourceCacheD3D12::Resource& Res) // { DvpVerifyResourceState(Res, range.RangeType); - } + } // ); } #endif - } + } // ); } -void RootSignature::TransitionResources(ShaderResourceCacheD3D12& ResourceCache, - CommandContext& Ctx)const +void RootSignature::TransitionResources(ShaderResourceCacheD3D12& ResourceCache, + CommandContext& Ctx) const { m_RootParams.ProcessRootTables( - [&](Uint32 RootInd, const RootParameter& RootTable, const D3D12_ROOT_PARAMETER& D3D12Param, bool IsResourceTable, D3D12_DESCRIPTOR_HEAP_TYPE dbgHeapType ) + [&](Uint32 RootInd, + const RootParameter& RootTable, + const D3D12_ROOT_PARAMETER& D3D12Param, + bool IsResourceTable, + D3D12_DESCRIPTOR_HEAP_TYPE dbgHeapType) // { - ProcessCachedTableResources(RootInd, D3D12Param, ResourceCache, dbgHeapType, - [&](UINT OffsetFromTableStart, const D3D12_DESCRIPTOR_RANGE &range, ShaderResourceCacheD3D12::Resource &Res) + ProcessCachedTableResources( + RootInd, D3D12Param, ResourceCache, dbgHeapType, + [&](UINT OffsetFromTableStart, + const D3D12_DESCRIPTOR_RANGE& range, + ShaderResourceCacheD3D12::Resource& Res) // { TransitionResource(Ctx, Res, range.RangeType); - } + } // ); - } + } // ); } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/SamplerD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/SamplerD3D12Impl.cpp index b7fd54e5..0b803248 100644 --- a/Graphics/GraphicsEngineD3D12/src/SamplerD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/SamplerD3D12Impl.cpp @@ -31,34 +31,34 @@ namespace Diligent SamplerD3D12Impl::SamplerD3D12Impl(IReferenceCounters* pRefCounters, RenderDeviceD3D12Impl* pRenderDeviceD3D12, - const SamplerDesc& SamplerDesc) : + const SamplerDesc& SamplerDesc) : TSamplerBase{pRefCounters, pRenderDeviceD3D12, SamplerDesc} { - auto *pD3D12Device = pRenderDeviceD3D12->GetD3D12Device(); - D3D12_SAMPLER_DESC D3D12SamplerDesc = - { - FilterTypeToD3D12Filter(SamplerDesc.MinFilter, SamplerDesc.MagFilter, SamplerDesc.MipFilter), - TexAddressModeToD3D12AddressMode(SamplerDesc.AddressU), - TexAddressModeToD3D12AddressMode(SamplerDesc.AddressV), - TexAddressModeToD3D12AddressMode(SamplerDesc.AddressW), - SamplerDesc.MipLODBias, - SamplerDesc.MaxAnisotropy, - ComparisonFuncToD3D12ComparisonFunc(SamplerDesc.ComparisonFunc), - {SamplerDesc.BorderColor[0], SamplerDesc.BorderColor[1], SamplerDesc.BorderColor[2], SamplerDesc.BorderColor[3]}, - SamplerDesc.MinLOD, - SamplerDesc.MaxLOD - }; + auto* pD3D12Device = pRenderDeviceD3D12->GetD3D12Device(); + + D3D12_SAMPLER_DESC D3D12SamplerDesc = + { + FilterTypeToD3D12Filter(SamplerDesc.MinFilter, SamplerDesc.MagFilter, SamplerDesc.MipFilter), + TexAddressModeToD3D12AddressMode(SamplerDesc.AddressU), + TexAddressModeToD3D12AddressMode(SamplerDesc.AddressV), + TexAddressModeToD3D12AddressMode(SamplerDesc.AddressW), + SamplerDesc.MipLODBias, + SamplerDesc.MaxAnisotropy, + ComparisonFuncToD3D12ComparisonFunc(SamplerDesc.ComparisonFunc), + {SamplerDesc.BorderColor[0], SamplerDesc.BorderColor[1], SamplerDesc.BorderColor[2], SamplerDesc.BorderColor[3]}, + SamplerDesc.MinLOD, + SamplerDesc.MaxLOD // + }; auto CPUDescriptorAlloc = pRenderDeviceD3D12->AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); - m_Descriptor = std::move(CPUDescriptorAlloc); - pD3D12Device->CreateSampler(&D3D12SamplerDesc, m_Descriptor.GetCpuHandle()); + m_Descriptor = std::move(CPUDescriptorAlloc); + pD3D12Device->CreateSampler(&D3D12SamplerDesc, m_Descriptor.GetCpuHandle()); } SamplerD3D12Impl::~SamplerD3D12Impl() { - } -IMPLEMENT_QUERY_INTERFACE( SamplerD3D12Impl, IID_SamplerD3D12, TSamplerBase ) +IMPLEMENT_QUERY_INTERFACE(SamplerD3D12Impl, IID_SamplerD3D12, TSamplerBase) -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderD3D12Impl.cpp index 42325bf5..27cb6017 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderD3D12Impl.cpp @@ -48,9 +48,10 @@ static const std::string GetD3D12ShaderModel(RenderDeviceD3D12Impl* /*pDevice*/, } } -ShaderD3D12Impl::ShaderD3D12Impl(IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pRenderDeviceD3D12, - const ShaderCreateInfo& ShaderCI) : +ShaderD3D12Impl::ShaderD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl* pRenderDeviceD3D12, + const ShaderCreateInfo& ShaderCI) : + // clang-format off TShaderBase { pRefCounters, @@ -58,10 +59,11 @@ ShaderD3D12Impl::ShaderD3D12Impl(IReferenceCounters* pRefCounters, ShaderCI.Desc }, ShaderD3DBase{ShaderCI, GetD3D12ShaderModel(pRenderDeviceD3D12, ShaderCI.HLSLVersion).c_str()} +// clang-format on { // Load shader resources - auto& Allocator = GetRawAllocator(); - auto* pRawMem = ALLOCATE(Allocator, "Allocator for ShaderResources", ShaderResourcesD3D12, 1); + auto& Allocator = GetRawAllocator(); + auto* pRawMem = ALLOCATE(Allocator, "Allocator for ShaderResources", ShaderResourcesD3D12, 1); auto* pResources = new (pRawMem) ShaderResourcesD3D12(m_pShaderByteCode, m_Desc, ShaderCI.UseCombinedTextureSamplers ? ShaderCI.CombinedSamplerSuffix : nullptr); m_pShaderResources.reset(pResources, STDDeleterRawMem(Allocator)); } @@ -81,8 +83,8 @@ void ShaderD3D12Impl::QueryInterface(const INTERFACE_ID& IID, IObject** ppInterf } else { - TShaderBase::QueryInterface( IID, ppInterface ); + TShaderBase::QueryInterface(IID, ppInterface); } } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderResourceBindingD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderResourceBindingD3D12Impl.cpp index 3a088ec8..a4bdf685 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderResourceBindingD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderResourceBindingD3D12Impl.cpp @@ -33,6 +33,7 @@ namespace Diligent ShaderResourceBindingD3D12Impl::ShaderResourceBindingD3D12Impl(IReferenceCounters* pRefCounters, PipelineStateD3D12Impl* pPSO, bool IsPSOInternal) : + // clang-format off TBase { pRefCounters, @@ -41,36 +42,37 @@ ShaderResourceBindingD3D12Impl::ShaderResourceBindingD3D12Impl(IReferenceCounter }, m_ShaderResourceCache{ShaderResourceCacheD3D12::DbgCacheContentType::SRBResources}, m_NumShaders {static_cast(pPSO->GetNumShaders())} +// clang-format on { auto* ppShaders = pPSO->GetShaders(); auto* pRenderDeviceD3D12Impl = ValidatedCast(pPSO->GetDevice()); - auto& ResCacheDataAllocator = pPSO->GetSRBMemoryAllocator().GetResourceCacheDataAllocator(0); + auto& ResCacheDataAllocator = pPSO->GetSRBMemoryAllocator().GetResourceCacheDataAllocator(0); pPSO->GetRootSignature().InitResourceCache(pRenderDeviceD3D12Impl, m_ShaderResourceCache, ResCacheDataAllocator); - + m_pShaderVarMgrs = ALLOCATE(GetRawAllocator(), "Raw memory for ShaderVariableManagerD3D12", ShaderVariableManagerD3D12, m_NumShaders); for (Uint32 s = 0; s < m_NumShaders; ++s) { - auto* pShader = ppShaders[s]; - auto ShaderType = pShader->GetDesc().ShaderType; - auto ShaderInd = GetShaderTypeIndex(ShaderType); + auto* pShader = ppShaders[s]; + auto ShaderType = pShader->GetDesc().ShaderType; + auto ShaderInd = GetShaderTypeIndex(ShaderType); auto& VarDataAllocator = pPSO->GetSRBMemoryAllocator().GetShaderVariableDataAllocator(s); // http://diligentgraphics.com/diligent-engine/architecture/d3d12/shader-resource-layout#Initializing-Resource-Layouts-in-a-Shader-Resource-Binding-Object - const SHADER_RESOURCE_VARIABLE_TYPE AllowedVarTypes[] = { SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC }; - const auto& SrcLayout = pPSO->GetShaderResLayout(s); + const SHADER_RESOURCE_VARIABLE_TYPE AllowedVarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; + const auto& SrcLayout = pPSO->GetShaderResLayout(s); // Create shader variable manager in place new (m_pShaderVarMgrs + s) - ShaderVariableManagerD3D12 + ShaderVariableManagerD3D12 // { *this, SrcLayout, VarDataAllocator, AllowedVarTypes, _countof(AllowedVarTypes), - m_ShaderResourceCache + m_ShaderResourceCache // }; m_ResourceLayoutIndex[ShaderInd] = static_cast(s); @@ -80,9 +82,9 @@ ShaderResourceBindingD3D12Impl::ShaderResourceBindingD3D12Impl(IReferenceCounter ShaderResourceBindingD3D12Impl::~ShaderResourceBindingD3D12Impl() { auto* pPSO = ValidatedCast(m_pPSO); - for(Uint32 s = 0; s < m_NumShaders; ++s) + for (Uint32 s = 0; s < m_NumShaders; ++s) { - auto &VarDataAllocator = pPSO->GetSRBMemoryAllocator().GetShaderVariableDataAllocator(s); + auto& VarDataAllocator = pPSO->GetSRBMemoryAllocator().GetShaderVariableDataAllocator(s); m_pShaderVarMgrs[s].Destroy(VarDataAllocator); m_pShaderVarMgrs[s].~ShaderVariableManagerD3D12(); } @@ -90,16 +92,16 @@ ShaderResourceBindingD3D12Impl::~ShaderResourceBindingD3D12Impl() GetRawAllocator().Free(m_pShaderVarMgrs); } -IMPLEMENT_QUERY_INTERFACE( ShaderResourceBindingD3D12Impl, IID_ShaderResourceBindingD3D12, TBase ) +IMPLEMENT_QUERY_INTERFACE(ShaderResourceBindingD3D12Impl, IID_ShaderResourceBindingD3D12, TBase) void ShaderResourceBindingD3D12Impl::BindResources(Uint32 ShaderFlags, IResourceMapping* pResMapping, Uint32 Flags) { - for (auto ShaderInd = 0; ShaderInd <= CSInd; ++ShaderInd ) + for (auto ShaderInd = 0; ShaderInd <= CSInd; ++ShaderInd) { if (ShaderFlags & GetShaderTypeFromIndex(ShaderInd)) { auto ResLayoutInd = m_ResourceLayoutIndex[ShaderInd]; - if(ResLayoutInd >= 0) + if (ResLayoutInd >= 0) { m_pShaderVarMgrs[ResLayoutInd].BindResources(pResMapping, Flags); } @@ -109,7 +111,7 @@ void ShaderResourceBindingD3D12Impl::BindResources(Uint32 ShaderFlags, IResource IShaderResourceVariable* ShaderResourceBindingD3D12Impl::GetVariableByName(SHADER_TYPE ShaderType, const char* Name) { - auto ShaderInd = GetShaderTypeIndex(ShaderType); + auto ShaderInd = GetShaderTypeIndex(ShaderType); auto ResLayoutInd = m_ResourceLayoutIndex[ShaderInd]; if (ResLayoutInd < 0) { @@ -120,9 +122,9 @@ IShaderResourceVariable* ShaderResourceBindingD3D12Impl::GetVariableByName(SHADE return m_pShaderVarMgrs[ResLayoutInd].GetVariable(Name); } -Uint32 ShaderResourceBindingD3D12Impl::GetVariableCount(SHADER_TYPE ShaderType) const +Uint32 ShaderResourceBindingD3D12Impl::GetVariableCount(SHADER_TYPE ShaderType) const { - auto ShaderInd = GetShaderTypeIndex(ShaderType); + auto ShaderInd = GetShaderTypeIndex(ShaderType); auto ResLayoutInd = m_ResourceLayoutIndex[ShaderInd]; if (ResLayoutInd < 0) { @@ -136,7 +138,7 @@ Uint32 ShaderResourceBindingD3D12Impl::GetVariableCount(SHADER_TYPE ShaderType) IShaderResourceVariable* ShaderResourceBindingD3D12Impl::GetVariableByIndex(SHADER_TYPE ShaderType, Uint32 Index) { - auto ShaderInd = GetShaderTypeIndex(ShaderType); + auto ShaderInd = GetShaderTypeIndex(ShaderType); auto ResLayoutInd = m_ResourceLayoutIndex[ShaderInd]; if (ResLayoutInd < 0) { @@ -150,7 +152,7 @@ IShaderResourceVariable* ShaderResourceBindingD3D12Impl::GetVariableByIndex(SHAD #ifdef DEVELOPMENT -void ShaderResourceBindingD3D12Impl::dvpVerifyResourceBindings(const PipelineStateD3D12Impl* pPSO)const +void ShaderResourceBindingD3D12Impl::dvpVerifyResourceBindings(const PipelineStateD3D12Impl* pPSO) const { auto* pRefPSO = GetPipelineState(); if (pPSO->IsIncompatibleWith(pRefPSO)) @@ -158,15 +160,15 @@ void ShaderResourceBindingD3D12Impl::dvpVerifyResourceBindings(const PipelineSta LOG_ERROR("Shader resource binding is incompatible with the pipeline state \"", pPSO->GetDesc().Name, '\"'); return; } - for(Uint32 l = 0; l < m_NumShaders; ++l) + for (Uint32 l = 0; l < m_NumShaders; ++l) { // Use reference layout from pipeline state that contains all shader resource types const auto& ShaderResLayout = pRefPSO->GetShaderResLayout(l); ShaderResLayout.dvpVerifyBindings(m_ShaderResourceCache); } -#ifdef _DEBUG +# ifdef _DEBUG m_ShaderResourceCache.DbgVerifyBoundDynamicCBsCounter(); -#endif +# endif } #endif @@ -175,7 +177,8 @@ void ShaderResourceBindingD3D12Impl::InitializeStaticResources(const IPipelineSt { if (StaticResourcesInitialized()) { - LOG_WARNING_MESSAGE("Static resources have already been initialized in this shader resource binding object. The operation will be ignored."); + LOG_WARNING_MESSAGE("Static resources have already been initialized in this shader " + "resource binding object. The operation will be ignored."); return; } @@ -188,21 +191,22 @@ void ShaderResourceBindingD3D12Impl::InitializeStaticResources(const IPipelineSt DEV_CHECK_ERR(pPSO->IsCompatibleWith(GetPipelineState()), "The pipeline state is not compatible with this SRB"); } - auto* pPSO12 = ValidatedCast(pPSO); - auto NumShaders = pPSO12->GetNumShaders(); + auto* pPSO12 = ValidatedCast(pPSO); + auto NumShaders = pPSO12->GetNumShaders(); // Copy static resources for (Uint32 s = 0; s < NumShaders; ++s) { const auto& ShaderResLayout = pPSO12->GetShaderResLayout(s); - auto& StaticResLayout = pPSO12->GetStaticShaderResLayout(s); - auto& StaticResCache = pPSO12->GetStaticShaderResCache(s); + auto& StaticResLayout = pPSO12->GetStaticShaderResLayout(s); + auto& StaticResCache = pPSO12->GetStaticShaderResCache(s); #ifdef DEVELOPMENT if (!StaticResLayout.dvpVerifyBindings(StaticResCache)) { auto* pShader = pPSO12->GetShader(s); - LOG_ERROR_MESSAGE("Static resources in SRB of PSO '", pPSO12->GetDesc().Name, "' will not be successfully initialized " - "because not all static resource bindings in shader '", pShader->GetDesc().Name, "' are valid. " - "Please make sure you bind all static resources to PSO before calling InitializeStaticResources() " + LOG_ERROR_MESSAGE("Static resources in SRB of PSO '", pPSO12->GetDesc().Name, + "' will not be successfully initialized because not all static resource bindings in shader '", + pShader->GetDesc().Name, + "' are valid. Please make sure you bind all static resources to PSO before calling InitializeStaticResources() " "directly or indirectly by passing InitStaticResources=true to CreateShaderResourceBinding() method."); } #endif @@ -216,4 +220,4 @@ void ShaderResourceBindingD3D12Impl::InitializeStaticResources(const IPipelineSt m_bStaticResourcesInitialized = true; } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderResourceCacheD3D12.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderResourceCacheD3D12.cpp index b5a54e2e..4594cb22 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderResourceCacheD3D12.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderResourceCacheD3D12.cpp @@ -28,87 +28,89 @@ namespace Diligent { - size_t ShaderResourceCacheD3D12::GetRequiredMemorySize(Uint32 NumTables, - Uint32 TableSizes[]) - { - size_t MemorySize = NumTables * sizeof(RootTable); - for(Uint32 t=0; t < NumTables; ++t) - MemorySize += TableSizes[t] * sizeof(Resource); - return MemorySize; - } - // http://diligentgraphics.com/diligent-engine/architecture/d3d12/shader-resource-cache#Cache-Structure - void ShaderResourceCacheD3D12::Initialize(IMemoryAllocator& MemAllocator, Uint32 NumTables, Uint32 TableSizes[]) +size_t ShaderResourceCacheD3D12::GetRequiredMemorySize(Uint32 NumTables, + Uint32 TableSizes[]) +{ + size_t MemorySize = NumTables * sizeof(RootTable); + for (Uint32 t = 0; t < NumTables; ++t) + MemorySize += TableSizes[t] * sizeof(Resource); + return MemorySize; +} + +// http://diligentgraphics.com/diligent-engine/architecture/d3d12/shader-resource-cache#Cache-Structure +void ShaderResourceCacheD3D12::Initialize(IMemoryAllocator& MemAllocator, Uint32 NumTables, Uint32 TableSizes[]) +{ + // Memory layout: + // __________________________________________________________ + // m_pMemory | m_pResources, m_NumResources | + // | | | + // V | V + // | RootTable[0] | .... | RootTable[Nrt-1] | Res[0] | ... | Res[n-1] | .... | Res[0] | ... | Res[m-1] | + // | A + // | | + // |________________________________________________| + // m_pResources, m_NumResources + // + + VERIFY(m_pAllocator == nullptr && m_pMemory == nullptr, "Cache already initialized"); + m_pAllocator = &MemAllocator; + m_NumTables = NumTables; + Uint32 TotalResources = 0; + for (Uint32 t = 0; t < NumTables; ++t) + TotalResources += TableSizes[t]; + auto MemorySize = NumTables * sizeof(RootTable) + TotalResources * sizeof(Resource); + VERIFY_EXPR(MemorySize == GetRequiredMemorySize(NumTables, TableSizes)); + if (MemorySize > 0) { - // Memory layout: - // __________________________________________________________ - // m_pMemory | m_pResources, m_NumResources | - // | | | - // V | V - // | RootTable[0] | .... | RootTable[Nrt-1] | Res[0] | ... | Res[n-1] | .... | Res[0] | ... | Res[m-1] | - // | A - // | | - // |________________________________________________| - // m_pResources, m_NumResources - // + m_pMemory = ALLOCATE_RAW(*m_pAllocator, "Memory for shader resource cache data", MemorySize); + auto* pTables = reinterpret_cast(m_pMemory); + auto* pCurrResPtr = reinterpret_cast(pTables + m_NumTables); + for (Uint32 res = 0; res < TotalResources; ++res) + new (pCurrResPtr + res) Resource(); - VERIFY(m_pAllocator == nullptr && m_pMemory == nullptr, "Cache already initialized"); - m_pAllocator = &MemAllocator; - m_NumTables = NumTables; - Uint32 TotalResources = 0; - for(Uint32 t=0; t < NumTables; ++t) - TotalResources += TableSizes[t]; - auto MemorySize = NumTables * sizeof(RootTable) + TotalResources * sizeof(Resource); - VERIFY_EXPR(MemorySize == GetRequiredMemorySize(NumTables, TableSizes)); - if(MemorySize > 0) + for (Uint32 t = 0; t < NumTables; ++t) { - m_pMemory = ALLOCATE_RAW( *m_pAllocator, "Memory for shader resource cache data", MemorySize); - auto* pTables = reinterpret_cast(m_pMemory); - auto* pCurrResPtr = reinterpret_cast(pTables + m_NumTables); - for(Uint32 res=0; res < TotalResources; ++res) - new(pCurrResPtr + res) Resource(); - - for (Uint32 t = 0; t < NumTables; ++t) - { - new(&GetRootTable(t)) RootTable(TableSizes[t], TableSizes[t] > 0 ? pCurrResPtr : nullptr); - pCurrResPtr += TableSizes[t]; - } - VERIFY_EXPR((char*)pCurrResPtr == (char*)m_pMemory + MemorySize); + new (&GetRootTable(t)) RootTable(TableSizes[t], TableSizes[t] > 0 ? pCurrResPtr : nullptr); + pCurrResPtr += TableSizes[t]; } + VERIFY_EXPR((char*)pCurrResPtr == (char*)m_pMemory + MemorySize); } +} - ShaderResourceCacheD3D12::~ShaderResourceCacheD3D12() +ShaderResourceCacheD3D12::~ShaderResourceCacheD3D12() +{ + if (m_pMemory) { - if (m_pMemory) - { - Uint32 TotalResources = 0; - for (Uint32 t = 0; t < m_NumTables; ++t) - TotalResources += GetRootTable(t).GetSize(); - auto *pResources = reinterpret_cast( reinterpret_cast(m_pMemory) + m_NumTables); - for(Uint32 res=0; res < TotalResources; ++res) - pResources[res].~Resource(); - for (Uint32 t = 0; t < m_NumTables; ++t) - GetRootTable(t).~RootTable(); + Uint32 TotalResources = 0; + for (Uint32 t = 0; t < m_NumTables; ++t) + TotalResources += GetRootTable(t).GetSize(); + auto* pResources = reinterpret_cast(reinterpret_cast(m_pMemory) + m_NumTables); + for (Uint32 res = 0; res < TotalResources; ++res) + pResources[res].~Resource(); + for (Uint32 t = 0; t < m_NumTables; ++t) + GetRootTable(t).~RootTable(); - m_pAllocator->Free(m_pMemory); - } + m_pAllocator->Free(m_pMemory); } +} #ifdef _DEBUG - void ShaderResourceCacheD3D12::DbgVerifyBoundDynamicCBsCounter()const +void ShaderResourceCacheD3D12::DbgVerifyBoundDynamicCBsCounter() const +{ + Uint32 NumDynamicCBsBound = 0; + for (Uint32 t = 0; t < m_NumTables; ++t) { - Uint32 NumDynamicCBsBound = 0; - for (Uint32 t = 0; t < m_NumTables; ++t) + const auto& RT = GetRootTable(t); + for (Uint32 res = 0; res < RT.GetSize(); ++res) { - const auto& RT = GetRootTable(t); - for (Uint32 res=0; res < RT.GetSize(); ++res) - { - const auto& Res = RT.GetResource(res); - if (Res.Type == CachedResourceType::CBV && Res.pObject && Res.pObject.RawPtr()->GetDesc().Usage == USAGE_DYNAMIC) - ++NumDynamicCBsBound; - } + const auto& Res = RT.GetResource(res); + if (Res.Type == CachedResourceType::CBV && Res.pObject && Res.pObject.RawPtr()->GetDesc().Usage == USAGE_DYNAMIC) + ++NumDynamicCBsBound; } - VERIFY(NumDynamicCBsBound == m_NumDynamicCBsBound, "The number of dynamic CBs bound is invalid"); } -#endif + VERIFY(NumDynamicCBsBound == m_NumDynamicCBsBound, "The number of dynamic CBs bound is invalid"); } +#endif + +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp index 39e003f0..5aebb084 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp @@ -37,10 +37,10 @@ namespace Diligent { - + ShaderResourceLayoutD3D12::~ShaderResourceLayoutD3D12() { - for(Uint32 r=0; r < GetTotalResourceCount(); ++r) + for (Uint32 r = 0; r < GetTotalResourceCount(); ++r) GetResource(r).~D3D12Resource(); } @@ -51,15 +51,17 @@ D3D12_DESCRIPTOR_RANGE_TYPE GetDescriptorRangeType(CachedResourceType ResType) public: ResTypeToD3D12DescrRangeType() { + // clang-format off m_Map[(size_t)CachedResourceType::CBV] = D3D12_DESCRIPTOR_RANGE_TYPE_CBV; m_Map[(size_t)CachedResourceType::TexSRV] = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; m_Map[(size_t)CachedResourceType::BufSRV] = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; m_Map[(size_t)CachedResourceType::TexUAV] = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; m_Map[(size_t)CachedResourceType::BufUAV] = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; m_Map[(size_t)CachedResourceType::Sampler] = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER; + // clang-format on } - D3D12_DESCRIPTOR_RANGE_TYPE operator[](CachedResourceType ResType)const + D3D12_DESCRIPTOR_RANGE_TYPE operator[](CachedResourceType ResType) const { auto Ind = static_cast(ResType); VERIFY(Ind >= 0 && Ind < (size_t)CachedResourceType::NumTypes, "Unexpected resource type"); @@ -80,27 +82,27 @@ void ShaderResourceLayoutD3D12::AllocateMemory(IMemoryAllocator& const std::array& SamplerCount) { m_CbvSrvUavOffsets[0] = 0; - for (SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType+1)) + for (SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType + 1)) { - VERIFY(m_CbvSrvUavOffsets[VarType] + CbvSrvUavCount[VarType] <= std::numeric_limits::max(), "Offset is not representable in 16 bits" ); - m_CbvSrvUavOffsets[VarType+1] = static_cast(m_CbvSrvUavOffsets[VarType] + CbvSrvUavCount[VarType]); + VERIFY(m_CbvSrvUavOffsets[VarType] + CbvSrvUavCount[VarType] <= std::numeric_limits::max(), "Offset is not representable in 16 bits"); + m_CbvSrvUavOffsets[VarType + 1] = static_cast(m_CbvSrvUavOffsets[VarType] + CbvSrvUavCount[VarType]); VERIFY_EXPR(GetCbvSrvUavCount(VarType) == CbvSrvUavCount[VarType]); } m_SamplersOffsets[0] = m_CbvSrvUavOffsets[SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES]; - for (SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType+1)) + for (SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType + 1)) { - VERIFY(m_SamplersOffsets[VarType] + SamplerCount[VarType] <= std::numeric_limits::max(), "Offset is not representable in 16 bits" ); - m_SamplersOffsets[VarType+1] = static_cast(m_SamplersOffsets[VarType] + SamplerCount[VarType]); + VERIFY(m_SamplersOffsets[VarType] + SamplerCount[VarType] <= std::numeric_limits::max(), "Offset is not representable in 16 bits"); + m_SamplersOffsets[VarType + 1] = static_cast(m_SamplersOffsets[VarType] + SamplerCount[VarType]); VERIFY_EXPR(GetSamplerCount(VarType) == SamplerCount[VarType]); } size_t MemSize = GetTotalResourceCount() * sizeof(D3D12Resource); - if(MemSize == 0) + if (MemSize == 0) return; - auto* pRawMem = ALLOCATE_RAW(Allocator, "Raw memory buffer for shader resource layout resources", MemSize); - m_ResourceBuffer = std::unique_ptr >(pRawMem, Allocator); + auto* pRawMem = ALLOCATE_RAW(Allocator, "Raw memory buffer for shader resource layout resources", MemSize); + m_ResourceBuffer = std::unique_ptr>(pRawMem, Allocator); } @@ -109,17 +111,19 @@ void ShaderResourceLayoutD3D12::AllocateMemory(IMemoryAllocator& ShaderResourceLayoutD3D12::ShaderResourceLayoutD3D12(IObject& Owner, ID3D12Device* pd3d12Device, const PipelineResourceLayoutDesc& ResourceLayout, - std::shared_ptr pSrcResources, + std::shared_ptr pSrcResources, IMemoryAllocator& LayoutDataAllocator, - const SHADER_RESOURCE_VARIABLE_TYPE* const AllowedVarTypes, - Uint32 NumAllowedTypes, + const SHADER_RESOURCE_VARIABLE_TYPE* const AllowedVarTypes, + Uint32 NumAllowedTypes, ShaderResourceCacheD3D12* pResourceCache, - RootSignature* pRootSig) : + RootSignature* pRootSig) : + // clang-format off m_Owner {Owner}, m_pd3d12Device {pd3d12Device}, m_pResources {std::move(pSrcResources)} +// clang-format on { - VERIFY_EXPR( (pResourceCache != nullptr) ^ (pRootSig != nullptr) ); + VERIFY_EXPR((pResourceCache != nullptr) ^ (pRootSig != nullptr)); const Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); @@ -128,25 +132,25 @@ ShaderResourceLayoutD3D12::ShaderResourceLayoutD3D12(IObject& // Count number of resources to allocate all needed memory m_pResources->ProcessResources( - [&](const D3DShaderResourceAttribs& CB, Uint32) + [&](const D3DShaderResourceAttribs& CB, Uint32) // { auto VarType = m_pResources->FindVariableType(CB, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) ++CbvSrvUavCount[VarType]; }, - [&](const D3DShaderResourceAttribs& Sam, Uint32) + [&](const D3DShaderResourceAttribs& Sam, Uint32) // { auto VarType = m_pResources->FindVariableType(Sam, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) { constexpr bool LogStaticSamplerArrayError = true; - auto StaticSamplerInd = m_pResources->FindStaticSampler(Sam, ResourceLayout, LogStaticSamplerArrayError); + auto StaticSamplerInd = m_pResources->FindStaticSampler(Sam, ResourceLayout, LogStaticSamplerArrayError); // Skip static samplers if (StaticSamplerInd < 0) ++SamplerCount[VarType]; } }, - [&](const D3DShaderResourceAttribs& TexSRV, Uint32) + [&](const D3DShaderResourceAttribs& TexSRV, Uint32) // { auto VarType = m_pResources->FindVariableType(TexSRV, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) @@ -155,51 +159,55 @@ ShaderResourceLayoutD3D12::ShaderResourceLayoutD3D12(IObject& if (TexSRV.IsCombinedWithSampler()) { const auto& SamplerAttribs = m_pResources->GetCombinedSampler(TexSRV); - auto SamplerVarType = m_pResources->FindVariableType(SamplerAttribs, ResourceLayout); + auto SamplerVarType = m_pResources->FindVariableType(SamplerAttribs, ResourceLayout); DEV_CHECK_ERR(SamplerVarType == VarType, - "The type (", GetShaderVariableTypeLiteralName(VarType),") of texture SRV variable '", TexSRV.Name, + "The type (", GetShaderVariableTypeLiteralName(VarType), ") of texture SRV variable '", TexSRV.Name, "' is not consistent with the type (", GetShaderVariableTypeLiteralName(SamplerVarType), - ") of the sampler '", SamplerAttribs.Name, "' that is assigned to it"); (void)SamplerVarType; + ") of the sampler '", SamplerAttribs.Name, "' that is assigned to it"); + (void)SamplerVarType; } } }, - [&](const D3DShaderResourceAttribs& TexUAV, Uint32) + [&](const D3DShaderResourceAttribs& TexUAV, Uint32) // { auto VarType = m_pResources->FindVariableType(TexUAV, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) ++CbvSrvUavCount[VarType]; }, - [&](const D3DShaderResourceAttribs& BufSRV, Uint32) + [&](const D3DShaderResourceAttribs& BufSRV, Uint32) // { auto VarType = m_pResources->FindVariableType(BufSRV, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) ++CbvSrvUavCount[VarType]; }, - [&](const D3DShaderResourceAttribs& BufUAV, Uint32) + [&](const D3DShaderResourceAttribs& BufUAV, Uint32) // { auto VarType = m_pResources->FindVariableType(BufUAV, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) ++CbvSrvUavCount[VarType]; - } + } // ); - + AllocateMemory(LayoutDataAllocator, CbvSrvUavCount, SamplerCount); std::array CurrCbvSrvUav = {}; std::array CurrSampler = {}; + Uint32 StaticResCacheTblSizes[4] = {0, 0, 0, 0}; auto AddResource = [&](const D3DShaderResourceAttribs& Attribs, CachedResourceType ResType, SHADER_RESOURCE_VARIABLE_TYPE VarType, - Uint32 SamplerId = D3D12Resource::InvalidSamplerId) + Uint32 SamplerId = D3D12Resource::InvalidSamplerId) // { Uint32 RootIndex = D3D12Resource::InvalidRootIndex; Uint32 Offset = D3D12Resource::InvalidOffset; + D3D12_DESCRIPTOR_RANGE_TYPE DescriptorRangeType = GetDescriptorRangeType(ResType); + if (pRootSig) { - pRootSig->AllocateResourceSlot(m_pResources->GetShaderType(), Attribs, VarType, DescriptorRangeType, RootIndex, Offset ); + pRootSig->AllocateResourceSlot(m_pResources->GetShaderType(), Attribs, VarType, DescriptorRangeType, RootIndex, Offset); VERIFY(RootIndex <= D3D12Resource::MaxRootIndex, "Root index excceeds allowed limit"); } else @@ -225,27 +233,27 @@ ShaderResourceLayoutD3D12::ShaderResourceLayoutD3D12(IObject& // Static samplers are never copied, and SamplerId == InvalidSamplerId auto& NewResource = (ResType == CachedResourceType::Sampler) ? - GetSampler (VarType, CurrSampler [VarType]++) : + GetSampler(VarType, CurrSampler[VarType]++) : GetSrvCbvUav(VarType, CurrCbvSrvUav[VarType]++); ::new (&NewResource) D3D12Resource(*this, Attribs, VarType, ResType, RootIndex, Offset, SamplerId); }; - + m_pResources->ProcessResources( - [&](const D3DShaderResourceAttribs& CB, Uint32) + [&](const D3DShaderResourceAttribs& CB, Uint32) // { auto VarType = m_pResources->FindVariableType(CB, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) AddResource(CB, CachedResourceType::CBV, VarType); }, - [&](const D3DShaderResourceAttribs& Sam, Uint32) + [&](const D3DShaderResourceAttribs& Sam, Uint32) // { auto VarType = m_pResources->FindVariableType(Sam, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) { // The error (if any) have already been logged when counting the resources constexpr bool LogStaticSamplerArrayError = false; - auto StaticSamplerInd = m_pResources->FindStaticSampler(Sam, ResourceLayout, LogStaticSamplerArrayError); + auto StaticSamplerInd = m_pResources->FindStaticSampler(Sam, ResourceLayout, LogStaticSamplerArrayError); if (StaticSamplerInd >= 0) { if (pRootSig != nullptr) @@ -257,30 +265,30 @@ ShaderResourceLayoutD3D12::ShaderResourceLayoutD3D12(IObject& } } }, - [&](const D3DShaderResourceAttribs& TexSRV, Uint32) + [&](const D3DShaderResourceAttribs& TexSRV, Uint32) // { auto VarType = m_pResources->FindVariableType(TexSRV, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) { static_assert(SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES == 3, "Unexpected number of shader variable types"); VERIFY(CurrSampler[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] + CurrSampler[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE] + CurrSampler[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC] == GetTotalSamplerCount(), "All samplers must be initialized before texture SRVs"); - + Uint32 SamplerId = D3D12Resource::InvalidSamplerId; if (TexSRV.IsCombinedWithSampler()) { const auto& SamplerAttribs = m_pResources->GetCombinedSampler(TexSRV); - auto SamplerVarType = m_pResources->FindVariableType(SamplerAttribs, ResourceLayout); + auto SamplerVarType = m_pResources->FindVariableType(SamplerAttribs, ResourceLayout); DEV_CHECK_ERR(SamplerVarType == VarType, - "The type (", GetShaderVariableTypeLiteralName(VarType),") of texture SRV variable '", TexSRV.Name, + "The type (", GetShaderVariableTypeLiteralName(VarType), ") of texture SRV variable '", TexSRV.Name, "' is not consistent with the type (", GetShaderVariableTypeLiteralName(SamplerVarType), - ") of the sampler '", SamplerAttribs.Name, "' that is assigned to it"); + ") of the sampler '", SamplerAttribs.Name, "' that is assigned to it"); // The error (if any) have already been logged when counting the resources constexpr bool LogStaticSamplerArrayError = false; - auto StaticSamplerInd = m_pResources->FindStaticSampler(SamplerAttribs, ResourceLayout, LogStaticSamplerArrayError); + auto StaticSamplerInd = m_pResources->FindStaticSampler(SamplerAttribs, ResourceLayout, LogStaticSamplerArrayError); if (StaticSamplerInd >= 0) { - // Static samplers are never copied, and SamplerId == InvalidSamplerId + // Static samplers are never copied, and SamplerId == InvalidSamplerId #ifdef _DEBUG auto SamplerCount = GetTotalSamplerCount(); for (Uint32 s = 0; s < SamplerCount; ++s) @@ -298,7 +306,7 @@ ShaderResourceLayoutD3D12::ShaderResourceLayoutD3D12(IObject& for (SamplerId = 0; SamplerId < SamplerCount; ++SamplerId) { const auto& Sampler = GetSampler(SamplerId); - SamplerFound = strcmp(Sampler.Attribs.Name, SamplerAttribs.Name) == 0; + SamplerFound = strcmp(Sampler.Attribs.Name, SamplerAttribs.Name) == 0; if (SamplerFound) break; } @@ -314,35 +322,35 @@ ShaderResourceLayoutD3D12::ShaderResourceLayoutD3D12(IObject& AddResource(TexSRV, CachedResourceType::TexSRV, VarType, SamplerId); } }, - [&](const D3DShaderResourceAttribs& TexUAV, Uint32) + [&](const D3DShaderResourceAttribs& TexUAV, Uint32) // { auto VarType = m_pResources->FindVariableType(TexUAV, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) AddResource(TexUAV, CachedResourceType::TexUAV, VarType); }, - [&](const D3DShaderResourceAttribs& BufSRV, Uint32) + [&](const D3DShaderResourceAttribs& BufSRV, Uint32) // { auto VarType = m_pResources->FindVariableType(BufSRV, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) AddResource(BufSRV, CachedResourceType::BufSRV, VarType); }, - [&](const D3DShaderResourceAttribs& BufUAV, Uint32) + [&](const D3DShaderResourceAttribs& BufUAV, Uint32) // { auto VarType = m_pResources->FindVariableType(BufUAV, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) AddResource(BufUAV, CachedResourceType::BufUAV, VarType); - } + } // ); #ifdef _DEBUG - for(SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType+1)) + for (SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType + 1)) { - VERIFY( CurrCbvSrvUav[VarType] == CbvSrvUavCount[VarType], "Not all Srv/Cbv/Uavs are initialized, which result in a crash when dtor is called" ); - VERIFY( CurrSampler[VarType] == SamplerCount [VarType], "Not all Samplers are initialized, which result in a crash when dtor is called" ); + VERIFY(CurrCbvSrvUav[VarType] == CbvSrvUavCount[VarType], "Not all Srv/Cbv/Uavs are initialized, which result in a crash when dtor is called"); + VERIFY(CurrSampler[VarType] == SamplerCount[VarType], "Not all Samplers are initialized, which result in a crash when dtor is called"); } #endif - if(pResourceCache) + if (pResourceCache) { // Initialize resource cache to store static resources // http://diligentgraphics.com/diligent-engine/architecture/d3d12/shader-resource-cache#Initializing-the-Cache-for-Static-Shader-Resources @@ -363,7 +371,7 @@ void ShaderResourceLayoutD3D12::D3D12Resource::CacheCB(IDeviceObject* ShaderResourceCacheD3D12::Resource& DstRes, Uint32 ArrayInd, D3D12_CPU_DESCRIPTOR_HANDLE ShdrVisibleHeapCPUDescriptorHandle, - Uint32& BoundDynamicCBsCounter)const + Uint32& BoundDynamicCBsCounter) const { // http://diligentgraphics.com/diligent-engine/architecture/d3d12/shader-resource-cache#Binding-Objects-to-Shader-Variables @@ -377,15 +385,15 @@ void ShaderResourceLayoutD3D12::D3D12Resource::CacheCB(IDeviceObject* { if (GetVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC && DstRes.pObject != nullptr) { - // Do not update resource if one is already bound unless it is dynamic. This may be + // Do not update resource if one is already bound unless it is dynamic. This may be // dangerous as CopyDescriptorsSimple() may interfere with GPU reading the same descriptor. return; } - DstRes.Type = GetResType(); + DstRes.Type = GetResType(); DstRes.CPUDescriptorHandle = pBuffD3D12->GetCBVHandle(); - VERIFY (DstRes.CPUDescriptorHandle.ptr != 0 || pBuffD3D12->GetDesc().Usage == USAGE_DYNAMIC, "No relevant CBV CPU descriptor handle"); - + VERIFY(DstRes.CPUDescriptorHandle.ptr != 0 || pBuffD3D12->GetDesc().Usage == USAGE_DYNAMIC, "No relevant CBV CPU descriptor handle"); + if (ShdrVisibleHeapCPUDescriptorHandle.ptr != 0) { // Dynamic resources are assigned descriptor in the GPU-visible heap at every draw call, and @@ -408,32 +416,33 @@ void ShaderResourceLayoutD3D12::D3D12Resource::CacheCB(IDeviceObject* } -template -struct ResourceViewTraits{}; +template +struct ResourceViewTraits +{}; -template<> +template <> struct ResourceViewTraits { - static const INTERFACE_ID &IID; + static const INTERFACE_ID& IID; }; const INTERFACE_ID& ResourceViewTraits::IID = IID_TextureViewD3D12; -template<> +template <> struct ResourceViewTraits { - static const INTERFACE_ID &IID; + static const INTERFACE_ID& IID; }; const INTERFACE_ID& ResourceViewTraits::IID = IID_BufferViewD3D12; -template ///< ResType of the procedure to set sampler -void ShaderResourceLayoutD3D12::D3D12Resource::CacheResourceView(IDeviceObject* pView, - ShaderResourceCacheD3D12::Resource& DstRes, +template ///< ResType of the procedure to set sampler +void ShaderResourceLayoutD3D12::D3D12Resource::CacheResourceView(IDeviceObject* pView, + ShaderResourceCacheD3D12::Resource& DstRes, Uint32 ArrayIndex, - D3D12_CPU_DESCRIPTOR_HANDLE ShdrVisibleHeapCPUDescriptorHandle, + D3D12_CPU_DESCRIPTOR_HANDLE ShdrVisibleHeapCPUDescriptorHandle, TViewTypeEnum dbgExpectedViewType, - TBindSamplerProcType BindSamplerProc)const + TBindSamplerProcType BindSamplerProc) const { // We cannot use ValidatedCast<> here as the resource retrieved from the // resource mapping can be of wrong type @@ -445,12 +454,12 @@ void ShaderResourceLayoutD3D12::D3D12Resource::CacheResourceView(IDeviceObject* { if (GetVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC && DstRes.pObject != nullptr) { - // Do not update resource if one is already bound unless it is dynamic. This may be + // Do not update resource if one is already bound unless it is dynamic. This may be // dangerous as CopyDescriptorsSimple() may interfere with GPU reading the same descriptor. return; } - DstRes.Type = GetResType(); + DstRes.Type = GetResType(); DstRes.CPUDescriptorHandle = pViewD3D12->GetCPUDescriptorHandle(); VERIFY(DstRes.CPUDescriptorHandle.ptr != 0, "No relevant D3D12 view"); @@ -463,7 +472,7 @@ void ShaderResourceLayoutD3D12::D3D12Resource::CacheResourceView(IDeviceObject* ID3D12Device* pd3d12Device = ParentResLayout.m_pd3d12Device; pd3d12Device->CopyDescriptorsSimple(1, ShdrVisibleHeapCPUDescriptorHandle, DstRes.CPUDescriptorHandle, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); } - + BindSamplerProc(pViewD3D12); DstRes.pObject = std::move(pViewD3D12); @@ -471,13 +480,13 @@ void ShaderResourceLayoutD3D12::D3D12Resource::CacheResourceView(IDeviceObject* } void ShaderResourceLayoutD3D12::D3D12Resource::CacheSampler(IDeviceObject* pSampler, - ShaderResourceCacheD3D12::Resource& DstSam, + ShaderResourceCacheD3D12::Resource& DstSam, Uint32 ArrayIndex, - D3D12_CPU_DESCRIPTOR_HANDLE ShdrVisibleHeapCPUDescriptorHandle)const + D3D12_CPU_DESCRIPTOR_HANDLE ShdrVisibleHeapCPUDescriptorHandle) const { VERIFY(Attribs.IsValidBindPoint(), "Invalid bind point"); VERIFY_EXPR(ArrayIndex < Attribs.BindCount); - + RefCntAutoPtr pSamplerD3D12(pSampler, IID_SamplerD3D12); if (pSamplerD3D12) { @@ -488,10 +497,10 @@ void ShaderResourceLayoutD3D12::D3D12Resource::CacheSampler(IDeviceObject* auto VarTypeStr = GetShaderVariableTypeLiteralName(GetVariableType()); LOG_ERROR_MESSAGE("Non-null sampler is already bound to ", VarTypeStr, " shader variable '", Attribs.GetPrintName(ArrayIndex), "' in shader '", ParentResLayout.GetShaderName(), "'. Attempting to bind another sampler is an error and will " - "be ignored. Use another shader resource binding instance or label the variable as dynamic." ); + "be ignored. Use another shader resource binding instance or label the variable as dynamic."); } - - // Do not update resource if one is already bound unless it is dynamic. This may be + + // Do not update resource if one is already bound unless it is dynamic. This may be // dangerous as CopyDescriptorsSimple() may interfere with GPU reading the same descriptor. return; } @@ -501,7 +510,7 @@ void ShaderResourceLayoutD3D12::D3D12Resource::CacheSampler(IDeviceObject* DstSam.CPUDescriptorHandle = pSamplerD3D12->GetCPUDescriptorHandle(); VERIFY(DstSam.CPUDescriptorHandle.ptr != 0, "No relevant D3D12 sampler descriptor handle"); - if(ShdrVisibleHeapCPUDescriptorHandle.ptr != 0) + if (ShdrVisibleHeapCPUDescriptorHandle.ptr != 0) { // Dynamic resources are assigned descriptor in the GPU-visible heap at every draw call, and // the descriptor is copied by the RootSignature when resources are committed @@ -518,9 +527,9 @@ void ShaderResourceLayoutD3D12::D3D12Resource::CacheSampler(IDeviceObject* LOG_ERROR_MESSAGE("Failed to bind object '", pSampler->GetDesc().Name, "' to variable '", Attribs.GetPrintName(ArrayIndex), "' in shader '", ParentResLayout.GetShaderName(), "'. Incorect object type: sampler is expected."); } -} +} -const ShaderResourceLayoutD3D12::D3D12Resource& ShaderResourceLayoutD3D12::GetAssignedSampler(const D3D12Resource& TexSrv)const +const ShaderResourceLayoutD3D12::D3D12Resource& ShaderResourceLayoutD3D12::GetAssignedSampler(const D3D12Resource& TexSrv) const { VERIFY(TexSrv.GetResType() == CachedResourceType::TexSRV, "Unexpected resource type: texture SRV is expected"); VERIFY(TexSrv.ValidSamplerAssigned(), "Texture SRV has no associated sampler"); @@ -538,15 +547,16 @@ ShaderResourceLayoutD3D12::D3D12Resource& ShaderResourceLayoutD3D12::GetAssigned void ShaderResourceLayoutD3D12::D3D12Resource::BindResource(IDeviceObject* pObj, Uint32 ArrayIndex, - ShaderResourceCacheD3D12& ResourceCache)const + ShaderResourceCacheD3D12& ResourceCache) const { VERIFY_EXPR(ArrayIndex < Attribs.BindCount); - const bool IsSampler = GetResType() == CachedResourceType::Sampler; - auto DescriptorHeapType = IsSampler ? D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER : D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; - auto& DstRes = ResourceCache.GetRootTable(RootIndex).GetResource(OffsetFromTableStart + ArrayIndex, DescriptorHeapType, ParentResLayout.m_pResources->GetShaderType()); - auto ShdrVisibleHeapCPUDescriptorHandle = IsSampler ? - ResourceCache.GetShaderVisibleTableCPUDescriptorHandle (RootIndex, OffsetFromTableStart + ArrayIndex) : + const bool IsSampler = GetResType() == CachedResourceType::Sampler; + auto DescriptorHeapType = IsSampler ? D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER : D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + auto& DstRes = ResourceCache.GetRootTable(RootIndex).GetResource(OffsetFromTableStart + ArrayIndex, DescriptorHeapType, ParentResLayout.m_pResources->GetShaderType()); + + auto ShdrVisibleHeapCPUDescriptorHandle = IsSampler ? + ResourceCache.GetShaderVisibleTableCPUDescriptorHandle(RootIndex, OffsetFromTableStart + ArrayIndex) : ResourceCache.GetShaderVisibleTableCPUDescriptorHandle(RootIndex, OffsetFromTableStart + ArrayIndex); #ifdef _DEBUG @@ -563,7 +573,7 @@ void ShaderResourceLayoutD3D12::D3D12Resource::BindResource(IDeviceObject* } else { - if(GetVariableType() == SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) + if (GetVariableType() == SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) VERIFY(ShdrVisibleHeapCPUDescriptorHandle.ptr == 0, "Dynamic resources of a shader resource binding should be assigned shader visible descriptor space at every draw call"); else VERIFY(ShdrVisibleHeapCPUDescriptorHandle.ptr != 0, "Non-dynamics resources of a shader resource binding must be assigned shader visible descriptor space"); @@ -581,68 +591,72 @@ void ShaderResourceLayoutD3D12::D3D12Resource::BindResource(IDeviceObject* switch (GetResType()) { case CachedResourceType::CBV: - CacheCB(pObj, DstRes, ArrayIndex, ShdrVisibleHeapCPUDescriptorHandle, ResourceCache.GetBoundDynamicCBsCounter()); - break; - - case CachedResourceType::TexSRV: - CacheResourceView(pObj, DstRes, ArrayIndex, ShdrVisibleHeapCPUDescriptorHandle, TEXTURE_VIEW_SHADER_RESOURCE, [&](ITextureViewD3D12* pTexView) - { - if (ValidSamplerAssigned()) + CacheCB(pObj, DstRes, ArrayIndex, ShdrVisibleHeapCPUDescriptorHandle, ResourceCache.GetBoundDynamicCBsCounter()); + break; + + case CachedResourceType::TexSRV: + CacheResourceView( + pObj, DstRes, ArrayIndex, ShdrVisibleHeapCPUDescriptorHandle, TEXTURE_VIEW_SHADER_RESOURCE, + [&](ITextureViewD3D12* pTexView) // { - auto& Sam = ParentResLayout.GetAssignedSampler(*this); - //VERIFY( !Sam.Attribs.IsStaticSampler(), "Static samplers should never be assigned space in the cache" ); - VERIFY_EXPR(Attribs.BindCount == Sam.Attribs.BindCount || Sam.Attribs.BindCount == 1); - auto SamplerArrInd = Sam.Attribs.BindCount > 1 ? ArrayIndex : 0; - auto ShdrVisibleSamplerHeapCPUDescriptorHandle = ResourceCache.GetShaderVisibleTableCPUDescriptorHandle(Sam.RootIndex, Sam.OffsetFromTableStart + SamplerArrInd); - auto& DstSam = ResourceCache.GetRootTable(Sam.RootIndex).GetResource(Sam.OffsetFromTableStart + SamplerArrInd, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, ParentResLayout.m_pResources->GetShaderType()); -#ifdef _DEBUG + if (ValidSamplerAssigned()) { - if (ResourceCache.DbgGetContentType() == ShaderResourceCacheD3D12::DbgCacheContentType::StaticShaderResources) + auto& Sam = ParentResLayout.GetAssignedSampler(*this); + //VERIFY( !Sam.Attribs.IsStaticSampler(), "Static samplers should never be assigned space in the cache" ); + VERIFY_EXPR(Attribs.BindCount == Sam.Attribs.BindCount || Sam.Attribs.BindCount == 1); + auto SamplerArrInd = Sam.Attribs.BindCount > 1 ? ArrayIndex : 0; + + auto ShdrVisibleSamplerHeapCPUDescriptorHandle = ResourceCache.GetShaderVisibleTableCPUDescriptorHandle(Sam.RootIndex, Sam.OffsetFromTableStart + SamplerArrInd); + + auto& DstSam = ResourceCache.GetRootTable(Sam.RootIndex).GetResource(Sam.OffsetFromTableStart + SamplerArrInd, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, ParentResLayout.m_pResources->GetShaderType()); +#ifdef _DEBUG { - VERIFY(ShdrVisibleSamplerHeapCPUDescriptorHandle.ptr == 0, "Static shader resources of a shader should not be assigned shader visible descriptor space"); + if (ResourceCache.DbgGetContentType() == ShaderResourceCacheD3D12::DbgCacheContentType::StaticShaderResources) + { + VERIFY(ShdrVisibleSamplerHeapCPUDescriptorHandle.ptr == 0, "Static shader resources of a shader should not be assigned shader visible descriptor space"); + } + else if (ResourceCache.DbgGetContentType() == ShaderResourceCacheD3D12::DbgCacheContentType::SRBResources) + { + if (GetVariableType() == SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) + VERIFY(ShdrVisibleSamplerHeapCPUDescriptorHandle.ptr == 0, "Dynamic resources of a shader resource binding should be assigned shader visible descriptor space at every draw call"); + else + VERIFY(ShdrVisibleSamplerHeapCPUDescriptorHandle.ptr != 0 || pTexView == nullptr, "Non-dynamics resources of a shader resource binding must be assigned shader visible descriptor space"); + } + else + { + UNEXPECTED("Unknown content type"); + } } - else if (ResourceCache.DbgGetContentType() == ShaderResourceCacheD3D12::DbgCacheContentType::SRBResources) +#endif + auto pSampler = pTexView->GetSampler(); + if (pSampler) { - if(GetVariableType() == SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) - VERIFY(ShdrVisibleSamplerHeapCPUDescriptorHandle.ptr == 0, "Dynamic resources of a shader resource binding should be assigned shader visible descriptor space at every draw call"); - else - VERIFY(ShdrVisibleSamplerHeapCPUDescriptorHandle.ptr != 0 || pTexView == nullptr, "Non-dynamics resources of a shader resource binding must be assigned shader visible descriptor space"); + Sam.CacheSampler(pSampler, DstSam, SamplerArrInd, ShdrVisibleSamplerHeapCPUDescriptorHandle); } else { - UNEXPECTED("Unknown content type"); + LOG_ERROR_MESSAGE("Failed to bind sampler to variable '", Sam.Attribs.Name, ". Sampler is not set in the texture view '", pTexView->GetDesc().Name, '\''); } } -#endif - auto pSampler = pTexView->GetSampler(); - if( pSampler ) - { - Sam.CacheSampler(pSampler, DstSam, SamplerArrInd, ShdrVisibleSamplerHeapCPUDescriptorHandle); - } - else - { - LOG_ERROR_MESSAGE( "Failed to bind sampler to variable '", Sam.Attribs.Name, ". Sampler is not set in the texture view '", pTexView->GetDesc().Name, '\'' ); - } - } - }); - break; + }); + break; - case CachedResourceType::TexUAV: - CacheResourceView(pObj, DstRes, ArrayIndex, ShdrVisibleHeapCPUDescriptorHandle, TEXTURE_VIEW_UNORDERED_ACCESS, [](ITextureViewD3D12*){}); - break; + case CachedResourceType::TexUAV: + CacheResourceView(pObj, DstRes, ArrayIndex, ShdrVisibleHeapCPUDescriptorHandle, TEXTURE_VIEW_UNORDERED_ACCESS, [](ITextureViewD3D12*) {}); + break; - case CachedResourceType::BufSRV: - CacheResourceView(pObj, DstRes, ArrayIndex, ShdrVisibleHeapCPUDescriptorHandle, BUFFER_VIEW_SHADER_RESOURCE, [](IBufferViewD3D12*){}); - break; + case CachedResourceType::BufSRV: + CacheResourceView(pObj, DstRes, ArrayIndex, ShdrVisibleHeapCPUDescriptorHandle, BUFFER_VIEW_SHADER_RESOURCE, [](IBufferViewD3D12*) {}); + break; - case CachedResourceType::BufUAV: - CacheResourceView(pObj, DstRes, ArrayIndex, ShdrVisibleHeapCPUDescriptorHandle, BUFFER_VIEW_UNORDERED_ACCESS, [](IBufferViewD3D12*){}); - break; + case CachedResourceType::BufUAV: + CacheResourceView(pObj, DstRes, ArrayIndex, ShdrVisibleHeapCPUDescriptorHandle, BUFFER_VIEW_UNORDERED_ACCESS, [](IBufferViewD3D12*) {}); + break; - case CachedResourceType::Sampler: + case CachedResourceType::Sampler: DEV_CHECK_ERR(ParentResLayout.IsUsingSeparateSamplers(), "Samplers should not be set directly when using combined texture samplers"); CacheSampler(pObj, DstRes, ArrayIndex, ShdrVisibleHeapCPUDescriptorHandle); - break; + break; default: UNEXPECTED("Unknown resource type ", static_cast(GetResType())); } @@ -650,35 +664,36 @@ void ShaderResourceLayoutD3D12::D3D12Resource::BindResource(IDeviceObject* else { if (DstRes.pObject != nullptr && GetVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) - LOG_ERROR_MESSAGE( "Shader variable '", Attribs.Name, "' in shader '", ParentResLayout.GetShaderName(), "' is not dynamic but is being reset to null. This is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic if you need to bind another resource." ); + LOG_ERROR_MESSAGE("Shader variable '", Attribs.Name, "' in shader '", ParentResLayout.GetShaderName(), "' is not dynamic but is being reset to null. This is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic if you need to bind another resource."); DstRes = ShaderResourceCacheD3D12::Resource{}; if (ValidSamplerAssigned()) { - auto& Sam = ParentResLayout.GetAssignedSampler(*this); - D3D12_CPU_DESCRIPTOR_HANDLE NullHandle = {0}; - auto SamplerArrInd = Sam.Attribs.BindCount > 1 ? ArrayIndex : 0; - auto& DstSam = ResourceCache.GetRootTable(Sam.RootIndex).GetResource(Sam.OffsetFromTableStart + SamplerArrInd, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, ParentResLayout.m_pResources->GetShaderType()); + auto& Sam = ParentResLayout.GetAssignedSampler(*this); + D3D12_CPU_DESCRIPTOR_HANDLE NullHandle = {0}; + auto SamplerArrInd = Sam.Attribs.BindCount > 1 ? ArrayIndex : 0; + auto& DstSam = ResourceCache.GetRootTable(Sam.RootIndex).GetResource(Sam.OffsetFromTableStart + SamplerArrInd, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, ParentResLayout.m_pResources->GetShaderType()); if (DstSam.pObject != nullptr && Sam.GetVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) - LOG_ERROR_MESSAGE( "Sampler variable '", Sam.Attribs.Name, "' in shader '", ParentResLayout.GetShaderName(), "' is not dynamic but is being reset to null. This is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic if you need to bind another sampler." ); + LOG_ERROR_MESSAGE("Sampler variable '", Sam.Attribs.Name, "' in shader '", ParentResLayout.GetShaderName(), "' is not dynamic but is being reset to null. This is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic if you need to bind another sampler."); DstSam = ShaderResourceCacheD3D12::Resource{}; } } } -bool ShaderResourceLayoutD3D12::D3D12Resource::IsBound(Uint32 ArrayIndex, const ShaderResourceCacheD3D12& ResourceCache)const +bool ShaderResourceLayoutD3D12::D3D12Resource::IsBound(Uint32 ArrayIndex, const ShaderResourceCacheD3D12& ResourceCache) const { VERIFY_EXPR(ArrayIndex < Attribs.BindCount); if (RootIndex < ResourceCache.GetNumRootTables()) { const auto& RootTable = ResourceCache.GetRootTable(RootIndex); - if(OffsetFromTableStart + ArrayIndex < RootTable.GetSize()) + if (OffsetFromTableStart + ArrayIndex < RootTable.GetSize()) { - const auto& CachedRes = RootTable.GetResource(OffsetFromTableStart + ArrayIndex, - GetResType() == CachedResourceType::Sampler ? D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER : D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, - ParentResLayout.m_pResources->GetShaderType()); - if( CachedRes.pObject != nullptr ) + const auto& CachedRes = + RootTable.GetResource(OffsetFromTableStart + ArrayIndex, + GetResType() == CachedResourceType::Sampler ? D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER : D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + ParentResLayout.m_pResources->GetShaderType()); + if (CachedRes.pObject != nullptr) { VERIFY(CachedRes.CPUDescriptorHandle.ptr != 0 || CachedRes.pObject.RawPtr()->GetDesc().Usage == USAGE_DYNAMIC, "No relevant descriptor handle"); return true; @@ -690,7 +705,7 @@ bool ShaderResourceLayoutD3D12::D3D12Resource::IsBound(Uint32 ArrayIndex, const } -void ShaderResourceLayoutD3D12::CopyStaticResourceDesriptorHandles(const ShaderResourceCacheD3D12& SrcCache, const ShaderResourceLayoutD3D12& DstLayout, ShaderResourceCacheD3D12& DstCache)const +void ShaderResourceLayoutD3D12::CopyStaticResourceDesriptorHandles(const ShaderResourceCacheD3D12& SrcCache, const ShaderResourceLayoutD3D12& DstLayout, ShaderResourceCacheD3D12& DstCache) const { // Static shader resources are stored as follows: // CBVs at root index D3D12_DESCRIPTOR_RANGE_TYPE_CBV, @@ -700,27 +715,27 @@ void ShaderResourceLayoutD3D12::CopyStaticResourceDesriptorHandles(const ShaderR // Every resource is stored at offset that equals resource bind point auto CbvSrvUavCount = DstLayout.GetCbvSrvUavCount(SHADER_RESOURCE_VARIABLE_TYPE_STATIC); - VERIFY(GetCbvSrvUavCount(SHADER_RESOURCE_VARIABLE_TYPE_STATIC) == CbvSrvUavCount, "Number of static resources in the source cache (", GetCbvSrvUavCount(SHADER_RESOURCE_VARIABLE_TYPE_STATIC), ") is not consistent with the number of static resources in destination cache (", CbvSrvUavCount, ")" ); + VERIFY(GetCbvSrvUavCount(SHADER_RESOURCE_VARIABLE_TYPE_STATIC) == CbvSrvUavCount, "Number of static resources in the source cache (", GetCbvSrvUavCount(SHADER_RESOURCE_VARIABLE_TYPE_STATIC), ") is not consistent with the number of static resources in destination cache (", CbvSrvUavCount, ")"); auto& DstBoundDynamicCBsCounter = DstCache.GetBoundDynamicCBsCounter(); - for(Uint32 r=0; r < CbvSrvUavCount; ++r) + for (Uint32 r = 0; r < CbvSrvUavCount; ++r) { // Get resource attributes - const auto& res = DstLayout.GetSrvCbvUav(SHADER_RESOURCE_VARIABLE_TYPE_STATIC, r); - auto RangeType = GetDescriptorRangeType(res.GetResType()); - for(Uint32 ArrInd = 0; ArrInd < res.Attribs.BindCount; ++ArrInd) + const auto& res = DstLayout.GetSrvCbvUav(SHADER_RESOURCE_VARIABLE_TYPE_STATIC, r); + auto RangeType = GetDescriptorRangeType(res.GetResType()); + for (Uint32 ArrInd = 0; ArrInd < res.Attribs.BindCount; ++ArrInd) { auto BindPoint = res.Attribs.BindPoint + ArrInd; - // Source resource in the static resource cache is in the root table at index RangeType, at offset BindPoint + // Source resource in the static resource cache is in the root table at index RangeType, at offset BindPoint // D3D12_DESCRIPTOR_RANGE_TYPE_SRV = 0, // D3D12_DESCRIPTOR_RANGE_TYPE_UAV = 1 // D3D12_DESCRIPTOR_RANGE_TYPE_CBV = 2 const auto& SrcRes = SrcCache.GetRootTable(RangeType).GetResource(BindPoint, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, m_pResources->GetShaderType()); - if( !SrcRes.pObject ) - LOG_ERROR_MESSAGE( "No resource is assigned to static shader variable '", res.Attribs.GetPrintName(ArrInd), "' in shader '", GetShaderName(), "'." ); + if (!SrcRes.pObject) + LOG_ERROR_MESSAGE("No resource is assigned to static shader variable '", res.Attribs.GetPrintName(ArrInd), "' in shader '", GetShaderName(), "'."); // Destination resource is at the root index and offset defined by the resource layout auto& DstRes = DstCache.GetRootTable(res.RootIndex).GetResource(res.OffsetFromTableStart + ArrInd, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, m_pResources->GetShaderType()); - - if(DstRes.pObject != SrcRes.pObject) + + if (DstRes.pObject != SrcRes.pObject) { VERIFY(DstRes.pObject == nullptr, "Static resource has already been initialized, and the resource to be assigned from the shader does not match previously assigned resource"); @@ -757,33 +772,33 @@ void ShaderResourceLayoutD3D12::CopyStaticResourceDesriptorHandles(const ShaderR } } - if(res.ValidSamplerAssigned()) + if (res.ValidSamplerAssigned()) { const auto& SamInfo = DstLayout.GetAssignedSampler(res); //VERIFY(!SamInfo.Attribs.IsStaticSampler(), "Static samplers should never be assigned space in the cache"); - + VERIFY(SamInfo.Attribs.IsValidBindPoint(), "Sampler bind point must be valid"); VERIFY_EXPR(SamInfo.Attribs.BindCount == res.Attribs.BindCount || SamInfo.Attribs.BindCount == 1); } } auto SamplerCount = DstLayout.GetSamplerCount(SHADER_RESOURCE_VARIABLE_TYPE_STATIC); - VERIFY(GetSamplerCount(SHADER_RESOURCE_VARIABLE_TYPE_STATIC) == SamplerCount, "Number of static-type samplers in the source cache (", GetSamplerCount(SHADER_RESOURCE_VARIABLE_TYPE_STATIC), ") is not consistent with the number of static-type samplers in destination cache (", SamplerCount, ")" ); - for(Uint32 s=0; s < SamplerCount; ++s) + VERIFY(GetSamplerCount(SHADER_RESOURCE_VARIABLE_TYPE_STATIC) == SamplerCount, "Number of static-type samplers in the source cache (", GetSamplerCount(SHADER_RESOURCE_VARIABLE_TYPE_STATIC), ") is not consistent with the number of static-type samplers in destination cache (", SamplerCount, ")"); + for (Uint32 s = 0; s < SamplerCount; ++s) { const auto& SamInfo = DstLayout.GetSampler(SHADER_RESOURCE_VARIABLE_TYPE_STATIC, s); - for(Uint32 ArrInd = 0; ArrInd < SamInfo.Attribs.BindCount; ++ArrInd) + for (Uint32 ArrInd = 0; ArrInd < SamInfo.Attribs.BindCount; ++ArrInd) { auto BindPoint = SamInfo.Attribs.BindPoint + ArrInd; - // Source sampler in the static resource cache is in the root table at index 3 - // (D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER = 3), at offset BindPoint + // Source sampler in the static resource cache is in the root table at index 3 + // (D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER = 3), at offset BindPoint const auto& SrcSampler = SrcCache.GetRootTable(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER).GetResource(BindPoint, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, m_pResources->GetShaderType()); - if( !SrcSampler.pObject ) - LOG_ERROR_MESSAGE( "No sampler assigned to static shader variable '", SamInfo.Attribs.GetPrintName(ArrInd), "' in shader '", GetShaderName(), "'." ); + if (!SrcSampler.pObject) + LOG_ERROR_MESSAGE("No sampler assigned to static shader variable '", SamInfo.Attribs.GetPrintName(ArrInd), "' in shader '", GetShaderName(), "'."); auto& DstSampler = DstCache.GetRootTable(SamInfo.RootIndex).GetResource(SamInfo.OffsetFromTableStart + ArrInd, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, m_pResources->GetShaderType()); - - if(DstSampler.pObject != SrcSampler.pObject) + + if (DstSampler.pObject != SrcSampler.pObject) { VERIFY(DstSampler.pObject == nullptr, "Static-type sampler has already been initialized, and the sampler to be assigned from the shader does not match previously assigned resource"); @@ -810,12 +825,12 @@ void ShaderResourceLayoutD3D12::CopyStaticResourceDesriptorHandles(const ShaderR #ifdef DEVELOPMENT -bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12& ResourceCache)const +bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12& ResourceCache) const { bool BindingsOK = true; - for (SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType+1)) + for (SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType + 1)) { - for (Uint32 r=0; r < GetCbvSrvUavCount(VarType); ++r) + for (Uint32 r = 0; r < GetCbvSrvUavCount(VarType); ++r) { const auto& res = GetSrvCbvUav(VarType, r); VERIFY(res.GetVariableType() == VarType, "Unexpected variable type"); @@ -828,14 +843,14 @@ bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12 else VERIFY(CachedRes.Type == CachedResourceType::Unknown, "Unexpected cached resource types"); - if (!CachedRes.pObject || - // Dynamic buffers do not have CPU descriptor handle as they do not keep D3D12 buffer, and space is allocated from the GPU ring buffer - CachedRes.CPUDescriptorHandle.ptr == 0 && !(CachedRes.Type==CachedResourceType::CBV && CachedRes.pObject.RawPtr()->GetDesc().Usage == USAGE_DYNAMIC) ) + if (!CachedRes.pObject || + // Dynamic buffers do not have CPU descriptor handle as they do not keep D3D12 buffer, and space is allocated from the GPU ring buffer + CachedRes.CPUDescriptorHandle.ptr == 0 && !(CachedRes.Type == CachedResourceType::CBV && CachedRes.pObject.RawPtr()->GetDesc().Usage == USAGE_DYNAMIC)) { - LOG_ERROR_MESSAGE( "No resource is bound to ", GetShaderVariableTypeLiteralName(res.GetVariableType()), " variable '", res.Attribs.GetPrintName(ArrInd), "' in shader '", GetShaderName(), "'" ); + LOG_ERROR_MESSAGE("No resource is bound to ", GetShaderVariableTypeLiteralName(res.GetVariableType()), " variable '", res.Attribs.GetPrintName(ArrInd), "' in shader '", GetShaderName(), "'"); BindingsOK = false; } - + if (res.Attribs.BindCount > 1 && res.ValidSamplerAssigned()) { // Verify that if single sampler is used for all texture array elements, all samplers set in the resource views are consistent @@ -849,13 +864,13 @@ bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12 const auto* pSampler = pTexView->GetSampler(); if (pSampler != nullptr && CachedSampler.pObject != nullptr && CachedSampler.pObject != pSampler) { - LOG_ERROR_MESSAGE( "All elements of texture array '", res.Attribs.Name, "' in shader '", GetShaderName(), "' share the same sampler. However, the sampler set in view for element ", ArrInd, " does not match bound sampler. This may cause incorrect behavior on GL platform." ); + LOG_ERROR_MESSAGE("All elements of texture array '", res.Attribs.Name, "' in shader '", GetShaderName(), "' share the same sampler. However, the sampler set in view for element ", ArrInd, " does not match bound sampler. This may cause incorrect behavior on GL platform."); } } } } -#ifdef _DEBUG +# ifdef _DEBUG { const auto ShdrVisibleHeapCPUDescriptorHandle = ResourceCache.GetShaderVisibleTableCPUDescriptorHandle(res.RootIndex, res.OffsetFromTableStart + ArrInd); if (ResourceCache.DbgGetContentType() == ShaderResourceCacheD3D12::DbgCacheContentType::StaticShaderResources) @@ -881,16 +896,16 @@ bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12 UNEXPECTED("Unknown content type"); } } -#endif +# endif } if (res.ValidSamplerAssigned()) { - VERIFY(res.GetResType() == CachedResourceType::TexSRV, "Sampler can only be assigned to a texture SRV" ); + VERIFY(res.GetResType() == CachedResourceType::TexSRV, "Sampler can only be assigned to a texture SRV"); const auto& SamInfo = GetAssignedSampler(res); //VERIFY(!SamInfo.Attribs.IsStaticSampler(), "Static samplers should never be assigned space in the cache" ); VERIFY(SamInfo.Attribs.IsValidBindPoint(), "Sampler bind point must be valid"); - + for (Uint32 ArrInd = 0; ArrInd < SamInfo.Attribs.BindCount; ++ArrInd) { const auto& CachedSampler = ResourceCache.GetRootTable(SamInfo.RootIndex).GetResource(SamInfo.OffsetFromTableStart + ArrInd, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, m_pResources->GetShaderType()); @@ -904,7 +919,7 @@ bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12 BindingsOK = false; } -#ifdef _DEBUG +# ifdef _DEBUG { const auto ShdrVisibleHeapCPUDescriptorHandle = ResourceCache.GetShaderVisibleTableCPUDescriptorHandle(SamInfo.RootIndex, SamInfo.OffsetFromTableStart + ArrInd); if (ResourceCache.DbgGetContentType() == ShaderResourceCacheD3D12::DbgCacheContentType::StaticShaderResources) @@ -923,16 +938,16 @@ bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12 UNEXPECTED("Unknown content type"); } } -#endif +# endif } } } - for (Uint32 s=0; s < GetSamplerCount(VarType); ++s) + for (Uint32 s = 0; s < GetSamplerCount(VarType); ++s) { const auto& sam = GetSampler(VarType, s); VERIFY(sam.GetVariableType() == VarType, "Unexpected sampler variable type"); - + for (Uint32 ArrInd = 0; ArrInd < sam.Attribs.BindCount; ++ArrInd) { const auto& CachedSampler = ResourceCache.GetRootTable(sam.RootIndex).GetResource(sam.OffsetFromTableStart + ArrInd, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, m_pResources->GetShaderType()); @@ -942,7 +957,7 @@ bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12 VERIFY(CachedSampler.Type == CachedResourceType::Unknown, "Unexpected cached sampler type"); if (!CachedSampler.pObject || CachedSampler.CPUDescriptorHandle.ptr == 0) { - LOG_ERROR_MESSAGE( "No sampler is bound to sampler variable '", sam.Attribs.GetPrintName(ArrInd), "' in shader '", GetShaderName(), "'" ); + LOG_ERROR_MESSAGE("No sampler is bound to sampler variable '", sam.Attribs.GetPrintName(ArrInd), "' in shader '", GetShaderName(), "'"); BindingsOK = false; } } @@ -953,4 +968,4 @@ bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12 } #endif -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderResourcesD3D12.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderResourcesD3D12.cpp index 75acee70..a3602e8f 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderResourcesD3D12.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderResourcesD3D12.cpp @@ -38,19 +38,20 @@ ShaderResourcesD3D12::ShaderResourcesD3D12(ID3DBlob* pShaderBytecode, const Shad class NewResourceHandler { public: + // clang-format off void OnNewCB (const D3DShaderResourceAttribs& CBAttribs) {} void OnNewTexUAV (const D3DShaderResourceAttribs& TexUAV) {} void OnNewBuffUAV(const D3DShaderResourceAttribs& BuffUAV) {} void OnNewBuffSRV(const D3DShaderResourceAttribs& BuffSRV) {} void OnNewSampler(const D3DShaderResourceAttribs& SamplerAttribs){} void OnNewTexSRV (const D3DShaderResourceAttribs& TexAttribs) {} + // clang-format on }; Initialize( pShaderBytecode, NewResourceHandler{}, ShdrDesc.Name, - CombinedSamplerSuffix - ); + CombinedSamplerSuffix); } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp index 851d0fdd..45b7f479 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp @@ -29,14 +29,14 @@ namespace Diligent { -size_t ShaderVariableManagerD3D12::GetRequiredMemorySize(const ShaderResourceLayoutD3D12& Layout, - const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - Uint32& NumVariables) +size_t ShaderVariableManagerD3D12::GetRequiredMemorySize(const ShaderResourceLayoutD3D12& Layout, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes, + Uint32& NumVariables) { - NumVariables = 0; + NumVariables = 0; Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); - for (SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType+1)) + for (SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType + 1)) { if (IsAllowedType(VarType, AllowedTypeBits)) { @@ -45,55 +45,56 @@ size_t ShaderVariableManagerD3D12::GetRequiredMemorySize(const ShaderResourceLay NumVariables += Layout.GetSamplerCount(VarType); } } - - return NumVariables*sizeof(ShaderVariableD3D12Impl); + + return NumVariables * sizeof(ShaderVariableD3D12Impl); } // Creates shader variable for every resource from SrcLayout whose type is one AllowedVarTypes -ShaderVariableManagerD3D12::ShaderVariableManagerD3D12(IObject& Owner, - const ShaderResourceLayoutD3D12& SrcLayout, - IMemoryAllocator& Allocator, - const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - ShaderResourceCacheD3D12& ResourceCache) : +ShaderVariableManagerD3D12::ShaderVariableManagerD3D12(IObject& Owner, + const ShaderResourceLayoutD3D12& SrcLayout, + IMemoryAllocator& Allocator, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes, + ShaderResourceCacheD3D12& ResourceCache) : + // clang-format off m_Owner {Owner}, m_ResourceCache {ResourceCache} #ifdef _DEBUG , m_DbgAllocator {Allocator} #endif - +// clang-format on { const Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); VERIFY_EXPR(m_NumVariables == 0); auto MemSize = GetRequiredMemorySize(SrcLayout, AllowedVarTypes, NumAllowedTypes, m_NumVariables); - - if(m_NumVariables == 0) + + if (m_NumVariables == 0) return; - + auto* pRawMem = ALLOCATE_RAW(Allocator, "Raw memory buffer for shader variables", MemSize); - m_pVariables = reinterpret_cast(pRawMem); + m_pVariables = reinterpret_cast(pRawMem); Uint32 VarInd = 0; - for (SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType+1)) + for (SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType + 1)) { if (!IsAllowedType(VarType, AllowedTypeBits)) continue; Uint32 NumResources = SrcLayout.GetCbvSrvUavCount(VarType); - for (Uint32 r=0; r < NumResources; ++r) + for (Uint32 r = 0; r < NumResources; ++r) { const auto& SrcRes = SrcLayout.GetSrvCbvUav(VarType, r); - ::new (m_pVariables + VarInd) ShaderVariableD3D12Impl(*this, SrcRes); + ::new (m_pVariables + VarInd) ShaderVariableD3D12Impl{*this, SrcRes}; ++VarInd; } if (SrcLayout.IsUsingSeparateSamplers()) { Uint32 NumSamplers = SrcLayout.GetSamplerCount(VarType); - for (Uint32 r=0; r < NumSamplers; ++r) + for (Uint32 r = 0; r < NumSamplers; ++r) { const auto& SrcSampler = SrcLayout.GetSampler(VarType, r); - ::new (m_pVariables + VarInd) ShaderVariableD3D12Impl(*this, SrcSampler); + ::new (m_pVariables + VarInd) ShaderVariableD3D12Impl{*this, SrcSampler}; ++VarInd; } } @@ -106,13 +107,13 @@ ShaderVariableManagerD3D12::~ShaderVariableManagerD3D12() VERIFY(m_pVariables == nullptr, "Destroy() has not been called"); } -void ShaderVariableManagerD3D12::Destroy(IMemoryAllocator &Allocator) +void ShaderVariableManagerD3D12::Destroy(IMemoryAllocator& Allocator) { VERIFY(&m_DbgAllocator == &Allocator, "Incosistent alloctor"); - if(m_pVariables != nullptr) + if (m_pVariables != nullptr) { - for(Uint32 v=0; v < m_NumVariables; ++v) + for (Uint32 v = 0; v < m_NumVariables; ++v) m_pVariables[v].~ShaderVariableD3D12Impl(); Allocator.Free(m_pVariables); m_pVariables = nullptr; @@ -166,41 +167,41 @@ Uint32 ShaderVariableManagerD3D12::GetVariableIndex(const ShaderVariableD3D12Imp } } -void ShaderVariableManagerD3D12::BindResources( IResourceMapping* pResourceMapping, Uint32 Flags) +void ShaderVariableManagerD3D12::BindResources(IResourceMapping* pResourceMapping, Uint32 Flags) { DEV_CHECK_ERR(pResourceMapping != nullptr, "Failed to bind resources: resource mapping is null"); - - if ( (Flags & BIND_SHADER_RESOURCES_UPDATE_ALL) == 0 ) + + if ((Flags & BIND_SHADER_RESOURCES_UPDATE_ALL) == 0) Flags |= BIND_SHADER_RESOURCES_UPDATE_ALL; - for (Uint32 v=0; v < m_NumVariables; ++v) + for (Uint32 v = 0; v < m_NumVariables; ++v) { - auto &Var = m_pVariables[v]; + auto& Var = m_pVariables[v]; const auto& Res = Var.m_Resource; - - if ( (Flags & (1 << Res.GetVariableType())) == 0 ) + + if ((Flags & (1 << Res.GetVariableType())) == 0) continue; for (Uint32 ArrInd = 0; ArrInd < Res.Attribs.BindCount; ++ArrInd) { - if( (Flags & BIND_SHADER_RESOURCES_KEEP_EXISTING) && Res.IsBound(ArrInd, m_ResourceCache) ) + if ((Flags & BIND_SHADER_RESOURCES_KEEP_EXISTING) && Res.IsBound(ArrInd, m_ResourceCache)) continue; RefCntAutoPtr pObj; VERIFY_EXPR(pResourceMapping != nullptr); - pResourceMapping->GetResource( Res.Attribs.Name, &pObj, ArrInd ); - if ( pObj ) + pResourceMapping->GetResource(Res.Attribs.Name, &pObj, ArrInd); + if (pObj) { // Call non-virtual function Res.BindResource(pObj, ArrInd, m_ResourceCache); } else { - if( (Flags & BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED) && !Res.IsBound(ArrInd, m_ResourceCache) ) - LOG_ERROR_MESSAGE( "Unable to bind resource to shader variable '", Res.Attribs.GetPrintName(ArrInd), "': resource is not found in the resource mapping" ); + if ((Flags & BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED) && !Res.IsBound(ArrInd, m_ResourceCache)) + LOG_ERROR_MESSAGE("Unable to bind resource to shader variable '", Res.Attribs.GetPrintName(ArrInd), "': resource is not found in the resource mapping"); } } } } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/SwapChainD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/SwapChainD3D12Impl.cpp index 0d24c669..86c2a068 100644 --- a/Graphics/GraphicsEngineD3D12/src/SwapChainD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/SwapChainD3D12Impl.cpp @@ -33,11 +33,12 @@ namespace Diligent { SwapChainD3D12Impl::SwapChainD3D12Impl(IReferenceCounters* pRefCounters, - const SwapChainDesc& SCDesc, + const SwapChainDesc& SCDesc, const FullScreenModeDesc& FSDesc, - RenderDeviceD3D12Impl* pRenderDeviceD3D12, - DeviceContextD3D12Impl* pDeviceContextD3D12, - void* pNativeWndHandle) : + RenderDeviceD3D12Impl* pRenderDeviceD3D12, + DeviceContextD3D12Impl* pDeviceContextD3D12, + void* pNativeWndHandle) : + // clang-format off TSwapChainBase { pRefCounters, @@ -48,12 +49,14 @@ SwapChainD3D12Impl::SwapChainD3D12Impl(IReferenceCounters* pRefCounters, pNativeWndHandle }, m_pBackBufferRTV{STD_ALLOCATOR_RAW_MEM(RefCntAutoPtr, GetRawAllocator(), "Allocator for vector>")} +// clang-format on { - pRenderDeviceD3D12->LockCmdQueueAndRun(0, - [this](ICommandQueueD3D12 *pCmdQueue) + pRenderDeviceD3D12->LockCmdQueueAndRun( + 0, + [this](ICommandQueueD3D12* pCmdQueue) // { CreateDXGISwapChain(pCmdQueue->GetD3D12CommandQueue()); - } + } // ); InitBuffersAndViews(); } @@ -67,16 +70,16 @@ void SwapChainD3D12Impl::InitBuffersAndViews() m_pBackBufferRTV.resize(m_SwapChainDesc.BufferCount); for (Uint32 backbuff = 0; backbuff < m_SwapChainDesc.BufferCount; ++backbuff) { - CComPtr pBackBuffer; - auto hr = m_pSwapChain->GetBuffer(backbuff, __uuidof(pBackBuffer), reinterpret_cast( static_cast(&pBackBuffer) )); - if(FAILED(hr)) - LOG_ERROR_AND_THROW("Failed to get back buffer ", backbuff," from the swap chain"); + CComPtr pBackBuffer; + auto hr = m_pSwapChain->GetBuffer(backbuff, __uuidof(pBackBuffer), reinterpret_cast(static_cast(&pBackBuffer))); + if (FAILED(hr)) + LOG_ERROR_AND_THROW("Failed to get back buffer ", backbuff, " from the swap chain"); hr = pBackBuffer->SetName(L"Main back buffer"); VERIFY_EXPR(SUCCEEDED(hr)); TextureDesc BackBufferDesc; - String Name = "Main back buffer "; + String Name = "Main back buffer "; Name += std::to_string(backbuff); BackBufferDesc.Name = Name.c_str(); @@ -104,56 +107,56 @@ void SwapChainD3D12Impl::InitBuffersAndViews() DepthBufferDesc.ClearValue.Format = DepthBufferDesc.Format; DepthBufferDesc.ClearValue.DepthStencil.Depth = m_SwapChainDesc.DefaultDepthValue; DepthBufferDesc.ClearValue.DepthStencil.Stencil = m_SwapChainDesc.DefaultStencilValue; - DepthBufferDesc.Name = "Main depth buffer"; + DepthBufferDesc.Name = "Main depth buffer"; RefCntAutoPtr pDepthBufferTex; - m_pRenderDevice->CreateTexture(DepthBufferDesc, nullptr, static_cast(&pDepthBufferTex) ); - auto pDSV = pDepthBufferTex->GetDefaultView(TEXTURE_VIEW_DEPTH_STENCIL); + m_pRenderDevice->CreateTexture(DepthBufferDesc, nullptr, static_cast(&pDepthBufferTex)); + auto pDSV = pDepthBufferTex->GetDefaultView(TEXTURE_VIEW_DEPTH_STENCIL); m_pDepthBufferDSV = RefCntAutoPtr(pDSV, IID_TextureViewD3D12); } } -IMPLEMENT_QUERY_INTERFACE( SwapChainD3D12Impl, IID_SwapChainD3D12, TSwapChainBase ) +IMPLEMENT_QUERY_INTERFACE(SwapChainD3D12Impl, IID_SwapChainD3D12, TSwapChainBase) void SwapChainD3D12Impl::Present(Uint32 SyncInterval) { #if PLATFORM_UNIVERSAL_WINDOWS - SyncInterval = 1; // Interval 0 is not supported on Windows Phone + SyncInterval = 1; // Interval 0 is not supported on Windows Phone #endif auto pDeviceContext = m_wpDeviceContext.Lock(); if (!pDeviceContext) { - LOG_ERROR_MESSAGE( "Immediate context has been released" ); + LOG_ERROR_MESSAGE("Immediate context has been released"); return; } auto* pImmediateCtxD3D12 = pDeviceContext.RawPtr(); - auto& CmdCtx = pImmediateCtxD3D12->GetCmdContext(); + auto& CmdCtx = pImmediateCtxD3D12->GetCmdContext(); auto* pBackBuffer = ValidatedCast(GetCurrentBackBufferRTV()->GetTexture()); CmdCtx.TransitionResource(pBackBuffer, RESOURCE_STATE_PRESENT); pImmediateCtxD3D12->Flush(); - auto hr = m_pSwapChain->Present( SyncInterval, 0 ); + auto hr = m_pSwapChain->Present(SyncInterval, 0); VERIFY(SUCCEEDED(hr), "Present failed"); if (m_SwapChainDesc.IsPrimary) { pImmediateCtxD3D12->FinishFrame(); - auto* pDeviceD3D12 = ValidatedCast( pImmediateCtxD3D12->GetDevice() ); + auto* pDeviceD3D12 = ValidatedCast(pImmediateCtxD3D12->GetDevice()); pDeviceD3D12->ReleaseStaleResources(); } #if 0 -#if PLATFORM_UNIVERSAL_WINDOWS +# if PLATFORM_UNIVERSAL_WINDOWS // A successful Present call for DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL SwapChains unbinds // backbuffer 0 from all GPU writeable bind points. // We need to rebind all render targets to make sure that // the back buffer is not unbound pImmediateCtxD3D12->CommitRenderTargets(); -#endif +# endif #endif } @@ -168,14 +171,15 @@ void SwapChainD3D12Impl::UpdateSwapChain(bool CreateNew) VERIFY(pDeviceContext, "Immediate context has been released"); if (pDeviceContext) { - RenderDeviceD3D12Impl *pDeviceD3D12 = m_pRenderDevice.RawPtr(); + RenderDeviceD3D12Impl* pDeviceD3D12 = m_pRenderDevice.RawPtr(); pDeviceContext->Flush(); try { auto* pImmediateCtxD3D12 = pDeviceContext.RawPtr(); + std::vector pBackBufferRTVs(m_pBackBufferRTV.size()); - for(size_t i=0; i < m_pBackBufferRTV.size(); ++i) + for (size_t i = 0; i < m_pBackBufferRTV.size(); ++i) pBackBufferRTVs[i] = m_pBackBufferRTV[i]; bool RebindRenderTargets = UnbindRenderTargets(pImmediateCtxD3D12, pBackBufferRTVs.data(), static_cast(m_pBackBufferRTV.size()), m_pDepthBufferDSV); @@ -187,15 +191,14 @@ void SwapChainD3D12Impl::UpdateSwapChain(bool CreateNew) // m_pBackBufferRTV[] pDeviceD3D12->IdleGPU(); - if(CreateNew) + if (CreateNew) { m_pSwapChain.Release(); - m_pRenderDevice.RawPtr()->LockCmdQueueAndRun(0, - [this](ICommandQueueD3D12* pCmdQueue) - { + m_pRenderDevice.RawPtr()->LockCmdQueueAndRun( + 0, + [this](ICommandQueueD3D12* pCmdQueue) { CreateDXGISwapChain(pCmdQueue->GetD3D12CommandQueue()); - } - ); + }); } else { @@ -203,9 +206,9 @@ void SwapChainD3D12Impl::UpdateSwapChain(bool CreateNew) memset(&SCDes, 0, sizeof(SCDes)); m_pSwapChain->GetDesc(&SCDes); CHECK_D3D_RESULT_THROW(m_pSwapChain->ResizeBuffers(SCDes.BufferCount, m_SwapChainDesc.Width, - m_SwapChainDesc.Height, SCDes.BufferDesc.Format, - SCDes.Flags), - "Failed to resize the DXGI swap chain"); + m_SwapChainDesc.Height, SCDes.BufferDesc.Format, + SCDes.Flags), + "Failed to resize the DXGI swap chain"); } InitBuffersAndViews(); @@ -217,19 +220,19 @@ void SwapChainD3D12Impl::UpdateSwapChain(bool CreateNew) pDeviceContext->SetViewports(1, nullptr, 0, 0); } } - catch (const std::runtime_error &) + catch (const std::runtime_error&) { LOG_ERROR("Failed to resize the swap chain"); } } } -void SwapChainD3D12Impl::Resize( Uint32 NewWidth, Uint32 NewHeight ) +void SwapChainD3D12Impl::Resize(Uint32 NewWidth, Uint32 NewHeight) { - if( TSwapChainBase::Resize(NewWidth, NewHeight) ) + if (TSwapChainBase::Resize(NewWidth, NewHeight)) { UpdateSwapChain(false); } } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/TextureD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/TextureD3D12Impl.cpp index 61cdc181..331f8a03 100644 --- a/Graphics/GraphicsEngineD3D12/src/TextureD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/TextureD3D12Impl.cpp @@ -39,20 +39,23 @@ namespace Diligent DXGI_FORMAT GetClearFormat(DXGI_FORMAT Fmt, D3D12_RESOURCE_FLAGS Flags) { - if( Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL ) + if (Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) { switch (Fmt) { + // clang-format off case DXGI_FORMAT_R32_TYPELESS: return DXGI_FORMAT_D32_FLOAT; case DXGI_FORMAT_R16_TYPELESS: return DXGI_FORMAT_D16_UNORM; case DXGI_FORMAT_R24G8_TYPELESS: return DXGI_FORMAT_D24_UNORM_S8_UINT; case DXGI_FORMAT_R32G8X24_TYPELESS: return DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + // clang-format on } } else if (Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) { switch (Fmt) { + // clang-format off case DXGI_FORMAT_R32G32B32A32_TYPELESS: return DXGI_FORMAT_R32G32B32A32_FLOAT; case DXGI_FORMAT_R32G32B32_TYPELESS: return DXGI_FORMAT_R32G32B32_FLOAT; case DXGI_FORMAT_R16G16B16A16_TYPELESS: return DXGI_FORMAT_R16G16B16A16_FLOAT; @@ -65,28 +68,29 @@ DXGI_FORMAT GetClearFormat(DXGI_FORMAT Fmt, D3D12_RESOURCE_FLAGS Flags) case DXGI_FORMAT_R16_TYPELESS: return DXGI_FORMAT_R16_FLOAT; case DXGI_FORMAT_R8_TYPELESS: return DXGI_FORMAT_R8_UNORM; case DXGI_FORMAT_B8G8R8A8_TYPELESS: return DXGI_FORMAT_B8G8R8A8_UNORM; - case DXGI_FORMAT_B8G8R8X8_TYPELESS: return DXGI_FORMAT_B8G8R8X8_UNORM; + case DXGI_FORMAT_B8G8R8X8_TYPELESS: return DXGI_FORMAT_B8G8R8X8_UNORM; + // clang-format on } } return Fmt; } -D3D12_RESOURCE_DESC TextureD3D12Impl :: GetD3D12TextureDesc()const +D3D12_RESOURCE_DESC TextureD3D12Impl ::GetD3D12TextureDesc() const { D3D12_RESOURCE_DESC Desc = {}; - Desc.Alignment = 0; + Desc.Alignment = 0; if (m_Desc.Type == RESOURCE_DIM_TEX_1D_ARRAY || m_Desc.Type == RESOURCE_DIM_TEX_2D_ARRAY || m_Desc.Type == RESOURCE_DIM_TEX_CUBE || m_Desc.Type == RESOURCE_DIM_TEX_CUBE_ARRAY) - Desc.DepthOrArraySize = (UINT16)m_Desc.ArraySize; - else if (m_Desc.Type == RESOURCE_DIM_TEX_3D ) + Desc.DepthOrArraySize = (UINT16)m_Desc.ArraySize; + else if (m_Desc.Type == RESOURCE_DIM_TEX_3D) Desc.DepthOrArraySize = (UINT16)m_Desc.Depth; else Desc.DepthOrArraySize = 1; if (m_Desc.Type == RESOURCE_DIM_TEX_1D || m_Desc.Type == RESOURCE_DIM_TEX_1D_ARRAY) - Desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE1D; + Desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE1D; else if (m_Desc.Type == RESOURCE_DIM_TEX_2D || m_Desc.Type == RESOURCE_DIM_TEX_2D_ARRAY || m_Desc.Type == RESOURCE_DIM_TEX_CUBE || m_Desc.Type == RESOURCE_DIM_TEX_CUBE_ARRAY) - Desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + Desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; else if (m_Desc.Type == RESOURCE_DIM_TEX_3D) Desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; else @@ -99,7 +103,7 @@ D3D12_RESOURCE_DESC TextureD3D12Impl :: GetD3D12TextureDesc()const Desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; if (m_Desc.BindFlags & BIND_DEPTH_STENCIL) Desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; - if ((m_Desc.BindFlags & BIND_UNORDERED_ACCESS) || (m_Desc.MiscFlags & MISC_TEXTURE_FLAG_GENERATE_MIPS) ) + if ((m_Desc.BindFlags & BIND_UNORDERED_ACCESS) || (m_Desc.MiscFlags & MISC_TEXTURE_FLAG_GENERATE_MIPS)) Desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; if ((m_Desc.BindFlags & BIND_SHADER_RESOURCE) == 0 && (m_Desc.BindFlags & BIND_DEPTH_STENCIL) != 0) Desc.Flags |= D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; @@ -111,20 +115,20 @@ D3D12_RESOURCE_DESC TextureD3D12Impl :: GetD3D12TextureDesc()const Desc.Format = Format; Desc.Height = UINT{m_Desc.Height}; - Desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; - Desc.MipLevels = static_cast(m_Desc.MipLevels); - Desc.SampleDesc.Count = m_Desc.SampleCount; - Desc.SampleDesc.Quality = 0; + Desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + Desc.MipLevels = static_cast(m_Desc.MipLevels); + Desc.SampleDesc.Count = m_Desc.SampleCount; + Desc.SampleDesc.Quality = 0; Desc.Width = UINT64{m_Desc.Width}; return Desc; } -TextureD3D12Impl :: TextureD3D12Impl(IReferenceCounters* pRefCounters, - FixedBlockMemoryAllocator& TexViewObjAllocator, - RenderDeviceD3D12Impl* pRenderDeviceD3D12, - const TextureDesc& TexDesc, - const TextureData* pInitData /*= nullptr*/) : +TextureD3D12Impl ::TextureD3D12Impl(IReferenceCounters* pRefCounters, + FixedBlockMemoryAllocator& TexViewObjAllocator, + RenderDeviceD3D12Impl* pRenderDeviceD3D12, + const TextureDesc& TexDesc, + const TextureData* pInitData /*= nullptr*/) : TTextureBase{pRefCounters, TexViewObjAllocator, pRenderDeviceD3D12, TexDesc} { if (m_Desc.Usage == USAGE_STATIC && (pInitData == nullptr || pInitData->pSubResources == nullptr)) @@ -138,12 +142,12 @@ TextureD3D12Impl :: TextureD3D12Impl(IReferenceCounters* pRefCounters, } } - D3D12_RESOURCE_DESC Desc = GetD3D12TextureDesc(); + D3D12_RESOURCE_DESC Desc = GetD3D12TextureDesc(); auto* pd3d12Device = pRenderDeviceD3D12->GetD3D12Device(); if (m_Desc.Usage == USAGE_STATIC || m_Desc.Usage == USAGE_DEFAULT || m_Desc.Usage == USAGE_DYNAMIC) { - D3D12_CLEAR_VALUE ClearValue; + D3D12_CLEAR_VALUE ClearValue; D3D12_CLEAR_VALUE* pClearValue = nullptr; if (Desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) { @@ -151,13 +155,13 @@ TextureD3D12Impl :: TextureD3D12Impl(IReferenceCounters* pRefCounters, ClearValue.Format = TexFormatToDXGI_Format(m_Desc.ClearValue.Format); else { - auto Format = TexFormatToDXGI_Format(m_Desc.Format, m_Desc.BindFlags); + auto Format = TexFormatToDXGI_Format(m_Desc.Format, m_Desc.BindFlags); ClearValue.Format = GetClearFormat(Format, Desc.Flags); } if (Desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) { - for(int i=0; i < 4; ++i) + for (int i = 0; i < 4; ++i) ClearValue.Color[i] = m_Desc.ClearValue.Color[i]; } else if (Desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) @@ -168,19 +172,19 @@ TextureD3D12Impl :: TextureD3D12Impl(IReferenceCounters* pRefCounters, pClearValue = &ClearValue; } - D3D12_HEAP_PROPERTIES HeapProps; - HeapProps.Type = D3D12_HEAP_TYPE_DEFAULT; - HeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; - HeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; - HeapProps.CreationNodeMask = 1; - HeapProps.VisibleNodeMask = 1; + D3D12_HEAP_PROPERTIES HeapProps; + HeapProps.Type = D3D12_HEAP_TYPE_DEFAULT; + HeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; + HeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; + HeapProps.CreationNodeMask = 1; + HeapProps.VisibleNodeMask = 1; bool bInitializeTexture = (pInitData != nullptr && pInitData->pSubResources != nullptr && pInitData->NumSubresources > 0); - auto InitialState = bInitializeTexture ? RESOURCE_STATE_COPY_DEST : RESOURCE_STATE_UNDEFINED; + auto InitialState = bInitializeTexture ? RESOURCE_STATE_COPY_DEST : RESOURCE_STATE_UNDEFINED; SetState(InitialState); auto D3D12State = ResourceStateFlagsToD3D12ResourceStates(InitialState); - auto hr = pd3d12Device->CreateCommittedResource( &HeapProps, D3D12_HEAP_FLAG_NONE, - &Desc, D3D12State, pClearValue, __uuidof(m_pd3d12Resource), reinterpret_cast(static_cast(&m_pd3d12Resource)) ); + auto hr = pd3d12Device->CreateCommittedResource(&HeapProps, D3D12_HEAP_FLAG_NONE, + &Desc, D3D12State, pClearValue, __uuidof(m_pd3d12Resource), reinterpret_cast(static_cast(&m_pd3d12Resource))); if (FAILED(hr)) LOG_ERROR_AND_THROW("Failed to create D3D12 texture"); @@ -193,54 +197,54 @@ TextureD3D12Impl :: TextureD3D12Impl(IReferenceCounters* pRefCounters, if (pInitData->NumSubresources != ExpectedNumSubresources) LOG_ERROR_AND_THROW("Incorrect number of subresources in init data. ", ExpectedNumSubresources, " expected, while ", pInitData->NumSubresources, " provided"); - UINT64 uploadBufferSize = 0; + UINT64 uploadBufferSize = 0; pd3d12Device->GetCopyableFootprints(&Desc, 0, pInitData->NumSubresources, 0, nullptr, nullptr, nullptr, &uploadBufferSize); D3D12_HEAP_PROPERTIES UploadHeapProps; - UploadHeapProps.Type = D3D12_HEAP_TYPE_UPLOAD; - UploadHeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; - UploadHeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; - UploadHeapProps.CreationNodeMask = 1; - UploadHeapProps.VisibleNodeMask = 1; - - D3D12_RESOURCE_DESC BufferDesc; - BufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - BufferDesc.Alignment = 0; - BufferDesc.Width = uploadBufferSize; - BufferDesc.Height = 1; - BufferDesc.DepthOrArraySize = 1; - BufferDesc.MipLevels = 1; - BufferDesc.Format = DXGI_FORMAT_UNKNOWN; - BufferDesc.SampleDesc.Count = 1; - BufferDesc.SampleDesc.Quality = 0; - BufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - BufferDesc.Flags = D3D12_RESOURCE_FLAG_NONE; + UploadHeapProps.Type = D3D12_HEAP_TYPE_UPLOAD; + UploadHeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; + UploadHeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; + UploadHeapProps.CreationNodeMask = 1; + UploadHeapProps.VisibleNodeMask = 1; + + D3D12_RESOURCE_DESC BufferDesc; + BufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + BufferDesc.Alignment = 0; + BufferDesc.Width = uploadBufferSize; + BufferDesc.Height = 1; + BufferDesc.DepthOrArraySize = 1; + BufferDesc.MipLevels = 1; + BufferDesc.Format = DXGI_FORMAT_UNKNOWN; + BufferDesc.SampleDesc.Count = 1; + BufferDesc.SampleDesc.Quality = 0; + BufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + BufferDesc.Flags = D3D12_RESOURCE_FLAG_NONE; CComPtr UploadBuffer; - hr = pd3d12Device->CreateCommittedResource( &UploadHeapProps, D3D12_HEAP_FLAG_NONE, - &BufferDesc, D3D12_RESOURCE_STATE_GENERIC_READ, - nullptr, __uuidof(UploadBuffer), reinterpret_cast(static_cast(&UploadBuffer))); - if(FAILED(hr)) + hr = pd3d12Device->CreateCommittedResource(&UploadHeapProps, D3D12_HEAP_FLAG_NONE, + &BufferDesc, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, __uuidof(UploadBuffer), reinterpret_cast(static_cast(&UploadBuffer))); + if (FAILED(hr)) LOG_ERROR_AND_THROW("Failed to create committed resource in an upload heap"); auto InitContext = pRenderDeviceD3D12->AllocateCommandContext(); - // copy data to the intermediate upload heap and then schedule a copy from the upload heap to the default texture + // copy data to the intermediate upload heap and then schedule a copy from the upload heap to the default texture VERIFY_EXPR(CheckState(RESOURCE_STATE_COPY_DEST)); - std::vector > D3D12SubResData(pInitData->NumSubresources, D3D12_SUBRESOURCE_DATA(), STD_ALLOCATOR_RAW_MEM(D3D12_SUBRESOURCE_DATA, GetRawAllocator(), "Allocator for vector") ); - for(size_t subres=0; subres < D3D12SubResData.size(); ++subres) + std::vector> D3D12SubResData(pInitData->NumSubresources, D3D12_SUBRESOURCE_DATA(), STD_ALLOCATOR_RAW_MEM(D3D12_SUBRESOURCE_DATA, GetRawAllocator(), "Allocator for vector")); + for (size_t subres = 0; subres < D3D12SubResData.size(); ++subres) { D3D12SubResData[subres].pData = pInitData->pSubResources[subres].pData; D3D12SubResData[subres].RowPitch = pInitData->pSubResources[subres].Stride; D3D12SubResData[subres].SlicePitch = pInitData->pSubResources[subres].DepthStride; } - auto UploadedSize = UpdateSubresources(InitContext->GetCommandList(), m_pd3d12Resource, UploadBuffer, 0, 0, pInitData->NumSubresources, D3D12SubResData.data()); + auto UploadedSize = UpdateSubresources(InitContext->GetCommandList(), m_pd3d12Resource, UploadBuffer, 0, 0, pInitData->NumSubresources, D3D12SubResData.data()); VERIFY(UploadedSize == uploadBufferSize, "Incorrect uploaded data size (", UploadedSize, "). ", uploadBufferSize, " is expected"); // Command list fence should only be signaled when submitting cmd list // from the immediate context, otherwise the basic requirement will be violated // as in the scenario below // See http://diligentgraphics.com/diligent-engine/architecture/d3d12/managing-resource-lifetimes/ - // + // // Signaled Fence | Immediate Context | InitContext | // | | | // N | Draw(ResourceX) | | @@ -255,10 +259,10 @@ TextureD3D12Impl :: TextureD3D12Impl(IReferenceCounters* pRefCounters, // | was added to the delete queue | | // | with value N | | Uint32 QueueIndex = 0; - pRenderDeviceD3D12->CloseAndExecuteTransientCommandContext(QueueIndex, std::move(InitContext)); + pRenderDeviceD3D12->CloseAndExecuteTransientCommandContext(QueueIndex, std::move(InitContext)); // We MUST NOT call TransitionResource() from here, because - // it will call AddRef() and potentially Release(), while + // it will call AddRef() and potentially Release(), while // the object is not constructed yet // Add reference to the object to the release queue to keep it alive // until copy operation is complete. This must be done after @@ -268,12 +272,12 @@ TextureD3D12Impl :: TextureD3D12Impl(IReferenceCounters* pRefCounters, } else if (m_Desc.Usage == USAGE_STAGING) { - // Create staging buffer + // Create staging buffer D3D12_HEAP_PROPERTIES StaginHeapProps; - DEV_CHECK_ERR( (m_Desc.CPUAccessFlags & (CPU_ACCESS_READ | CPU_ACCESS_WRITE)) == CPU_ACCESS_READ || - (m_Desc.CPUAccessFlags & (CPU_ACCESS_READ | CPU_ACCESS_WRITE)) == CPU_ACCESS_WRITE, + DEV_CHECK_ERR((m_Desc.CPUAccessFlags & (CPU_ACCESS_READ | CPU_ACCESS_WRITE)) == CPU_ACCESS_READ || + (m_Desc.CPUAccessFlags & (CPU_ACCESS_READ | CPU_ACCESS_WRITE)) == CPU_ACCESS_WRITE, "Exactly one of CPU_ACCESS_READ or CPU_ACCESS_WRITE flags must be specified"); - + RESOURCE_STATE InitialState = RESOURCE_STATE_UNKNOWN; if (m_Desc.CPUAccessFlags & CPU_ACCESS_READ) { @@ -282,8 +286,8 @@ TextureD3D12Impl :: TextureD3D12Impl(IReferenceCounters* pRefCounters, } else if (m_Desc.CPUAccessFlags & CPU_ACCESS_WRITE) { - StaginHeapProps.Type = D3D12_HEAP_TYPE_UPLOAD; - InitialState = RESOURCE_STATE_GENERIC_READ; + StaginHeapProps.Type = D3D12_HEAP_TYPE_UPLOAD; + InitialState = RESOURCE_STATE_GENERIC_READ; } else UNEXPECTED("Unexpected CPU access"); @@ -291,38 +295,38 @@ TextureD3D12Impl :: TextureD3D12Impl(IReferenceCounters* pRefCounters, SetState(InitialState); auto D3D12State = ResourceStateFlagsToD3D12ResourceStates(InitialState); - StaginHeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; - StaginHeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; - StaginHeapProps.CreationNodeMask = 1; - StaginHeapProps.VisibleNodeMask = 1; + StaginHeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; + StaginHeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; + StaginHeapProps.CreationNodeMask = 1; + StaginHeapProps.VisibleNodeMask = 1; - UINT64 stagingBufferSize = 0; - Uint32 NumSubresources = Uint32{Desc.MipLevels} * (Desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1 : Uint32{Desc.DepthOrArraySize}); - m_StagingFootprints = ALLOCATE(GetRawAllocator(), "Memory for staging footprints", D3D12_PLACED_SUBRESOURCE_FOOTPRINT, NumSubresources+1); + UINT64 stagingBufferSize = 0; + Uint32 NumSubresources = Uint32{Desc.MipLevels} * (Desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1 : Uint32{Desc.DepthOrArraySize}); + m_StagingFootprints = ALLOCATE(GetRawAllocator(), "Memory for staging footprints", D3D12_PLACED_SUBRESOURCE_FOOTPRINT, NumSubresources + 1); pd3d12Device->GetCopyableFootprints(&Desc, 0, NumSubresources, 0, m_StagingFootprints, nullptr, nullptr, &stagingBufferSize); m_StagingFootprints[NumSubresources] = D3D12_PLACED_SUBRESOURCE_FOOTPRINT{stagingBufferSize}; - D3D12_RESOURCE_DESC BufferDesc; - BufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - BufferDesc.Alignment = 0; - BufferDesc.Width = stagingBufferSize; - BufferDesc.Height = 1; - BufferDesc.DepthOrArraySize = 1; - BufferDesc.MipLevels = 1; - BufferDesc.Format = DXGI_FORMAT_UNKNOWN; - BufferDesc.SampleDesc.Count = 1; - BufferDesc.SampleDesc.Quality = 0; - BufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - BufferDesc.Flags = D3D12_RESOURCE_FLAG_NONE; + D3D12_RESOURCE_DESC BufferDesc; + BufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + BufferDesc.Alignment = 0; + BufferDesc.Width = stagingBufferSize; + BufferDesc.Height = 1; + BufferDesc.DepthOrArraySize = 1; + BufferDesc.MipLevels = 1; + BufferDesc.Format = DXGI_FORMAT_UNKNOWN; + BufferDesc.SampleDesc.Count = 1; + BufferDesc.SampleDesc.Quality = 0; + BufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + BufferDesc.Flags = D3D12_RESOURCE_FLAG_NONE; // Resources on D3D12_HEAP_TYPE_READBACK heaps do not support persistent map. Map() and Unmap() must be // called between CPU and GPU accesses to the same memory address on some system architectures, when the // page caching behavior is write-back. Map() and Unmap() invalidate and flush the last level CPU cache // on some ARM systems, to marshal data between the CPU and GPU through memory addresses with write-back behavior. // https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/nf-d3d12-id3d12resource-map - auto hr = pd3d12Device->CreateCommittedResource( &StaginHeapProps, D3D12_HEAP_FLAG_NONE, &BufferDesc, D3D12State, - nullptr, __uuidof(m_pd3d12Resource), reinterpret_cast(static_cast(&m_pd3d12Resource))); - if(FAILED(hr)) + auto hr = pd3d12Device->CreateCommittedResource(&StaginHeapProps, D3D12_HEAP_FLAG_NONE, &BufferDesc, D3D12State, + nullptr, __uuidof(m_pd3d12Resource), reinterpret_cast(static_cast(&m_pd3d12Resource))); + if (FAILED(hr)) LOG_ERROR_AND_THROW("Failed to create staging buffer"); } else @@ -343,37 +347,38 @@ static TextureDesc InitTexDescFromD3D12Resource(ID3D12Resource* pTexture, const { auto RefFormat = DXGI_FormatToTexFormat(ResourceDesc.Format); DEV_CHECK_ERR(RefFormat == TexDesc.Format, "The format specified by texture description (", GetTextureFormatAttribs(TexDesc.Format).Name, ")" - " does not match the D3D12 resource format (", GetTextureFormatAttribs(RefFormat).Name, ")"); + " does not match the D3D12 resource format (", + GetTextureFormatAttribs(RefFormat).Name, ")"); (void)RefFormat; } - TexDesc.Width = static_cast( ResourceDesc.Width ); - TexDesc.Height = Uint32{ ResourceDesc.Height }; - TexDesc.ArraySize = Uint32{ ResourceDesc.DepthOrArraySize }; - TexDesc.MipLevels = Uint32{ ResourceDesc.MipLevels }; - switch(ResourceDesc.Dimension) + TexDesc.Width = static_cast(ResourceDesc.Width); + TexDesc.Height = Uint32{ResourceDesc.Height}; + TexDesc.ArraySize = Uint32{ResourceDesc.DepthOrArraySize}; + TexDesc.MipLevels = Uint32{ResourceDesc.MipLevels}; + switch (ResourceDesc.Dimension) { case D3D12_RESOURCE_DIMENSION_TEXTURE1D: TexDesc.Type = TexDesc.ArraySize == 1 ? RESOURCE_DIM_TEX_1D : RESOURCE_DIM_TEX_1D_ARRAY; break; case D3D12_RESOURCE_DIMENSION_TEXTURE2D: TexDesc.Type = TexDesc.ArraySize == 1 ? RESOURCE_DIM_TEX_2D : RESOURCE_DIM_TEX_2D_ARRAY; break; case D3D12_RESOURCE_DIMENSION_TEXTURE3D: TexDesc.Type = RESOURCE_DIM_TEX_3D; break; } - + TexDesc.SampleCount = ResourceDesc.SampleDesc.Count; - - TexDesc.Usage = USAGE_DEFAULT; + + TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_NONE; - if( (ResourceDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) != 0 ) + if ((ResourceDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) != 0) TexDesc.BindFlags |= BIND_RENDER_TARGET; - if( (ResourceDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) != 0 ) + if ((ResourceDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) != 0) TexDesc.BindFlags |= BIND_DEPTH_STENCIL; - if( (ResourceDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) != 0 ) + if ((ResourceDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) != 0) TexDesc.BindFlags |= BIND_UNORDERED_ACCESS; if ((ResourceDesc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) == 0) { auto FormatAttribs = GetTextureFormatAttribs(TexDesc.Format); if (FormatAttribs.IsTypeless || (FormatAttribs.ComponentType != COMPONENT_TYPE_DEPTH && - FormatAttribs.ComponentType != COMPONENT_TYPE_DEPTH_STENCIL) ) + FormatAttribs.ComponentType != COMPONENT_TYPE_DEPTH_STENCIL)) { TexDesc.BindFlags |= BIND_SHADER_RESOURCE; } @@ -384,70 +389,70 @@ static TextureDesc InitTexDescFromD3D12Resource(ID3D12Resource* pTexture, const TextureD3D12Impl::TextureD3D12Impl(IReferenceCounters* pRefCounters, FixedBlockMemoryAllocator& TexViewObjAllocator, - RenderDeviceD3D12Impl* pDeviceD3D12, - const TextureDesc& TexDesc, + RenderDeviceD3D12Impl* pDeviceD3D12, + const TextureDesc& TexDesc, RESOURCE_STATE InitialState, - ID3D12Resource* pTexture) : + ID3D12Resource* pTexture) : TTextureBase{pRefCounters, TexViewObjAllocator, pDeviceD3D12, InitTexDescFromD3D12Resource(pTexture, TexDesc)} { m_pd3d12Resource = pTexture; SetState(InitialState); } -IMPLEMENT_QUERY_INTERFACE( TextureD3D12Impl, IID_TextureD3D12, TTextureBase ) +IMPLEMENT_QUERY_INTERFACE(TextureD3D12Impl, IID_TextureD3D12, TTextureBase) -void TextureD3D12Impl::CreateViewInternal( const struct TextureViewDesc &ViewDesc, ITextureView **ppView, bool bIsDefaultView ) +void TextureD3D12Impl::CreateViewInternal(const struct TextureViewDesc& ViewDesc, ITextureView** ppView, bool bIsDefaultView) { - VERIFY( ppView != nullptr, "View pointer address is null" ); - if( !ppView )return; - VERIFY( *ppView == nullptr, "Overwriting reference to existing object may cause memory leaks" ); - + VERIFY(ppView != nullptr, "View pointer address is null"); + if (!ppView) return; + VERIFY(*ppView == nullptr, "Overwriting reference to existing object may cause memory leaks"); + *ppView = nullptr; try { - auto *pDeviceD3D12Impl = ValidatedCast(GetDevice()); - auto &TexViewAllocator = pDeviceD3D12Impl->GetTexViewObjAllocator(); - VERIFY( &TexViewAllocator == &m_dbgTexViewObjAllocator, "Texture view allocator does not match allocator provided during texture initialization" ); + auto* pDeviceD3D12Impl = ValidatedCast(GetDevice()); + auto& TexViewAllocator = pDeviceD3D12Impl->GetTexViewObjAllocator(); + VERIFY(&TexViewAllocator == &m_dbgTexViewObjAllocator, "Texture view allocator does not match allocator provided during texture initialization"); auto UpdatedViewDesc = ViewDesc; - CorrectTextureViewDesc( UpdatedViewDesc ); + CorrectTextureViewDesc(UpdatedViewDesc); DescriptorHeapAllocation ViewDescriptor; - switch( ViewDesc.ViewType ) + switch (ViewDesc.ViewType) { case TEXTURE_VIEW_SHADER_RESOURCE: { - VERIFY( m_Desc.BindFlags & BIND_SHADER_RESOURCE, "BIND_SHADER_RESOURCE flag is not set" ); + VERIFY(m_Desc.BindFlags & BIND_SHADER_RESOURCE, "BIND_SHADER_RESOURCE flag is not set"); ViewDescriptor = pDeviceD3D12Impl->AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - CreateSRV( UpdatedViewDesc, ViewDescriptor.GetCpuHandle() ); + CreateSRV(UpdatedViewDesc, ViewDescriptor.GetCpuHandle()); } break; case TEXTURE_VIEW_RENDER_TARGET: { - VERIFY( m_Desc.BindFlags & BIND_RENDER_TARGET, "BIND_RENDER_TARGET flag is not set" ); + VERIFY(m_Desc.BindFlags & BIND_RENDER_TARGET, "BIND_RENDER_TARGET flag is not set"); ViewDescriptor = pDeviceD3D12Impl->AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); - CreateRTV( UpdatedViewDesc, ViewDescriptor.GetCpuHandle() ); + CreateRTV(UpdatedViewDesc, ViewDescriptor.GetCpuHandle()); } break; case TEXTURE_VIEW_DEPTH_STENCIL: { - VERIFY( m_Desc.BindFlags & BIND_DEPTH_STENCIL, "BIND_DEPTH_STENCIL is not set" ); + VERIFY(m_Desc.BindFlags & BIND_DEPTH_STENCIL, "BIND_DEPTH_STENCIL is not set"); ViewDescriptor = pDeviceD3D12Impl->AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); - CreateDSV( UpdatedViewDesc, ViewDescriptor.GetCpuHandle() ); + CreateDSV(UpdatedViewDesc, ViewDescriptor.GetCpuHandle()); } break; case TEXTURE_VIEW_UNORDERED_ACCESS: { - VERIFY( m_Desc.BindFlags & BIND_UNORDERED_ACCESS, "BIND_UNORDERED_ACCESS flag is not set" ); + VERIFY(m_Desc.BindFlags & BIND_UNORDERED_ACCESS, "BIND_UNORDERED_ACCESS flag is not set"); ViewDescriptor = pDeviceD3D12Impl->AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - CreateUAV( UpdatedViewDesc, ViewDescriptor.GetCpuHandle() ); + CreateUAV(UpdatedViewDesc, ViewDescriptor.GetCpuHandle()); } break; - default: UNEXPECTED( "Unknown view type" ); break; + default: UNEXPECTED("Unknown view type"); break; } DescriptorHeapAllocation TexArraySRVDescriptor, MipUAVDescriptors; @@ -456,12 +461,12 @@ void TextureD3D12Impl::CreateViewInternal( const struct TextureViewDesc &ViewDes VERIFY_EXPR((m_Desc.MiscFlags & MISC_TEXTURE_FLAG_GENERATE_MIPS) != 0 && (m_Desc.Type == RESOURCE_DIM_TEX_2D || m_Desc.Type == RESOURCE_DIM_TEX_2D_ARRAY)); { - TexArraySRVDescriptor = pDeviceD3D12Impl->AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1); + TexArraySRVDescriptor = pDeviceD3D12Impl->AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1); TextureViewDesc TexArraySRVDesc = UpdatedViewDesc; // Create texture array SRV TexArraySRVDesc.TextureDim = RESOURCE_DIM_TEX_2D_ARRAY; TexArraySRVDesc.ViewType = TEXTURE_VIEW_SHADER_RESOURCE; - CreateSRV( TexArraySRVDesc, TexArraySRVDescriptor.GetCpuHandle() ); + CreateSRV(TexArraySRVDesc, TexArraySRVDescriptor.GetCpuHandle()); } MipUAVDescriptors = pDeviceD3D12Impl->AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, m_Desc.MipLevels); @@ -475,31 +480,30 @@ void TextureD3D12Impl::CreateViewInternal( const struct TextureViewDesc &ViewDes UAVDesc.NumMipLevels = 1; if (UAVDesc.Format == TEX_FORMAT_RGBA8_UNORM_SRGB) UAVDesc.Format = TEX_FORMAT_RGBA8_UNORM; - else if(UAVDesc.Format == TEX_FORMAT_BGRA8_UNORM_SRGB) + else if (UAVDesc.Format == TEX_FORMAT_BGRA8_UNORM_SRGB) UAVDesc.Format = TEX_FORMAT_BGRA8_UNORM; - CreateUAV( UAVDesc, MipUAVDescriptors.GetCpuHandle(MipLevel) ); + CreateUAV(UAVDesc, MipUAVDescriptors.GetCpuHandle(MipLevel)); } } - auto pViewD3D12 = NEW_RC_OBJ(TexViewAllocator, "TextureViewD3D12Impl instance", TextureViewD3D12Impl, bIsDefaultView ? this : nullptr) - (GetDevice(), UpdatedViewDesc, this, std::move(ViewDescriptor), std::move(TexArraySRVDescriptor), std::move(MipUAVDescriptors), bIsDefaultView); - VERIFY( pViewD3D12->GetDesc().ViewType == ViewDesc.ViewType, "Incorrect view type" ); + auto pViewD3D12 = NEW_RC_OBJ(TexViewAllocator, "TextureViewD3D12Impl instance", TextureViewD3D12Impl, bIsDefaultView ? this : nullptr)(GetDevice(), UpdatedViewDesc, this, std::move(ViewDescriptor), std::move(TexArraySRVDescriptor), std::move(MipUAVDescriptors), bIsDefaultView); + VERIFY(pViewD3D12->GetDesc().ViewType == ViewDesc.ViewType, "Incorrect view type"); - if( bIsDefaultView ) + if (bIsDefaultView) *ppView = pViewD3D12; else - pViewD3D12->QueryInterface(IID_TextureView, reinterpret_cast(ppView) ); + pViewD3D12->QueryInterface(IID_TextureView, reinterpret_cast(ppView)); } - catch( const std::runtime_error & ) + catch (const std::runtime_error&) { - const auto *ViewTypeName = GetTexViewTypeLiteralName(ViewDesc.ViewType); - LOG_ERROR("Failed to create view \"", ViewDesc.Name ? ViewDesc.Name : "", "\" (", ViewTypeName, ") for texture \"", m_Desc.Name ? m_Desc.Name : "", "\"" ); + const auto* ViewTypeName = GetTexViewTypeLiteralName(ViewDesc.ViewType); + LOG_ERROR("Failed to create view \"", ViewDesc.Name ? ViewDesc.Name : "", "\" (", ViewTypeName, ") for texture \"", m_Desc.Name ? m_Desc.Name : "", "\""); } } -TextureD3D12Impl :: ~TextureD3D12Impl() +TextureD3D12Impl ::~TextureD3D12Impl() { // D3D12 object can only be destroyed when it is no longer used by the GPU - auto *pDeviceD3D12Impl = ValidatedCast(GetDevice()); + auto* pDeviceD3D12Impl = ValidatedCast(GetDevice()); pDeviceD3D12Impl->SafeReleaseDeviceObject(std::move(m_pd3d12Resource), m_Desc.CommandQueueMask); if (m_StagingFootprints != nullptr) { @@ -507,26 +511,26 @@ TextureD3D12Impl :: ~TextureD3D12Impl() } } -void TextureD3D12Impl::CreateSRV( TextureViewDesc& SRVDesc, D3D12_CPU_DESCRIPTOR_HANDLE SRVHandle ) +void TextureD3D12Impl::CreateSRV(TextureViewDesc& SRVDesc, D3D12_CPU_DESCRIPTOR_HANDLE SRVHandle) { - VERIFY( SRVDesc.ViewType == TEXTURE_VIEW_SHADER_RESOURCE, "Incorrect view type: shader resource is expected" ); - - if( SRVDesc.Format == TEX_FORMAT_UNKNOWN ) + VERIFY(SRVDesc.ViewType == TEXTURE_VIEW_SHADER_RESOURCE, "Incorrect view type: shader resource is expected"); + + if (SRVDesc.Format == TEX_FORMAT_UNKNOWN) { SRVDesc.Format = m_Desc.Format; } D3D12_SHADER_RESOURCE_VIEW_DESC D3D12_SRVDesc; TextureViewDesc_to_D3D12_SRV_DESC(SRVDesc, D3D12_SRVDesc, m_Desc.SampleCount); - auto *pDeviceD3D12 = static_cast(GetDevice())->GetD3D12Device(); + auto* pDeviceD3D12 = static_cast(GetDevice())->GetD3D12Device(); pDeviceD3D12->CreateShaderResourceView(m_pd3d12Resource, &D3D12_SRVDesc, SRVHandle); } -void TextureD3D12Impl::CreateRTV( TextureViewDesc& RTVDesc, D3D12_CPU_DESCRIPTOR_HANDLE RTVHandle ) +void TextureD3D12Impl::CreateRTV(TextureViewDesc& RTVDesc, D3D12_CPU_DESCRIPTOR_HANDLE RTVHandle) { - VERIFY( RTVDesc.ViewType == TEXTURE_VIEW_RENDER_TARGET, "Incorrect view type: render target is expected" ); + VERIFY(RTVDesc.ViewType == TEXTURE_VIEW_RENDER_TARGET, "Incorrect view type: render target is expected"); - if( RTVDesc.Format == TEX_FORMAT_UNKNOWN ) + if (RTVDesc.Format == TEX_FORMAT_UNKNOWN) { RTVDesc.Format = m_Desc.Format; } @@ -534,15 +538,15 @@ void TextureD3D12Impl::CreateRTV( TextureViewDesc& RTVDesc, D3D12_CPU_DESCRIPTOR D3D12_RENDER_TARGET_VIEW_DESC D3D12_RTVDesc; TextureViewDesc_to_D3D12_RTV_DESC(RTVDesc, D3D12_RTVDesc, m_Desc.SampleCount); - auto *pDeviceD3D12 = static_cast(GetDevice())->GetD3D12Device(); - pDeviceD3D12->CreateRenderTargetView( m_pd3d12Resource, &D3D12_RTVDesc, RTVHandle ); + auto* pDeviceD3D12 = static_cast(GetDevice())->GetD3D12Device(); + pDeviceD3D12->CreateRenderTargetView(m_pd3d12Resource, &D3D12_RTVDesc, RTVHandle); } -void TextureD3D12Impl::CreateDSV( TextureViewDesc& DSVDesc, D3D12_CPU_DESCRIPTOR_HANDLE DSVHandle ) +void TextureD3D12Impl::CreateDSV(TextureViewDesc& DSVDesc, D3D12_CPU_DESCRIPTOR_HANDLE DSVHandle) { - VERIFY( DSVDesc.ViewType == TEXTURE_VIEW_DEPTH_STENCIL, "Incorrect view type: depth stencil is expected" ); + VERIFY(DSVDesc.ViewType == TEXTURE_VIEW_DEPTH_STENCIL, "Incorrect view type: depth stencil is expected"); - if( DSVDesc.Format == TEX_FORMAT_UNKNOWN ) + if (DSVDesc.Format == TEX_FORMAT_UNKNOWN) { DSVDesc.Format = m_Desc.Format; } @@ -550,15 +554,15 @@ void TextureD3D12Impl::CreateDSV( TextureViewDesc& DSVDesc, D3D12_CPU_DESCRIPTOR D3D12_DEPTH_STENCIL_VIEW_DESC D3D12_DSVDesc; TextureViewDesc_to_D3D12_DSV_DESC(DSVDesc, D3D12_DSVDesc, m_Desc.SampleCount); - auto *pDeviceD3D12 = static_cast(GetDevice())->GetD3D12Device(); - pDeviceD3D12->CreateDepthStencilView( m_pd3d12Resource, &D3D12_DSVDesc, DSVHandle ); + auto* pDeviceD3D12 = static_cast(GetDevice())->GetD3D12Device(); + pDeviceD3D12->CreateDepthStencilView(m_pd3d12Resource, &D3D12_DSVDesc, DSVHandle); } -void TextureD3D12Impl::CreateUAV( TextureViewDesc& UAVDesc, D3D12_CPU_DESCRIPTOR_HANDLE UAVHandle ) +void TextureD3D12Impl::CreateUAV(TextureViewDesc& UAVDesc, D3D12_CPU_DESCRIPTOR_HANDLE UAVHandle) { - VERIFY( UAVDesc.ViewType == TEXTURE_VIEW_UNORDERED_ACCESS, "Incorrect view type: unordered access is expected" ); - - if( UAVDesc.Format == TEX_FORMAT_UNKNOWN ) + VERIFY(UAVDesc.ViewType == TEXTURE_VIEW_UNORDERED_ACCESS, "Incorrect view type: unordered access is expected"); + + if (UAVDesc.Format == TEX_FORMAT_UNKNOWN) { UAVDesc.Format = m_Desc.Format; } @@ -566,8 +570,8 @@ void TextureD3D12Impl::CreateUAV( TextureViewDesc& UAVDesc, D3D12_CPU_DESCRIPTOR D3D12_UNORDERED_ACCESS_VIEW_DESC D3D12_UAVDesc; TextureViewDesc_to_D3D12_UAV_DESC(UAVDesc, D3D12_UAVDesc); - auto *pDeviceD3D12 = static_cast(GetDevice())->GetD3D12Device(); - pDeviceD3D12->CreateUnorderedAccessView( m_pd3d12Resource, nullptr, &D3D12_UAVDesc, UAVHandle ); + auto* pDeviceD3D12 = static_cast(GetDevice())->GetD3D12Device(); + pDeviceD3D12->CreateUnorderedAccessView(m_pd3d12Resource, nullptr, &D3D12_UAVDesc, UAVHandle); } void TextureD3D12Impl::SetD3D12ResourceState(D3D12_RESOURCE_STATES state) @@ -575,9 +579,9 @@ void TextureD3D12Impl::SetD3D12ResourceState(D3D12_RESOURCE_STATES state) SetState(D3D12ResourceStatesToResourceStateFlags(state)); } -D3D12_RESOURCE_STATES TextureD3D12Impl::GetD3D12ResourceState()const +D3D12_RESOURCE_STATES TextureD3D12Impl::GetD3D12ResourceState() const { return ResourceStateFlagsToD3D12ResourceStates(GetState()); } -} +} // namespace Diligent diff --git a/Graphics/GraphicsEngineD3D12/src/TextureViewD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/TextureViewD3D12Impl.cpp index 93090b3e..e1ed0372 100644 --- a/Graphics/GraphicsEngineD3D12/src/TextureViewD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/TextureViewD3D12Impl.cpp @@ -28,14 +28,15 @@ namespace Diligent { -TextureViewD3D12Impl::TextureViewD3D12Impl( IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pDevice, - const TextureViewDesc& ViewDesc, - ITexture* pTexture, - DescriptorHeapAllocation&& Descriptor, - DescriptorHeapAllocation&& TexArraySRVDescriptor, - DescriptorHeapAllocation&& MipLevelUAVDescriptors, - bool bIsDefaultView) : +TextureViewD3D12Impl::TextureViewD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl* pDevice, + const TextureViewDesc& ViewDesc, + ITexture* pTexture, + DescriptorHeapAllocation&& Descriptor, + DescriptorHeapAllocation&& TexArraySRVDescriptor, + DescriptorHeapAllocation&& MipLevelUAVDescriptors, + bool bIsDefaultView) : + // clang-format off TTextureViewBase { pRefCounters, @@ -45,12 +46,13 @@ TextureViewD3D12Impl::TextureViewD3D12Impl( IReferenceCounters* pRefCount bIsDefaultView }, m_Descriptor{std::move(Descriptor)} + // clang-format on { if (!TexArraySRVDescriptor.IsNull() && !MipLevelUAVDescriptors.IsNull()) { m_MipGenerationDescriptors = ALLOCATE(GetRawAllocator(), "Raw memory for DescriptorHeapAllocation", DescriptorHeapAllocation, 2); - new (&m_MipGenerationDescriptors[0])DescriptorHeapAllocation(std::move(TexArraySRVDescriptor)); - new (&m_MipGenerationDescriptors[1])DescriptorHeapAllocation(std::move(MipLevelUAVDescriptors)); + new (&m_MipGenerationDescriptors[0]) DescriptorHeapAllocation(std::move(TexArraySRVDescriptor)); + new (&m_MipGenerationDescriptors[1]) DescriptorHeapAllocation(std::move(MipLevelUAVDescriptors)); } } @@ -66,6 +68,6 @@ TextureViewD3D12Impl::~TextureViewD3D12Impl() } } -IMPLEMENT_QUERY_INTERFACE( TextureViewD3D12Impl, IID_TextureViewD3D12, TTextureViewBase ) +IMPLEMENT_QUERY_INTERFACE(TextureViewD3D12Impl, IID_TextureViewD3D12, TTextureViewBase) -} +} // namespace Diligent -- cgit v1.2.3