From c07ee39e4241251ef4583ecbc22a369935ad8b9a Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Mon, 25 Feb 2019 20:41:16 -0800 Subject: Cosmetic changes --- Graphics/GraphicsEngineVulkan/include/BufferViewVkImpl.h | 14 +++++++------- Graphics/GraphicsEngineVulkan/include/BufferVkImpl.h | 6 +++--- Graphics/GraphicsEngineVulkan/include/SamplerVkImpl.h | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/include/BufferViewVkImpl.h b/Graphics/GraphicsEngineVulkan/include/BufferViewVkImpl.h index abedce7d..f7245d0a 100644 --- a/Graphics/GraphicsEngineVulkan/include/BufferViewVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/BufferViewVkImpl.h @@ -44,15 +44,15 @@ class BufferViewVkImpl final : public BufferViewBase; - BufferViewVkImpl( IReferenceCounters* pRefCounters, - RenderDeviceVkImpl* pDevice, - const BufferViewDesc& ViewDesc, - class IBuffer* pBuffer, - VulkanUtilities::BufferViewWrapper&& BuffView, - bool bIsDefaultView); + BufferViewVkImpl(IReferenceCounters* pRefCounters, + RenderDeviceVkImpl* pDevice, + const BufferViewDesc& ViewDesc, + class IBuffer* pBuffer, + VulkanUtilities::BufferViewWrapper&& BuffView, + bool bIsDefaultView); ~BufferViewVkImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject** ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual VkBufferView GetVkBufferView()const override final{return m_BuffView;} diff --git a/Graphics/GraphicsEngineVulkan/include/BufferVkImpl.h b/Graphics/GraphicsEngineVulkan/include/BufferVkImpl.h index f3d1784b..c3afd4ee 100644 --- a/Graphics/GraphicsEngineVulkan/include/BufferVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/BufferVkImpl.h @@ -63,7 +63,7 @@ public: VkBuffer vkBuffer); ~BufferVkImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject** ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override; #ifdef DEVELOPMENT void DvpVerifyDynamicAllocation(DeviceContextVkImpl* pCtx)const; @@ -104,14 +104,14 @@ public: private: friend class DeviceContextVkImpl; - virtual void CreateViewInternal( const struct BufferViewDesc& ViewDesc, IBufferView** ppView, bool bIsDefaultView )override; + virtual void CreateViewInternal(const struct BufferViewDesc& ViewDesc, IBufferView** ppView, bool bIsDefaultView)override; VulkanUtilities::BufferViewWrapper CreateView(struct BufferViewDesc &ViewDesc); Uint32 m_DynamicOffsetAlignment = 0; std::vector > m_DynamicAllocations; - VulkanUtilities::BufferWrapper m_VulkanBuffer; + VulkanUtilities::BufferWrapper m_VulkanBuffer; VulkanUtilities::VulkanMemoryAllocation m_MemoryAllocation; }; diff --git a/Graphics/GraphicsEngineVulkan/include/SamplerVkImpl.h b/Graphics/GraphicsEngineVulkan/include/SamplerVkImpl.h index e257506e..3f986515 100644 --- a/Graphics/GraphicsEngineVulkan/include/SamplerVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/SamplerVkImpl.h @@ -45,7 +45,7 @@ public: SamplerVkImpl(IReferenceCounters* pRefCounters, RenderDeviceVkImpl* pRenderDeviceVk, const SamplerDesc& SamplerDesc); ~SamplerVkImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override; virtual VkSampler GetVkSampler()const override final{return m_VkSampler;} -- cgit v1.2.3 From 324c7540bfe3a30c94f18941e2e4131e0aee4b84 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Mon, 25 Feb 2019 21:01:54 -0800 Subject: Updated SPIRVShaderResources: removed immutable samplers and variable type --- Graphics/GLSLTools/include/SPIRVShaderResources.h | 161 +++------------ Graphics/GLSLTools/src/SPIRVShaderResources.cpp | 230 +++------------------- 2 files changed, 52 insertions(+), 339 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GLSLTools/include/SPIRVShaderResources.h b/Graphics/GLSLTools/include/SPIRVShaderResources.h index f4c9edfe..7f0796ed 100644 --- a/Graphics/GLSLTools/include/SPIRVShaderResources.h +++ b/Graphics/GLSLTools/include/SPIRVShaderResources.h @@ -30,17 +30,15 @@ // // m_MemoryBuffer m_TotalResources // | | -// | Uniform Buffers | Storage Buffers | Storage Images | Sampled Images | Atomic Counters | Separate Samplers | Separate Images | Immutable Samplers | Stage Inputs | Resource Names | +// | Uniform Buffers | Storage Buffers | Storage Images | Sampled Images | Atomic Counters | Separate Samplers | Separate Images | Stage Inputs | Resource Names | #include #include #include #include "Shader.h" -#include "Sampler.h" #include "RenderDevice.h" #include "STDAllocator.h" -#include "HashUtils.h" #include "RefCntAutoPtr.h" #include "StringPool.h" @@ -53,22 +51,6 @@ struct Resource; namespace Diligent { -inline bool IsAllowedType(SHADER_VARIABLE_TYPE VarType, Uint32 AllowedTypeBits)noexcept -{ - return ((1 << VarType) & AllowedTypeBits) != 0; -} - -inline Uint32 GetAllowedTypeBits(const SHADER_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes)noexcept -{ - if(AllowedVarTypes == nullptr) - return 0xFFFFFFFF; - - Uint32 AllowedTypeBits = 0; - for(Uint32 i=0; i < NumAllowedTypes; ++i) - AllowedTypeBits |= 1 << AllowedVarTypes[i]; - return AllowedTypeBits; -} - // sizeof(SPIRVShaderResourceAttribs) == 24, msvc x64 struct SPIRVShaderResourceAttribs { @@ -86,21 +68,12 @@ struct SPIRVShaderResourceAttribs NumResourceTypes }; - static constexpr const Uint32 ResourceTypeBits = 4; - static constexpr const Uint32 VarTypeBits = 4; - static_assert(SHADER_VARIABLE_TYPE_NUM_TYPES < (1 << VarTypeBits), "Not enough bits to represent SHADER_VARIABLE_TYPE"); - static_assert(ResourceType::NumResourceTypes < (1 << ResourceTypeBits), "Not enough bits to represent ResourceType"); - - static constexpr const Uint32 InvalidSepSmplrOrImgInd = static_cast(-1); + static constexpr const Uint32 InvalidSepSmplrOrImgInd = static_cast(-1); /* 0 */const char* const Name; /* 8 */const Uint16 ArraySize; -/*10.0*/const ResourceType Type : ResourceTypeBits; -/*10.4*/const SHADER_VARIABLE_TYPE VarType : VarTypeBits; +/*10 */const ResourceType Type; private: - static constexpr const Uint8 InvalidImmutableSamplerInd = static_cast(-1); -/*11*/const Uint8 ImmutableSamplerInd; - // Defines mapping between separate samplers and seperate images when HLSL-style // combined texture samplers are in use (i.e. texture2D g_Tex + sampler g_Tex_sampler). /*12*/ Uint32 SepSmplrOrImgInd = InvalidSepSmplrOrImgInd; @@ -110,13 +83,11 @@ public: /*20*/const uint32_t DescriptorSetDecorationOffset; - SPIRVShaderResourceAttribs(const spirv_cross::Compiler& Compiler, - const spirv_cross::Resource& Res, - const char* _Name, - ResourceType _Type, - SHADER_VARIABLE_TYPE _VarType, - Int32 _ImmutableSamplerInd = -1, - Uint32 _SamplerOrSepImgInd = InvalidSepSmplrOrImgInd)noexcept; + SPIRVShaderResourceAttribs(const spirv_cross::Compiler& Compiler, + const spirv_cross::Resource& Res, + const char* _Name, + ResourceType _Type, + Uint32 _SamplerOrSepImgInd = InvalidSepSmplrOrImgInd) noexcept; bool IsValidSepSamplerAssigned() const { @@ -154,17 +125,6 @@ public: SepSmplrOrImgInd = SepImageInd; } - bool IsImmutableSamplerAssigned() const - { - return ImmutableSamplerInd != InvalidImmutableSamplerInd; - } - - Uint32 GetImmutableSamplerInd()const - { - VERIFY(Type == ResourceType::SampledImage || Type == ResourceType::SeparateSampler, "Only sampled images and separate samplers can be assigned immutable samplers"); - return ImmutableSamplerInd; - } - String GetPrintName(Uint32 ArrayInd)const { VERIFY_EXPR(ArrayInd < ArraySize); @@ -182,10 +142,7 @@ public: { return ArraySize == Attribs.ArraySize && Type == Attribs.Type && - VarType == Attribs.VarType && - SepSmplrOrImgInd == Attribs.SepSmplrOrImgInd && - ( (IsImmutableSamplerAssigned() && Attribs.IsImmutableSamplerAssigned()) || - (!IsImmutableSamplerAssigned() && !Attribs.IsImmutableSamplerAssigned()) ); + SepSmplrOrImgInd == Attribs.SepSmplrOrImgInd; } }; static_assert(sizeof(SPIRVShaderResourceAttribs) % sizeof(void*) == 0, "Size of SPIRVShaderResourceAttribs struct must be multiple of sizeof(void*)" ); @@ -221,8 +178,6 @@ public: ~SPIRVShaderResources(); - using SamplerPtrType = RefCntAutoPtr; - Uint32 GetNumUBs ()const noexcept{ return (m_StorageBufferOffset - 0); } Uint32 GetNumSBs ()const noexcept{ return (m_StorageImageOffset - m_StorageBufferOffset); } Uint32 GetNumImgs ()const noexcept{ return (m_SampledImageOffset - m_StorageImageOffset); } @@ -231,7 +186,6 @@ public: Uint32 GetNumSepSmplrs()const noexcept{ return (m_SeparateImageOffset - m_SeparateSamplerOffset);} Uint32 GetNumSepImgs ()const noexcept{ return (m_TotalResources - m_SeparateImageOffset); } Uint32 GetTotalResources() const noexcept { return m_TotalResources; } - Uint32 GetNumImmutableSamplers()const noexcept { return m_NumImmutableSamplers; } Uint32 GetNumShaderStageInputs()const noexcept { return m_NumShaderStageInputs; } const SPIRVShaderResourceAttribs& GetUB (Uint32 n)const noexcept{ return GetResAttribs(n, GetNumUBs(), 0 ); } @@ -243,23 +197,11 @@ public: const SPIRVShaderResourceAttribs& GetSepImg (Uint32 n)const noexcept{ return GetResAttribs(n, GetNumSepImgs(), m_SeparateImageOffset ); } const SPIRVShaderResourceAttribs& GetResource(Uint32 n)const noexcept{ return GetResAttribs(n, GetTotalResources(), 0 ); } - ISampler* GetImmutableSampler(const SPIRVShaderResourceAttribs& ResAttribs)const noexcept - { - if (!ResAttribs.IsImmutableSamplerAssigned()) - return nullptr; - - auto ImmutableSamplerInd = ResAttribs.GetImmutableSamplerInd(); - VERIFY(ImmutableSamplerInd < m_NumImmutableSamplers, "Static sampler index (", ImmutableSamplerInd, ") is out of range. Array size: ", m_NumImmutableSamplers); - auto* ResourceMemoryEnd = reinterpret_cast(m_MemoryBuffer.get()) + m_TotalResources; - return reinterpret_cast(ResourceMemoryEnd)[ImmutableSamplerInd]; - } - const SPIRVShaderStageInputAttribs& GetShaderStageInputAttribs(Uint32 n)const noexcept { VERIFY(n < m_NumShaderStageInputs, "Shader stage input index (", n, ") is out of range. Total input count: ", m_NumShaderStageInputs); auto* ResourceMemoryEnd = reinterpret_cast(m_MemoryBuffer.get()) + m_TotalResources; - auto* ImmutableSamplerMemoryEnd = reinterpret_cast(ResourceMemoryEnd) + m_NumImmutableSamplers; - return reinterpret_cast(ImmutableSamplerMemoryEnd)[n]; + return reinterpret_cast(ResourceMemoryEnd)[n]; } struct ResourceCounters @@ -272,8 +214,6 @@ public: Uint32 NumSepSmplrs = 0; Uint32 NumSepImgs = 0; }; - ResourceCounters CountResources(const SHADER_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes)const noexcept; SHADER_TYPE GetShaderType()const noexcept{return m_ShaderType;} @@ -285,80 +225,64 @@ public: typename THandleAC, typename THandleSepSmpl, typename THandleSepImg> - void ProcessResources(const SHADER_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - THandleUB HandleUB, - THandleSB HandleSB, - THandleImg HandleImg, - THandleSmplImg HandleSmplImg, - THandleAC HandleAC, - THandleSepSmpl HandleSepSmpl, - THandleSepImg HandleSepImg)const + void ProcessResources(THandleUB HandleUB, + THandleSB HandleSB, + THandleImg HandleImg, + THandleSmplImg HandleSmplImg, + THandleAC HandleAC, + THandleSepSmpl HandleSepSmpl, + THandleSepImg HandleSepImg)const { - Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); - for(Uint32 n=0; n < GetNumUBs(); ++n) { const auto& UB = GetUB(n); - if( IsAllowedType(UB.VarType, AllowedTypeBits) ) - HandleUB(UB, n); + HandleUB(UB, n); } for (Uint32 n = 0; n < GetNumSBs(); ++n) { const auto& SB = GetSB(n); - if (IsAllowedType(SB.VarType, AllowedTypeBits)) - HandleSB(SB, n); + HandleSB(SB, n); } for (Uint32 n = 0; n < GetNumImgs(); ++n) { const auto& Img = GetImg(n); - if (IsAllowedType(Img.VarType, AllowedTypeBits)) - HandleImg(Img, n); + HandleImg(Img, n); } for (Uint32 n = 0; n < GetNumSmpldImgs(); ++n) { const auto& SmplImg = GetSmpldImg(n); - if (IsAllowedType(SmplImg.VarType, AllowedTypeBits)) - HandleSmplImg(SmplImg, n); + HandleSmplImg(SmplImg, n); } for (Uint32 n = 0; n < GetNumACs(); ++n) { const auto& AC = GetAC(n); - if (IsAllowedType(AC.VarType, AllowedTypeBits)) - HandleAC(AC, n); + HandleAC(AC, n); } for (Uint32 n = 0; n < GetNumSepSmplrs(); ++n) { const auto& SepSmpl = GetSepSmplr(n); - if (IsAllowedType(SepSmpl.VarType, AllowedTypeBits)) - HandleSepSmpl(SepSmpl, n); + HandleSepSmpl(SepSmpl, n); } for (Uint32 n = 0; n < GetNumSepImgs(); ++n) { const auto& SepImg = GetSepImg(n); - if (IsAllowedType(SepImg.VarType, AllowedTypeBits)) - HandleSepImg(SepImg, n); + HandleSepImg(SepImg, n); } } template - void ProcessResources(const SHADER_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - THandler Handler)const + void ProcessResources(THandler Handler)const { - Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); - for(Uint32 n=0; n < GetTotalResources(); ++n) { const auto& Res = GetResource(n); - if( IsAllowedType(Res.VarType, AllowedTypeBits) ) - Handler(Res, n); + Handler(Res, n); } } @@ -375,7 +299,6 @@ public: private: void Initialize(IMemoryAllocator& Allocator, const ResourceCounters& Counters, - Uint32 NumImmutableSamplers, Uint32 NumShaderStageInputs, size_t ResourceNamesPoolSize); @@ -402,20 +325,13 @@ private: SPIRVShaderResourceAttribs& GetSepImg (Uint32 n)noexcept{ return GetResAttribs(n, GetNumSepImgs(), m_SeparateImageOffset ); } SPIRVShaderResourceAttribs& GetResource(Uint32 n)noexcept{ return GetResAttribs(n, GetTotalResources(), 0 ); } - SamplerPtrType& GetImmutableSampler(Uint32 n)noexcept - { - VERIFY(n < m_NumImmutableSamplers, "Immutable sampler index (", n, ") is out of range. Total immutable sampler count: ", m_NumImmutableSamplers); - auto* ResourceMemoryEnd = reinterpret_cast(m_MemoryBuffer.get()) + m_TotalResources; - return reinterpret_cast(ResourceMemoryEnd)[n]; - } - SPIRVShaderStageInputAttribs& GetShaderStageInputAttribs(Uint32 n)noexcept { return const_cast(const_cast(this)->GetShaderStageInputAttribs(n)); } // Memory buffer that holds all resources as continuous chunk of memory: - // | UBs | SBs | StrgImgs | SmplImgs | ACs | SepSamplers | SepImgs | Immutable Samplers | Stage Inputs | Resource Names | + // | UBs | SBs | StrgImgs | SmplImgs | ACs | SepSamplers | SepImgs | Stage Inputs | Resource Names | std::unique_ptr< void, STDDeleterRawMem > m_MemoryBuffer; StringPool m_ResourceNames; @@ -429,7 +345,6 @@ private: OffsetType m_SeparateSamplerOffset = 0; OffsetType m_SeparateImageOffset = 0; OffsetType m_TotalResources = 0; - OffsetType m_NumImmutableSamplers = 0; OffsetType m_NumShaderStageInputs = 0; SHADER_TYPE m_ShaderType = SHADER_TYPE_UNKNOWN; @@ -437,25 +352,3 @@ private: } -namespace std -{ -#if 0 - template<> - struct hash - { - size_t operator()(const Diligent::D3DShaderResourceAttribs &Attribs) const - { - return Attribs.GetHash(); - } - }; - - template<> - struct hash - { - size_t operator()(const Diligent::ShaderResources &Res) const - { - return Res.GetHash(); - } - }; -#endif -} diff --git a/Graphics/GLSLTools/src/SPIRVShaderResources.cpp b/Graphics/GLSLTools/src/SPIRVShaderResources.cpp index 6b896c8d..4f733103 100644 --- a/Graphics/GLSLTools/src/SPIRVShaderResources.cpp +++ b/Graphics/GLSLTools/src/SPIRVShaderResources.cpp @@ -50,7 +50,7 @@ Type GetResourceArraySize(const spirv_cross::Compiler& Compiler, static uint32_t GetDecorationOffset(const spirv_cross::Compiler& Compiler, const spirv_cross::Resource& Res, - spv::Decoration Decoration) + spv::Decoration Decoration) { VERIFY(Compiler.has_decoration(Res.id, Decoration), "Res \'", Res.name, "\' has no requested decoration"); uint32_t offset = 0; @@ -63,34 +63,18 @@ SPIRVShaderResourceAttribs::SPIRVShaderResourceAttribs(const spirv_cross::Compil const spirv_cross::Resource& Res, const char* _Name, ResourceType _Type, - SHADER_VARIABLE_TYPE _VarType, - Int32 _ImmutableSamplerInd, Uint32 _SepSmplrOrImgInd)noexcept : Name (_Name), ArraySize (GetResourceArraySize(Compiler, Res)), Type (_Type), - VarType (_VarType), - ImmutableSamplerInd (_ImmutableSamplerInd >= 0 ? static_cast(_ImmutableSamplerInd) : InvalidImmutableSamplerInd), SepSmplrOrImgInd (_SepSmplrOrImgInd), BindingDecorationOffset (GetDecorationOffset(Compiler, Res, spv::Decoration::DecorationBinding)), DescriptorSetDecorationOffset(GetDecorationOffset(Compiler, Res, spv::Decoration::DecorationDescriptorSet)) { - VERIFY(_ImmutableSamplerInd < 0 || _ImmutableSamplerInd <= std::numeric_limits::max(), "Static sampler index is out of representable range" ); VERIFY(_SepSmplrOrImgInd == SPIRVShaderResourceAttribs::InvalidSepSmplrOrImgInd || _Type == ResourceType::SeparateSampler || _Type == ResourceType::SeparateImage, "Only separate images or separate samplers can be assinged valid SepSmplrOrImgInd value"); } -static Int32 FindImmutableSampler(const ShaderDesc& shaderDesc, const std::string& SamplerName, const char* SamplerSuffix) -{ - for (Uint32 s=0; s < shaderDesc.NumStaticSamplers; ++s) - { - const auto& StSam = shaderDesc.StaticSamplers[s]; - if (StreqSuff(SamplerName.c_str(), StSam.SamplerOrTextureName, SamplerSuffix)) - return s; - } - - return -1; -} static spv::ExecutionModel ShaderTypeToExecutionModel(SHADER_TYPE ShaderType) { @@ -256,7 +240,7 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, ResCounters.NumACs = static_cast(resources.atomic_counters.size()); ResCounters.NumSepSmplrs = static_cast(resources.separate_samplers.size()); ResCounters.NumSepImgs = static_cast(resources.separate_images.size()); - Initialize(Allocator, ResCounters, shaderDesc.NumStaticSamplers, NumShaderStageInputs, ResourceNamesPoolSize); + Initialize(Allocator, ResCounters, NumShaderStageInputs, ResourceNamesPoolSize); { Uint32 CurrUB = 0; @@ -267,8 +251,7 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, SPIRVShaderResourceAttribs(Compiler, UB, m_ResourceNames.CopyString(name), - SPIRVShaderResourceAttribs::ResourceType::UniformBuffer, - GetShaderVariableType(name, shaderDesc)); + SPIRVShaderResourceAttribs::ResourceType::UniformBuffer); } VERIFY_EXPR(CurrUB == GetNumUBs()); } @@ -281,8 +264,7 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, SPIRVShaderResourceAttribs(Compiler, SB, m_ResourceNames.CopyString(SB.name), - SPIRVShaderResourceAttribs::ResourceType::StorageBuffer, - GetShaderVariableType(SB.name, shaderDesc)); + SPIRVShaderResourceAttribs::ResourceType::StorageBuffer); } VERIFY_EXPR(CurrSB == GetNumSBs()); } @@ -291,7 +273,6 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, Uint32 CurrSmplImg = 0; for (const auto &SmplImg : resources.sampled_images) { - auto ImmutableSamplerInd = FindImmutableSampler(shaderDesc, SmplImg.name, nullptr); const auto& type = Compiler.get_type(SmplImg.type_id); auto ResType = type.image.dim == spv::DimBuffer ? SPIRVShaderResourceAttribs::ResourceType::UniformTexelBuffer : @@ -300,16 +281,14 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, SPIRVShaderResourceAttribs(Compiler, SmplImg, m_ResourceNames.CopyString(SmplImg.name), - ResType, - GetShaderVariableType(SmplImg.name, shaderDesc), - ImmutableSamplerInd); + ResType); } VERIFY_EXPR(CurrSmplImg == GetNumSmpldImgs()); } { Uint32 CurrImg = 0; - for (const auto &Img : resources.storage_images) + for (const auto& Img : resources.storage_images) { const auto& type = Compiler.get_type(Img.type_id); auto ResType = type.image.dim == spv::DimBuffer ? @@ -319,52 +298,40 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, SPIRVShaderResourceAttribs(Compiler, Img, m_ResourceNames.CopyString(Img.name), - ResType, - GetShaderVariableType(Img.name, shaderDesc)); + ResType); } VERIFY_EXPR(CurrImg == GetNumImgs()); } { Uint32 CurrAC = 0; - for (const auto &AC : resources.atomic_counters) + for (const auto& AC : resources.atomic_counters) { new (&GetAC(CurrAC++)) SPIRVShaderResourceAttribs(Compiler, AC, m_ResourceNames.CopyString(AC.name), - SPIRVShaderResourceAttribs::ResourceType::AtomicCounter, - GetShaderVariableType(AC.name, shaderDesc)); + SPIRVShaderResourceAttribs::ResourceType::AtomicCounter); } VERIFY_EXPR(CurrAC == GetNumACs()); } { Uint32 CurrSepSmpl = 0; - for (const auto &SepSam : resources.separate_samplers) + for (const auto& SepSam : resources.separate_samplers) { - auto ImmutableSamplerInd = FindImmutableSampler(shaderDesc, SepSam.name, CombinedSamplerSuffix); - // Use texture or sampler name to derive sampler type - auto VarType = GetShaderVariableType(shaderDesc.DefaultVariableType, shaderDesc.VariableDesc, shaderDesc.NumVariables, - [&](const char* VarName) - { - return StreqSuff(SepSam.name.c_str(), VarName, CombinedSamplerSuffix); - }); - new (&GetSepSmplr(CurrSepSmpl++)) SPIRVShaderResourceAttribs(Compiler, SepSam, m_ResourceNames.CopyString(SepSam.name), - SPIRVShaderResourceAttribs::ResourceType::SeparateSampler, - VarType, - ImmutableSamplerInd); + SPIRVShaderResourceAttribs::ResourceType::SeparateSampler); } VERIFY_EXPR(CurrSepSmpl == GetNumSepSmplrs()); } { Uint32 CurrSepImg = 0; - for (const auto &SepImg : resources.separate_images) + for (const auto& SepImg : resources.separate_images) { Uint32 SamplerInd = SPIRVShaderResourceAttribs::InvalidSepSmplrOrImgInd; if (CombinedSamplerSuffix != nullptr) @@ -376,10 +343,6 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, if (StreqSuff(SepSmplr.Name, SepImg.name.c_str(), CombinedSamplerSuffix)) { SepSmplr.AssignSeparateImage(CurrSepImg); - // Do no assign immutable samplers to separate images as immutable - // samplers are permanently bound into the set layout - if (SepSmplr.IsImmutableSamplerAssigned()) - SamplerInd = NumSepSmpls; break; } } @@ -391,8 +354,6 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, SepImg, m_ResourceNames.CopyString(SepImg.name), SPIRVShaderResourceAttribs::ResourceType::SeparateImage, - GetShaderVariableType(SepImg.name, shaderDesc), - -1, SamplerInd); if (pNewSepImg->IsValidSepSamplerAssigned()) { @@ -413,13 +374,6 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, m_CombinedSamplerSuffix = m_ResourceNames.CopyString(CombinedSamplerSuffix); } - for (Uint32 s = 0; s < m_NumImmutableSamplers; ++s) - { - SamplerPtrType& pStaticSampler = GetImmutableSampler(s); - new (std::addressof(pStaticSampler)) SamplerPtrType; - pRenderDevice->CreateSampler(shaderDesc.StaticSamplers[s].Desc, &pStaticSampler); - } - if (LoadShaderStageInputs) { Uint32 CurrStageInput = 0; @@ -438,85 +392,10 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, VERIFY(m_ResourceNames.GetRemainingSize() == 0, "Names pool must be empty"); //LOG_INFO_MESSAGE(DumpResources()); - -#ifdef DEVELOPMENT - if (shaderDesc.NumVariables != 0) - { - for (Uint32 v = 0; v < shaderDesc.NumVariables; ++v) - { - bool VariableFound = false; - const auto* VarName = shaderDesc.VariableDesc[v].Name; - auto VarType = shaderDesc.VariableDesc[v].Type; - - for (Uint32 res = 0; res < GetTotalResources(); ++res) - { - const auto& ResAttribs = GetResource(res); - if (strcmp(ResAttribs.Name, VarName) == 0) - { - VariableFound = true; - break; - } - } - if (!VariableFound) - { - LOG_WARNING_MESSAGE("Variable '", VarName, "' labeled as ", GetShaderVariableTypeLiteralName(VarType), " is not found in shader '", shaderDesc.Name, "'"); - } - } - } - - if (shaderDesc.NumStaticSamplers != 0) - { - for (Uint32 s = 0; s < shaderDesc.NumStaticSamplers; ++s) - { - const auto* SamName = shaderDesc.StaticSamplers[s].SamplerOrTextureName; - bool SamplerFound = false; - - // Irrespective of whether HLSL-style combined image samplers are used, - // a static sampler can be assigned to GLSL sampled image (i.e. sampler2D g_tex) - for (Uint32 i = 0; i < GetNumSmpldImgs(); ++i) - { - const auto& SmplImg = GetSmpldImg(i); - SamplerFound = (strcmp(SmplImg.Name, SamName) == 0); - if (SamplerFound) - break; - } - - if (!SamplerFound) - { - // Check if static sampler is assigned to a separate sampler or - // separate image depending on whether HLSL-style combined samplers - // are used - for (Uint32 i = 0; i < GetNumSepSmplrs(); ++i) - { - const auto& SepSmpl = GetSepSmplr(i); - SamplerFound = StreqSuff(SepSmpl.Name, SamName, CombinedSamplerSuffix); - if (SamplerFound) - break; - } - } - - if (!SamplerFound) - { - LOG_WARNING_MESSAGE("Static sampler '", SamName, "' is not found in shader '", shaderDesc.Name, "'"); - } - } - } - - if (CombinedSamplerSuffix != nullptr) - { - for (Uint32 n=0; n < GetNumSepSmplrs(); ++n) - { - const auto& SepSmplr = GetSepSmplr(n); - if (!SepSmplr.IsValidSepImageAssigned()) - LOG_ERROR_MESSAGE("Shader '", shaderDesc.Name, "' uses combined texture samplers, but separate sampler '", SepSmplr.Name, "' is not assigned to any texture"); - } - } -#endif } void SPIRVShaderResources::Initialize(IMemoryAllocator& Allocator, const ResourceCounters& Counters, - Uint32 NumImmutableSamplers, Uint32 NumShaderStageInputs, size_t ResourceNamesPoolSize) { @@ -539,16 +418,11 @@ void SPIRVShaderResources::Initialize(IMemoryAllocator& Allocator, m_SeparateImageOffset = AdvanceOffset(Counters.NumSepImgs); m_TotalResources = AdvanceOffset(0); - VERIFY(NumImmutableSamplers <= MaxOffset, "Max offset exceeded"); - m_NumImmutableSamplers = static_cast(NumImmutableSamplers); - VERIFY(NumShaderStageInputs <= MaxOffset, "Max offset exceeded"); m_NumShaderStageInputs = static_cast(NumShaderStageInputs); static_assert(sizeof(SPIRVShaderResourceAttribs) % sizeof(void*) == 0, "Size of SPIRVShaderResourceAttribs struct must be multiple of sizeof(void*)"); - static_assert(sizeof(SamplerPtrType) % sizeof(void*) == 0, "Size of SamplerPtrType must be multiple of sizeof(void*)"); auto MemorySize = m_TotalResources * sizeof(SPIRVShaderResourceAttribs) + - m_NumImmutableSamplers * sizeof(SamplerPtrType) + m_NumShaderStageInputs * sizeof(SPIRVShaderStageInputAttribs) + ResourceNamesPoolSize * sizeof(char); @@ -562,11 +436,10 @@ void SPIRVShaderResources::Initialize(IMemoryAllocator& Allocator, if (MemorySize) { - auto *pRawMem = Allocator.Allocate(MemorySize, "Memory for shader resources", __FILE__, __LINE__); + auto* pRawMem = Allocator.Allocate(MemorySize, "Memory for shader resources", __FILE__, __LINE__); m_MemoryBuffer = std::unique_ptr>(pRawMem, Allocator); char* NamesPool = reinterpret_cast(m_MemoryBuffer.get()) + m_TotalResources * sizeof(SPIRVShaderResourceAttribs) + - m_NumImmutableSamplers * sizeof(SamplerPtrType) + m_NumShaderStageInputs * sizeof(SPIRVShaderStageInputAttribs); m_ResourceNames.AssignMemory(NamesPool, ResourceNamesPoolSize); } @@ -595,67 +468,11 @@ SPIRVShaderResources::~SPIRVShaderResources() for (Uint32 n = 0; n < GetNumSepImgs(); ++n) GetSepImg(n).~SPIRVShaderResourceAttribs(); - for (Uint32 n = 0; n < GetNumImmutableSamplers(); ++n) - GetImmutableSampler(n).~SamplerPtrType(); - for (Uint32 n = 0; n < GetNumShaderStageInputs(); ++n) GetShaderStageInputAttribs(n).~SPIRVShaderStageInputAttribs(); } -SPIRVShaderResources::ResourceCounters SPIRVShaderResources::CountResources(const SHADER_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes)const noexcept -{ - Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); (void)AllowedTypeBits; - ResourceCounters Counters; - ProcessResources( - AllowedVarTypes, NumAllowedTypes, - - [&](const SPIRVShaderResourceAttribs& UB, Uint32) - { - VERIFY_EXPR(UB.Type == SPIRVShaderResourceAttribs::ResourceType::UniformBuffer); - VERIFY_EXPR(IsAllowedType(UB.VarType, AllowedTypeBits)); - ++Counters.NumUBs; - }, - [&](const SPIRVShaderResourceAttribs& SB, Uint32) - { - VERIFY_EXPR(SB.Type == SPIRVShaderResourceAttribs::ResourceType::StorageBuffer); - VERIFY_EXPR(IsAllowedType(SB.VarType, AllowedTypeBits)); - ++Counters.NumSBs; - }, - [&](const SPIRVShaderResourceAttribs& Img, Uint32) - { - VERIFY_EXPR(Img.Type == SPIRVShaderResourceAttribs::ResourceType::StorageImage || Img.Type == SPIRVShaderResourceAttribs::ResourceType::StorageTexelBuffer); - VERIFY_EXPR(IsAllowedType(Img.VarType, AllowedTypeBits)); - ++Counters.NumImgs; - }, - [&](const SPIRVShaderResourceAttribs& SmplImg, Uint32) - { - VERIFY_EXPR(SmplImg.Type == SPIRVShaderResourceAttribs::ResourceType::SampledImage || SmplImg.Type == SPIRVShaderResourceAttribs::ResourceType::UniformTexelBuffer); - VERIFY_EXPR(IsAllowedType(SmplImg.VarType, AllowedTypeBits)); - ++Counters.NumSmpldImgs; - }, - [&](const SPIRVShaderResourceAttribs& AC, Uint32) - { - VERIFY_EXPR(AC.Type == SPIRVShaderResourceAttribs::ResourceType::AtomicCounter); - VERIFY_EXPR(IsAllowedType(AC.VarType, AllowedTypeBits)); - ++Counters.NumACs; - }, - [&](const SPIRVShaderResourceAttribs& SepSmpl, Uint32) - { - VERIFY_EXPR(SepSmpl.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler); - VERIFY_EXPR(IsAllowedType(SepSmpl.VarType, AllowedTypeBits)); - ++Counters.NumSepSmplrs; - }, - [&](const SPIRVShaderResourceAttribs& SepImg, Uint32) - { - VERIFY_EXPR(SepImg.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateImage); - VERIFY_EXPR(IsAllowedType(SepImg.VarType, AllowedTypeBits)); - ++Counters.NumSepImgs; - } - ); - return Counters; -} std::string SPIRVShaderResources::DumpResources() { @@ -663,7 +480,7 @@ std::string SPIRVShaderResources::DumpResources() ss << "Resource counters (" << GetTotalResources() << " total):" << std::endl << "UBs: " << GetNumUBs() << "; SBs: " << GetNumSBs() << "; Imgs: " << GetNumImgs() << "; Smpl Imgs: " << GetNumSmpldImgs() << "; ACs: " << GetNumACs() << "; Sep Imgs: " << GetNumSepImgs() << "; Sep Smpls: " << GetNumSepSmplrs() << '.' << std::endl - << "Num Static Samplers: " << GetNumImmutableSamplers() << std::endl << "Resources:"; + << "Resources:"; Uint32 ResNum = 0; auto DumpResource = [&ss, &ResNum](const SPIRVShaderResourceAttribs& Res) @@ -674,16 +491,20 @@ std::string SPIRVShaderResources::DumpResources() FullResNameSS << '[' << Res.ArraySize << ']'; FullResNameSS << '\''; ss << std::setw(32) << FullResNameSS.str(); - ss << " (" << GetShaderVariableTypeLiteralName(Res.VarType) << ")"; - - if (Res.IsImmutableSamplerAssigned()) + + if (Res.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateImage && Res.IsValidSepSamplerAssigned()) { - ss << " Immutable sampler: " << Res.GetImmutableSamplerInd(); + ss << " Assigned sep sampler ind: " << Res.GetAssignedSepSamplerInd(); } + else if (Res.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler && Res.IsValidSepImageAssigned()) + { + ss << " Assigned sep image ind: " << Res.GetAssignedSepImageInd(); + } + ++ResNum; }; - ProcessResources(nullptr, 0, + ProcessResources( [&](const SPIRVShaderResourceAttribs &UB, Uint32) { VERIFY(UB.Type == SPIRVShaderResourceAttribs::ResourceType::UniformBuffer, "Unexpected resource type"); @@ -750,13 +571,12 @@ bool SPIRVShaderResources::IsCompatibleWith(const SPIRVShaderResources& Resource GetNumSmpldImgs() != Resources.GetNumSmpldImgs() || GetNumACs() != Resources.GetNumACs() || GetNumSepImgs() != Resources.GetNumSepImgs() || - GetNumSepSmplrs() != Resources.GetNumSepSmplrs() || - GetNumImmutableSamplers() != Resources.GetNumImmutableSamplers()) + GetNumSepSmplrs() != Resources.GetNumSepSmplrs()) return false; VERIFY_EXPR(GetTotalResources() == Resources.GetTotalResources()); bool IsCompatible = true; - ProcessResources(nullptr, 0, + ProcessResources( [&](const SPIRVShaderResourceAttribs& Res, Uint32 n) { const auto& Res2 = Resources.GetResource(n); -- cgit v1.2.3 From ccce7d6fb134a653d7f9b6fd4089f1ba99777bb7 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Mon, 25 Feb 2019 21:16:05 -0800 Subject: Updated SaderVkImpl: removed static resources --- .../GraphicsEngineVulkan/include/ShaderVkImpl.h | 40 ++++++---------------- Graphics/GraphicsEngineVulkan/src/ShaderVkImpl.cpp | 23 +++---------- 2 files changed, 14 insertions(+), 49 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderVkImpl.h b/Graphics/GraphicsEngineVulkan/include/ShaderVkImpl.h index c21e10a2..c646820c 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderVkImpl.h @@ -29,9 +29,7 @@ #include "RenderDeviceVk.h" #include "ShaderVk.h" #include "ShaderBase.h" -#include "ShaderResourceLayoutVk.h" #include "SPIRVShaderResources.h" -#include "ShaderVariableVk.h" #include "RenderDeviceVkImpl.h" namespace Diligent @@ -46,55 +44,37 @@ class ShaderVkImpl final : public ShaderBase public: using TShaderBase = ShaderBase; - ShaderVkImpl(IReferenceCounters* pRefCounters, RenderDeviceVkImpl* pRenderDeviceVk, const ShaderCreationAttribs &CreationAttribs); + ShaderVkImpl(IReferenceCounters* pRefCounters, RenderDeviceVkImpl* pRenderDeviceVk, const ShaderCreateInfo &CreationAttribs); ~ShaderVkImpl(); - //virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override; + IMPLEMENT_QUERY_INTERFACE_IN_PLACE(IID_ShaderVk, TShaderBase); - virtual void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags )override + virtual Uint32 GetResourceCount()const { - m_StaticVarsMgr.BindResources(pResourceMapping, Flags); + UNSUPPORTED("Not yet implemented"); + return 0; } - virtual IShaderVariable* GetShaderVariable(const Char* Name)override + virtual const ShaderResourceDesc* GetResources()const { - return m_StaticVarsMgr.GetVariable(Name); - } - - virtual Uint32 GetVariableCount() const override final - { - return m_StaticVarsMgr.GetVariableCount(); - } - - virtual IShaderVariable* GetShaderVariable(Uint32 Index)override final - { - return m_StaticVarsMgr.GetVariable(Index); + UNSUPPORTED("Not yet implemented"); + return nullptr; } virtual const std::vector& GetSPIRV()const override final { return m_SPIRV; } - + const std::shared_ptr& GetShaderResources()const{return m_pShaderResources;} - const ShaderResourceLayoutVk& GetStaticResLayout()const { return m_StaticResLayout; } - const ShaderResourceCacheVk& GetStaticResCache() const { return m_StaticResCache; } - const char* GetEntryPoint() const { return m_EntryPoint.c_str(); } -#ifdef DEVELOPMENT - bool DvpVerifyStaticResourceBindings()const; -#endif - private: void MapHLSLVertexShaderInputs(); - // ShaderResources class instance must be referenced through the shared pointer, because + // SPIRVShaderResources class instance must be referenced through the shared pointer, because // it is referenced by ShaderResourceLayoutVk class instances std::shared_ptr m_pShaderResources; - ShaderResourceLayoutVk m_StaticResLayout; - ShaderResourceCacheVk m_StaticResCache; - ShaderVariableManagerVk m_StaticVarsMgr; std::string m_EntryPoint; std::vector m_SPIRV; diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderVkImpl.cpp index fef2d052..3cf4c3f0 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderVkImpl.cpp @@ -37,13 +37,10 @@ namespace Diligent { -ShaderVkImpl::ShaderVkImpl(IReferenceCounters* pRefCounters, - RenderDeviceVkImpl* pRenderDeviceVk, - const ShaderCreationAttribs& CreationAttribs) : - TShaderBase (pRefCounters, pRenderDeviceVk, CreationAttribs.Desc), - m_StaticResLayout (*this, pRenderDeviceVk->GetLogicalDevice()), - m_StaticResCache (ShaderResourceCacheVk::DbgCacheContentType::StaticShaderResources), - m_StaticVarsMgr (*this) +ShaderVkImpl::ShaderVkImpl(IReferenceCounters* pRefCounters, + RenderDeviceVkImpl* pRenderDeviceVk, + const ShaderCreateInfo& CreationAttribs) : + TShaderBase(pRefCounters, pRenderDeviceVk, CreationAttribs.Desc) { if (CreationAttribs.Source != nullptr || CreationAttribs.FilePath != nullptr) { @@ -95,10 +92,6 @@ ShaderVkImpl::ShaderVkImpl(IReferenceCounters* pRefCounters, { MapHLSLVertexShaderInputs(); } - - m_StaticResLayout.InitializeStaticResourceLayout(m_pShaderResources, GetRawAllocator(), m_StaticResCache); - // m_StaticResLayout only contains static resources, so reference all of them - m_StaticVarsMgr.Initialize(m_StaticResLayout, GetRawAllocator(), nullptr, 0, m_StaticResCache); } void ShaderVkImpl::MapHLSLVertexShaderInputs() @@ -134,14 +127,6 @@ void ShaderVkImpl::MapHLSLVertexShaderInputs() ShaderVkImpl::~ShaderVkImpl() { - m_StaticVarsMgr.Destroy(GetRawAllocator()); } -#ifdef DEVELOPMENT -bool ShaderVkImpl::DvpVerifyStaticResourceBindings()const -{ - return m_StaticResLayout.dvpVerifyBindings(m_StaticResCache); -} -#endif - } -- cgit v1.2.3 From c03fae535f3e5080906c43690e800ae34572278c Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Tue, 26 Feb 2019 22:49:28 -0800 Subject: Updating some files to match the new API --- Graphics/GLSLTools/include/GLSLSourceBuilder.h | 2 +- Graphics/GLSLTools/include/SPIRVUtils.h | 2 +- Graphics/GLSLTools/src/GLSLSourceBuilder.cpp | 2 +- Graphics/GLSLTools/src/SPIRVShaderResources.cpp | 12 ++++++++++++ Graphics/GLSLTools/src/SPIRVUtils.cpp | 2 +- .../interface/GraphicsAccessories.h | 4 ++-- .../src/GraphicsAccessories.cpp | 22 +++++++++++----------- .../src/GenerateMipsVkHelper.cpp | 6 +++--- 8 files changed, 32 insertions(+), 20 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GLSLTools/include/GLSLSourceBuilder.h b/Graphics/GLSLTools/include/GLSLSourceBuilder.h index bfd6e55c..958f0faf 100644 --- a/Graphics/GLSLTools/include/GLSLSourceBuilder.h +++ b/Graphics/GLSLTools/include/GLSLSourceBuilder.h @@ -36,7 +36,7 @@ enum TargetGLSLCompiler driver }; -String BuildGLSLSourceString(const ShaderCreationAttribs& CreationAttribs, +String BuildGLSLSourceString(const ShaderCreateInfo& CreationAttribs, const DeviceCaps& deviceCaps, TargetGLSLCompiler TargetCompiler, const char* ExtraDefinitions = nullptr); diff --git a/Graphics/GLSLTools/include/SPIRVUtils.h b/Graphics/GLSLTools/include/SPIRVUtils.h index 75fa8108..3859a587 100644 --- a/Graphics/GLSLTools/include/SPIRVUtils.h +++ b/Graphics/GLSLTools/include/SPIRVUtils.h @@ -33,6 +33,6 @@ namespace Diligent void InitializeGlslang(); void FinalizeGlslang(); std::vector GLSLtoSPIRV(SHADER_TYPE ShaderType, const char* ShaderSource, int SourceCodeLen, IDataBlob** ppCompilerOutput); -std::vector HLSLtoSPIRV(const ShaderCreationAttribs& Attribs, IDataBlob** ppCompilerOutput); +std::vector HLSLtoSPIRV(const ShaderCreateInfo& Attribs, IDataBlob** ppCompilerOutput); } \ No newline at end of file diff --git a/Graphics/GLSLTools/src/GLSLSourceBuilder.cpp b/Graphics/GLSLTools/src/GLSLSourceBuilder.cpp index 905ecfa1..2da42437 100644 --- a/Graphics/GLSLTools/src/GLSLSourceBuilder.cpp +++ b/Graphics/GLSLTools/src/GLSLSourceBuilder.cpp @@ -33,7 +33,7 @@ namespace Diligent { -String BuildGLSLSourceString(const ShaderCreationAttribs& CreationAttribs, +String BuildGLSLSourceString(const ShaderCreateInfo& CreationAttribs, const DeviceCaps& deviceCaps, TargetGLSLCompiler TargetCompiler, const char* ExtraDefinitions) diff --git a/Graphics/GLSLTools/src/SPIRVShaderResources.cpp b/Graphics/GLSLTools/src/SPIRVShaderResources.cpp index 4f733103..8c8f673f 100644 --- a/Graphics/GLSLTools/src/SPIRVShaderResources.cpp +++ b/Graphics/GLSLTools/src/SPIRVShaderResources.cpp @@ -392,6 +392,18 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, VERIFY(m_ResourceNames.GetRemainingSize() == 0, "Names pool must be empty"); //LOG_INFO_MESSAGE(DumpResources()); + +#ifdef DEVELOPMENT + if (CombinedSamplerSuffix != nullptr) + { + for (Uint32 n=0; n < GetNumSepSmplrs(); ++n) + { + const auto& SepSmplr = GetSepSmplr(n); + if (!SepSmplr.IsValidSepImageAssigned()) + LOG_ERROR_MESSAGE("Shader '", shaderDesc.Name, "' uses combined texture samplers, but separate sampler '", SepSmplr.Name, "' is not assigned to any texture"); + } + } +#endif } void SPIRVShaderResources::Initialize(IMemoryAllocator& Allocator, diff --git a/Graphics/GLSLTools/src/SPIRVUtils.cpp b/Graphics/GLSLTools/src/SPIRVUtils.cpp index 9f9a7d88..894560fe 100644 --- a/Graphics/GLSLTools/src/SPIRVUtils.cpp +++ b/Graphics/GLSLTools/src/SPIRVUtils.cpp @@ -411,7 +411,7 @@ private: std::unordered_map> m_DataBlobs; }; -std::vector HLSLtoSPIRV(const ShaderCreationAttribs& Attribs, IDataBlob** ppCompilerOutput) +std::vector HLSLtoSPIRV(const ShaderCreateInfo& Attribs, IDataBlob** ppCompilerOutput) { EShLanguage ShLang = ShaderTypeToShLanguage(Attribs.Desc.ShaderType); glslang::TShader Shader(ShLang); diff --git a/Graphics/GraphicsAccessories/interface/GraphicsAccessories.h b/Graphics/GraphicsAccessories/interface/GraphicsAccessories.h index 69de47c7..ef769bfc 100644 --- a/Graphics/GraphicsAccessories/interface/GraphicsAccessories.h +++ b/Graphics/GraphicsAccessories/interface/GraphicsAccessories.h @@ -185,13 +185,13 @@ const Char *GetShaderTypeLiteralName(SHADER_TYPE ShaderType); /// Returns the literal name of a shader variable type. For instance, -/// for SHADER_VARIABLE_TYPE_STATIC, if bGetFullName == true, "SHADER_VARIABLE_TYPE_STATIC" will be returned; +/// for SHADER_RESOURCE_VARIABLE_TYPE_STATIC, if bGetFullName == true, "SHADER_RESOURCE_VARIABLE_TYPE_STATIC" will be returned; /// if bGetFullName == false, "static" will be returned /// \param [in] VarType - Variable type. /// \param [in] bGetFullName - Whether to return string representation of the enum value /// \return Literal name of the shader variable type. -const Char *GetShaderVariableTypeLiteralName(SHADER_VARIABLE_TYPE VarType, bool bGetFullName = false); +const Char *GetShaderVariableTypeLiteralName(SHADER_RESOURCE_VARIABLE_TYPE VarType, bool bGetFullName = false); /// Overloaded function that returns the literal name of a texture view type. /// see GetTexViewTypeLiteralName(). diff --git a/Graphics/GraphicsAccessories/src/GraphicsAccessories.cpp b/Graphics/GraphicsAccessories/src/GraphicsAccessories.cpp index 74727eb0..3613076f 100644 --- a/Graphics/GraphicsAccessories/src/GraphicsAccessories.cpp +++ b/Graphics/GraphicsAccessories/src/GraphicsAccessories.cpp @@ -475,25 +475,25 @@ const Char *GetShaderTypeLiteralName( SHADER_TYPE ShaderType ) } } -const Char *GetShaderVariableTypeLiteralName(SHADER_VARIABLE_TYPE VarType, bool bGetFullName) +const Char *GetShaderVariableTypeLiteralName(SHADER_RESOURCE_VARIABLE_TYPE VarType, bool bGetFullName) { - static const Char* ShortVarTypeNameStrings[SHADER_VARIABLE_TYPE_NUM_TYPES]; - static const Char* FullVarTypeNameStrings[SHADER_VARIABLE_TYPE_NUM_TYPES]; + static const Char* ShortVarTypeNameStrings[SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES]; + static const Char* FullVarTypeNameStrings[SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES]; static bool bVarTypeStrsInit = false; if( !bVarTypeStrsInit ) { - ShortVarTypeNameStrings[SHADER_VARIABLE_TYPE_STATIC] = "static"; - ShortVarTypeNameStrings[SHADER_VARIABLE_TYPE_MUTABLE] = "mutable"; - ShortVarTypeNameStrings[SHADER_VARIABLE_TYPE_DYNAMIC] = "dynamic"; - FullVarTypeNameStrings[SHADER_VARIABLE_TYPE_STATIC] = "SHADER_VARIABLE_TYPE_STATIC"; - FullVarTypeNameStrings[SHADER_VARIABLE_TYPE_MUTABLE] = "SHADER_VARIABLE_TYPE_MUTABLE"; - FullVarTypeNameStrings[SHADER_VARIABLE_TYPE_DYNAMIC] = "SHADER_VARIABLE_TYPE_DYNAMIC"; + ShortVarTypeNameStrings[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] = "static"; + ShortVarTypeNameStrings[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE] = "mutable"; + ShortVarTypeNameStrings[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC] = "dynamic"; + FullVarTypeNameStrings[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] = "SHADER_RESOURCE_VARIABLE_TYPE_STATIC"; + FullVarTypeNameStrings[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE] = "SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE"; + FullVarTypeNameStrings[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC] = "SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC"; - static_assert(SHADER_VARIABLE_TYPE_NUM_TYPES == SHADER_VARIABLE_TYPE_DYNAMIC + 1, "Not all shader variable types initialized."); + static_assert(SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES == SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC + 1, "Not all shader variable types initialized."); bVarTypeStrsInit = true; } - if( VarType >= SHADER_VARIABLE_TYPE_STATIC && VarType < SHADER_VARIABLE_TYPE_NUM_TYPES ) + if( VarType >= SHADER_RESOURCE_VARIABLE_TYPE_STATIC && VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES ) return (bGetFullName ? FullVarTypeNameStrings : ShortVarTypeNameStrings)[VarType]; else { diff --git a/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp b/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp index fc9af5a8..793aea80 100644 --- a/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp +++ b/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp @@ -104,16 +104,16 @@ namespace Diligent std::array, 4> GenerateMipsVkHelper::CreatePSOs(TEXTURE_FORMAT Fmt) { - ShaderCreationAttribs CSCreateAttribs; + ShaderCreateInfo CSCreateAttribs; std::array, 4> PSOs; CSCreateAttribs.Source = g_GenerateMipsCSSource; CSCreateAttribs.EntryPoint = "main"; CSCreateAttribs.SourceLanguage = SHADER_SOURCE_LANGUAGE_GLSL; CSCreateAttribs.Desc.ShaderType = SHADER_TYPE_COMPUTE; - CSCreateAttribs.Desc.DefaultVariableType = SHADER_VARIABLE_TYPE_DYNAMIC; + CSCreateAttribs.Desc.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; - ShaderVariableDesc VarDesc{"CB", SHADER_VARIABLE_TYPE_STATIC}; + ShaderResourceVariableDesc VarDesc{"CB", SHADER_RESOURCE_VARIABLE_TYPE_STATIC}; CSCreateAttribs.Desc.VariableDesc = &VarDesc; CSCreateAttribs.Desc.NumVariables = 1; -- cgit v1.2.3 From 786c4f793220a7ca259f8ed9f5854a2d07941f99 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Wed, 27 Feb 2019 08:55:49 -0800 Subject: Updated ShaderResourceLayoutVk --- .../include/ShaderResourceLayoutVk.h | 141 +++++--- .../src/ShaderResourceLayoutVk.cpp | 377 +++++++++++++++------ 2 files changed, 354 insertions(+), 164 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h index a4970680..f49bc342 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h @@ -30,14 +30,14 @@ // // m_ResourceBuffer // | -// || VkResource[0] ... VkResource[s-1] | VkResource[s] ... VkResource[s+m-1] | VkResource[s+m] ... VkResource[s+m+d-1] || -// || | | || -// || SHADER_VARIABLE_TYPE_STATIC | SHADER_VARIABLE_TYPE_MUTABLE | SHADER_VARIABLE_TYPE_DYNAMIC || -// || | | || +// || VkResource[0] ... VkResource[s-1] | VkResource[s] ... VkResource[s+m-1] | VkResource[s+m] ... VkResource[s+m+d-1] || || +// || | | || || +// || VARIABLE_TYPE_STATIC | VARIABLE_TYPE_MUTABLE | VARIABLE_TYPE_DYNAMIC || Immutable Samplers || +// || | | || || // -// s == m_NumResources[SHADER_VARIABLE_TYPE_STATIC] -// m == m_NumResources[SHADER_VARIABLE_TYPE_MUTABLE] -// d == m_NumResources[SHADER_VARIABLE_TYPE_DYNAMIC] +// s == m_NumResources[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] +// m == m_NumResources[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE] +// d == m_NumResources[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC] // // // @@ -86,17 +86,17 @@ // // // -// ShaderResourceLayoutVk is used as follows: -// * Every shader object (ShaderVkImpl) contains shader resource layout that facilitates management of static shader resources -// ** The resource layout defines artificial layout where resource binding matches the -// resource type (SPIRVShaderResourceAttribs::ResourceType) -// * Every pipeline state object (PipelineStateVkImpl) maintains shader resource layout for every active shader stage -// ** All variable types are preserved -// ** Bindings, descriptor sets and offsets are assigned during the initialization +// Every pipeline state object (PipelineStateVkImpl) keeps the following layouts: +// * One layout object per shader stage to facilitate management of static shader resources +// - Uses artificial layout where resource binding matches the resource type (SPIRVShaderResourceAttribs::ResourceType) +// * One layout object per shader stage used by SRBs to manage all resource types: +// - All variable types are preserved +// - Bindings, descriptor sets and offsets are assigned during the initialization #include #include +#include "PipelineState.h" #include "ShaderBase.h" #include "HashUtils.h" #include "ShaderResourceCacheVk.h" @@ -107,7 +107,7 @@ namespace Diligent { /// Diligent::ShaderResourceLayoutVk class -// sizeof(ShaderResourceLayoutVk)==56 (MS compiler, x64) +// sizeof(ShaderResourceLayoutVk)==64 (MS compiler, x64) - TODO: verify class ShaderResourceLayoutVk { public: @@ -121,53 +121,68 @@ public: ~ShaderResourceLayoutVk(); - // This method is called by ShaderVkImpl class instance to initialize static - // shader resource layout and cache + // This method is called by PipelineStateVkImpl class instance to initialize static + // shader resource layout and the cache void InitializeStaticResourceLayout(std::shared_ptr pSrcResources, IMemoryAllocator& LayoutDataAllocator, + const PipelineLayoutDesc& LayoutDesc, ShaderResourceCacheVk& StaticResourceCache); // This method is called by PipelineStateVkImpl class instance to initialize resource - // layouts for all shader stages in a pipeline. - static void Initialize(Uint32 NumShaders, + // layouts for all shader stages in the pipeline. + static void Initialize(IRenderDevice* pRenderDevice, + Uint32 NumShaders, ShaderResourceLayoutVk Layouts[], std::shared_ptr pShaderResources[], IMemoryAllocator& LayoutDataAllocator, + const PipelineLayoutDesc& LayoutDesc, std::vector SPIRVs[], class PipelineLayout& PipelineLayout); - // sizeof(VkResource) == 24 (x64) + // sizeof(VkResource) == 24 (x64) - TODO: Verify struct VkResource { - VkResource(const VkResource&) = delete; - VkResource(VkResource&&) = delete; - VkResource& operator = (const VkResource&) = delete; - VkResource& operator = (VkResource&&) = delete; + VkResource (const VkResource&) = delete; + VkResource ( VkResource&&) = delete; + VkResource& operator = (const VkResource&) = delete; + VkResource& operator = ( VkResource&&) = delete; + + static constexpr const Uint32 CacheOffsetBits = 21; + static constexpr const Uint32 SamplerIndBits = 8; + static constexpr const Uint32 VariableTypeBits = 2; + static constexpr const Uint32 ImmutableSamplerFlagBits = 1; + static_assert(CacheOffsetBits + SamplerIndBits + VariableTypeBits + ImmutableSamplerFlagBits == 32, "Elements are expected to be packed into 32 bits"); + static_assert(SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES <= (1<(_Binding)), - DescriptorSet (static_cast(_DescriptorSet)), - CacheOffset (_CacheOffset), - SamplerInd (_SamplerInd), - SpirvAttribs (_SpirvAttribs), - ParentResLayout (_ParentLayout) + Uint32 _SamplerInd, + bool _ImmutableSamplerAssigned = false)noexcept : + Binding (static_cast(_Binding)), + DescriptorSet (static_cast(_DescriptorSet)), + CacheOffset (_CacheOffset), + SamplerInd (_SamplerInd), + VariableType (_VariableType), + ImmutableSamplerAssigned (_ImmutableSamplerAssigned ? 1 : 0), + SpirvAttribs (_SpirvAttribs), + ParentResLayout (_ParentLayout) { VERIFY(_CacheOffset < (1 << CacheOffsetBits), "Cache offset (", _CacheOffset, ") exceeds max representable value ", (1 << CacheOffsetBits) ); VERIFY(_SamplerInd < (1 << SamplerIndBits), "Sampler index (", _SamplerInd, ") exceeds max representable value ", (1 << SamplerIndBits) ); @@ -188,6 +203,17 @@ public: const VkDescriptorBufferInfo* pBufferInfo, const VkBufferView* pTexelBufferView)const; + bool IsImmutableSamplerAssigned() const + { + VERIFY_EXPR(SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateImage); + return ImmutableSamplerAssigned != 0; + } + + SHADER_RESOURCE_VARIABLE_TYPE GetVariableType() const + { + return static_cast(VariableType); + } + private: void CacheUniformBuffer(IDeviceObject* pBuffer, ShaderResourceCacheVk::Resource& DstRes, @@ -233,7 +259,7 @@ public: bool dvpVerifyBindings(const ShaderResourceCacheVk& ResourceCache)const; #endif - Uint32 GetResourceCount(SHADER_VARIABLE_TYPE VarType)const + Uint32 GetResourceCount(SHADER_RESOURCE_VARIABLE_TYPE VarType)const { return m_NumResources[VarType]; } @@ -247,7 +273,7 @@ public: const Char* GetShaderName()const; - const VkResource& GetResource(SHADER_VARIABLE_TYPE VarType, Uint32 r)const + const VkResource& GetResource(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 r)const { VERIFY_EXPR( r < m_NumResources[VarType] ); auto* Resources = reinterpret_cast(m_ResourceBuffer.get()); @@ -257,16 +283,16 @@ public: bool IsUsingSeparateSamplers()const {return !m_pResources->IsUsingCombinedSamplers();} private: - Uint32 GetResourceOffset(SHADER_VARIABLE_TYPE VarType, Uint32 r)const + Uint32 GetResourceOffset(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 r)const { VERIFY_EXPR( r < m_NumResources[VarType] ); - static_assert(SHADER_VARIABLE_TYPE_STATIC == 0, "SHADER_VARIABLE_TYPE_STATIC == 0 expected"); - r += (VarType > SHADER_VARIABLE_TYPE_STATIC) ? m_NumResources[SHADER_VARIABLE_TYPE_STATIC] : 0; - static_assert(SHADER_VARIABLE_TYPE_MUTABLE == 1, "SHADER_VARIABLE_TYPE_MUTABLE == 1 expected"); - r += (VarType > SHADER_VARIABLE_TYPE_MUTABLE) ? m_NumResources[SHADER_VARIABLE_TYPE_MUTABLE] : 0; + static_assert(SHADER_RESOURCE_VARIABLE_TYPE_STATIC == 0, "SHADER_RESOURCE_VARIABLE_TYPE_STATIC == 0 expected"); + r += (VarType > SHADER_RESOURCE_VARIABLE_TYPE_STATIC) ? m_NumResources[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] : 0; + static_assert(SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE == 1, "SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE == 1 expected"); + r += (VarType > SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE) ? m_NumResources[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE] : 0; return r; } - VkResource& GetResource(SHADER_VARIABLE_TYPE VarType, Uint32 r) + VkResource& GetResource(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 r) { VERIFY_EXPR( r < m_NumResources[VarType] ); auto* Resources = reinterpret_cast(m_ResourceBuffer.get()); @@ -282,16 +308,26 @@ private: Uint32 GetTotalResourceCount()const { - return m_NumResources[SHADER_VARIABLE_TYPE_NUM_TYPES]; + return m_NumResources[SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES]; } void AllocateMemory(std::shared_ptr pSrcResources, IMemoryAllocator& Allocator, - const SHADER_VARIABLE_TYPE* AllowedVarTypes, + const PipelineLayoutDesc& LayoutDesc, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes); - Uint32 FindAssignedSampler(const SPIRVShaderResourceAttribs& SepImg, Uint32 CurrResourceCount)const; + Uint32 FindAssignedSampler(const SPIRVShaderResourceAttribs& SepImg, + Uint32 CurrResourceCount, + SHADER_RESOURCE_VARIABLE_TYPE ImgVarType)const; + using ImmutableSamplerPtrType = RefCntAutoPtr; + ImmutableSamplerPtrType& GetImmutableSampler(Uint32 n)noexcept + { + VERIFY(n < m_NumImmutableSamplers, "Immutable sampler index (", n, ") is out of range. Total immutable sampler count: ", m_NumImmutableSamplers); + auto* ResourceMemoryEnd = reinterpret_cast(m_ResourceBuffer.get()) + GetTotalResourceCount(); + return reinterpret_cast(ResourceMemoryEnd)[n]; + } IObject& m_Owner; const VulkanUtilities::VulkanLogicalDevice& m_LogicalDevice; @@ -301,7 +337,8 @@ private: // there may be multiple objects referencing the same set of resources std::shared_ptr m_pResources; - std::array m_NumResources = {}; + std::array m_NumResources = {}; + Uint32 m_NumImmutableSamplers = 0; }; } diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp index 8915d67f..9151fc9a 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp @@ -32,11 +32,64 @@ #include "SamplerVkImpl.h" #include "ShaderVkImpl.h" #include "PipelineLayout.h" +#include "ShaderResourceVariableBase.h" +#include "StringTools.h" #include "PipelineStateVkImpl.h" namespace Diligent { +static Int32 FindImmutableSampler(SHADER_TYPE ShaderType, + const PipelineLayoutDesc& LayoutDesc, + const SPIRVShaderResourceAttribs& Attribs, + const char* SamplerSuffix) +{ + if (Attribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateImage) + { + SamplerSuffix = nullptr; + } + else if (Attribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler) + { + // Use SamplerSuffix. If HLSL-style combined images samplers are not used, + // SamplerSuffix will be null and we will be looking for the sampler itself. + } + else + { + return -1; + } + + for (Uint32 s=0; s < LayoutDesc.NumStaticSamplers; ++s) + { + const auto& StSam = LayoutDesc.StaticSamplers[s]; + if ( ((StSam.ShaderStages & ShaderType) != 0) && StreqSuff(Attribs.Name, StSam.SamplerOrTextureName, SamplerSuffix) ) + return s; + } + + return -1; +} + +static SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE ShaderType, + const SPIRVShaderResourceAttribs& Attribs, + const PipelineLayoutDesc& LayoutDesc, + const char* CombinedSamplerSuffix) +{ + if (Attribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler) + { + // Use texture or sampler name to derive separate sampler type + // When HLSL-style combined image samplers are not used, CombinedSamplerSuffix is null + return GetShaderVariableType(ShaderType, LayoutDesc.DefaultVariableType, LayoutDesc.Variables, LayoutDesc.NumVariables, + [&](const char* VarName) + { + return StreqSuff(Attribs.Name, VarName, CombinedSamplerSuffix); + }); + } + else + { + return GetShaderVariableType(ShaderType, Attribs.Name, LayoutDesc); + } +} + + ShaderResourceLayoutVk::ShaderResourceLayoutVk(IObject& Owner, const VulkanUtilities::VulkanLogicalDevice& LogicalDevice) : m_Owner(Owner), @@ -49,11 +102,15 @@ ShaderResourceLayoutVk::~ShaderResourceLayoutVk() auto* Resources = reinterpret_cast(m_ResourceBuffer.get()); for (Uint32 r=0; r < GetTotalResourceCount(); ++r) Resources[r].~VkResource(); + + for(Uint32 s=0; s < m_NumImmutableSamplers; ++s) + GetImmutableSampler(s).~ImmutableSamplerPtrType(); } void ShaderResourceLayoutVk::AllocateMemory(std::shared_ptr pSrcResources, IMemoryAllocator& Allocator, - const SHADER_VARIABLE_TYPE* AllowedVarTypes, + const PipelineLayoutDesc& LayoutDesc, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes) { VERIFY(!m_ResourceBuffer, "Memory has already been initialized"); @@ -62,50 +119,77 @@ void ShaderResourceLayoutVk::AllocateMemory(std::shared_ptrGetShaderType(); + const auto* CombinedSamplerSuffix = m_pResources->GetCombinedSamplerSuffix(); // Count number of resources to allocate all needed memory m_pResources->ProcessResources( - AllowedVarTypes, NumAllowedTypes, - [&](const SPIRVShaderResourceAttribs& ResAttribs, Uint32) { - VERIFY_EXPR(IsAllowedType(ResAttribs.VarType, AllowedTypeBits)); - VERIFY( Uint32{m_NumResources[ResAttribs.VarType]} + 1 <= Uint32{std::numeric_limits::max()}, "Number of resources exceeds max representable value"); - ++m_NumResources[ResAttribs.VarType]; + auto VarType = GetShaderVariableType(ShaderType, ResAttribs, LayoutDesc, CombinedSamplerSuffix); + if (IsAllowedType(VarType, AllowedTypeBits)) + { + VERIFY( Uint32{m_NumResources[VarType]} + 1 <= Uint32{std::numeric_limits::max()}, "Number of resources exceeds max representable value"); + ++m_NumResources[VarType]; + } } ); Uint32 TotalResources = 0; - for (SHADER_VARIABLE_TYPE VarType = SHADER_VARIABLE_TYPE_STATIC; VarType < SHADER_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)) { TotalResources += m_NumResources[VarType]; } VERIFY(TotalResources <= Uint32{std::numeric_limits::max()}, "Total number of resources exceeds Uint16 max representable value" ); - m_NumResources[SHADER_VARIABLE_TYPE_NUM_TYPES] = static_cast(TotalResources); + m_NumResources[SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES] = static_cast(TotalResources); - size_t MemSize = TotalResources * sizeof(VkResource); + m_NumImmutableSamplers = 0; + for(Uint32 s=0; s < LayoutDesc.NumStaticSamplers; ++s) + { + const auto& StSamDesc = LayoutDesc.StaticSamplers[s]; + if ((StSamDesc.ShaderStages & ShaderType) != 0) + ++m_NumImmutableSamplers; + } + + size_t MemSize = TotalResources * sizeof(VkResource) + m_NumImmutableSamplers * sizeof(ImmutableSamplerPtrType); + static_assert( (sizeof(VkResource) % sizeof(void*)) == 0, "sizeof(VkResource) must be multiple of sizeof(void*)" ); if (MemSize == 0) return; auto* pRawMem = ALLOCATE(Allocator, "Raw memory buffer for shader resource layout resources", MemSize); m_ResourceBuffer = std::unique_ptr >(pRawMem, Allocator); + for(Uint32 s=0; s < m_NumImmutableSamplers; ++s) + { + // We need to initialize immutable samplers + new(&GetImmutableSampler(s)) ImmutableSamplerPtrType; + } } + void ShaderResourceLayoutVk::InitializeStaticResourceLayout(std::shared_ptr pSrcResources, IMemoryAllocator& LayoutDataAllocator, + const PipelineLayoutDesc& LayoutDesc, ShaderResourceCacheVk& StaticResourceCache) { - auto AllowedVarType = SHADER_VARIABLE_TYPE_STATIC; - AllocateMemory(std::move(pSrcResources), LayoutDataAllocator, &AllowedVarType, 1); + auto AllowedVarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; + AllocateMemory(std::move(pSrcResources), LayoutDataAllocator, LayoutDesc, &AllowedVarType, 1); - std::array CurrResInd = {}; + std::array CurrResInd = {}; Uint32 StaticResCacheSize = 0; + const Uint32 AllowedTypeBits = GetAllowedTypeBits(&AllowedVarType, 1); + const auto ShaderType = pSrcResources->GetShaderType(); + const auto* CombinedSamplerSuffix = pSrcResources->GetCombinedSamplerSuffix(); + m_pResources->ProcessResources( - &AllowedVarType, 1, [&](const SPIRVShaderResourceAttribs& Attribs, Uint32) { + auto VarType = GetShaderVariableType(ShaderType, Attribs, LayoutDesc, CombinedSamplerSuffix); + if (!IsAllowedType(VarType, AllowedTypeBits)) + return; + + //TODO: how to handle static samplers? + Uint32 Binding = Attribs.Type; Uint32 DescriptorSet = 0; Uint32 CacheOffset = StaticResCacheSize; @@ -115,15 +199,15 @@ void ShaderResourceLayoutVk::InitializeStaticResourceLayout(std::shared_ptr(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(CurrResInd[VarType] == m_NumResources[VarType], "Not all resources are initialized, which will cause a crash when dtor is called"); } @@ -133,25 +217,89 @@ void ShaderResourceLayoutVk::InitializeStaticResourceLayout(std::shared_ptr pShaderResources[], IMemoryAllocator& LayoutDataAllocator, + const PipelineLayoutDesc& LayoutDesc, std::vector SPIRVs[], class PipelineLayout& PipelineLayout) { - SHADER_VARIABLE_TYPE* AllowedVarTypes = nullptr; - Uint32 NumAllowedTypes = 0; - Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); +#ifdef DEVELOPMENT + for (Uint32 v = 0; v < LayoutDesc.NumVariables; ++v) + { + bool VariableFound = false; + const auto& VarDesc = LayoutDesc.Variables[v]; + for(Uint32 s=0; s < NumShaders && !VariableFound; ++s) + { + const auto& Resources = *pShaderResources[s]; + if ( (VarDesc.ShaderStages & Resources.GetShaderType()) != 0 ) + { + for (Uint32 res = 0; res < Resources.GetTotalResources() && !VariableFound; ++res) + { + const auto& ResAttribs = Resources.GetResource(res); + VariableFound = (strcmp(ResAttribs.Name, VarDesc.Name) == 0); + } + } + } + if (!VariableFound) + { + LOG_WARNING_MESSAGE("Variable '", VarDesc.Name, "' labeled as ", GetShaderVariableTypeLiteralName(VarDesc.Type), " is not found in any of shader stages"); + } + } + + for (Uint32 sam = 0; sam < LayoutDesc.NumStaticSamplers; ++sam) + { + const auto& StSamDesc = LayoutDesc.StaticSamplers[sam]; + bool SamplerFound = false; + for(Uint32 s=0; s < NumShaders && !SamplerFound; ++s) + { + const auto& Resources = *pShaderResources[s]; + // Irrespective of whether HLSL-style combined image samplers are used, + // a static sampler can be assigned to GLSL sampled image (i.e. sampler2D g_tex) + for (Uint32 i = 0; i < Resources.GetNumSmpldImgs() && !SamplerFound; ++i) + { + const auto& SmplImg = Resources.GetSmpldImg(i); + SamplerFound = (strcmp(SmplImg.Name, StSamDesc.SamplerOrTextureName) == 0); + } + + if (!SamplerFound) + { + // Check if static sampler is assigned to a separate sampler or + // separate image depending on whether HLSL-style combined samplers + // are used + const auto* CombinedSamplerSuffix = Resources.GetCombinedSamplerSuffix(); + for (Uint32 i = 0; i < Resources.GetNumSepSmplrs(); ++i) + { + const auto& SepSmpl = Resources.GetSepSmplr(i); + SamplerFound = StreqSuff(SepSmpl.Name, StSamDesc.SamplerOrTextureName, CombinedSamplerSuffix); + if (SamplerFound) + break; + } + } + } + + if (!SamplerFound) + { + LOG_WARNING_MESSAGE("Static sampler '", StSamDesc.SamplerOrTextureName, "' is not found in any of shader stages"); + } + } +#endif + + + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes = nullptr; + const Uint32 NumAllowedTypes = 0; + const Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); for (Uint32 s=0; s < NumShaders; ++s) { - Layouts[s].AllocateMemory(std::move(pShaderResources[s]), LayoutDataAllocator, AllowedVarTypes, NumAllowedTypes); + Layouts[s].AllocateMemory(std::move(pShaderResources[s]), LayoutDataAllocator, LayoutDesc, AllowedVarTypes, NumAllowedTypes); } VERIFY_EXPR(NumShaders <= MaxShadersInPipeline); - std::array, MaxShadersInPipeline> CurrResInd = {}; + std::array, MaxShadersInPipeline> CurrResInd = {}; + std::array CurrImmutableSamplerInd = {}; #ifdef _DEBUG std::unordered_map> dbgBindings_CacheOffsets; #endif @@ -159,17 +307,35 @@ void ShaderResourceLayoutVk::Initialize(Uint32 NumShaders, auto AddResource = [&](Uint32 ShaderInd, ShaderResourceLayoutVk& ResLayout, const SPIRVShaderResources& Resources, - const SPIRVShaderResourceAttribs& Attribs, - Uint32 SamplerInd = VkResource::InvalidSamplerInd) + const SPIRVShaderResourceAttribs& Attribs) { Uint32 Binding = 0; Uint32 DescriptorSet = 0; Uint32 CacheOffset = 0; + const auto ShaderType = Resources.GetShaderType(); + const SHADER_RESOURCE_VARIABLE_TYPE VarType = GetShaderVariableType(ShaderType, Attribs, LayoutDesc, Resources.GetCombinedSamplerSuffix()); + if (!IsAllowedType(VarType, AllowedTypeBits)) + return; - auto* pImmutableSampler = Resources.GetImmutableSampler(Attribs); + Uint32 SamplerInd = VkResource::InvalidSamplerInd; + + if (Attribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateImage) + { + // Separate samplers are enumerated before separate images, so the sampler + // assigned to this separate image must have already been created. + SamplerInd = ResLayout.FindAssignedSampler(Attribs, CurrResInd[ShaderInd][VarType], VarType); + } + + Int32 SrcImmutableSamplerInd = FindImmutableSampler(ShaderType, LayoutDesc, Attribs, Resources.GetCombinedSamplerSuffix()); VkSampler vkImmutableSampler = VK_NULL_HANDLE; - if (pImmutableSampler != nullptr) - vkImmutableSampler = ValidatedCast(pImmutableSampler)->GetVkSampler(); + if (SrcImmutableSamplerInd >= 0) + { + auto& ImmutableSampler = ResLayout.GetImmutableSampler(CurrImmutableSamplerInd[ShaderInd]++); + VERIFY(!ImmutableSampler, "Immutable sampler has already been initialized!"); + const auto& ImmutableSamplerDesc = LayoutDesc.StaticSamplers[SrcImmutableSamplerInd].Desc; + pRenderDevice->CreateSampler(ImmutableSamplerDesc, &ImmutableSampler); + vkImmutableSampler = ImmutableSampler.RawPtr()->GetVkSampler(); + } auto& ShaderSPIRV = SPIRVs[ShaderInd]; PipelineLayout.AllocateResourceSlot(Attribs, vkImmutableSampler, Resources.GetShaderType(), DescriptorSet, Binding, CacheOffset, ShaderSPIRV); @@ -187,8 +353,8 @@ void ShaderResourceLayoutVk::Initialize(Uint32 NumShaders, dbgBindings_CacheOffsets[DescriptorSet] = std::make_pair(Binding, CacheOffset); #endif - auto& ResInd = CurrResInd[ShaderInd][Attribs.VarType]; - ::new (&ResLayout.GetResource(Attribs.VarType, ResInd++)) VkResource(ResLayout, Attribs, Binding, DescriptorSet, CacheOffset, SamplerInd); + auto& ResInd = CurrResInd[ShaderInd][VarType]; + ::new (&ResLayout.GetResource(VarType, ResInd++)) VkResource(ResLayout, Attribs, VarType, Binding, DescriptorSet, CacheOffset, SamplerInd, vkImmutableSampler != VK_NULL_HANDLE ? 1 : 0); }; // First process uniform buffers for all shader stages to make sure all UBs go first in every descriptor set @@ -199,7 +365,8 @@ void ShaderResourceLayoutVk::Initialize(Uint32 NumShaders, for (Uint32 n = 0; n < Resources.GetNumUBs(); ++n) { const auto& UB = Resources.GetUB(n); - if (IsAllowedType(UB.VarType, AllowedTypeBits)) + auto VarType = GetShaderVariableType(Resources.GetShaderType(), UB.Name, LayoutDesc); + if (IsAllowedType(VarType, AllowedTypeBits)) { AddResource(s, Layout, Resources, UB); } @@ -214,7 +381,8 @@ void ShaderResourceLayoutVk::Initialize(Uint32 NumShaders, for (Uint32 n = 0; n < Resources.GetNumSBs(); ++n) { const auto& SB = Resources.GetSB(n); - if (IsAllowedType(SB.VarType, AllowedTypeBits)) + auto VarType = GetShaderVariableType(Resources.GetShaderType(), SB.Name, LayoutDesc); + if (IsAllowedType(VarType, AllowedTypeBits)) { AddResource(s, Layout, Resources, SB); } @@ -227,50 +395,40 @@ void ShaderResourceLayoutVk::Initialize(Uint32 NumShaders, auto& Layout = Layouts[s]; const auto& Resources = *Layout.m_pResources; Resources.ProcessResources( - AllowedVarTypes, NumAllowedTypes, - [&](const SPIRVShaderResourceAttribs& UB, Uint32) { VERIFY_EXPR(UB.Type == SPIRVShaderResourceAttribs::ResourceType::UniformBuffer); - VERIFY_EXPR(IsAllowedType(UB.VarType, AllowedTypeBits)); // Skip }, [&](const SPIRVShaderResourceAttribs& SB, Uint32) { VERIFY_EXPR(SB.Type == SPIRVShaderResourceAttribs::ResourceType::StorageBuffer); - VERIFY_EXPR(IsAllowedType(SB.VarType, AllowedTypeBits)); // Skip }, [&](const SPIRVShaderResourceAttribs& Img, Uint32) { VERIFY_EXPR(Img.Type == SPIRVShaderResourceAttribs::ResourceType::StorageImage || Img.Type == SPIRVShaderResourceAttribs::ResourceType::StorageTexelBuffer); - VERIFY_EXPR(IsAllowedType(Img.VarType, AllowedTypeBits)); AddResource(s, Layout, Resources, Img); }, [&](const SPIRVShaderResourceAttribs& SmplImg, Uint32) { VERIFY_EXPR(SmplImg.Type == SPIRVShaderResourceAttribs::ResourceType::SampledImage || SmplImg.Type == SPIRVShaderResourceAttribs::ResourceType::UniformTexelBuffer); - VERIFY_EXPR(IsAllowedType(SmplImg.VarType, AllowedTypeBits)); AddResource(s, Layout, Resources, SmplImg); }, [&](const SPIRVShaderResourceAttribs& AC, Uint32) { VERIFY_EXPR(AC.Type == SPIRVShaderResourceAttribs::ResourceType::AtomicCounter); - VERIFY_EXPR(IsAllowedType(AC.VarType, AllowedTypeBits)); AddResource(s, Layout, Resources, AC); }, [&](const SPIRVShaderResourceAttribs& SepSmpl, Uint32) { VERIFY_EXPR(SepSmpl.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler); - VERIFY_EXPR(IsAllowedType(SepSmpl.VarType, AllowedTypeBits)); AddResource(s, Layout, Resources, SepSmpl); }, [&](const SPIRVShaderResourceAttribs& SepImg, Uint32) { VERIFY_EXPR(SepImg.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateImage); - VERIFY_EXPR(IsAllowedType(SepImg.VarType, AllowedTypeBits)); - Uint32 SamplerInd = Layout.FindAssignedSampler(SepImg, CurrResInd[s][SepImg.VarType]); - AddResource(s, Layout, Resources, SepImg, SamplerInd); + AddResource(s, Layout, Resources, SepImg); } ); } @@ -279,7 +437,7 @@ void ShaderResourceLayoutVk::Initialize(Uint32 NumShaders, for (Uint32 s = 0; s < NumShaders; ++s) { auto& Layout = Layouts[s]; - for (SHADER_VARIABLE_TYPE VarType = SHADER_VARIABLE_TYPE_STATIC; VarType < SHADER_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(CurrResInd[s][VarType] == Layout.m_NumResources[VarType], "Not all resources are initialized, which will cause a crash when dtor is called"); } @@ -288,7 +446,9 @@ void ShaderResourceLayoutVk::Initialize(Uint32 NumShaders, } -Uint32 ShaderResourceLayoutVk::FindAssignedSampler(const SPIRVShaderResourceAttribs& SepImg, Uint32 CurrResourceCount)const +Uint32 ShaderResourceLayoutVk::FindAssignedSampler(const SPIRVShaderResourceAttribs& SepImg, + Uint32 CurrResourceCount, + SHADER_RESOURCE_VARIABLE_TYPE ImgVarType)const { VERIFY_EXPR(SepImg.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateImage); @@ -296,17 +456,16 @@ Uint32 ShaderResourceLayoutVk::FindAssignedSampler(const SPIRVShaderResourceAttr if (m_pResources->IsUsingCombinedSamplers() && SepImg.IsValidSepSamplerAssigned()) { const auto& SepSampler = m_pResources->GetSepSmplr(SepImg.GetAssignedSepSamplerInd()); - DEV_CHECK_ERR(SepImg.VarType == SepSampler.VarType, - "The type (", GetShaderVariableTypeLiteralName(SepImg.VarType),") of separate image variable '", SepImg.Name, - "' is not consistent with the type (", GetShaderVariableTypeLiteralName(SepSampler.VarType), - ") of the separate sampler '", SepSampler.Name, "' that is assigned to it."); - for (SamplerInd = 0; SamplerInd < CurrResourceCount; ++SamplerInd) { - const auto& Res = GetResource(SepSampler.VarType, SamplerInd); + const auto& Res = GetResource(ImgVarType, SamplerInd); if (Res.SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler && strcmp(Res.SpirvAttribs.Name, SepSampler.Name) == 0) { + DEV_CHECK_ERR(ImgVarType == Res.GetVariableType(), + "The type (", GetShaderVariableTypeLiteralName(ImgVarType),") of separate image variable '", SepImg.Name, + "' is not consistent with the type (", GetShaderVariableTypeLiteralName(Res.GetVariableType()), + ") of the separate sampler '", SepSampler.Name, "' that is assigned to it."); break; } } @@ -319,9 +478,11 @@ Uint32 ShaderResourceLayoutVk::FindAssignedSampler(const SPIRVShaderResourceAttr return SamplerInd; } + + #define LOG_RESOURCE_BINDING_ERROR(ResType, pResource, VarName, ShaderName, ...)\ { \ - const auto &ResName = pResource->GetDesc().Name; \ + const auto& ResName = pResource->GetDesc().Name; \ LOG_ERROR_MESSAGE( "Failed to bind ", ResType, " '", ResName, "' to variable '", VarName, \ "' in shader '", ShaderName, "'. ", __VA_ARGS__ ); \ } @@ -362,11 +523,11 @@ bool ShaderResourceLayoutVk::VkResource::UpdateCachedResource(ShaderResourceCach RefCntAutoPtr pResource(pObject, InterfaceId); if(pResource) { - if (SpirvAttribs.VarType != SHADER_VARIABLE_TYPE_DYNAMIC && DstRes.pObject != nullptr) + if (GetVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC && DstRes.pObject != nullptr) { if (DstRes.pObject != pResource) { - auto VarTypeStr = GetShaderVariableTypeLiteralName(SpirvAttribs.VarType); + auto VarTypeStr = GetShaderVariableTypeLiteralName(GetVariableType()); LOG_ERROR_MESSAGE("Non-null resource is already bound to ", VarTypeStr, " shader variable '", SpirvAttribs.GetPrintName(ArrayInd), "' in shader '", ParentResLayout.GetShaderName(), "'. Attempring to bind another resource is an error and will be ignored. Use another shader resource binding instance or label the variable as dynamic."); } @@ -408,7 +569,7 @@ void ShaderResourceLayoutVk::VkResource::CacheUniformBuffer(IDeviceObject* // Do not update descriptor for a dynamic uniform buffer. All dynamic resource // descriptors are updated at once by CommitDynamicResources() when SRB is committed. - if (vkDescrSet != VK_NULL_HANDLE && SpirvAttribs.VarType != SHADER_VARIABLE_TYPE_DYNAMIC) + if (vkDescrSet != VK_NULL_HANDLE && GetVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) { VkDescriptorBufferInfo DescrBuffInfo = DstRes.GetUniformBufferDescriptorWriteInfo(); UpdateDescriptorHandle(vkDescrSet, ArrayInd, nullptr, &DescrBuffInfo, nullptr); @@ -440,7 +601,7 @@ void ShaderResourceLayoutVk::VkResource::CacheStorageBuffer(IDeviceObject* // Do not update descriptor for a dynamic storage buffer. All dynamic resource // descriptors are updated at once by CommitDynamicResources() when SRB is committed. - if (vkDescrSet != VK_NULL_HANDLE && SpirvAttribs.VarType != SHADER_VARIABLE_TYPE_DYNAMIC) + if (vkDescrSet != VK_NULL_HANDLE && GetVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) { VkDescriptorBufferInfo DescrBuffInfo = DstRes.GetStorageBufferDescriptorWriteInfo(); UpdateDescriptorHandle(vkDescrSet, ArrayInd, nullptr, &DescrBuffInfo, nullptr); @@ -470,8 +631,8 @@ void ShaderResourceLayoutVk::VkResource::CacheTexelBuffer(IDeviceObject* const auto dbgExpectedViewType = IsStorageBuffer ? BUFFER_VIEW_UNORDERED_ACCESS : BUFFER_VIEW_SHADER_RESOURCE; if (ViewType != dbgExpectedViewType) { - const auto *ExpectedViewTypeName = GetViewTypeLiteralName(dbgExpectedViewType); - const auto *ActualViewTypeName = GetViewTypeLiteralName(ViewType); + const auto* ExpectedViewTypeName = GetViewTypeLiteralName(dbgExpectedViewType); + const auto* ActualViewTypeName = GetViewTypeLiteralName(ViewType); LOG_RESOURCE_BINDING_ERROR("Texture view", pBuffViewVk, SpirvAttribs.GetPrintName(ArrayInd), ParentResLayout.GetShaderName(), "Incorrect view type: ", ExpectedViewTypeName, " is expected, but ", ActualViewTypeName, " is provided."); DstRes.pObject.Release(); @@ -481,7 +642,7 @@ void ShaderResourceLayoutVk::VkResource::CacheTexelBuffer(IDeviceObject* // Do not update descriptor for a dynamic texel buffer. All dynamic resource descriptors // are updated at once by CommitDynamicResources() when SRB is committed. - if (vkDescrSet != VK_NULL_HANDLE && SpirvAttribs.VarType != SHADER_VARIABLE_TYPE_DYNAMIC) + if (vkDescrSet != VK_NULL_HANDLE && GetVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) { VkBufferView BuffView = pBuffViewVk->GetVkBufferView(); UpdateDescriptorHandle(vkDescrSet, ArrayInd, nullptr, nullptr, &BuffView); @@ -511,15 +672,15 @@ void ShaderResourceLayoutVk::VkResource::CacheImage(IDeviceObject* const auto dbgExpectedViewType = IsStorageImage ? TEXTURE_VIEW_UNORDERED_ACCESS : TEXTURE_VIEW_SHADER_RESOURCE; if (ViewType != dbgExpectedViewType) { - const auto *ExpectedViewTypeName = GetViewTypeLiteralName(dbgExpectedViewType); - const auto *ActualViewTypeName = GetViewTypeLiteralName(ViewType); + const auto* ExpectedViewTypeName = GetViewTypeLiteralName(dbgExpectedViewType); + const auto* ActualViewTypeName = GetViewTypeLiteralName(ViewType); LOG_RESOURCE_BINDING_ERROR("Texture view", pTexViewVk, SpirvAttribs.GetPrintName(ArrayInd), ParentResLayout.GetShaderName(), "Incorrect view type: ", ExpectedViewTypeName, " is expected, but ", ActualViewTypeName, " is provided."); DstRes.pObject.Release(); return; } - if (SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SampledImage && !SpirvAttribs.IsImmutableSamplerAssigned()) + if (SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SampledImage && !IsImmutableSamplerAssigned()) { if(pTexViewVk->GetSampler() == nullptr) { @@ -530,18 +691,18 @@ void ShaderResourceLayoutVk::VkResource::CacheImage(IDeviceObject* // Do not update descriptor for a dynamic image. All dynamic resource descriptors // are updated at once by CommitDynamicResources() when SRB is committed. - if (vkDescrSet != VK_NULL_HANDLE && SpirvAttribs.VarType != SHADER_VARIABLE_TYPE_DYNAMIC) + if (vkDescrSet != VK_NULL_HANDLE && GetVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) { - VkDescriptorImageInfo DescrImgInfo = DstRes.GetImageDescriptorWriteInfo(SpirvAttribs.IsImmutableSamplerAssigned()); + VkDescriptorImageInfo DescrImgInfo = DstRes.GetImageDescriptorWriteInfo(IsImmutableSamplerAssigned()); UpdateDescriptorHandle(vkDescrSet, ArrayInd, &DescrImgInfo, nullptr, nullptr); } if (SamplerInd != InvalidSamplerInd) { VERIFY_EXPR(SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateImage); - VERIFY_EXPR(!SpirvAttribs.IsImmutableSamplerAssigned()); + VERIFY_EXPR(!IsImmutableSamplerAssigned()); auto* pSampler = pTexViewVk->GetSampler(); - const auto& SamplerAttribs = ParentResLayout.GetResource(SpirvAttribs.VarType, SamplerInd); + const auto& SamplerAttribs = ParentResLayout.GetResource(GetVariableType(), SamplerInd); if (pSampler != nullptr) { CacheSampler(SamplerAttribs, pSampler); @@ -567,7 +728,7 @@ void ShaderResourceLayoutVk::VkResource::CacheSeparateSampler(IDeviceObject* { // Do not update descriptor for a dynamic sampler. All dynamic resource descriptors // are updated at once by CommitDynamicResources() when SRB is committed. - if (vkDescrSet != VK_NULL_HANDLE && SpirvAttribs.VarType != SHADER_VARIABLE_TYPE_DYNAMIC) + if (vkDescrSet != VK_NULL_HANDLE && GetVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) { VkDescriptorImageInfo DescrImgInfo = DstRes.GetSamplerDescriptorWriteInfo(); UpdateDescriptorHandle(vkDescrSet, ArrayInd, &DescrImgInfo, nullptr, nullptr); @@ -576,16 +737,16 @@ void ShaderResourceLayoutVk::VkResource::CacheSeparateSampler(IDeviceObject* } -void ShaderResourceLayoutVk::VkResource::BindResource(IDeviceObject *pObj, Uint32 ArrayIndex, ShaderResourceCacheVk& ResourceCache)const +void ShaderResourceLayoutVk::VkResource::BindResource(IDeviceObject* pObj, Uint32 ArrayIndex, ShaderResourceCacheVk& ResourceCache)const { VERIFY_EXPR(ArrayIndex < SpirvAttribs.ArraySize); - auto &DstDescrSet = ResourceCache.GetDescriptorSet(DescriptorSet); + auto& DstDescrSet = ResourceCache.GetDescriptorSet(DescriptorSet); auto vkDescrSet = DstDescrSet.GetVkDescriptorSet(); #ifdef _DEBUG if (ResourceCache.DbgGetContentType() == ShaderResourceCacheVk::DbgCacheContentType::SRBResources) { - if(SpirvAttribs.VarType == SHADER_VARIABLE_TYPE_STATIC || SpirvAttribs.VarType == SHADER_VARIABLE_TYPE_MUTABLE) + if(VariableType == SHADER_RESOURCE_VARIABLE_TYPE_STATIC || VariableType == SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE) { VERIFY(vkDescrSet != VK_NULL_HANDLE, "Static and mutable variables must have valid vulkan descriptor set assigned"); // Dynamic variables do not have vulkan descriptor set only until they are assigned one the first time @@ -638,7 +799,7 @@ void ShaderResourceLayoutVk::VkResource::BindResource(IDeviceObject *pObj, Uint3 break; case SPIRVShaderResourceAttribs::ResourceType::SeparateSampler: - if (!SpirvAttribs.IsImmutableSamplerAssigned()) + if (!IsImmutableSamplerAssigned()) { CacheSeparateSampler(pObj, DstRes, vkDescrSet, ArrayIndex); } @@ -655,7 +816,7 @@ void ShaderResourceLayoutVk::VkResource::BindResource(IDeviceObject *pObj, Uint3 } else { - if (DstRes.pObject && SpirvAttribs.VarType != SHADER_VARIABLE_TYPE_DYNAMIC) + if (DstRes.pObject && GetVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) { LOG_ERROR_MESSAGE( "Shader variable '", SpirvAttribs.Name, "' in shader '", ParentResLayout.GetShaderName(), "' is not dynamic but being unbound. This is an error and may cause unpredicted behavior. Use another shader resource binding instance or label shader variable as dynamic if you need to bind another resource." ); } @@ -686,21 +847,21 @@ void ShaderResourceLayoutVk::InitializeStaticResources(const ShaderResourceLayou const ShaderResourceCacheVk& SrcResourceCache, ShaderResourceCacheVk& DstResourceCache)const { - auto NumStaticResources = m_NumResources[SHADER_VARIABLE_TYPE_STATIC]; - VERIFY(NumStaticResources == SrcLayout.m_NumResources[SHADER_VARIABLE_TYPE_STATIC], "Inconsistent number of static resources"); + auto NumStaticResources = m_NumResources[SHADER_RESOURCE_VARIABLE_TYPE_STATIC]; + VERIFY(NumStaticResources == SrcLayout.m_NumResources[SHADER_RESOURCE_VARIABLE_TYPE_STATIC], "Inconsistent number of static resources"); VERIFY(SrcLayout.m_pResources->GetShaderType() == m_pResources->GetShaderType(), "Incosistent shader types"); // Static shader resources are stored in one large continuous descriptor set for (Uint32 r=0; r < NumStaticResources; ++r) { // Get resource attributes - auto &DstRes = GetResource(SHADER_VARIABLE_TYPE_STATIC, r); - const auto &SrcRes = SrcLayout.GetResource(SHADER_VARIABLE_TYPE_STATIC, r); + auto& DstRes = GetResource(SHADER_RESOURCE_VARIABLE_TYPE_STATIC, r); + const auto& SrcRes = SrcLayout.GetResource(SHADER_RESOURCE_VARIABLE_TYPE_STATIC, r); VERIFY(SrcRes.Binding == SrcRes.SpirvAttribs.Type, "Unexpected binding"); VERIFY(SrcRes.SpirvAttribs.ArraySize == DstRes.SpirvAttribs.ArraySize, "Inconsistent array size"); if (DstRes.SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler && - DstRes.SpirvAttribs.IsImmutableSamplerAssigned()) + DstRes.IsImmutableSamplerAssigned()) continue; // Skip immutable samplers for (Uint32 ArrInd = 0; ArrInd < DstRes.SpirvAttribs.ArraySize; ++ArrInd) @@ -728,21 +889,21 @@ void ShaderResourceLayoutVk::InitializeStaticResources(const ShaderResourceLayou bool ShaderResourceLayoutVk::dvpVerifyBindings(const ShaderResourceCacheVk& ResourceCache)const { bool BindingsOK = true; - for(SHADER_VARIABLE_TYPE VarType = SHADER_VARIABLE_TYPE_STATIC; VarType < SHADER_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 < m_NumResources[VarType]; ++r) { const auto& Res = GetResource(VarType, r); - VERIFY(Res.SpirvAttribs.VarType == VarType, "Unexpected variable type"); + VERIFY(Res.GetVariableType() == VarType, "Unexpected variable type"); for(Uint32 ArrInd = 0; ArrInd < Res.SpirvAttribs.ArraySize; ++ArrInd) { const auto& CachedDescrSet = ResourceCache.GetDescriptorSet(Res.DescriptorSet); const auto& CachedRes = CachedDescrSet.GetResource(Res.CacheOffset + ArrInd); VERIFY(CachedRes.Type == Res.SpirvAttribs.Type, "Inconsistent types"); if (CachedRes.pObject == nullptr && - !(Res.SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler && Res.SpirvAttribs.IsImmutableSamplerAssigned())) + !(Res.SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler && Res.IsImmutableSamplerAssigned())) { - LOG_ERROR_MESSAGE("No resource is bound to ", GetShaderVariableTypeLiteralName(Res.SpirvAttribs.VarType), " variable '", Res.SpirvAttribs.GetPrintName(ArrInd), "' in shader '", GetShaderName(), "'"); + LOG_ERROR_MESSAGE("No resource is bound to ", GetShaderVariableTypeLiteralName(Res.GetVariableType()), " variable '", Res.SpirvAttribs.GetPrintName(ArrInd), "' in shader '", GetShaderName(), "'"); BindingsOK = false; } #ifdef _DEBUG @@ -752,11 +913,11 @@ bool ShaderResourceLayoutVk::dvpVerifyBindings(const ShaderResourceCacheVk& Reso VERIFY(vkDescSet == VK_NULL_HANDLE, "Static resource cache should never have vulkan descriptor set"); else if (dbgCacheContentType == ShaderResourceCacheVk::DbgCacheContentType::SRBResources) { - if (VarType == SHADER_VARIABLE_TYPE_STATIC || VarType == SHADER_VARIABLE_TYPE_MUTABLE) + if (VarType == SHADER_RESOURCE_VARIABLE_TYPE_STATIC || VarType == SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE) { VERIFY(vkDescSet != VK_NULL_HANDLE, "Static and mutable variables must have valid vulkan descriptor set assigned"); } - else if (VarType == SHADER_VARIABLE_TYPE_DYNAMIC) + else if (VarType == SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) { VERIFY(vkDescSet == VK_NULL_HANDLE, "Dynamic variables must not be assigned a vulkan descriptor set"); } @@ -774,31 +935,23 @@ bool ShaderResourceLayoutVk::dvpVerifyBindings(const ShaderResourceCacheVk& Reso const Char* ShaderResourceLayoutVk::GetShaderName()const { - RefCntAutoPtr pShader(&m_Owner, IID_Shader); - if (pShader) + RefCntAutoPtr pPSO(&m_Owner, IID_PipelineState); + if (pPSO) { - return pShader->GetDesc().Name; + auto* pPSOVk = pPSO.RawPtr(); + auto* ppShaders = pPSOVk->GetShaders(); + auto NumShaders = pPSOVk->GetNumShaders(); + for (Uint32 s = 0; s < NumShaders; ++s) + { + const auto& ShaderDesc = ppShaders[s]->GetDesc(); + if (ShaderDesc.ShaderType == m_pResources->GetShaderType()) + return ShaderDesc.Name; + } + UNEXPECTED("Shader not found"); } else { - RefCntAutoPtr pPSO(&m_Owner, IID_PipelineState); - if (pPSO) - { - auto *pPSOVk = pPSO.RawPtr(); - auto *ppShaders = pPSOVk->GetShaders(); - auto NumShaders = pPSOVk->GetNumShaders(); - for (Uint32 s = 0; s < NumShaders; ++s) - { - const auto &ShaderDesc = ppShaders[s]->GetDesc(); - if(ShaderDesc.ShaderType == m_pResources->GetShaderType()) - return ShaderDesc.Name; - } - UNEXPECTED("Shader not found"); - } - else - { - UNEXPECTED("Shader resource layout owner must be a shader or a pipeline state"); - } + UNEXPECTED("Shader resource layout owner must be a shader or a pipeline state"); } return ""; } @@ -816,7 +969,7 @@ void ShaderResourceLayoutVk::InitializeResourceMemoryInCache(ShaderResourceCache void ShaderResourceLayoutVk::CommitDynamicResources(const ShaderResourceCacheVk& ResourceCache, VkDescriptorSet vkDynamicDescriptorSet)const { - Uint32 NumDynamicResources = m_NumResources[SHADER_VARIABLE_TYPE_DYNAMIC]; + Uint32 NumDynamicResources = m_NumResources[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC]; VERIFY(NumDynamicResources != 0, "This shader resource layout does not contain dynamic resources"); VERIFY_EXPR(vkDynamicDescriptorSet != VK_NULL_HANDLE); @@ -850,8 +1003,8 @@ void ShaderResourceLayoutVk::CommitDynamicResources(const ShaderResourceCacheVk& while(ResNum < NumDynamicResources) { - const auto& Res = GetResource(SHADER_VARIABLE_TYPE_DYNAMIC, ResNum); - VERIFY_EXPR(Res.SpirvAttribs.VarType == SHADER_VARIABLE_TYPE_DYNAMIC); + const auto& Res = GetResource(SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC, ResNum); + VERIFY_EXPR(Res.GetVariableType() == SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC); #ifdef _DEBUG if(DynamicDescrSetIndex < 0) DynamicDescrSetIndex = Res.DescriptorSet; @@ -914,7 +1067,7 @@ void ShaderResourceLayoutVk::CommitDynamicResources(const ShaderResourceCacheVk& while (ArrElem < Res.SpirvAttribs.ArraySize && DescrImgIt != DescrImgInfoArr.end()) { const auto& CachedRes = SetResources.GetResource(Res.CacheOffset + ArrElem); - *DescrImgIt = CachedRes.GetImageDescriptorWriteInfo(Res.SpirvAttribs.IsImmutableSamplerAssigned()); + *DescrImgIt = CachedRes.GetImageDescriptorWriteInfo(Res.IsImmutableSamplerAssigned()); ++DescrImgIt; ++ArrElem; } @@ -928,7 +1081,7 @@ void ShaderResourceLayoutVk::CommitDynamicResources(const ShaderResourceCacheVk& case SPIRVShaderResourceAttribs::ResourceType::SeparateSampler: // Immutable samplers are permanently bound into the set layout; later binding a sampler // into an immutable sampler slot in a descriptor set is not allowed (13.2.1) - if (!Res.SpirvAttribs.IsImmutableSamplerAssigned()) + if (!Res.IsImmutableSamplerAssigned()) { WriteDescrSetIt->pImageInfo = &(*DescrImgIt); while (ArrElem < Res.SpirvAttribs.ArraySize && DescrImgIt != DescrImgInfoArr.end()) -- cgit v1.2.3 From db55aa475fb2c13118e29c4ece91b99d20ab798a Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Wed, 27 Feb 2019 09:05:39 -0800 Subject: Updated ShaderVariableVk and ShaderResourceBindingVk --- .../include/ShaderResourceBindingVkImpl.h | 4 ++-- .../include/ShaderVariableVk.h | 26 +++++++++++----------- .../src/ShaderResourceBindingVkImpl.cpp | 6 ++--- .../GraphicsEngineVulkan/src/ShaderVariableVk.cpp | 13 ++++++----- 4 files changed, 25 insertions(+), 24 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderResourceBindingVkImpl.h b/Graphics/GraphicsEngineVulkan/include/ShaderResourceBindingVkImpl.h index 451ddcb8..b3933747 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderResourceBindingVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderResourceBindingVkImpl.h @@ -52,11 +52,11 @@ public: virtual void BindResources(Uint32 ShaderFlags, IResourceMapping* pResMapping, Uint32 Flags)override final; - virtual IShaderVariable* GetVariable(SHADER_TYPE ShaderType, const char* Name)override final; + virtual IShaderResourceVariable* GetVariable(SHADER_TYPE ShaderType, const char* Name)override final; virtual Uint32 GetVariableCount(SHADER_TYPE ShaderType) const override final; - virtual IShaderVariable* GetVariable(SHADER_TYPE ShaderType, Uint32 Index)override final; + virtual IShaderResourceVariable* GetVariable(SHADER_TYPE ShaderType, Uint32 Index)override final; virtual void InitializeStaticResources(const IPipelineState* pPipelineState)override final; diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h index 92af69a3..5f7a0628 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h @@ -73,11 +73,11 @@ public: {} ~ShaderVariableManagerVk(); - void Initialize(const ShaderResourceLayoutVk& Layout, - IMemoryAllocator& Allocator, - const SHADER_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - ShaderResourceCacheVk& ResourceCache); + void Initialize(const ShaderResourceLayoutVk& Layout, + IMemoryAllocator& Allocator, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes, + ShaderResourceCacheVk& ResourceCache); void Destroy(IMemoryAllocator& Allocator); ShaderVariableVkImpl* GetVariable(const Char* Name); @@ -85,10 +85,10 @@ public: void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags); - static size_t GetRequiredMemorySize(const ShaderResourceLayoutVk& Layout, - const SHADER_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - Uint32& NumVariables); + static size_t GetRequiredMemorySize(const ShaderResourceLayoutVk& Layout, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes, + Uint32& NumVariables); Uint32 GetVariableCount()const { return m_NumVariables; } @@ -117,7 +117,7 @@ private: }; // sizeof(ShaderVariableVkImpl) == 24 (x64) -class ShaderVariableVkImpl final : public IShaderVariable +class ShaderVariableVkImpl final : public IShaderResourceVariable { public: ShaderVariableVkImpl(ShaderVariableManagerVk& ParentManager, @@ -153,16 +153,16 @@ public: return; *ppInterface = nullptr; - if (IID == IID_ShaderVariable || IID == IID_Unknown) + if (IID == IID_ShaderResourceVariable || IID == IID_Unknown) { *ppInterface = this; (*ppInterface)->AddRef(); } } - virtual SHADER_VARIABLE_TYPE GetType()const override final + virtual SHADER_RESOURCE_VARIABLE_TYPE GetType()const override final { - return m_Resource.SpirvAttribs.VarType; + return m_Resource.GetVariableType(); } virtual void Set(IDeviceObject *pObject)override final diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp index 02a98d11..342f5ae6 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp @@ -64,7 +64,7 @@ ShaderResourceBindingVkImpl::ShaderResourceBindingVkImpl( IReferenceCounters* pR // Initialize vars manager to reference mutable and dynamic variables // Note that the cache has space for all variable types - std::array VarTypes = {{SHADER_VARIABLE_TYPE_MUTABLE, SHADER_VARIABLE_TYPE_DYNAMIC}}; + std::array VarTypes = {{SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}}; m_pShaderVarMgrs[s].Initialize(SrcLayout, VarDataAllocator, VarTypes.data(), static_cast(VarTypes.size()), m_ShaderResourceCache); m_ResourceLayoutIndex[ShaderInd] = static_cast(s); @@ -101,7 +101,7 @@ void ShaderResourceBindingVkImpl::BindResources(Uint32 ShaderFlags, IResourceMap } } -IShaderVariable* ShaderResourceBindingVkImpl::GetVariable(SHADER_TYPE ShaderType, const char *Name) +IShaderResourceVariable* ShaderResourceBindingVkImpl::GetVariable(SHADER_TYPE ShaderType, const char *Name) { auto ShaderInd = GetShaderTypeIndex(ShaderType); auto ResLayoutInd = m_ResourceLayoutIndex[ShaderInd]; @@ -125,7 +125,7 @@ Uint32 ShaderResourceBindingVkImpl::GetVariableCount(SHADER_TYPE ShaderType) con return m_pShaderVarMgrs[ResLayoutInd].GetVariableCount(); } -IShaderVariable* ShaderResourceBindingVkImpl::GetVariable(SHADER_TYPE ShaderType, Uint32 Index) +IShaderResourceVariable* ShaderResourceBindingVkImpl::GetVariable(SHADER_TYPE ShaderType, Uint32 Index) { auto ShaderInd = GetShaderTypeIndex(ShaderType); auto ResLayoutInd = m_ResourceLayoutIndex[ShaderInd]; diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp index 485ca318..22acaf5c 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp @@ -24,18 +24,19 @@ #include "pch.h" #include "ShaderVariableVk.h" +#include "ShaderResourceVariableBase.h" namespace Diligent { size_t ShaderVariableManagerVk::GetRequiredMemorySize(const ShaderResourceLayoutVk& Layout, - const SHADER_VARIABLE_TYPE* AllowedVarTypes, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes, Uint32& NumVariables) { NumVariables = 0; Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); - for(SHADER_VARIABLE_TYPE VarType = SHADER_VARIABLE_TYPE_STATIC; VarType < SHADER_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)) { @@ -61,7 +62,7 @@ size_t ShaderVariableManagerVk::GetRequiredMemorySize(const ShaderResourceLayout // Creates shader variable for every resource from SrcLayout whose type is one AllowedVarTypes void ShaderVariableManagerVk::Initialize(const ShaderResourceLayoutVk& SrcLayout, IMemoryAllocator& Allocator, - const SHADER_VARIABLE_TYPE* AllowedVarTypes, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes, ShaderResourceCacheVk& ResourceCache) { @@ -82,7 +83,7 @@ void ShaderVariableManagerVk::Initialize(const ShaderResourceLayoutVk& SrcLayout m_pVariables = reinterpret_cast(pRawMem); Uint32 VarInd = 0; - for(SHADER_VARIABLE_TYPE VarType = SHADER_VARIABLE_TYPE_STATIC; VarType < SHADER_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; @@ -186,10 +187,10 @@ void ShaderVariableManagerVk::BindResources( IResourceMapping* pResourceMapping, const auto& Res = Var.m_Resource; // Skip immutable separate samplers - if (Res.SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler && Res.SpirvAttribs.IsImmutableSamplerAssigned()) + if (Res.SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler && Res.IsImmutableSamplerAssigned()) continue; - if ( (Flags & (1 << Res.SpirvAttribs.VarType)) == 0 ) + if ( (Flags & (1 << Res.GetVariableType())) == 0 ) continue; for (Uint32 ArrInd = 0; ArrInd < Res.SpirvAttribs.ArraySize; ++ArrInd) -- cgit v1.2.3 From 43302d5fc3b3978952dd4215eea8f3f5668b95dd Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Wed, 27 Feb 2019 20:45:24 -0800 Subject: Working on resource binding API refactor --- Graphics/GraphicsEngine/CMakeLists.txt | 2 + Graphics/GraphicsEngine/include/ShaderBase.h | 147 +------------------ .../include/ShaderResourceVariableBase.h | 161 +++++++++++++++++++++ Graphics/GraphicsEngine/interface/RenderDevice.h | 7 +- Graphics/GraphicsEngine/interface/Texture.h | 6 +- Graphics/GraphicsEngine/interface/TextureView.h | 2 +- .../include/PipelineStateVkImpl.h | 42 +++++- .../src/GenerateMipsVkHelper.cpp | 23 +-- .../src/PipelineStateVkImpl.cpp | 120 ++++++++++++--- .../src/RenderDeviceVkImpl.cpp | 6 +- .../src/ShaderResourceBindingVkImpl.cpp | 19 +-- 11 files changed, 329 insertions(+), 206 deletions(-) create mode 100644 Graphics/GraphicsEngine/include/ShaderResourceVariableBase.h (limited to 'Graphics') diff --git a/Graphics/GraphicsEngine/CMakeLists.txt b/Graphics/GraphicsEngine/CMakeLists.txt index 1fc418f3..25618d84 100644 --- a/Graphics/GraphicsEngine/CMakeLists.txt +++ b/Graphics/GraphicsEngine/CMakeLists.txt @@ -18,6 +18,7 @@ set(INCLUDE include/SamplerBase.h include/ShaderBase.h include/ShaderResourceBindingBase.h + include/ShaderResourceVariableBase.h include/StateObjectsRegistry.h include/SwapChainBase.h include/TextureBase.h @@ -45,6 +46,7 @@ set(INTERFACE interface/Sampler.h interface/Shader.h interface/ShaderResourceBinding.h + interface/ShaderResourceVariable.h interface/SwapChain.h interface/Texture.h interface/TextureView.h diff --git a/Graphics/GraphicsEngine/include/ShaderBase.h b/Graphics/GraphicsEngine/include/ShaderBase.h index ff015829..a9c1ae13 100644 --- a/Graphics/GraphicsEngine/include/ShaderBase.h +++ b/Graphics/GraphicsEngine/include/ShaderBase.h @@ -37,12 +37,12 @@ namespace Diligent { -inline SHADER_TYPE GetShaderTypeFromIndex( Int32 Index ) +inline SHADER_TYPE GetShaderTypeFromIndex(Int32 Index) { return static_cast(1 << Index); } -inline Int32 GetShaderTypeIndex( SHADER_TYPE Type ) +inline Int32 GetShaderTypeIndex(SHADER_TYPE Type) { Int32 ShaderIndex = PlatformMisc::GetLSB(Type); @@ -70,100 +70,6 @@ static const int HSInd = GetShaderTypeIndex(SHADER_TYPE_HULL); static const int DSInd = GetShaderTypeIndex(SHADER_TYPE_DOMAIN); static const int CSInd = GetShaderTypeIndex(SHADER_TYPE_COMPUTE); -template -SHADER_VARIABLE_TYPE GetShaderVariableType(SHADER_VARIABLE_TYPE DefaultVariableType, const ShaderVariableDesc* VariableDesc, Uint32 NumVars, TNameCompare NameCompare) -{ - for (Uint32 v = 0; v < NumVars; ++v) - { - const auto &CurrVarDesc = VariableDesc[v]; - if ( NameCompare(CurrVarDesc.Name) ) - { - return CurrVarDesc.Type; - } - } - return DefaultVariableType; -} - -inline SHADER_VARIABLE_TYPE GetShaderVariableType(const Char* Name, SHADER_VARIABLE_TYPE DefaultVariableType, const ShaderVariableDesc* VariableDesc, Uint32 NumVars) -{ - return GetShaderVariableType(DefaultVariableType, VariableDesc, NumVars, - [&](const char *VarName) - { - return strcmp(VarName, Name) == 0; - } - ); -} - -inline SHADER_VARIABLE_TYPE GetShaderVariableType(const Char* Name, const ShaderDesc& ShdrDesc) -{ - return GetShaderVariableType(Name, ShdrDesc.DefaultVariableType, ShdrDesc.VariableDesc, ShdrDesc.NumVariables); -} - -inline SHADER_VARIABLE_TYPE GetShaderVariableType(const String& Name, SHADER_VARIABLE_TYPE DefaultVariableType, const ShaderVariableDesc *VariableDesc, Uint32 NumVars) -{ - return GetShaderVariableType(DefaultVariableType, VariableDesc, NumVars, - [&](const char *VarName) - { - return Name.compare(VarName) == 0; - } - ); -} - -inline SHADER_VARIABLE_TYPE GetShaderVariableType(const String& Name, const ShaderDesc& ShdrDesc) -{ - return GetShaderVariableType(Name, ShdrDesc.DefaultVariableType, ShdrDesc.VariableDesc, ShdrDesc.NumVariables); -} - - -/// Base implementation of a shader variable - -struct ShaderVariableBase : public IShaderVariable -{ - ShaderVariableBase(IObject& Owner) : - // Shader variables are always created as part of the shader, or - // shader resource binding, so we must provide owner pointer to - // the base class constructor - m_Owner(Owner) - { - } - - IObject& GetOwner() - { - return m_Owner; - } - - virtual IReferenceCounters* GetReferenceCounters()const override final - { - return m_Owner.GetReferenceCounters(); - } - - virtual Atomics::Long AddRef()override final - { - return m_Owner.AddRef(); - } - - virtual Atomics::Long Release()override final - { - return m_Owner.Release(); - } - - virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface )override final - { - if( ppInterface == nullptr ) - return; - - *ppInterface = nullptr; - if( IID == IID_ShaderVariable || IID == IID_Unknown ) - { - *ppInterface = this; - (*ppInterface)->AddRef(); - } - } - -protected: - IObject& m_Owner; -}; - /// Template class implementing base functionality for a shader object @@ -184,57 +90,12 @@ public: /// \param ShdrDesc - shader description. /// \param bIsDeviceInternal - flag indicating if the shader is an internal device object and /// must not keep a strong reference to the device. - ShaderBase( IReferenceCounters* pRefCounters, RenderDeviceImplType* pDevice, const ShaderDesc& ShdrDesc, bool bIsDeviceInternal = false ) : - TDeviceObjectBase( pRefCounters, pDevice, ShdrDesc, bIsDeviceInternal ), - m_VariablesDesc (ShdrDesc.NumVariables, ShaderVariableDesc(), STD_ALLOCATOR_RAW_MEM(ShaderVariableDesc, GetRawAllocator(), "Allocator for vector") ), - m_StringPool (ShdrDesc.NumVariables + ShdrDesc.NumStaticSamplers, String(), STD_ALLOCATOR_RAW_MEM(String, GetRawAllocator(), "Allocator for vector")), - m_StaticSamplers(ShdrDesc.NumStaticSamplers, StaticSamplerDesc(), STD_ALLOCATOR_RAW_MEM(StaticSamplerDesc, GetRawAllocator(), "Allocator for vector") ) + ShaderBase(IReferenceCounters* pRefCounters, RenderDeviceImplType* pDevice, const ShaderDesc& ShdrDesc, bool bIsDeviceInternal = false) : + TDeviceObjectBase(pRefCounters, pDevice, ShdrDesc, bIsDeviceInternal) { - auto Str = m_StringPool.begin(); - if(this->m_Desc.VariableDesc) - { - for (Uint32 v = 0; v < this->m_Desc.NumVariables; ++v, ++Str) - { - m_VariablesDesc[v] = this->m_Desc.VariableDesc[v]; - VERIFY(m_VariablesDesc[v].Name != nullptr, "Variable name not provided"); - *Str = m_VariablesDesc[v].Name; - m_VariablesDesc[v].Name = Str->c_str(); - } - this->m_Desc.VariableDesc = m_VariablesDesc.data(); - } - if(this->m_Desc.StaticSamplers) - { - for (Uint32 s = 0; s < this->m_Desc.NumStaticSamplers; ++s, ++Str) - { - m_StaticSamplers[s] = this->m_Desc.StaticSamplers[s]; - VERIFY(m_StaticSamplers[s].SamplerOrTextureName != nullptr, "Static sampler or texture name is not provided"); - *Str = m_StaticSamplers[s].SamplerOrTextureName; - m_StaticSamplers[s].SamplerOrTextureName = Str->c_str(); -#ifdef DEVELOPMENT - const auto &BorderColor = m_StaticSamplers[s].Desc.BorderColor; - if( !( (BorderColor[0] == 0 && BorderColor[1] == 0 && BorderColor[2] == 0 && BorderColor[3] == 0) || - (BorderColor[0] == 0 && BorderColor[1] == 0 && BorderColor[2] == 0 && BorderColor[3] == 1) || - (BorderColor[0] == 1 && BorderColor[1] == 1 && BorderColor[2] == 1 && BorderColor[3] == 1) ) ) - { - LOG_WARNING_MESSAGE("Static sampler for variable \"", *Str , "\" specifies border color (", BorderColor[0], ", ", BorderColor[1], ", ", BorderColor[2], ", ", BorderColor[3], "). D3D12 static samplers only allow transparent black (0,0,0,0), opaque black (0,0,0,1) or opaque white (1,1,1,1) as border colors"); - } -#endif - } - this->m_Desc.StaticSamplers = m_StaticSamplers.data(); - } - - VERIFY_EXPR(Str == m_StringPool.end()); } IMPLEMENT_QUERY_INTERFACE_IN_PLACE( IID_Shader, TDeviceObjectBase ) - -protected: - /// Shader variable descriptions - std::vector > m_VariablesDesc; - /// String pool that is used to hold copies of variable names and static sampler names - std::vector > m_StringPool; - /// Static sampler descriptions - std::vector > m_StaticSamplers; }; } diff --git a/Graphics/GraphicsEngine/include/ShaderResourceVariableBase.h b/Graphics/GraphicsEngine/include/ShaderResourceVariableBase.h new file mode 100644 index 00000000..5c5629d3 --- /dev/null +++ b/Graphics/GraphicsEngine/include/ShaderResourceVariableBase.h @@ -0,0 +1,161 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +/// \file +/// Implementation of the Diligent::ShaderBase template class + +#include + +#include "ShaderResourceVariable.h" +#include "PipelineState.h" + +namespace Diligent +{ + +template +SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE ShaderStage, + SHADER_RESOURCE_VARIABLE_TYPE DefaultVariableType, + const ShaderResourceVariableDesc* Variables, + Uint32 NumVars, + TNameCompare NameCompare) +{ + for (Uint32 v = 0; v < NumVars; ++v) + { + const auto& CurrVarDesc = Variables[v]; + if ( ((CurrVarDesc.ShaderStages & ShaderStage) != 0) && NameCompare(CurrVarDesc.Name) ) + { + return CurrVarDesc.Type; + } + } + return DefaultVariableType; +} + +inline SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE ShaderStage, + const Char* Name, + SHADER_RESOURCE_VARIABLE_TYPE DefaultVariableType, + const ShaderResourceVariableDesc* Variables, + Uint32 NumVars) +{ + return GetShaderVariableType(ShaderStage, DefaultVariableType, Variables, NumVars, + [&](const char* VarName) + { + return strcmp(VarName, Name) == 0; + } + ); +} + +inline SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE ShaderStage, + const Char* Name, + const PipelineLayoutDesc& LayoutDesc) +{ + return GetShaderVariableType(ShaderStage, Name, LayoutDesc.DefaultVariableType, LayoutDesc.Variables, LayoutDesc.NumVariables); +} + +inline SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE ShaderStage, + const String& Name, + SHADER_RESOURCE_VARIABLE_TYPE DefaultVariableType, + const ShaderResourceVariableDesc* Variables, + Uint32 NumVars) +{ + return GetShaderVariableType(ShaderStage, DefaultVariableType, Variables, NumVars, + [&](const char* VarName) + { + return Name.compare(VarName) == 0; + } + ); +} + +inline SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE ShaderStage, + const String& Name, + const PipelineLayoutDesc& LayoutDesc) +{ + return GetShaderVariableType(ShaderStage, Name, LayoutDesc.DefaultVariableType, LayoutDesc.Variables, LayoutDesc.NumVariables); +} + +inline bool IsAllowedType(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 AllowedTypeBits)noexcept +{ + return ((1 << VarType) & AllowedTypeBits) != 0; +} + +inline Uint32 GetAllowedTypeBits(const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes)noexcept +{ + if(AllowedVarTypes == nullptr) + return 0xFFFFFFFF; + + Uint32 AllowedTypeBits = 0; + for(Uint32 i=0; i < NumAllowedTypes; ++i) + AllowedTypeBits |= 1 << AllowedVarTypes[i]; + return AllowedTypeBits; +} + +/// Base implementation of a shader variable +struct ShaderVariableBase : public IShaderResourceVariable +{ + ShaderVariableBase(IObject& Owner) : + // Shader variables are always created as part of the shader, or + // shader resource binding, so we must provide owner pointer to + // the base class constructor + m_Owner(Owner) + { + } + + IObject& GetOwner() + { + return m_Owner; + } + + virtual IReferenceCounters* GetReferenceCounters()const override final + { + return m_Owner.GetReferenceCounters(); + } + + virtual Atomics::Long AddRef()override final + { + return m_Owner.AddRef(); + } + + virtual Atomics::Long Release()override final + { + return m_Owner.Release(); + } + + virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface )override final + { + if( ppInterface == nullptr ) + return; + + *ppInterface = nullptr; + if( IID == IID_ShaderResourceVariable || IID == IID_Unknown ) + { + *ppInterface = this; + (*ppInterface)->AddRef(); + } + } + +protected: + IObject& m_Owner; +}; + +} diff --git a/Graphics/GraphicsEngine/interface/RenderDevice.h b/Graphics/GraphicsEngine/interface/RenderDevice.h index c844df8a..fd10f17c 100644 --- a/Graphics/GraphicsEngine/interface/RenderDevice.h +++ b/Graphics/GraphicsEngine/interface/RenderDevice.h @@ -80,14 +80,13 @@ public: /// Creates a new shader object - /// \param [in] CreationAttribs - Shader creation attributes, see - /// Diligent::ShaderCreationAttribs for details. + /// \param [in] ShaderCI - Shader create info, see Diligent::ShaderCreateInfo for details. /// \param [out] ppShader - Address of the memory location where the pointer to the /// shader interface will be stored. /// The function calls AddRef(), so that the new object will contain /// one refernce. - virtual void CreateShader(const ShaderCreationAttribs& CreationAttribs, - IShader** ppShader) = 0; + virtual void CreateShader(const ShaderCreateInfo& ShaderCI, + IShader** ppShader) = 0; /// Creates a new texture object diff --git a/Graphics/GraphicsEngine/interface/Texture.h b/Graphics/GraphicsEngine/interface/Texture.h index 7c3cb941..a1b56ed9 100644 --- a/Graphics/GraphicsEngine/interface/Texture.h +++ b/Graphics/GraphicsEngine/interface/Texture.h @@ -273,7 +273,7 @@ class ITexture : public IDeviceObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; /// Returns the texture description used to create the object virtual const TextureDesc& GetDesc()const = 0; @@ -297,7 +297,7 @@ public: /// until all views are released.\n /// The function calls AddRef() for the created interface, so it must be released by /// a call to Release() when it is no longer needed. - virtual void CreateView(const struct TextureViewDesc &ViewDesc, class ITextureView **ppView) = 0; + virtual void CreateView(const struct TextureViewDesc& ViewDesc, class ITextureView** ppView) = 0; /// Returns the pointer to the default view. @@ -306,7 +306,7 @@ public: /// /// \note The function does not increase the reference counter for the returned interface, so /// Release() must *NOT* be called. - virtual ITextureView* GetDefaultView( TEXTURE_VIEW_TYPE ViewType ) = 0; + virtual ITextureView* GetDefaultView(TEXTURE_VIEW_TYPE ViewType) = 0; /// Returns native texture handle specific to the underlying graphics API diff --git a/Graphics/GraphicsEngine/interface/TextureView.h b/Graphics/GraphicsEngine/interface/TextureView.h index d77cf87a..84df8ce4 100644 --- a/Graphics/GraphicsEngine/interface/TextureView.h +++ b/Graphics/GraphicsEngine/interface/TextureView.h @@ -163,7 +163,7 @@ class ITextureView : public IDeviceObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface ) = 0; /// Returns the texture view description used to create the object virtual const TextureViewDesc& GetDesc()const = 0; diff --git a/Graphics/GraphicsEngineVulkan/include/PipelineStateVkImpl.h b/Graphics/GraphicsEngineVulkan/include/PipelineStateVkImpl.h index cd7d1cab..07b0f414 100644 --- a/Graphics/GraphicsEngineVulkan/include/PipelineStateVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/PipelineStateVkImpl.h @@ -33,6 +33,7 @@ #include "PipelineStateBase.h" #include "PipelineLayout.h" #include "ShaderResourceLayoutVk.h" +#include "ShaderVariableVk.h" #include "FixedBlockMemoryAllocator.h" #include "SRBMemoryAllocator.h" #include "VulkanUtilities/VulkanObjectWrappers.h" @@ -44,6 +45,7 @@ namespace Diligent { class FixedBlockMemoryAllocator; +class ShaderVariableManagerVk; /// Implementation of the Diligent::IRenderDeviceVk interface class PipelineStateVkImpl final : public PipelineStateBase @@ -54,9 +56,9 @@ public: PipelineStateVkImpl( IReferenceCounters* pRefCounters, RenderDeviceVkImpl* pDeviceVk, const PipelineStateDesc &PipelineDesc ); ~PipelineStateVkImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject** ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; - virtual void CreateShaderResourceBinding( IShaderResourceBinding **ppShaderResourceBinding, bool InitStaticResources )override final; + virtual void CreateShaderResourceBinding(IShaderResourceBinding** ppShaderResourceBinding, bool InitStaticResources)override final; virtual bool IsCompatibleWith(const IPipelineState* pPSO)const override final; @@ -64,6 +66,14 @@ public: virtual VkPipeline GetVkPipeline()const override final { return m_Pipeline; } + virtual void BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags)override final; + + virtual Uint32 GetStaticVariableCount(SHADER_TYPE ShaderType) const override final; + + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) override final; + + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) override final; + void CommitAndTransitionShaderResources(IShaderResourceBinding* pShaderResourceBinding, DeviceContextVkImpl* pCtxVkImpl, bool CommitResources, @@ -98,9 +108,31 @@ public: VkSubpassDescription& SubpassDesc); + void InitializeStaticSRBResources(ShaderResourceCacheVk& ResourceCache)const; + private: - ShaderResourceLayoutVk* m_ShaderResourceLayouts = nullptr; - + const ShaderResourceLayoutVk& GetStaticShaderResLayout(Uint32 ShaderInd)const + { + VERIFY_EXPR(ShaderInd < m_NumShaders); + return m_ShaderResourceLayouts[m_NumShaders + ShaderInd]; + } + + const ShaderResourceCacheVk& GetStaticResCache(Uint32 ShaderInd)const + { + VERIFY_EXPR(ShaderInd < m_NumShaders); + return m_StaticResCaches[ShaderInd]; + } + + ShaderVariableManagerVk& GetStaticVarMgr(Uint32 ShaderInd)const + { + VERIFY_EXPR(ShaderInd < m_NumShaders); + return m_StaticVarsMgrs[ShaderInd]; + } + + ShaderResourceLayoutVk* m_ShaderResourceLayouts = nullptr; + ShaderResourceCacheVk* m_StaticResCaches = nullptr; + ShaderVariableManagerVk* m_StaticVarsMgrs = nullptr; + // SRB memory allocator must be declared before m_pDefaultShaderResBinding SRBMemoryAllocator m_SRBMemAllocator; @@ -109,6 +141,8 @@ private: VkRenderPass m_RenderPass = VK_NULL_HANDLE; // Render passes are managed by the render device VulkanUtilities::PipelineWrapper m_Pipeline; PipelineLayout m_PipelineLayout; + + Int8 m_ResourceLayoutIndex[6] = {-1, -1, -1, -1, -1, -1}; bool m_HasStaticResources = false; bool m_HasNonStaticResources = false; }; diff --git a/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp b/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp index 793aea80..d177ca46 100644 --- a/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp +++ b/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp @@ -109,17 +109,8 @@ namespace Diligent CSCreateAttribs.Source = g_GenerateMipsCSSource; CSCreateAttribs.EntryPoint = "main"; - CSCreateAttribs.SourceLanguage = SHADER_SOURCE_LANGUAGE_GLSL; + CSCreateAttribs.SourceLanguage = SHADER_SOURCE_LANGUAGE_GLSL; CSCreateAttribs.Desc.ShaderType = SHADER_TYPE_COMPUTE; - CSCreateAttribs.Desc.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; - - ShaderResourceVariableDesc VarDesc{"CB", SHADER_RESOURCE_VARIABLE_TYPE_STATIC}; - CSCreateAttribs.Desc.VariableDesc = &VarDesc; - CSCreateAttribs.Desc.NumVariables = 1; - - const StaticSamplerDesc StaticSampler("SrcMip", Sam_LinearClamp); - CSCreateAttribs.Desc.StaticSamplers = &StaticSampler; - CSCreateAttribs.Desc.NumStaticSamplers = 1; const auto& FmtAttribs = GetTextureFormatAttribs(Fmt); bool IsGamma = FmtAttribs.ComponentType == COMPONENT_TYPE_UNORM_SRGB; @@ -155,8 +146,18 @@ namespace Diligent PSODesc.IsComputePipeline = true; PSODesc.Name = name.c_str(); PSODesc.ComputePipeline.pCS = pCS; - pCS->GetShaderVariable("CB")->Set(m_ConstantsCB); + + PSODesc.Layout.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; + ShaderResourceVariableDesc VarDesc{SHADER_TYPE_COMPUTE, "CB", SHADER_RESOURCE_VARIABLE_TYPE_STATIC}; + PSODesc.Layout.Variables = &VarDesc; + PSODesc.Layout.NumVariables = 1; + + const StaticSamplerDesc StaticSampler(SHADER_TYPE_COMPUTE, "SrcMip", Sam_LinearClamp); + PSODesc.Layout.StaticSamplers = &StaticSampler; + PSODesc.Layout.NumStaticSamplers = 1; + m_DeviceVkImpl.CreatePipelineState(PSODesc, &PSOs[NonPowOfTwo]); + PSOs[NonPowOfTwo]->GetStaticShaderVariable(SHADER_TYPE_COMPUTE, "CB")->Set(m_ConstantsCB); } return PSOs; diff --git a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp index 8fd4583c..2a60ce96 100644 --- a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp @@ -60,12 +60,12 @@ VkRenderPassCreateInfo PipelineStateVkImpl::GetRenderPassCreateInfo( { auto& DepthAttachment = Attachments[AttachmentInd]; - DepthAttachment.flags = 0; // Allowed value VK_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT - DepthAttachment.format = TexFormatToVkFormat(DSVFormat); + DepthAttachment.flags = 0; // Allowed value VK_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT + DepthAttachment.format = TexFormatToVkFormat(DSVFormat); DepthAttachment.samples = SampleCountFlags; - DepthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; // previous contents of the image within the render area - // will be preserved. For attachments with a depth/stencil format, - // this uses the access type VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT. + DepthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; // previous contents of the image within the render area + // will be preserved. For attachments with a depth/stencil format, + // this uses the access type VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT. DepthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; // the contents generated during the render pass and within the render // area are written to memory. For attachments with a depth/stencil format, // this uses the access type VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT. @@ -113,12 +113,12 @@ VkRenderPassCreateInfo PipelineStateVkImpl::GetRenderPassCreateInfo( // dependencies between pairs of subpasses, or NULL if dependencyCount is zero. - SubpassDesc.flags = 0; // All bits for this type are defined by extensions - SubpassDesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; // Currently, only graphics subpasses are supported. - SubpassDesc.inputAttachmentCount = 0; - SubpassDesc.pInputAttachments = nullptr; - SubpassDesc.colorAttachmentCount = NumRenderTargets; - SubpassDesc.pColorAttachments = pColorAttachmentsReference; + SubpassDesc.flags = 0; // All bits for this type are defined by extensions + SubpassDesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; // Currently, only graphics subpasses are supported. + SubpassDesc.inputAttachmentCount = 0; + SubpassDesc.pInputAttachments = nullptr; + SubpassDesc.colorAttachmentCount = NumRenderTargets; + SubpassDesc.pColorAttachments = pColorAttachmentsReference; SubpassDesc.pResolveAttachments = nullptr; SubpassDesc.pDepthStencilAttachment = pDepthAttachmentReference; SubpassDesc.preserveAttachmentCount = 0; @@ -147,7 +147,7 @@ PipelineStateVkImpl :: PipelineStateVkImpl(IReferenceCounters* pRefCounters RenderDeviceVkImpl* pDeviceVk, const PipelineStateDesc& PipelineDesc) : TPipelineStateBase(pRefCounters, pDeviceVk, PipelineDesc), - m_SRBMemAllocator(GetRawAllocator()) + m_SRBMemAllocator (GetRawAllocator()) { const auto& LogicalDevice = pDeviceVk->GetLogicalDevice(); @@ -155,16 +155,32 @@ PipelineStateVkImpl :: PipelineStateVkImpl(IReferenceCounters* pRefCounters auto& ShaderResLayoutAllocator = GetRawAllocator(); std::array, MaxShadersInPipeline> ShaderResources; std::array, MaxShadersInPipeline> ShaderSPIRVs; - auto* pResLayoutRawMem = ALLOCATE(ShaderResLayoutAllocator, "Raw memory for ShaderResourceLayoutVk", sizeof(ShaderResourceLayoutVk) * m_NumShaders); + auto* pResLayoutRawMem = ALLOCATE(ShaderResLayoutAllocator, "Raw memory for ShaderResourceLayoutVk", sizeof(ShaderResourceLayoutVk) * m_NumShaders * 2); + auto* pStaticResCacheRawMem = ALLOCATE(GetRawAllocator(), "Raw memory for ShaderResourceCacheVk", sizeof(ShaderResourceCacheVk) * m_NumShaders); + auto* pStaticVarMgrRawMem = ALLOCATE(GetRawAllocator(), "Raw memory for ShaderVariableManagerVk", sizeof(ShaderVariableManagerVk) * m_NumShaders); m_ShaderResourceLayouts = reinterpret_cast(pResLayoutRawMem); + m_StaticResCaches = reinterpret_cast(pStaticResCacheRawMem); + m_StaticVarsMgrs = reinterpret_cast(pStaticVarMgrRawMem); for (Uint32 s=0; s < m_NumShaders; ++s) { new (m_ShaderResourceLayouts + s) ShaderResourceLayoutVk(*this, LogicalDevice); auto* pShaderVk = GetShader(s); ShaderResources[s] = pShaderVk->GetShaderResources(); ShaderSPIRVs[s] = pShaderVk->GetSPIRV(); + + const auto ShaderType = pShaderVk->GetDesc().ShaderType; + const auto ShaderTypeInd = GetShaderTypeIndex(ShaderType); + m_ResourceLayoutIndex[ShaderTypeInd] = static_cast(s); + + auto* pStaticResLayout = new (m_ShaderResourceLayouts + m_NumShaders + s) ShaderResourceLayoutVk(*this, LogicalDevice); + auto* pStaticResCache = new (m_StaticResCaches + s) ShaderResourceCacheVk(ShaderResourceCacheVk::DbgCacheContentType::StaticShaderResources); + pStaticResLayout->InitializeStaticResourceLayout(ShaderResources[s], ShaderResLayoutAllocator, PipelineDesc.Layout, m_StaticResCaches[s]); + + auto* pStaticVarMgr = new (m_StaticVarsMgrs + s) ShaderVariableManagerVk(*this); + pStaticVarMgr->Initialize(*pStaticResLayout, GetRawAllocator(), nullptr, 0, *pStaticResCache); } - ShaderResourceLayoutVk::Initialize(m_NumShaders, m_ShaderResourceLayouts, ShaderResources.data(), GetRawAllocator(), ShaderSPIRVs.data(), m_PipelineLayout); + ShaderResourceLayoutVk::Initialize(pDeviceVk, m_NumShaders, m_ShaderResourceLayouts, ShaderResources.data(), GetRawAllocator(), + PipelineDesc.Layout, ShaderSPIRVs.data(), m_PipelineLayout); m_PipelineLayout.Finalize(LogicalDevice); if (PipelineDesc.SRBAllocationGranularity > 1) @@ -172,7 +188,7 @@ PipelineStateVkImpl :: PipelineStateVkImpl(IReferenceCounters* pRefCounters std::array ShaderVariableDataSizes = {}; for (Uint32 s = 0; s < m_NumShaders; ++s) { - std::array AllowedVarTypes = { {SHADER_VARIABLE_TYPE_MUTABLE, SHADER_VARIABLE_TYPE_DYNAMIC} }; + std::array AllowedVarTypes = { {SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC} }; Uint32 UnusedNumVars = 0; ShaderVariableDataSizes[s] = ShaderVariableManagerVk::GetRequiredMemorySize(m_ShaderResourceLayouts[s], AllowedVarTypes.data(), static_cast(AllowedVarTypes.size()), UnusedNumVars); } @@ -412,11 +428,11 @@ PipelineStateVkImpl :: PipelineStateVkImpl(IReferenceCounters* pRefCounters for (Uint32 s=0; s < m_NumShaders; ++s) { const auto& Layout = m_ShaderResourceLayouts[s]; - if (Layout.GetResourceCount(SHADER_VARIABLE_TYPE_STATIC) != 0) + if (Layout.GetResourceCount(SHADER_RESOURCE_VARIABLE_TYPE_STATIC) != 0) m_HasStaticResources = true; - if (Layout.GetResourceCount(SHADER_VARIABLE_TYPE_MUTABLE) != 0 || - Layout.GetResourceCount(SHADER_VARIABLE_TYPE_DYNAMIC) != 0) + if (Layout.GetResourceCount(SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE) != 0 || + Layout.GetResourceCount(SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) != 0) m_HasNonStaticResources = true; } @@ -440,8 +456,13 @@ PipelineStateVkImpl::~PipelineStateVkImpl() for (Uint32 s=0; s < m_NumShaders; ++s) { m_ShaderResourceLayouts[s].~ShaderResourceLayoutVk(); + m_StaticResCaches[s].~ShaderResourceCacheVk(); + m_StaticVarsMgrs[s].Destroy(GetRawAllocator()); + m_StaticVarsMgrs[s].~ShaderVariableManagerVk(); } RawAllocator.Free(m_ShaderResourceLayouts); + RawAllocator.Free(m_StaticResCaches); + RawAllocator.Free(m_StaticVarsMgrs); } IMPLEMENT_QUERY_INTERFACE( PipelineStateVkImpl, IID_PipelineStateVk, TPipelineStateBase ) @@ -581,7 +602,7 @@ void PipelineStateVkImpl::CommitAndTransitionShaderResources(IShaderResourceBind for (Uint32 s=0; s < m_NumShaders; ++s) { const auto& Layout = m_ShaderResourceLayouts[s]; - if (Layout.GetResourceCount(SHADER_VARIABLE_TYPE_DYNAMIC) != 0) + if (Layout.GetResourceCount(SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) != 0) Layout.CommitDynamicResources(ResourceCache, DynamicDescrSet); } } @@ -593,4 +614,65 @@ void PipelineStateVkImpl::CommitAndTransitionShaderResources(IShaderResourceBind } } +void PipelineStateVkImpl::BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags) +{ + for (Uint32 s=0; s < m_NumShaders; ++s) + { + auto& StaticVarMgr = GetStaticVarMgr(s); + StaticVarMgr.BindResources(pResourceMapping, Flags); + } +} + +Uint32 PipelineStateVkImpl::GetStaticVariableCount(SHADER_TYPE ShaderType) const +{ + const auto ShaderTypeInd = GetShaderTypeIndex(ShaderType); + if (ShaderTypeInd < 0) + return 0; + + auto& StaticVarMgr = GetStaticVarMgr(ShaderTypeInd); + return StaticVarMgr.GetVariableCount(); +} + +IShaderResourceVariable* PipelineStateVkImpl::GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) +{ + const auto ShaderTypeInd = GetShaderTypeIndex(ShaderType); + if (ShaderTypeInd < 0) + return nullptr; + + auto& StaticVarMgr = GetStaticVarMgr(ShaderTypeInd); + return StaticVarMgr.GetVariable(Name); +} + +IShaderResourceVariable* PipelineStateVkImpl::GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) +{ + const auto ShaderTypeInd = GetShaderTypeIndex(ShaderType); + if (ShaderTypeInd < 0) + return nullptr; + + auto& StaticVarMgr = GetStaticVarMgr(ShaderTypeInd); + return StaticVarMgr.GetVariable(Index); +} + + +void PipelineStateVkImpl::InitializeStaticSRBResources(ShaderResourceCacheVk& ResourceCache)const +{ + for (Uint32 s = 0; s < m_NumShaders; ++s) + { + const auto& StaticResLayout = GetStaticShaderResLayout(s); +#ifdef DEVELOPMENT + if (!StaticResLayout.dvpVerifyBindings(ResourceCache)) + { + const auto* pShaderVk = GetShader(s); + LOG_ERROR_MESSAGE("Static resources in SRB of PSO '", GetDesc().Name, "' will not be successfully initialized " + "because not all static resource bindings in shader '", pShaderVk->GetDesc().Name, "' are valid. " + "Please make sure you bind all static resources to the shader before calling InitializeStaticResources() " + "directly or indirectly by passing InitStaticResources=true to CreateShaderResourceBinding() method."); + } +#endif + const auto& StaticResCache = GetStaticResCache(s); + const auto& ShaderResourceLayouts = GetShaderResLayout(s); + ShaderResourceLayouts.InitializeStaticResources(StaticResLayout, StaticResCache, ResourceCache); + } +} + } diff --git a/Graphics/GraphicsEngineVulkan/src/RenderDeviceVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/RenderDeviceVkImpl.cpp index dbf2893f..89ed5d01 100644 --- a/Graphics/GraphicsEngineVulkan/src/RenderDeviceVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/RenderDeviceVkImpl.cpp @@ -433,12 +433,12 @@ void RenderDeviceVkImpl :: CreateBuffer(const BufferDesc& BuffDesc, const Buffer } -void RenderDeviceVkImpl :: CreateShader(const ShaderCreationAttribs &ShaderCreationAttribs, IShader **ppShader) +void RenderDeviceVkImpl :: CreateShader(const ShaderCreateInfo& ShaderCI, IShader **ppShader) { - CreateDeviceObject( "shader", ShaderCreationAttribs.Desc, ppShader, + CreateDeviceObject( "shader", ShaderCI.Desc, ppShader, [&]() { - ShaderVkImpl *pShaderVk( NEW_RC_OBJ(m_ShaderObjAllocator, "ShaderVkImpl instance", ShaderVkImpl)(this, ShaderCreationAttribs ) ); + ShaderVkImpl *pShaderVk( NEW_RC_OBJ(m_ShaderObjAllocator, "ShaderVkImpl instance", ShaderVkImpl)(this, ShaderCI) ); pShaderVk->QueryInterface( IID_Shader, reinterpret_cast(ppShader) ); OnCreateDeviceObject( pShaderVk ); diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp index 342f5ae6..3077a5dd 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp @@ -155,24 +155,7 @@ void ShaderResourceBindingVkImpl::InitializeStaticResources(const IPipelineState } auto* pPSOVK = ValidatedCast(pPipelineState); - for (Uint32 s = 0; s < m_NumShaders; ++s) - { - const auto* pShaderVk = pPSOVK->GetShader(s); -#ifdef DEVELOPMENT - if (!pShaderVk->DvpVerifyStaticResourceBindings()) - { - LOG_ERROR_MESSAGE("Static resources in SRB of PSO '", pPSOVK->GetDesc().Name, "' will not be successfully initialized " - "because not all static resource bindings in shader '", pShaderVk->GetDesc().Name, "' are valid. " - "Please make sure you bind all static resources to the shader before calling InitializeStaticResources() " - "directly or indirectly by passing InitStaticResources=true to CreateShaderResourceBinding() method."); - } -#endif - const auto& StaticResLayout = pShaderVk->GetStaticResLayout(); - const auto& StaticResCache = pShaderVk->GetStaticResCache(); - const auto& ShaderResourceLayouts = pPSOVK->GetShaderResLayout(s); - ShaderResourceLayouts.InitializeStaticResources(StaticResLayout, StaticResCache, m_ShaderResourceCache); - } - + pPSOVK->InitializeStaticSRBResources(m_ShaderResourceCache); m_bStaticResourcesInitialized = true; } -- cgit v1.2.3 From 26e240dfcb3dad8527a25c0f6270395528a5a71e Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Wed, 27 Feb 2019 20:56:45 -0800 Subject: Fixed PipelineLayoutVk --- .../GraphicsEngineVulkan/include/PipelineLayout.h | 12 ++++++----- .../include/RenderDeviceVkImpl.h | 6 +++--- .../GraphicsEngineVulkan/src/PipelineLayout.cpp | 23 +++++++++++----------- .../src/ShaderResourceLayoutVk.cpp | 2 +- 4 files changed, 23 insertions(+), 20 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/include/PipelineLayout.h b/Graphics/GraphicsEngineVulkan/include/PipelineLayout.h index f970501a..a875cb90 100644 --- a/Graphics/GraphicsEngineVulkan/include/PipelineLayout.h +++ b/Graphics/GraphicsEngineVulkan/include/PipelineLayout.h @@ -58,6 +58,7 @@ public: const char* DbgPipelineName)const; void AllocateResourceSlot(const SPIRVShaderResourceAttribs& ResAttribs, + SHADER_RESOURCE_VARIABLE_TYPE VariableType, VkSampler vkStaticSampler, SHADER_TYPE ShaderType, Uint32& DescriptorSet, @@ -65,9 +66,9 @@ public: Uint32& OffsetInCache, std::vector& SPIRV); - Uint32 GetTotalDescriptors(SHADER_VARIABLE_TYPE VarType)const + Uint32 GetTotalDescriptors(SHADER_RESOURCE_VARIABLE_TYPE VarType)const { - VERIFY_EXPR(VarType >= 0 && VarType < SHADER_VARIABLE_TYPE_NUM_TYPES); + VERIFY_EXPR(VarType >= 0 && VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES); return m_LayoutMgr.GetDescriptorSet(VarType).TotalDescriptors; } @@ -82,7 +83,7 @@ public: VkDescriptorSetLayout GetDynamicDescriptorSetVkLayout()const { - return m_LayoutMgr.GetDescriptorSet(SHADER_VARIABLE_TYPE_DYNAMIC).VkLayout; + return m_LayoutMgr.GetDescriptorSet(SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC).VkLayout; } struct DescriptorSetBindInfo @@ -178,8 +179,8 @@ private: void Finalize(const VulkanUtilities::VulkanLogicalDevice &LogicalDevice); void Release(RenderDeviceVkImpl* pRenderDeviceVk, Uint64 CommandQueueMask); - DescriptorSetLayout& GetDescriptorSet(SHADER_VARIABLE_TYPE VarType) { return m_DescriptorSetLayouts[VarType == SHADER_VARIABLE_TYPE_DYNAMIC ? 1 : 0]; } - const DescriptorSetLayout& GetDescriptorSet(SHADER_VARIABLE_TYPE VarType)const { return m_DescriptorSetLayouts[VarType == SHADER_VARIABLE_TYPE_DYNAMIC ? 1 : 0]; } + DescriptorSetLayout& GetDescriptorSet(SHADER_RESOURCE_VARIABLE_TYPE VarType) { return m_DescriptorSetLayouts[VarType == SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC ? 1 : 0]; } + const DescriptorSetLayout& GetDescriptorSet(SHADER_RESOURCE_VARIABLE_TYPE VarType)const { return m_DescriptorSetLayouts[VarType == SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC ? 1 : 0]; } bool operator == (const DescriptorSetLayoutManager& rhs)const; bool operator != (const DescriptorSetLayoutManager& rhs)const {return !(*this == rhs);} @@ -187,6 +188,7 @@ private: VkPipelineLayout GetVkPipelineLayout()const{return m_VkPipelineLayout;} void AllocateResourceSlot(const SPIRVShaderResourceAttribs& ResAttribs, + SHADER_RESOURCE_VARIABLE_TYPE VariableType, VkSampler vkStaticSampler, SHADER_TYPE ShaderType, Uint32& DescriptorSet, diff --git a/Graphics/GraphicsEngineVulkan/include/RenderDeviceVkImpl.h b/Graphics/GraphicsEngineVulkan/include/RenderDeviceVkImpl.h index 64410774..c0e2847b 100644 --- a/Graphics/GraphicsEngineVulkan/include/RenderDeviceVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/RenderDeviceVkImpl.h @@ -66,13 +66,13 @@ public: Uint32 NumDeferredContexts ); ~RenderDeviceVkImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject** ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface )override final; - virtual void CreatePipelineState( const PipelineStateDesc &PipelineDesc, IPipelineState** ppPipelineState )override final; + virtual void CreatePipelineState(const PipelineStateDesc& PipelineDesc, IPipelineState** ppPipelineState)override final; virtual void CreateBuffer(const BufferDesc& BuffDesc, const BufferData* pBuffData, IBuffer** ppBuffer)override final; - virtual void CreateShader(const ShaderCreationAttribs& ShaderCreationAttribs, IShader** ppShader)override final; + virtual void CreateShader(const ShaderCreateInfo& ShaderCreateInfo, IShader** ppShader)override final; virtual void CreateTexture(const TextureDesc& TexDesc, const TextureData* pData, ITexture** ppTexture)override final; diff --git a/Graphics/GraphicsEngineVulkan/src/PipelineLayout.cpp b/Graphics/GraphicsEngineVulkan/src/PipelineLayout.cpp index 6e930bcc..7ce29a6f 100644 --- a/Graphics/GraphicsEngineVulkan/src/PipelineLayout.cpp +++ b/Graphics/GraphicsEngineVulkan/src/PipelineLayout.cpp @@ -315,13 +315,14 @@ size_t PipelineLayout::DescriptorSetLayoutManager::GetHash()const } void PipelineLayout::DescriptorSetLayoutManager::AllocateResourceSlot(const SPIRVShaderResourceAttribs& ResAttribs, + SHADER_RESOURCE_VARIABLE_TYPE VariableType, VkSampler vkStaticSampler, SHADER_TYPE ShaderType, Uint32& DescriptorSet, Uint32& Binding, Uint32& OffsetInCache) { - auto& DescrSet = GetDescriptorSet(ResAttribs.VarType); + auto& DescrSet = GetDescriptorSet(VariableType); if (DescrSet.SetIndex < 0) { DescrSet.SetIndex = m_ActiveSets++; @@ -335,9 +336,8 @@ void PipelineLayout::DescriptorSetLayoutManager::AllocateResourceSlot(const SPIR VkBinding.descriptorCount = ResAttribs.ArraySize; // There are no limitations on what combinations of stages can use a descriptor binding (13.2.1) VkBinding.stageFlags = ShaderTypeToVkShaderStageFlagBit(ShaderType); - if (ResAttribs.IsImmutableSamplerAssigned()) + if (vkStaticSampler != VK_NULL_HANDLE) { - VERIFY(vkStaticSampler != VK_NULL_HANDLE, "No static sampler provided"); // If descriptorType is VK_DESCRIPTOR_TYPE_SAMPLER or VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, and // descriptorCount is not 0 and pImmutableSamplers is not NULL, pImmutableSamplers must be a valid pointer // to an array of descriptorCount valid VkSampler handles (13.2.1) @@ -365,6 +365,7 @@ void PipelineLayout::Release(RenderDeviceVkImpl *pDeviceVkImpl, Uint64 CommandQu } void PipelineLayout::AllocateResourceSlot(const SPIRVShaderResourceAttribs& ResAttribs, + SHADER_RESOURCE_VARIABLE_TYPE VariableType, VkSampler vkStaticSampler, SHADER_TYPE ShaderType, Uint32& DescriptorSet, // Output parameter @@ -372,7 +373,7 @@ void PipelineLayout::AllocateResourceSlot(const SPIRVShaderResourceAttribs& ResA Uint32& OffsetInCache, std::vector& SPIRV) { - m_LayoutMgr.AllocateResourceSlot(ResAttribs, vkStaticSampler, ShaderType, DescriptorSet, Binding, OffsetInCache); + m_LayoutMgr.AllocateResourceSlot(ResAttribs, VariableType,vkStaticSampler, ShaderType, DescriptorSet, Binding, OffsetInCache); SPIRV[ResAttribs.BindingDecorationOffset] = Binding; SPIRV[ResAttribs.DescriptorSetDecorationOffset] = DescriptorSet; } @@ -387,14 +388,14 @@ std::array PipelineLayout::GetDescriptorSetSizes(Uint32& NumSets)cons NumSets = 0; std::array SetSizes = {}; - const auto &StaticAndMutSet = m_LayoutMgr.GetDescriptorSet(SHADER_VARIABLE_TYPE_STATIC); + const auto &StaticAndMutSet = m_LayoutMgr.GetDescriptorSet(SHADER_RESOURCE_VARIABLE_TYPE_STATIC); if (StaticAndMutSet.SetIndex >= 0) { NumSets = std::max(NumSets, static_cast(StaticAndMutSet.SetIndex + 1)); SetSizes[StaticAndMutSet.SetIndex] = StaticAndMutSet.TotalDescriptors; } - const auto &DynamicSet = m_LayoutMgr.GetDescriptorSet(SHADER_VARIABLE_TYPE_DYNAMIC); + const auto &DynamicSet = m_LayoutMgr.GetDescriptorSet(SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC); if (DynamicSet.SetIndex >= 0) { NumSets = std::max(NumSets, static_cast(DynamicSet.SetIndex + 1)); @@ -416,7 +417,7 @@ void PipelineLayout::InitResourceCache(RenderDeviceVkImpl* pDeviceVkImpl, // Resources are initialized by source layout when shader resource binding objects are created ResourceCache.InitializeSets(CacheMemAllocator, NumSets, SetSizes.data()); - const auto& StaticAndMutSet = m_LayoutMgr.GetDescriptorSet(SHADER_VARIABLE_TYPE_STATIC); + const auto& StaticAndMutSet = m_LayoutMgr.GetDescriptorSet(SHADER_RESOURCE_VARIABLE_TYPE_STATIC); if (StaticAndMutSet.SetIndex >= 0) { const char* DescrSetName = "Static/Mutable Descriptor Set"; @@ -443,11 +444,11 @@ void PipelineLayout::PrepareDescriptorSets(DeviceContextVkImpl* pCtxVkI // Do not use vector::resize for BindInfo.vkSets and BindInfo.DynamicOffsets as this // causes unnecessary work to zero-initialize new elements - VERIFY(m_LayoutMgr.GetDescriptorSet(SHADER_VARIABLE_TYPE_STATIC).SetIndex == m_LayoutMgr.GetDescriptorSet(SHADER_VARIABLE_TYPE_MUTABLE).SetIndex, + VERIFY(m_LayoutMgr.GetDescriptorSet(SHADER_RESOURCE_VARIABLE_TYPE_STATIC).SetIndex == m_LayoutMgr.GetDescriptorSet(SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE).SetIndex, "Static and mutable variables are expected to share the same descriptor set"); Uint32 TotalDynamicDescriptors = 0; BindInfo.SetCout = 0; - for(SHADER_VARIABLE_TYPE VarType = SHADER_VARIABLE_TYPE_MUTABLE; VarType <= SHADER_VARIABLE_TYPE_DYNAMIC; VarType = static_cast(VarType+1)) + for(SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE; VarType <= SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; VarType = static_cast(VarType+1)) { const auto& Set = m_LayoutMgr.GetDescriptorSet(VarType); if (Set.SetIndex >= 0) @@ -456,7 +457,7 @@ void PipelineLayout::PrepareDescriptorSets(DeviceContextVkImpl* pCtxVkI if (BindInfo.SetCout > BindInfo.vkSets.size()) BindInfo.vkSets.resize(BindInfo.SetCout); VERIFY_EXPR(BindInfo.vkSets[Set.SetIndex] == VK_NULL_HANDLE); - if (VarType == SHADER_VARIABLE_TYPE_MUTABLE) + if (VarType == SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE) BindInfo.vkSets[Set.SetIndex] = ResourceCache.GetDescriptorSet(Set.SetIndex).GetVkDescriptorSet(); else { @@ -506,7 +507,7 @@ void PipelineLayout::BindDescriptorSetsWithDynamicOffsets(DeviceContextVkImpl* VERIFY_EXPR(BindInfo.pResourceCache != nullptr); #ifdef _DEBUG Uint32 TotalDynamicDescriptors = 0; - for (SHADER_VARIABLE_TYPE VarType = SHADER_VARIABLE_TYPE_MUTABLE; VarType <= SHADER_VARIABLE_TYPE_DYNAMIC; VarType = static_cast(VarType + 1)) + for (SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE; VarType <= SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; VarType = static_cast(VarType + 1)) { const auto &Set = m_LayoutMgr.GetDescriptorSet(VarType); TotalDynamicDescriptors += Set.NumDynamicDescriptors; diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp index 9151fc9a..546fd01e 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp @@ -338,7 +338,7 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* } auto& ShaderSPIRV = SPIRVs[ShaderInd]; - PipelineLayout.AllocateResourceSlot(Attribs, vkImmutableSampler, Resources.GetShaderType(), DescriptorSet, Binding, CacheOffset, ShaderSPIRV); + PipelineLayout.AllocateResourceSlot(Attribs, VarType, vkImmutableSampler, Resources.GetShaderType(), DescriptorSet, Binding, CacheOffset, ShaderSPIRV); VERIFY(DescriptorSet <= std::numeric_limits::max(), "Descriptor set (", DescriptorSet, ") excceeds max representable value"); VERIFY(Binding <= std::numeric_limits::max(), "Binding (", Binding, ") excceeds max representable value"); -- cgit v1.2.3 From 59f58900fed7fa5c2ed490d31252950b55308175 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Wed, 27 Feb 2019 21:15:52 -0800 Subject: Keeping copy of a shader name in SPIRVShaderResources --- Graphics/GLSLTools/include/SPIRVShaderResources.h | 2 ++ Graphics/GLSLTools/src/SPIRVShaderResources.cpp | 4 +++ .../include/ShaderResourceLayoutVk.h | 15 ++++++--- .../src/PipelineStateVkImpl.cpp | 4 +-- .../src/ShaderResourceLayoutVk.cpp | 37 +++------------------- 5 files changed, 22 insertions(+), 40 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GLSLTools/include/SPIRVShaderResources.h b/Graphics/GLSLTools/include/SPIRVShaderResources.h index 7f0796ed..4809bb71 100644 --- a/Graphics/GLSLTools/include/SPIRVShaderResources.h +++ b/Graphics/GLSLTools/include/SPIRVShaderResources.h @@ -293,6 +293,7 @@ public: //size_t GetHash()const; const char* GetCombinedSamplerSuffix() const { return m_CombinedSamplerSuffix; } + const char* GetShaderName() const { return m_ShaderName; } bool IsUsingCombinedSamplers() const { return m_CombinedSamplerSuffix != nullptr; } @@ -336,6 +337,7 @@ private: StringPool m_ResourceNames; const char* m_CombinedSamplerSuffix = nullptr; + const char* m_ShaderName = nullptr; using OffsetType = Uint16; OffsetType m_StorageBufferOffset = 0; diff --git a/Graphics/GLSLTools/src/SPIRVShaderResources.cpp b/Graphics/GLSLTools/src/SPIRVShaderResources.cpp index 8c8f673f..50bebf47 100644 --- a/Graphics/GLSLTools/src/SPIRVShaderResources.cpp +++ b/Graphics/GLSLTools/src/SPIRVShaderResources.cpp @@ -191,6 +191,8 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, ResourceNamesPoolSize += strlen(CombinedSamplerSuffix) + 1; } + ResourceNamesPoolSize += strlen(shaderDesc.Name) + 1; + Uint32 NumShaderStageInputs = 0; if (resources.stage_inputs.empty()) @@ -374,6 +376,8 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, m_CombinedSamplerSuffix = m_ResourceNames.CopyString(CombinedSamplerSuffix); } + m_ShaderName = m_ResourceNames.CopyString(shaderDesc.Name); + if (LoadShaderStageInputs) { Uint32 CurrStageInput = 0; diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h index f49bc342..b4712d70 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h @@ -107,12 +107,15 @@ namespace Diligent { /// Diligent::ShaderResourceLayoutVk class -// sizeof(ShaderResourceLayoutVk)==64 (MS compiler, x64) - TODO: verify +// sizeof(ShaderResourceLayoutVk)==56 (MS compiler, x64) - TODO: verify class ShaderResourceLayoutVk { public: - ShaderResourceLayoutVk(IObject& Owner, - const VulkanUtilities::VulkanLogicalDevice& LogicalDevice); + ShaderResourceLayoutVk(const VulkanUtilities::VulkanLogicalDevice& LogicalDevice) : + m_LogicalDevice(LogicalDevice) + { + } + ShaderResourceLayoutVk (const ShaderResourceLayoutVk&) = delete; ShaderResourceLayoutVk (ShaderResourceLayoutVk&&) = delete; @@ -271,7 +274,10 @@ public: void CommitDynamicResources(const ShaderResourceCacheVk& ResourceCache, VkDescriptorSet vkDynamicDescriptorSet)const; - const Char* GetShaderName()const; + const Char* GetShaderName()const + { + return m_pResources->GetShaderName(); + } const VkResource& GetResource(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 r)const { @@ -329,7 +335,6 @@ private: return reinterpret_cast(ResourceMemoryEnd)[n]; } - IObject& m_Owner; const VulkanUtilities::VulkanLogicalDevice& m_LogicalDevice; std::unique_ptr > m_ResourceBuffer; diff --git a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp index 2a60ce96..14f4c962 100644 --- a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp @@ -163,7 +163,7 @@ PipelineStateVkImpl :: PipelineStateVkImpl(IReferenceCounters* pRefCounters m_StaticVarsMgrs = reinterpret_cast(pStaticVarMgrRawMem); for (Uint32 s=0; s < m_NumShaders; ++s) { - new (m_ShaderResourceLayouts + s) ShaderResourceLayoutVk(*this, LogicalDevice); + new (m_ShaderResourceLayouts + s) ShaderResourceLayoutVk(LogicalDevice); auto* pShaderVk = GetShader(s); ShaderResources[s] = pShaderVk->GetShaderResources(); ShaderSPIRVs[s] = pShaderVk->GetSPIRV(); @@ -172,7 +172,7 @@ PipelineStateVkImpl :: PipelineStateVkImpl(IReferenceCounters* pRefCounters const auto ShaderTypeInd = GetShaderTypeIndex(ShaderType); m_ResourceLayoutIndex[ShaderTypeInd] = static_cast(s); - auto* pStaticResLayout = new (m_ShaderResourceLayouts + m_NumShaders + s) ShaderResourceLayoutVk(*this, LogicalDevice); + auto* pStaticResLayout = new (m_ShaderResourceLayouts + m_NumShaders + s) ShaderResourceLayoutVk(LogicalDevice); auto* pStaticResCache = new (m_StaticResCaches + s) ShaderResourceCacheVk(ShaderResourceCacheVk::DbgCacheContentType::StaticShaderResources); pStaticResLayout->InitializeStaticResourceLayout(ShaderResources[s], ShaderResLayoutAllocator, PipelineDesc.Layout, m_StaticResCaches[s]); diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp index 546fd01e..a0835334 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp @@ -90,13 +90,6 @@ static SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE } -ShaderResourceLayoutVk::ShaderResourceLayoutVk(IObject& Owner, - const VulkanUtilities::VulkanLogicalDevice& LogicalDevice) : - m_Owner(Owner), - m_LogicalDevice(LogicalDevice) -{ -} - ShaderResourceLayoutVk::~ShaderResourceLayoutVk() { auto* Resources = reinterpret_cast(m_ResourceBuffer.get()); @@ -521,14 +514,16 @@ bool ShaderResourceLayoutVk::VkResource::UpdateCachedResource(ShaderResourceCach // We cannot use ValidatedCast<> here as the resource retrieved from the // resource mapping can be of wrong type RefCntAutoPtr pResource(pObject, InterfaceId); - if(pResource) + if (pResource) { if (GetVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC && DstRes.pObject != nullptr) { if (DstRes.pObject != pResource) { auto VarTypeStr = GetShaderVariableTypeLiteralName(GetVariableType()); - LOG_ERROR_MESSAGE("Non-null resource is already bound to ", VarTypeStr, " shader variable '", SpirvAttribs.GetPrintName(ArrayInd), "' in shader '", ParentResLayout.GetShaderName(), "'. Attempring to bind another resource is an error and will be ignored. Use another shader resource binding instance or label the variable as dynamic."); + LOG_ERROR_MESSAGE("Non-null resource is already bound to ", VarTypeStr, " shader variable '", SpirvAttribs.GetPrintName(ArrayInd), + "' in shader '", ParentResLayout.GetShaderName(), "'. Attempring to bind another resource is an error and will 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 @@ -932,30 +927,6 @@ bool ShaderResourceLayoutVk::dvpVerifyBindings(const ShaderResourceCacheVk& Reso } #endif - -const Char* ShaderResourceLayoutVk::GetShaderName()const -{ - RefCntAutoPtr pPSO(&m_Owner, IID_PipelineState); - if (pPSO) - { - auto* pPSOVk = pPSO.RawPtr(); - auto* ppShaders = pPSOVk->GetShaders(); - auto NumShaders = pPSOVk->GetNumShaders(); - for (Uint32 s = 0; s < NumShaders; ++s) - { - const auto& ShaderDesc = ppShaders[s]->GetDesc(); - if (ShaderDesc.ShaderType == m_pResources->GetShaderType()) - return ShaderDesc.Name; - } - UNEXPECTED("Shader not found"); - } - else - { - UNEXPECTED("Shader resource layout owner must be a shader or a pipeline state"); - } - return ""; -} - void ShaderResourceLayoutVk::InitializeResourceMemoryInCache(ShaderResourceCacheVk& ResourceCache)const { auto TotalResources = GetTotalResourceCount(); -- cgit v1.2.3 From 1e138ea5cd724747ff21a852cc25550e436da633 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Wed, 27 Feb 2019 23:48:25 -0800 Subject: Finished refactoring pipeline layout definition in Vk backend --- .../GraphicsEngine/include/PipelineStateBase.h | 76 ++++++- Graphics/GraphicsEngine/interface/PipelineState.h | 117 ++++++++++- Graphics/GraphicsEngine/interface/Shader.h | 221 ++++----------------- .../interface/ShaderResourceBinding.h | 25 +-- .../interface/ShaderResourceVariable.h | 134 +++++++++++++ 5 files changed, 367 insertions(+), 206 deletions(-) create mode 100644 Graphics/GraphicsEngine/interface/ShaderResourceVariable.h (limited to 'Graphics') diff --git a/Graphics/GraphicsEngine/include/PipelineStateBase.h b/Graphics/GraphicsEngine/include/PipelineStateBase.h index 2683d63c..3dde7b85 100644 --- a/Graphics/GraphicsEngine/include/PipelineStateBase.h +++ b/Graphics/GraphicsEngine/include/PipelineStateBase.h @@ -34,6 +34,7 @@ #include "STDAllocator.h" #include "EngineMemory.h" #include "GraphicsAccessories.h" +#include "StringPool.h" namespace Diligent { @@ -65,6 +66,62 @@ public: m_LayoutElements (PSODesc.GraphicsPipeline.InputLayout.NumElements, LayoutElement{}, STD_ALLOCATOR_RAW_MEM(LayoutElement, GetRawAllocator(), "Allocator for vector")), m_NumShaders(0) { + const auto& SrcLayout = PSODesc.Layout; + size_t StringPoolSize = 0; + if (SrcLayout.Variables != nullptr) + { + for (Uint32 i=0; i < SrcLayout.NumVariables; ++i) + StringPoolSize += strlen(SrcLayout.Variables[i].Name) + 1; + } + + if (SrcLayout.StaticSamplers != nullptr) + { + for (Uint32 i=0; i < SrcLayout.NumStaticSamplers; ++i) + StringPoolSize += strlen(SrcLayout.StaticSamplers[i].SamplerOrTextureName) + 1; + } + m_StringPool.Allocate(StringPoolSize); + + auto& DstLayout = this->m_Desc.Layout; + if (SrcLayout.Variables != nullptr) + { + ShaderResourceVariableDesc* Variables = + reinterpret_cast(ALLOCATE(GetRawAllocator(), "Memory for ShaderResourceVariableDesc array", sizeof(ShaderResourceVariableDesc) * SrcLayout.NumVariables)); + DstLayout.Variables = Variables; + for (Uint32 i=0; i < SrcLayout.NumVariables; ++i) + { + VERIFY(SrcLayout.Variables[i].Name != nullptr, "Variable name can't be null"); + Variables[i] = SrcLayout.Variables[i]; + Variables[i].Name = m_StringPool.CopyString(SrcLayout.Variables[i].Name); + } + } + + if (SrcLayout.StaticSamplers != nullptr) + { + StaticSamplerDesc* StaticSamplers = + reinterpret_cast(ALLOCATE(GetRawAllocator(), "Memory for StaticSamplerDesc array", sizeof(StaticSamplerDesc) * SrcLayout.NumStaticSamplers)); + DstLayout.StaticSamplers = StaticSamplers; + for (Uint32 i=0; i < SrcLayout.NumStaticSamplers; ++i) + { + VERIFY(SrcLayout.StaticSamplers[i].SamplerOrTextureName != nullptr, "Static sampler or texture name can't be null"); +#ifdef DEVELOPMENT + const auto &BorderColor = SrcLayout.StaticSamplers[i].Desc.BorderColor; + if( !( (BorderColor[0] == 0 && BorderColor[1] == 0 && BorderColor[2] == 0 && BorderColor[3] == 0) || + (BorderColor[0] == 0 && BorderColor[1] == 0 && BorderColor[2] == 0 && BorderColor[3] == 1) || + (BorderColor[0] == 1 && BorderColor[1] == 1 && BorderColor[2] == 1 && BorderColor[3] == 1) ) ) + { + LOG_WARNING_MESSAGE("Static sampler for variable \"", SrcLayout.StaticSamplers[i].SamplerOrTextureName, "\" specifies border color (", + BorderColor[0], ", ", BorderColor[1], ", ", BorderColor[2], ", ", BorderColor[3], "). " + "D3D12 static samplers only allow transparent black (0,0,0,0), opaque black (0,0,0,1) or opaque white (1,1,1,1) as border colors"); + } +#endif + + StaticSamplers[i] = SrcLayout.StaticSamplers[i]; + StaticSamplers[i].SamplerOrTextureName = m_StringPool.CopyString(SrcLayout.StaticSamplers[i].SamplerOrTextureName); + } + } + VERIFY_EXPR(m_StringPool.GetRemainingSize() == 0); + + if (this->m_Desc.IsComputePipeline) { const auto &ComputePipeline = PSODesc.ComputePipeline; @@ -206,6 +263,12 @@ public: RasterizerStateRegistry.ReportDeletedObject(); DSSRegistry.ReportDeletedObject(); */ + + auto& RawAllocator = GetRawAllocator(); + if (this->m_Desc.Layout.Variables != nullptr) + RawAllocator.Free(const_cast(this->m_Desc.Layout.Variables)); + if (this->m_Desc.Layout.StaticSamplers != nullptr) + RawAllocator.Free(const_cast(this->m_Desc.Layout.StaticSamplers)); } IMPLEMENT_QUERY_INTERFACE_IN_PLACE( IID_PipelineState, TDeviceObjectBase ) @@ -250,21 +313,19 @@ public: return m_ShaderResourceLayoutHash != ValidatedCast(pPSO)->m_ShaderResourceLayoutHash; } - virtual void BindShaderResources( IResourceMapping* pResourceMapping, Uint32 Flags )override - { - for(Uint32 s=0; s < m_NumShaders; ++s) - m_ppShaders[s]->BindResources(pResourceMapping, Flags); - } - protected: + // TODO: rework this std::vector > m_LayoutElements; Uint32 m_BufferSlotsUsed = 0; + Uint32 m_NumShaders = 0; ///< Number of shaders that this PSO uses + // The size of this array must be equal to the // maximum number of buffer slots, because a layout // element can refer to any input slot - std::array m_Strides = {}; + std::array m_Strides = {}; // TODO: rework this + StringPool m_StringPool; RefCntAutoPtr m_pVS; ///< Strong reference to the vertex shader RefCntAutoPtr m_pPS; ///< Strong reference to the pixel shader RefCntAutoPtr m_pGS; ///< Strong reference to the geometry shader @@ -272,7 +333,6 @@ protected: RefCntAutoPtr m_pHS; ///< Strong reference to the hull shader RefCntAutoPtr m_pCS; ///< Strong reference to the compute shader IShader* m_ppShaders[5] = {}; ///< Array of pointers to the shaders used by this PSO - Uint32 m_NumShaders = 0; ///< Number of shaders that this PSO uses size_t m_ShaderResourceLayoutHash = 0;///< Hash computed from the shader resource layout }; diff --git a/Graphics/GraphicsEngine/interface/PipelineState.h b/Graphics/GraphicsEngine/interface/PipelineState.h index 4bbbbe9e..39064c75 100644 --- a/Graphics/GraphicsEngine/interface/PipelineState.h +++ b/Graphics/GraphicsEngine/interface/PipelineState.h @@ -34,6 +34,8 @@ #include "DepthStencilState.h" #include "InputLayout.h" #include "ShaderResourceBinding.h" +#include "ShaderResourceVariable.h" +#include "Shader.h" namespace Diligent { @@ -51,14 +53,82 @@ struct SampleDesc SampleDesc()noexcept{} - SampleDesc(Uint8 _Count, - Uint8 _Quality) : + SampleDesc(Uint8 _Count, Uint8 _Quality) noexcept : Count (_Count), Quality (_Quality) {} }; +/// Describes shader variable +struct ShaderResourceVariableDesc +{ + /// Shader stages this resources variable applies to. More than one shader stage can be specified. + SHADER_TYPE ShaderStages = SHADER_TYPE_UNKNOWN; + + /// Shader variable name + const Char* Name = nullptr; + + /// Shader variable type. See Diligent::SHADER_RESOURCE_VARIABLE_TYPE for a list of allowed types + SHADER_RESOURCE_VARIABLE_TYPE Type = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; + + ShaderResourceVariableDesc()noexcept{} + + ShaderResourceVariableDesc(SHADER_TYPE _ShaderStages, const Char* _Name, SHADER_RESOURCE_VARIABLE_TYPE _Type)noexcept : + ShaderStages(_ShaderStages), + Name (_Name), + Type (_Type) + {} +}; + + +/// Static sampler description +struct StaticSamplerDesc +{ + /// Shader stages that this static sampler applies to. More than one shader stage can be specified. + SHADER_TYPE ShaderStages = SHADER_TYPE_UNKNOWN; + + /// The name of the sampler itself or the name of the texture variable that + /// this static sampler is assigned to if combined texture samplers are used. + const Char* SamplerOrTextureName = nullptr; + + /// Sampler description + SamplerDesc Desc; + + StaticSamplerDesc()noexcept{} + + StaticSamplerDesc(SHADER_TYPE _ShaderStages, + const Char* _SamplerOrTextureName, + const SamplerDesc& _Desc)noexcept : + ShaderStages (_ShaderStages), + SamplerOrTextureName(_SamplerOrTextureName), + Desc (_Desc) + {} +}; + + +/// Pipeline layout description +struct PipelineLayoutDesc +{ + /// Default shader resource variable type. This type will be used if shader + /// variable description is not found in the Variables array + /// or if Variables == nullptr + SHADER_RESOURCE_VARIABLE_TYPE DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; + + /// Number of elements in Variables array + Uint32 NumVariables = 0; + + /// Array of shader resource variable descriptions + const ShaderResourceVariableDesc* Variables = nullptr; + + /// Number of static samplers in StaticSamplers array + Uint32 NumStaticSamplers = 0; + + /// Array of static sampler descriptions + const StaticSamplerDesc* StaticSamplers = nullptr; +}; + + /// Graphics pipeline state description /// This structure describes the graphics pipeline state and is part of the PipelineStateDesc structure. @@ -150,6 +220,9 @@ struct PipelineStateDesc : DeviceObjectAttribs /// Defines which command queues this pipeline state can be used with Uint64 CommandQueueMask = 1; + /// Pipeline layout description + PipelineLayoutDesc Layout; + /// Graphics pipeline state description. This memeber is ignored if IsComputePipeline == True GraphicsPipelineDesc GraphicsPipeline; @@ -170,14 +243,49 @@ public: /// Queries the specific interface, see IObject::QueryInterface() for details virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface ) = 0; + /// Returns the blend state description used to create the object virtual const PipelineStateDesc& GetDesc()const = 0; + /// Binds resources for all shaders in the pipeline state /// \param [in] pResourceMapping - Pointer to the resource mapping interface. /// \param [in] Flags - Additional flags. See Diligent::BIND_SHADER_RESOURCES_FLAGS. - virtual void BindShaderResources( IResourceMapping* pResourceMapping, Uint32 Flags ) = 0; + virtual void BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags) = 0; + + + /// Returns the number of static shader resource variables. + + /// \param [in] ShaderType - Type of the shader. + /// \remark Only static variables (that can be accessed directly through the PSO) are counted. + /// Mutable and dynamic variables are accessed through Shader Resource Binding object. + virtual Uint32 GetStaticVariableCount(SHADER_TYPE ShaderType) const = 0; + + + /// Returns static shader resource variable. If the variable is not found, + /// returns nullptr. + + /// \param [in] ShaderType - Type of the shader to look up the variable. + /// Must be one of Diligent::SHADER_TYPE. + /// \param [in] Name - Name of the variable. + /// \remark The method does not increment the reference counter + /// of the returned interface. + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) = 0; + + + /// Returns static shader resource variable by its index. + + /// \param [in] ShaderType - Type of the shader to look up the variable. + /// Must be one of Diligent::SHADER_TYPE. + /// \param [in] Index - Shader variable index. The index must be between + /// 0 and the total number of variables returned by + /// GetStaticVariableCount(). + /// \remark Only static shader resource variables can be accessed through this method. + /// Mutable and dynamic variables are accessed through Shader Resource + /// Binding object + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) = 0; + /// Creates a shader resource binding object @@ -186,7 +294,8 @@ public: /// \param [in] InitStaticResources - if set to true, the method will initialize static resources in /// the created object, which has the exact same effect as calling /// IShaderResourceBinding::InitializeStaticResources(). - virtual void CreateShaderResourceBinding( IShaderResourceBinding** ppShaderResourceBinding, bool InitStaticResources = false ) = 0; + virtual void CreateShaderResourceBinding(IShaderResourceBinding** ppShaderResourceBinding, bool InitStaticResources = false) = 0; + /// Checks if this pipeline state object is compatible with another PSO diff --git a/Graphics/GraphicsEngine/interface/Shader.h b/Graphics/GraphicsEngine/interface/Shader.h index d9e90d87..43d6021a 100644 --- a/Graphics/GraphicsEngine/interface/Shader.h +++ b/Graphics/GraphicsEngine/interface/Shader.h @@ -28,8 +28,6 @@ #include "../../../Primitives/interface/FileStream.h" #include "DeviceObject.h" -#include "ResourceMapping.h" -#include "Sampler.h" namespace Diligent { @@ -38,10 +36,6 @@ namespace Diligent static constexpr INTERFACE_ID IID_Shader = { 0x2989b45c, 0x143d, 0x4886, { 0xb8, 0x9c, 0xc3, 0x27, 0x1c, 0x2d, 0xcc, 0x5d } }; -// {0D57DF3F-977D-4C8F-B64C-6675814BC80C} -static constexpr INTERFACE_ID IID_ShaderVariable = -{ 0xd57df3f, 0x977d, 0x4c8f, { 0xb6, 0x4c, 0x66, 0x75, 0x81, 0x4b, 0xc8, 0xc } }; - /// Describes the shader type enum SHADER_TYPE : Uint32 { @@ -76,128 +70,16 @@ enum SHADER_SOURCE_LANGUAGE : Uint32 SHADER_SOURCE_LANGUAGE_GLSL }; -/// Describes shader variable type that is used by ShaderVariableDesc -enum SHADER_VARIABLE_TYPE : Uint8 -{ - /// Shader variable is constant across all shader instances. - /// It must be set *once* directly through IShader::BindResources() or through - /// the shader variable. - SHADER_VARIABLE_TYPE_STATIC = 0, - - /// Shader variable is constant across shader resource bindings instance (see IShaderResourceBinding). - /// It must be set *once* through IShaderResourceBinding::BindResources() or through - /// the shader variable. It cannot be set through IShader interface - SHADER_VARIABLE_TYPE_MUTABLE, - - /// Shader variable is dynamic. It can be set multiple times for every instance of shader resource - /// bindings (see IShaderResourceBinding). It cannot be set through IShader interface - SHADER_VARIABLE_TYPE_DYNAMIC, - - /// Total number of shader variable types - SHADER_VARIABLE_TYPE_NUM_TYPES -}; - - -static_assert(SHADER_VARIABLE_TYPE_STATIC == 0 && SHADER_VARIABLE_TYPE_MUTABLE == 1 && SHADER_VARIABLE_TYPE_DYNAMIC == 2 && SHADER_VARIABLE_TYPE_NUM_TYPES == 3, "BIND_SHADER_RESOURCES_UPDATE_* flags rely on shader variable SHADER_VARIABLE_TYPE_* values being 0,1,2"); -/// Describes flags that can be given to IShader::BindResources(), -/// IPipelineState::BindShaderResources(), and IDeviceContext::BindShaderResources() methods. -enum BIND_SHADER_RESOURCES_FLAGS : Uint32 -{ - /// Indicates that static variable bindings are to be updated. - BIND_SHADER_RESOURCES_UPDATE_STATIC = (0x01 << SHADER_VARIABLE_TYPE_STATIC), - - /// Indicates that mutable variable bindings are to be updated. - BIND_SHADER_RESOURCES_UPDATE_MUTABLE = (0x01 << SHADER_VARIABLE_TYPE_MUTABLE), - - /// Indicates that dynamic variable bindings are to be updated. - BIND_SHADER_RESOURCES_UPDATE_DYNAMIC = (0x01 << SHADER_VARIABLE_TYPE_DYNAMIC), - - /// Indicates that all variable types (static, mutable and dynamic) are to be updated. - /// \note If none of BIND_SHADER_RESOURCES_UPDATE_STATIC, BIND_SHADER_RESOURCES_UPDATE_MUTABLE, - /// and BIND_SHADER_RESOURCES_UPDATE_DYNAMIC flags are set, all variable types are updated - /// as if BIND_SHADER_RESOURCES_UPDATE_ALL was specified. - BIND_SHADER_RESOURCES_UPDATE_ALL = (BIND_SHADER_RESOURCES_UPDATE_STATIC | BIND_SHADER_RESOURCES_UPDATE_MUTABLE | BIND_SHADER_RESOURCES_UPDATE_DYNAMIC), - - /// If this flag is specified, all existing bindings will be preserved and - /// only unresolved ones will be updated. - /// If this flag is not specified, every shader variable will be - /// updated if the mapping contains corresponding resource. - BIND_SHADER_RESOURCES_KEEP_EXISTING = 0x08, - - /// If this flag is specified, all shader bindings are expected - /// to be resolved after the call. If this is not the case, debug message - /// will be displayed. - /// \note Only these variables are verified that are being updated by setting - /// BIND_SHADER_RESOURCES_UPDATE_STATIC, BIND_SHADER_RESOURCES_UPDATE_MUTABLE, and - /// BIND_SHADER_RESOURCES_UPDATE_DYNAMIC flags. - BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED = 0x10 -}; - -/// Describes shader variable -struct ShaderVariableDesc -{ - /// Shader variable name - const Char* Name = nullptr; - - /// Shader variable type. See Diligent::SHADER_VARIABLE_TYPE for a list of allowed types - SHADER_VARIABLE_TYPE Type = SHADER_VARIABLE_TYPE_STATIC; - - ShaderVariableDesc()noexcept{} - - ShaderVariableDesc(const Char* _Name, - SHADER_VARIABLE_TYPE _Type) : - Name(_Name), - Type(_Type) - {} -}; - - -/// Static sampler description -struct StaticSamplerDesc -{ - /// The name of the sampler itself or the name of the texture variable that - /// this static sampler is assigned to if combined texture samplers are used. - const Char* SamplerOrTextureName = nullptr; - - /// Sampler description - SamplerDesc Desc; - - StaticSamplerDesc()noexcept{} - StaticSamplerDesc(const Char* _SamplerOrTextureName, - const SamplerDesc& _Desc)noexcept : - SamplerOrTextureName(_SamplerOrTextureName), - Desc (_Desc) - {} -}; - /// Shader description struct ShaderDesc : DeviceObjectAttribs { - /// Shader type. See Diligent::SHADER_TYPE - SHADER_TYPE ShaderType = SHADER_TYPE_VERTEX; - - Bool bCacheCompiledShader = False; - - SHADER_PROFILE TargetProfile = SHADER_PROFILE_DEFAULT; + /// Shader type. See Diligent::SHADER_TYPE. + SHADER_TYPE ShaderType = SHADER_TYPE_VERTEX; - /// Default shader variable type. This type will be used if shader - /// variable description is not found in array VariableDesc points to - /// or if VariableDesc == nullptr - SHADER_VARIABLE_TYPE DefaultVariableType = SHADER_VARIABLE_TYPE_STATIC; - - /// Array of shader variable descriptions - const ShaderVariableDesc* VariableDesc = nullptr; - - /// Number of elements in VariableDesc array - Uint32 NumVariables = 0; - - /// Number of static samplers in StaticSamplers array - Uint32 NumStaticSamplers = 0; - - /// Array of static sampler descriptions - const StaticSamplerDesc* StaticSamplers = nullptr; + SHADER_PROFILE TargetProfile = SHADER_PROFILE_DEFAULT; }; + /// Shader source stream factory interface class IShaderSourceInputStreamFactory { @@ -219,7 +101,7 @@ struct ShaderMacro }; /// Shader creation attributes -struct ShaderCreationAttribs +struct ShaderCreateInfo { /// Source file path @@ -258,7 +140,7 @@ struct ShaderCreationAttribs /// backend expects SPIRV bytecode. /// The bytecode must contain reflection information. If shaders were compiled /// using fxc, make sure that /Qstrip_reflect option is *not* specified. - /// Also, shaders need to be compiled against 4.0 profile or higher. + /// HLSL shaders need to be compiled against 4.0 profile or higher. const void* ByteCode = nullptr; /// Size of the compiled shader bytecode @@ -305,41 +187,42 @@ struct ShaderCreationAttribs IDataBlob** ppCompilerOutput = nullptr; }; - -/// Shader resource variable -class IShaderVariable : public IObject +/// Describes shader resource type +enum SHADER_RESOURCE_TYPE { -public: - /// Sets the variable to the given value + /// Shader resource type is unknown + SHADER_RESOURCE_TYPE_UNKNOWN = 0, + + /// Constant (uniform) buffer + SHADER_RESOURCE_TYPE_CONSTANT_BUFFER, - /// \remark The method performs run-time correctness checks. - /// For instance, shader resource view cannot - /// be assigned to a constant buffer variable. - virtual void Set(IDeviceObject* pObject) = 0; + /// Shader resource view of a texture (sampled image) + SHADER_RESOURCE_TYPE_TEXTURE_SRV, - /// Sets the variable array + /// Shader resource view of a buffer (read-only storage image) + SHADER_RESOURCE_TYPE_BUFFER_SRV, - /// \param [in] ppObjects - pointer to the array of objects - /// \param [in] FirstElement - first array element to set - /// \param [in] NumElements - number of objects in ppObjects array - /// - /// \remark The method performs run-time correctness checks. - /// For instance, shader resource view cannot - /// be assigned to a constant buffer variable. - virtual void SetArray(IDeviceObject* const* ppObjects, Uint32 FirstElement, Uint32 NumElements) = 0; + /// Unordered access view of a texture (sotrage image) + SHADER_RESOURCE_TYPE_TEXTURE_UAV, - /// Returns shader variable type - virtual SHADER_VARIABLE_TYPE GetType()const = 0; + /// Unordered access view of a buffer (storage buffer) + SHADER_RESOURCE_TYPE_BUFFER_UAV, - /// Returns array size. For non-array variables returns one. - virtual Uint32 GetArraySize()const = 0; + /// Sampler (separate sampler) + SHADER_RESOURCE_TYPE_SAMPLER +}; + +/// Shader resource description +struct ShaderResourceDesc +{ + /// Shader resource name + const char* Name = nullptr; - /// Returns the variable name - virtual const Char* GetName()const = 0; + /// Shader resource type, see Diligent::SHADER_RESOURCE_TYPE. + SHADER_RESOURCE_TYPE Type = SHADER_RESOURCE_TYPE_UNKNOWN; - /// Returns variable index that can be used to access the variable through - /// shader or shader resource binding object - virtual Uint32 GetIndex()const = 0; + /// Array size. For non-array resource this value is 1. + Uint32 ArraySize = 0; }; /// Shader interface @@ -347,42 +230,16 @@ class IShader : public IDeviceObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; /// Returns the shader description virtual const ShaderDesc& GetDesc()const = 0; - /// Binds shader resources. - /// \param [in] pResourceMapping - Pointer to IResourceMapping interface to - /// look for resources. - /// \param [in] Flags - Additional flags for the operation. See - /// Diligent::BIND_SHADER_RESOURCES_FLAGS for details. - /// \remark The shader will keep strong references to all resources bound to it. - virtual void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags ) = 0; + /// Returns the total number of shader resources + virtual Uint32 GetResourceCount()const = 0; - /// Returns an interface to a shader variable. If the shader variable - /// is not found, an interface to a dummy variable will be returned. - - /// \param [in] Name - Name of the variable. - /// \remark The method does not increment the reference counter - /// of the returned interface. - virtual IShaderVariable* GetShaderVariable(const Char* Name) = 0; - - /// Returns the number of shader variables. - - /// \remark Only static variables (that can be accessed directly through the shader) are counted. - /// Mutable and dynamic variables are accessed through Shader Resource Binding object. - virtual Uint32 GetVariableCount() const = 0; - - /// Returns shader variable by its index. - - /// \param [in] Index - Shader variable index. The index must be between - /// 0 and the total number of variables returned by - /// GetVariableCount(). - /// \remark Only static shader variables can be accessed through this method. - /// Mutable and dynamic variables are accessed through Shader Resource - /// Binding object - virtual IShaderVariable* GetShaderVariable(Uint32 Index) = 0; + /// Returns the pointer to the array of shader resources + virtual const ShaderResourceDesc* GetResources()const = 0; }; } diff --git a/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h b/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h index 8671c3f7..970f1ff1 100644 --- a/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h +++ b/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h @@ -27,7 +27,7 @@ /// Definition of the Diligent::IShaderResourceBinding interface and related data structures #include "../../../Primitives/interface/Object.h" -#include "Shader.h" +#include "ShaderResourceVariable.h" namespace Diligent { @@ -44,7 +44,7 @@ class IShaderResourceBinding : public IObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface ) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; /// Returns pointer to the referenced buffer object. @@ -52,20 +52,20 @@ public: /// so Release() must be called to avoid memory leaks. virtual IPipelineState* GetPipelineState() = 0; - /// Binds all resource using the resource mapping + /// Binds mutable and dynamice resources using the resource mapping /// \param [in] ShaderFlags - Flags for the shader stages, for which resources will be bound. /// Any combination of Diligent::SHADER_TYPE may be specified. /// \param [in] pResMapping - Shader resource mapping, where required resources will be looked up - /// \param [in] Flags - Additional flags. See Diligent::BIND_SHADER_RESOURCES_FLAGS. + /// \param [in] Flags - Additional flags. See Diligent::BIND_SHADER_RESOURCES_FLAGS. virtual void BindResources(Uint32 ShaderFlags, IResourceMapping* pResMapping, Uint32 Flags) = 0; /// Returns variable /// \param [in] ShaderType - Type of the shader to look up the variable. /// Must be one of Diligent::SHADER_TYPE. - /// \param Name - Variable name - virtual IShaderVariable* GetVariable(SHADER_TYPE ShaderType, const char *Name) = 0; + /// \param [in] Name - Variable name + virtual IShaderResourceVariable* GetVariable(SHADER_TYPE ShaderType, const char* Name) = 0; /// Returns the total variable count for the specific shader stage. @@ -79,20 +79,21 @@ public: /// \param [in] ShaderType - Type of the shader to look up the variable. /// Must be one of Diligent::SHADER_TYPE. - /// \param Index - Variable index. The index must be between 0 and the total number - /// of variables in this shader stage as returned by GetVariableCount(). + /// \param [in] Index - Variable index. The index must be between 0 and the total number + /// of variables in this shader stage as returned by + /// IShaderResourceBinding::GetVariableCount(). /// \remark Only mutable and dynamic variables can be accessed through this method. /// Static variables are accessed through the Shader object. - virtual IShaderVariable* GetVariable(SHADER_TYPE ShaderType, Uint32 Index) = 0; + virtual IShaderResourceVariable* GetVariable(SHADER_TYPE ShaderType, Uint32 Index) = 0; /// Initializes static resources - /// If shaders in the pipeline state contain static resources - /// (see Diligent::SHADER_VARIABLE_TYPE_STATIC), this method must be called + /// If the parent pipeline state object contain static resources + /// (see Diligent::SHADER_RESOURCE_VARIABLE_TYPE_STATIC), this method must be called /// once to initialize static resources in this shader resource binding object. /// The method must be called after all static variables are initialized - /// in the shaders. + /// in the PSO. /// \param [in] pPipelineState - Pipeline state to copy static shader resource /// bindings from. The pipeline state must be compatible /// with this shader resource binding object. diff --git a/Graphics/GraphicsEngine/interface/ShaderResourceVariable.h b/Graphics/GraphicsEngine/interface/ShaderResourceVariable.h new file mode 100644 index 00000000..95b6eae5 --- /dev/null +++ b/Graphics/GraphicsEngine/interface/ShaderResourceVariable.h @@ -0,0 +1,134 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +/// \file +/// Definition of the Diligent::IShaderResourceVariable interface and related data structures + +#include "../../../Primitives/interface/BasicTypes.h" +#include "../../../Primitives/interface/Object.h" +#include "DeviceObject.h" + +namespace Diligent +{ + +// {0D57DF3F-977D-4C8F-B64C-6675814BC80C} +static constexpr INTERFACE_ID IID_ShaderResourceVariable = +{ 0xd57df3f, 0x977d, 0x4c8f, { 0xb6, 0x4c, 0x66, 0x75, 0x81, 0x4b, 0xc8, 0xc } }; + + +/// Describes the type of the shader resource variable +enum SHADER_RESOURCE_VARIABLE_TYPE : Uint8 +{ + /// Shader resource bound to the variable is the same for all SRB instances. + /// It must be set *once* directly through Pipeline State object. + SHADER_RESOURCE_VARIABLE_TYPE_STATIC = 0, + + /// Shader resource bound to the variable is specific to the shader resource binding + /// instance (see Diligent::IShaderResourceBinding). It must be set *once* through + /// Diligent::IShaderResourceBinding interface. It cannot be set through Diligent::IPipelineState + /// interface and cannot be change once bound. + SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, + + /// Shader variable binding is dynamic. It can be set multiple times for every instance of shader resource + /// binding (see Diligent::IShaderResourceBinding). It cannot be set through Diligent::IPipelineState interface. + SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC, + + /// Total number of shader variable types + SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES +}; + + +static_assert(SHADER_RESOURCE_VARIABLE_TYPE_STATIC == 0 && SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE == 1 && SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC == 2 && SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES == 3, "BIND_SHADER_RESOURCES_UPDATE_* flags rely on shader variable SHADER_RESOURCE_VARIABLE_TYPE_* values being 0,1,2"); + +/// Shader resource binding flags +enum BIND_SHADER_RESOURCES_FLAGS : Uint32 +{ + /// Indicates that static shader variable bindings are to be updated. + BIND_SHADER_RESOURCES_UPDATE_STATIC = (0x01 << SHADER_RESOURCE_VARIABLE_TYPE_STATIC), + + /// Indicates that mutable shader variable bindings are to be updated. + BIND_SHADER_RESOURCES_UPDATE_MUTABLE = (0x01 << SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE), + + /// Indicates that dynamic shader variable bindings are to be updated. + BIND_SHADER_RESOURCES_UPDATE_DYNAMIC = (0x01 << SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC), + + /// Indicates that all shader variable types (static, mutable and dynamic) are to be updated. + /// \note If none of BIND_SHADER_RESOURCES_UPDATE_STATIC, BIND_SHADER_RESOURCES_UPDATE_MUTABLE, + /// and BIND_SHADER_RESOURCES_UPDATE_DYNAMIC flags are set, all variable types are updated + /// as if BIND_SHADER_RESOURCES_UPDATE_ALL was specified. + BIND_SHADER_RESOURCES_UPDATE_ALL = (BIND_SHADER_RESOURCES_UPDATE_STATIC | BIND_SHADER_RESOURCES_UPDATE_MUTABLE | BIND_SHADER_RESOURCES_UPDATE_DYNAMIC), + + /// If this flag is specified, all existing bindings will be preserved and + /// only unresolved ones will be updated. + /// If this flag is not specified, every shader variable will be + /// updated if the mapping contains corresponding resource. + BIND_SHADER_RESOURCES_KEEP_EXISTING = 0x08, + + /// If this flag is specified, all shader bindings are expected + /// to be resolved after the call. If this is not the case, debug message + /// will be displayed. + /// \note Only these variables are verified that are being updated by setting + /// BIND_SHADER_RESOURCES_UPDATE_STATIC, BIND_SHADER_RESOURCES_UPDATE_MUTABLE, and + /// BIND_SHADER_RESOURCES_UPDATE_DYNAMIC flags. + BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED = 0x10 +}; + + +/// Shader resource variable +class IShaderResourceVariable : public IObject +{ +public: + /// Binds resource to the variable + + /// \remark The method performs run-time correctness checks. + /// For instance, shader resource view cannot + /// be assigned to a constant buffer variable. + virtual void Set(IDeviceObject* pObject) = 0; + + /// Binds resource array to the variable + + /// \param [in] ppObjects - pointer to the array of objects + /// \param [in] FirstElement - first array element to set + /// \param [in] NumElements - number of objects in ppObjects array + /// + /// \remark The method performs run-time correctness checks. + /// For instance, shader resource view cannot + /// be assigned to a constant buffer variable. + virtual void SetArray(IDeviceObject* const* ppObjects, Uint32 FirstElement, Uint32 NumElements) = 0; + + /// Returns the shader resource variable type + virtual SHADER_RESOURCE_VARIABLE_TYPE GetType()const = 0; + + /// Returns array size. For non-array variables returns one. + virtual Uint32 GetArraySize()const = 0; + + /// Returns the variable name + virtual const Char* GetName()const = 0; + + /// Returns the variable index that can be used to access the variable. + virtual Uint32 GetIndex()const = 0; +}; + +} -- cgit v1.2.3 From ea25e99aaca4dd9c4a442d9ce39a5365aaf72bc1 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Thu, 28 Feb 2019 00:29:49 -0800 Subject: Fixed some issues in Vk backend --- Graphics/GraphicsEngine/include/PipelineStateBase.h | 3 ++- .../include/ShaderResourceLayoutVk.h | 2 +- .../GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp | 18 +++++++++--------- .../src/ShaderResourceLayoutVk.cpp | 7 ++++--- 4 files changed, 16 insertions(+), 14 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngine/include/PipelineStateBase.h b/Graphics/GraphicsEngine/include/PipelineStateBase.h index 3dde7b85..fbc492e3 100644 --- a/Graphics/GraphicsEngine/include/PipelineStateBase.h +++ b/Graphics/GraphicsEngine/include/PipelineStateBase.h @@ -79,7 +79,7 @@ public: for (Uint32 i=0; i < SrcLayout.NumStaticSamplers; ++i) StringPoolSize += strlen(SrcLayout.StaticSamplers[i].SamplerOrTextureName) + 1; } - m_StringPool.Allocate(StringPoolSize); + m_StringPool.Reserve(StringPoolSize, GetRawAllocator()); auto& DstLayout = this->m_Desc.Layout; if (SrcLayout.Variables != nullptr) @@ -164,6 +164,7 @@ public: if (GraphicsPipeline.pHS) m_ppShaders[m_NumShaders++] = GraphicsPipeline.pHS; if (GraphicsPipeline.pDS) m_ppShaders[m_NumShaders++] = GraphicsPipeline.pDS; } + VERIFY(m_NumShaders > 0, "There must be at least one shader in the Pipeline State"); const auto& InputLayout = PSODesc.GraphicsPipeline.InputLayout; for (size_t Elem = 0; Elem < InputLayout.NumElements; ++Elem) diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h index b4712d70..c3dd9146 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h @@ -142,7 +142,7 @@ public: std::vector SPIRVs[], class PipelineLayout& PipelineLayout); - // sizeof(VkResource) == 24 (x64) - TODO: Verify + // sizeof(VkResource) == 24 (x64) struct VkResource { VkResource (const VkResource&) = delete; diff --git a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp index 14f4c962..443076df 100644 --- a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp @@ -625,31 +625,31 @@ void PipelineStateVkImpl::BindStaticResources(IResourceMapping* pResourceMapping Uint32 PipelineStateVkImpl::GetStaticVariableCount(SHADER_TYPE ShaderType) const { - const auto ShaderTypeInd = GetShaderTypeIndex(ShaderType); - if (ShaderTypeInd < 0) + const auto LayoutInd = m_ResourceLayoutIndex[GetShaderTypeIndex(ShaderType)]; + if (LayoutInd < 0) return 0; - auto& StaticVarMgr = GetStaticVarMgr(ShaderTypeInd); + auto& StaticVarMgr = GetStaticVarMgr(LayoutInd); return StaticVarMgr.GetVariableCount(); } IShaderResourceVariable* PipelineStateVkImpl::GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) { - const auto ShaderTypeInd = GetShaderTypeIndex(ShaderType); - if (ShaderTypeInd < 0) + const auto LayoutInd = m_ResourceLayoutIndex[GetShaderTypeIndex(ShaderType)]; + if (LayoutInd < 0) return nullptr; - auto& StaticVarMgr = GetStaticVarMgr(ShaderTypeInd); + auto& StaticVarMgr = GetStaticVarMgr(LayoutInd); return StaticVarMgr.GetVariable(Name); } IShaderResourceVariable* PipelineStateVkImpl::GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) { - const auto ShaderTypeInd = GetShaderTypeIndex(ShaderType); - if (ShaderTypeInd < 0) + const auto LayoutInd = m_ResourceLayoutIndex[GetShaderTypeIndex(ShaderType)]; + if (LayoutInd < 0) return nullptr; - auto& StaticVarMgr = GetStaticVarMgr(ShaderTypeInd); + auto& StaticVarMgr = GetStaticVarMgr(LayoutInd); return StaticVarMgr.GetVariable(Index); } diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp index a0835334..201fadc6 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp @@ -154,7 +154,8 @@ void ShaderResourceLayoutVk::AllocateMemory(std::shared_ptrGetShaderType(); - const auto* CombinedSamplerSuffix = pSrcResources->GetCombinedSamplerSuffix(); + const auto ShaderType = m_pResources->GetShaderType(); + const auto* CombinedSamplerSuffix = m_pResources->GetCombinedSamplerSuffix(); m_pResources->ProcessResources( [&](const SPIRVShaderResourceAttribs& Attribs, Uint32) -- cgit v1.2.3 From 3f69e88e20ebabc9b4ee363106e7646cbff7d754 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Thu, 28 Feb 2019 07:13:07 -0800 Subject: Fixed memory leak --- Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp index 443076df..ec5ff6b3 100644 --- a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp @@ -453,9 +453,13 @@ PipelineStateVkImpl::~PipelineStateVkImpl() } auto& RawAllocator = GetRawAllocator(); - for (Uint32 s=0; s < m_NumShaders; ++s) + for (Uint32 s=0; s < m_NumShaders*2; ++s) { m_ShaderResourceLayouts[s].~ShaderResourceLayoutVk(); + } + + for (Uint32 s=0; s < m_NumShaders; ++s) + { m_StaticResCaches[s].~ShaderResourceCacheVk(); m_StaticVarsMgrs[s].Destroy(GetRawAllocator()); m_StaticVarsMgrs[s].~ShaderVariableManagerVk(); -- cgit v1.2.3 From 6384ebb550a265f60dc30220d21460164df07936 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Thu, 28 Feb 2019 07:35:57 -0800 Subject: Improved shader resource binding error reporting in ShaderResourceLayoutVk --- .../interface/GraphicsAccessories.h | 6 ++++++ .../GraphicsAccessories/src/GraphicsAccessories.cpp | 20 +++++++++++++++++++- Graphics/GraphicsEngine/interface/Shader.h | 2 ++ .../src/ShaderResourceLayoutVk.cpp | 17 +++++++++++++++-- 4 files changed, 42 insertions(+), 3 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsAccessories/interface/GraphicsAccessories.h b/Graphics/GraphicsAccessories/interface/GraphicsAccessories.h index ef769bfc..4ad6ba4a 100644 --- a/Graphics/GraphicsAccessories/interface/GraphicsAccessories.h +++ b/Graphics/GraphicsAccessories/interface/GraphicsAccessories.h @@ -183,6 +183,12 @@ const Char *GetBufferViewTypeLiteralName(BUFFER_VIEW_TYPE ViewType); /// \return Literal name of the shader type. const Char *GetShaderTypeLiteralName(SHADER_TYPE ShaderType); +/// \param [in] ShaderStages - Shader stages. +/// \return The string representing the shader stages. For example, +/// if ShaderStages == SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, +/// the following string will be returned: +/// "SHADER_TYPE_VERTEX, SHADER_TYPE_PIXEL" +String GetShaderStagesString(SHADER_TYPE ShaderStages); /// Returns the literal name of a shader variable type. For instance, /// for SHADER_RESOURCE_VARIABLE_TYPE_STATIC, if bGetFullName == true, "SHADER_RESOURCE_VARIABLE_TYPE_STATIC" will be returned; diff --git a/Graphics/GraphicsAccessories/src/GraphicsAccessories.cpp b/Graphics/GraphicsAccessories/src/GraphicsAccessories.cpp index 3613076f..7a8b1226 100644 --- a/Graphics/GraphicsAccessories/src/GraphicsAccessories.cpp +++ b/Graphics/GraphicsAccessories/src/GraphicsAccessories.cpp @@ -471,10 +471,28 @@ const Char *GetShaderTypeLiteralName( SHADER_TYPE ShaderType ) RETURN_SHADER_TYPE_NAME( SHADER_TYPE_COMPUTE ) #undef RETURN_SHADER_TYPE_NAME - default: UNEXPECTED( "Unknown shader type" ); return ""; + default: UNEXPECTED( "Unknown shader type constant ", Uint32{ShaderType} ); return ""; } } +String GetShaderStagesString(SHADER_TYPE ShaderStages) +{ + String StagesStr; + while(ShaderStages != 0) + for( Uint32 Stage = SHADER_TYPE_VERTEX; ShaderStages != 0 && Stage <= SHADER_TYPE_COMPUTE; Stage <<= 1 ) + { + if( ShaderStages&Stage ) + { + if( StagesStr.length() ) + StagesStr += ", "; + StagesStr += GetShaderTypeLiteralName( static_cast(Stage)); + ShaderStages &= ~static_cast(Stage); + } + } + VERIFY_EXPR( ShaderStages == 0); + return StagesStr; +} + const Char *GetShaderVariableTypeLiteralName(SHADER_RESOURCE_VARIABLE_TYPE VarType, bool bGetFullName) { static const Char* ShortVarTypeNameStrings[SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES]; diff --git a/Graphics/GraphicsEngine/interface/Shader.h b/Graphics/GraphicsEngine/interface/Shader.h index 43d6021a..2ac6a2c6 100644 --- a/Graphics/GraphicsEngine/interface/Shader.h +++ b/Graphics/GraphicsEngine/interface/Shader.h @@ -27,6 +27,7 @@ /// Definition of the Diligent::IShader interface and related data structures #include "../../../Primitives/interface/FileStream.h" +#include "../../../Primitives/interface/FlagEnum.h" #include "DeviceObject.h" namespace Diligent @@ -47,6 +48,7 @@ enum SHADER_TYPE : Uint32 SHADER_TYPE_DOMAIN = 0x010, ///< Domain (tessellation evaluation) shader SHADER_TYPE_COMPUTE = 0x020 ///< Compute shader }; +DEFINE_FLAG_ENUM_OPERATORS(SHADER_TYPE); enum SHADER_PROFILE : Uint8 { diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp index 201fadc6..7f1eb1bb 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp @@ -225,6 +225,11 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* { bool VariableFound = false; const auto& VarDesc = LayoutDesc.Variables[v]; + if (VarDesc.ShaderStages == SHADER_TYPE_UNKNOWN) + { + LOG_WARNING_MESSAGE("No allowed shader stages specified for variable '", VarDesc.Name, "' labeled as ", GetShaderVariableTypeLiteralName(VarDesc.Type), "."); + } + for(Uint32 s=0; s < NumShaders && !VariableFound; ++s) { const auto& Resources = *pShaderResources[s]; @@ -239,17 +244,25 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* } if (!VariableFound) { - LOG_WARNING_MESSAGE("Variable '", VarDesc.Name, "' labeled as ", GetShaderVariableTypeLiteralName(VarDesc.Type), " is not found in any of shader stages"); + LOG_WARNING_MESSAGE("Variable '", VarDesc.Name, "' labeled as ", GetShaderVariableTypeLiteralName(VarDesc.Type), " is not found in any of the specified shader stages: ", GetShaderStagesString(VarDesc.ShaderStages)); } } for (Uint32 sam = 0; sam < LayoutDesc.NumStaticSamplers; ++sam) { const auto& StSamDesc = LayoutDesc.StaticSamplers[sam]; + if (StSamDesc.ShaderStages == SHADER_TYPE_UNKNOWN) + { + LOG_WARNING_MESSAGE("No allowed shader stages specified for static sampler '", StSamDesc.SamplerOrTextureName, "."); + } + bool SamplerFound = false; for(Uint32 s=0; s < NumShaders && !SamplerFound; ++s) { const auto& Resources = *pShaderResources[s]; + if ( (StSamDesc.ShaderStages & Resources.GetShaderType()) == 0 ) + continue; + // Irrespective of whether HLSL-style combined image samplers are used, // a static sampler can be assigned to GLSL sampled image (i.e. sampler2D g_tex) for (Uint32 i = 0; i < Resources.GetNumSmpldImgs() && !SamplerFound; ++i) @@ -276,7 +289,7 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* if (!SamplerFound) { - LOG_WARNING_MESSAGE("Static sampler '", StSamDesc.SamplerOrTextureName, "' is not found in any of shader stages"); + LOG_WARNING_MESSAGE("Static sampler '", StSamDesc.SamplerOrTextureName, "' is not found in any of the specified shader stages: ", GetShaderStagesString(StSamDesc.ShaderStages)); } } #endif -- cgit v1.2.3 From a11b4c46b33a49501b81ce638474abd36b89582b Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Thu, 28 Feb 2019 07:56:53 -0800 Subject: Renamed PipelineLayoutDesc to PipelineResourceLayoutDesc --- .../GraphicsEngine/include/PipelineStateBase.h | 12 +++--- .../include/ShaderResourceVariableBase.h | 12 +++--- Graphics/GraphicsEngine/interface/PipelineState.h | 4 +- .../include/ShaderResourceLayoutVk.h | 6 +-- .../src/GenerateMipsVkHelper.cpp | 10 ++--- .../src/PipelineStateVkImpl.cpp | 4 +- .../src/ShaderResourceLayoutVk.cpp | 48 +++++++++++----------- 7 files changed, 48 insertions(+), 48 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngine/include/PipelineStateBase.h b/Graphics/GraphicsEngine/include/PipelineStateBase.h index fbc492e3..ddc682ef 100644 --- a/Graphics/GraphicsEngine/include/PipelineStateBase.h +++ b/Graphics/GraphicsEngine/include/PipelineStateBase.h @@ -66,7 +66,7 @@ public: m_LayoutElements (PSODesc.GraphicsPipeline.InputLayout.NumElements, LayoutElement{}, STD_ALLOCATOR_RAW_MEM(LayoutElement, GetRawAllocator(), "Allocator for vector")), m_NumShaders(0) { - const auto& SrcLayout = PSODesc.Layout; + const auto& SrcLayout = PSODesc.ResourceLayout; size_t StringPoolSize = 0; if (SrcLayout.Variables != nullptr) { @@ -81,7 +81,7 @@ public: } m_StringPool.Reserve(StringPoolSize, GetRawAllocator()); - auto& DstLayout = this->m_Desc.Layout; + auto& DstLayout = this->m_Desc.ResourceLayout; if (SrcLayout.Variables != nullptr) { ShaderResourceVariableDesc* Variables = @@ -266,10 +266,10 @@ public: */ auto& RawAllocator = GetRawAllocator(); - if (this->m_Desc.Layout.Variables != nullptr) - RawAllocator.Free(const_cast(this->m_Desc.Layout.Variables)); - if (this->m_Desc.Layout.StaticSamplers != nullptr) - RawAllocator.Free(const_cast(this->m_Desc.Layout.StaticSamplers)); + if (this->m_Desc.ResourceLayout.Variables != nullptr) + RawAllocator.Free(const_cast(this->m_Desc.ResourceLayout.Variables)); + if (this->m_Desc.ResourceLayout.StaticSamplers != nullptr) + RawAllocator.Free(const_cast(this->m_Desc.ResourceLayout.StaticSamplers)); } IMPLEMENT_QUERY_INTERFACE_IN_PLACE( IID_PipelineState, TDeviceObjectBase ) diff --git a/Graphics/GraphicsEngine/include/ShaderResourceVariableBase.h b/Graphics/GraphicsEngine/include/ShaderResourceVariableBase.h index 5c5629d3..2282a3f7 100644 --- a/Graphics/GraphicsEngine/include/ShaderResourceVariableBase.h +++ b/Graphics/GraphicsEngine/include/ShaderResourceVariableBase.h @@ -66,9 +66,9 @@ inline SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE ); } -inline SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE ShaderStage, - const Char* Name, - const PipelineLayoutDesc& LayoutDesc) +inline SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE ShaderStage, + const Char* Name, + const PipelineResourceLayoutDesc& LayoutDesc) { return GetShaderVariableType(ShaderStage, Name, LayoutDesc.DefaultVariableType, LayoutDesc.Variables, LayoutDesc.NumVariables); } @@ -87,9 +87,9 @@ inline SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE ); } -inline SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE ShaderStage, - const String& Name, - const PipelineLayoutDesc& LayoutDesc) +inline SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE ShaderStage, + const String& Name, + const PipelineResourceLayoutDesc& LayoutDesc) { return GetShaderVariableType(ShaderStage, Name, LayoutDesc.DefaultVariableType, LayoutDesc.Variables, LayoutDesc.NumVariables); } diff --git a/Graphics/GraphicsEngine/interface/PipelineState.h b/Graphics/GraphicsEngine/interface/PipelineState.h index 39064c75..61a4e68e 100644 --- a/Graphics/GraphicsEngine/interface/PipelineState.h +++ b/Graphics/GraphicsEngine/interface/PipelineState.h @@ -108,7 +108,7 @@ struct StaticSamplerDesc /// Pipeline layout description -struct PipelineLayoutDesc +struct PipelineResourceLayoutDesc { /// Default shader resource variable type. This type will be used if shader /// variable description is not found in the Variables array @@ -221,7 +221,7 @@ struct PipelineStateDesc : DeviceObjectAttribs Uint64 CommandQueueMask = 1; /// Pipeline layout description - PipelineLayoutDesc Layout; + PipelineResourceLayoutDesc ResourceLayout; /// Graphics pipeline state description. This memeber is ignored if IsComputePipeline == True GraphicsPipelineDesc GraphicsPipeline; diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h index c3dd9146..5fd6f520 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h @@ -128,7 +128,7 @@ public: // shader resource layout and the cache void InitializeStaticResourceLayout(std::shared_ptr pSrcResources, IMemoryAllocator& LayoutDataAllocator, - const PipelineLayoutDesc& LayoutDesc, + const PipelineResourceLayoutDesc& ResourceLayoutDesc, ShaderResourceCacheVk& StaticResourceCache); // This method is called by PipelineStateVkImpl class instance to initialize resource @@ -138,7 +138,7 @@ public: ShaderResourceLayoutVk Layouts[], std::shared_ptr pShaderResources[], IMemoryAllocator& LayoutDataAllocator, - const PipelineLayoutDesc& LayoutDesc, + const PipelineResourceLayoutDesc& ResourceLayoutDesc, std::vector SPIRVs[], class PipelineLayout& PipelineLayout); @@ -319,7 +319,7 @@ private: void AllocateMemory(std::shared_ptr pSrcResources, IMemoryAllocator& Allocator, - const PipelineLayoutDesc& LayoutDesc, + const PipelineResourceLayoutDesc& ResourceLayoutDesc, const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes); diff --git a/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp b/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp index d177ca46..305f04ef 100644 --- a/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp +++ b/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp @@ -147,14 +147,14 @@ namespace Diligent PSODesc.Name = name.c_str(); PSODesc.ComputePipeline.pCS = pCS; - PSODesc.Layout.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; + PSODesc.ResourceLayout.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; ShaderResourceVariableDesc VarDesc{SHADER_TYPE_COMPUTE, "CB", SHADER_RESOURCE_VARIABLE_TYPE_STATIC}; - PSODesc.Layout.Variables = &VarDesc; - PSODesc.Layout.NumVariables = 1; + PSODesc.ResourceLayout.Variables = &VarDesc; + PSODesc.ResourceLayout.NumVariables = 1; const StaticSamplerDesc StaticSampler(SHADER_TYPE_COMPUTE, "SrcMip", Sam_LinearClamp); - PSODesc.Layout.StaticSamplers = &StaticSampler; - PSODesc.Layout.NumStaticSamplers = 1; + PSODesc.ResourceLayout.StaticSamplers = &StaticSampler; + PSODesc.ResourceLayout.NumStaticSamplers = 1; m_DeviceVkImpl.CreatePipelineState(PSODesc, &PSOs[NonPowOfTwo]); PSOs[NonPowOfTwo]->GetStaticShaderVariable(SHADER_TYPE_COMPUTE, "CB")->Set(m_ConstantsCB); diff --git a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp index ec5ff6b3..548441a7 100644 --- a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp @@ -174,13 +174,13 @@ PipelineStateVkImpl :: PipelineStateVkImpl(IReferenceCounters* pRefCounters auto* pStaticResLayout = new (m_ShaderResourceLayouts + m_NumShaders + s) ShaderResourceLayoutVk(LogicalDevice); auto* pStaticResCache = new (m_StaticResCaches + s) ShaderResourceCacheVk(ShaderResourceCacheVk::DbgCacheContentType::StaticShaderResources); - pStaticResLayout->InitializeStaticResourceLayout(ShaderResources[s], ShaderResLayoutAllocator, PipelineDesc.Layout, m_StaticResCaches[s]); + pStaticResLayout->InitializeStaticResourceLayout(ShaderResources[s], ShaderResLayoutAllocator, PipelineDesc.ResourceLayout, m_StaticResCaches[s]); auto* pStaticVarMgr = new (m_StaticVarsMgrs + s) ShaderVariableManagerVk(*this); pStaticVarMgr->Initialize(*pStaticResLayout, GetRawAllocator(), nullptr, 0, *pStaticResCache); } ShaderResourceLayoutVk::Initialize(pDeviceVk, m_NumShaders, m_ShaderResourceLayouts, ShaderResources.data(), GetRawAllocator(), - PipelineDesc.Layout, ShaderSPIRVs.data(), m_PipelineLayout); + PipelineDesc.ResourceLayout, ShaderSPIRVs.data(), m_PipelineLayout); m_PipelineLayout.Finalize(LogicalDevice); if (PipelineDesc.SRBAllocationGranularity > 1) diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp index 7f1eb1bb..abd606b4 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp @@ -40,7 +40,7 @@ namespace Diligent { static Int32 FindImmutableSampler(SHADER_TYPE ShaderType, - const PipelineLayoutDesc& LayoutDesc, + const PipelineResourceLayoutDesc& ResourceLayoutDesc, const SPIRVShaderResourceAttribs& Attribs, const char* SamplerSuffix) { @@ -58,9 +58,9 @@ static Int32 FindImmutableSampler(SHADER_TYPE ShaderType, return -1; } - for (Uint32 s=0; s < LayoutDesc.NumStaticSamplers; ++s) + for (Uint32 s=0; s < ResourceLayoutDesc.NumStaticSamplers; ++s) { - const auto& StSam = LayoutDesc.StaticSamplers[s]; + const auto& StSam = ResourceLayoutDesc.StaticSamplers[s]; if ( ((StSam.ShaderStages & ShaderType) != 0) && StreqSuff(Attribs.Name, StSam.SamplerOrTextureName, SamplerSuffix) ) return s; } @@ -70,14 +70,14 @@ static Int32 FindImmutableSampler(SHADER_TYPE ShaderType, static SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE ShaderType, const SPIRVShaderResourceAttribs& Attribs, - const PipelineLayoutDesc& LayoutDesc, + const PipelineResourceLayoutDesc& ResourceLayoutDesc, const char* CombinedSamplerSuffix) { if (Attribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler) { // Use texture or sampler name to derive separate sampler type // When HLSL-style combined image samplers are not used, CombinedSamplerSuffix is null - return GetShaderVariableType(ShaderType, LayoutDesc.DefaultVariableType, LayoutDesc.Variables, LayoutDesc.NumVariables, + return GetShaderVariableType(ShaderType, ResourceLayoutDesc.DefaultVariableType, ResourceLayoutDesc.Variables, ResourceLayoutDesc.NumVariables, [&](const char* VarName) { return StreqSuff(Attribs.Name, VarName, CombinedSamplerSuffix); @@ -85,7 +85,7 @@ static SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE } else { - return GetShaderVariableType(ShaderType, Attribs.Name, LayoutDesc); + return GetShaderVariableType(ShaderType, Attribs.Name, ResourceLayoutDesc); } } @@ -102,7 +102,7 @@ ShaderResourceLayoutVk::~ShaderResourceLayoutVk() void ShaderResourceLayoutVk::AllocateMemory(std::shared_ptr pSrcResources, IMemoryAllocator& Allocator, - const PipelineLayoutDesc& LayoutDesc, + const PipelineResourceLayoutDesc& ResourceLayoutDesc, const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes) { @@ -119,7 +119,7 @@ void ShaderResourceLayoutVk::AllocateMemory(std::shared_ptrProcessResources( [&](const SPIRVShaderResourceAttribs& ResAttribs, Uint32) { - auto VarType = GetShaderVariableType(ShaderType, ResAttribs, LayoutDesc, CombinedSamplerSuffix); + auto VarType = GetShaderVariableType(ShaderType, ResAttribs, ResourceLayoutDesc, CombinedSamplerSuffix); if (IsAllowedType(VarType, AllowedTypeBits)) { VERIFY( Uint32{m_NumResources[VarType]} + 1 <= Uint32{std::numeric_limits::max()}, "Number of resources exceeds max representable value"); @@ -137,9 +137,9 @@ void ShaderResourceLayoutVk::AllocateMemory(std::shared_ptr(TotalResources); m_NumImmutableSamplers = 0; - for(Uint32 s=0; s < LayoutDesc.NumStaticSamplers; ++s) + for(Uint32 s=0; s < ResourceLayoutDesc.NumStaticSamplers; ++s) { - const auto& StSamDesc = LayoutDesc.StaticSamplers[s]; + const auto& StSamDesc = ResourceLayoutDesc.StaticSamplers[s]; if ((StSamDesc.ShaderStages & ShaderType) != 0) ++m_NumImmutableSamplers; } @@ -162,11 +162,11 @@ void ShaderResourceLayoutVk::AllocateMemory(std::shared_ptr pSrcResources, IMemoryAllocator& LayoutDataAllocator, - const PipelineLayoutDesc& LayoutDesc, + const PipelineResourceLayoutDesc& ResourceLayoutDesc, ShaderResourceCacheVk& StaticResourceCache) { auto AllowedVarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; - AllocateMemory(std::move(pSrcResources), LayoutDataAllocator, LayoutDesc, &AllowedVarType, 1); + AllocateMemory(std::move(pSrcResources), LayoutDataAllocator, ResourceLayoutDesc, &AllowedVarType, 1); std::array CurrResInd = {}; Uint32 StaticResCacheSize = 0; @@ -178,7 +178,7 @@ void ShaderResourceLayoutVk::InitializeStaticResourceLayout(std::shared_ptrProcessResources( [&](const SPIRVShaderResourceAttribs& Attribs, Uint32) { - auto VarType = GetShaderVariableType(ShaderType, Attribs, LayoutDesc, CombinedSamplerSuffix); + auto VarType = GetShaderVariableType(ShaderType, Attribs, ResourceLayoutDesc, CombinedSamplerSuffix); if (!IsAllowedType(VarType, AllowedTypeBits)) return; @@ -216,15 +216,15 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* ShaderResourceLayoutVk Layouts[], std::shared_ptr pShaderResources[], IMemoryAllocator& LayoutDataAllocator, - const PipelineLayoutDesc& LayoutDesc, + const PipelineResourceLayoutDesc& ResourceLayoutDesc, std::vector SPIRVs[], class PipelineLayout& PipelineLayout) { #ifdef DEVELOPMENT - for (Uint32 v = 0; v < LayoutDesc.NumVariables; ++v) + for (Uint32 v = 0; v < ResourceLayoutDesc.NumVariables; ++v) { bool VariableFound = false; - const auto& VarDesc = LayoutDesc.Variables[v]; + const auto& VarDesc = ResourceLayoutDesc.Variables[v]; if (VarDesc.ShaderStages == SHADER_TYPE_UNKNOWN) { LOG_WARNING_MESSAGE("No allowed shader stages specified for variable '", VarDesc.Name, "' labeled as ", GetShaderVariableTypeLiteralName(VarDesc.Type), "."); @@ -248,9 +248,9 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* } } - for (Uint32 sam = 0; sam < LayoutDesc.NumStaticSamplers; ++sam) + for (Uint32 sam = 0; sam < ResourceLayoutDesc.NumStaticSamplers; ++sam) { - const auto& StSamDesc = LayoutDesc.StaticSamplers[sam]; + const auto& StSamDesc = ResourceLayoutDesc.StaticSamplers[sam]; if (StSamDesc.ShaderStages == SHADER_TYPE_UNKNOWN) { LOG_WARNING_MESSAGE("No allowed shader stages specified for static sampler '", StSamDesc.SamplerOrTextureName, "."); @@ -301,7 +301,7 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* for (Uint32 s=0; s < NumShaders; ++s) { - Layouts[s].AllocateMemory(std::move(pShaderResources[s]), LayoutDataAllocator, LayoutDesc, AllowedVarTypes, NumAllowedTypes); + Layouts[s].AllocateMemory(std::move(pShaderResources[s]), LayoutDataAllocator, ResourceLayoutDesc, AllowedVarTypes, NumAllowedTypes); } VERIFY_EXPR(NumShaders <= MaxShadersInPipeline); @@ -320,7 +320,7 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* Uint32 DescriptorSet = 0; Uint32 CacheOffset = 0; const auto ShaderType = Resources.GetShaderType(); - const SHADER_RESOURCE_VARIABLE_TYPE VarType = GetShaderVariableType(ShaderType, Attribs, LayoutDesc, Resources.GetCombinedSamplerSuffix()); + const SHADER_RESOURCE_VARIABLE_TYPE VarType = GetShaderVariableType(ShaderType, Attribs, ResourceLayoutDesc, Resources.GetCombinedSamplerSuffix()); if (!IsAllowedType(VarType, AllowedTypeBits)) return; @@ -333,13 +333,13 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* SamplerInd = ResLayout.FindAssignedSampler(Attribs, CurrResInd[ShaderInd][VarType], VarType); } - Int32 SrcImmutableSamplerInd = FindImmutableSampler(ShaderType, LayoutDesc, Attribs, Resources.GetCombinedSamplerSuffix()); + Int32 SrcImmutableSamplerInd = FindImmutableSampler(ShaderType, ResourceLayoutDesc, Attribs, Resources.GetCombinedSamplerSuffix()); VkSampler vkImmutableSampler = VK_NULL_HANDLE; if (SrcImmutableSamplerInd >= 0) { auto& ImmutableSampler = ResLayout.GetImmutableSampler(CurrImmutableSamplerInd[ShaderInd]++); VERIFY(!ImmutableSampler, "Immutable sampler has already been initialized!"); - const auto& ImmutableSamplerDesc = LayoutDesc.StaticSamplers[SrcImmutableSamplerInd].Desc; + const auto& ImmutableSamplerDesc = ResourceLayoutDesc.StaticSamplers[SrcImmutableSamplerInd].Desc; pRenderDevice->CreateSampler(ImmutableSamplerDesc, &ImmutableSampler); vkImmutableSampler = ImmutableSampler.RawPtr()->GetVkSampler(); } @@ -372,7 +372,7 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* for (Uint32 n = 0; n < Resources.GetNumUBs(); ++n) { const auto& UB = Resources.GetUB(n); - auto VarType = GetShaderVariableType(Resources.GetShaderType(), UB.Name, LayoutDesc); + auto VarType = GetShaderVariableType(Resources.GetShaderType(), UB.Name, ResourceLayoutDesc); if (IsAllowedType(VarType, AllowedTypeBits)) { AddResource(s, Layout, Resources, UB); @@ -388,7 +388,7 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* for (Uint32 n = 0; n < Resources.GetNumSBs(); ++n) { const auto& SB = Resources.GetSB(n); - auto VarType = GetShaderVariableType(Resources.GetShaderType(), SB.Name, LayoutDesc); + auto VarType = GetShaderVariableType(Resources.GetShaderType(), SB.Name, ResourceLayoutDesc); if (IsAllowedType(VarType, AllowedTypeBits)) { AddResource(s, Layout, Resources, SB); -- cgit v1.2.3 From 0865ee3b7b5d4558e2cea100e615b8ce39b3aa91 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Fri, 1 Mar 2019 09:53:55 -0800 Subject: Fixed a number of issue with resource binding --- .../include/ShaderResourceLayoutVk.h | 5 +- .../src/GenerateMipsVkHelper.cpp | 16 +++--- .../GraphicsEngineVulkan/src/PipelineLayout.cpp | 3 ++ .../src/PipelineStateVkImpl.cpp | 4 +- .../src/ShaderResourceCacheVk.cpp | 4 +- .../src/ShaderResourceLayoutVk.cpp | 62 ++++++++++++++-------- 6 files changed, 61 insertions(+), 33 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h index 5fd6f520..b9f0ea10 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h @@ -208,7 +208,10 @@ public: bool IsImmutableSamplerAssigned() const { - VERIFY_EXPR(SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateImage); + VERIFY(ImmutableSamplerAssigned == 0 || + SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SampledImage || + SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler, + "Immutable sampler can only be assigned to a sampled image or separate sampler"); return ImmutableSamplerAssigned != 0; } diff --git a/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp b/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp index 305f04ef..4ae8243e 100644 --- a/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp +++ b/Graphics/GraphicsEngineVulkan/src/GenerateMipsVkHelper.cpp @@ -104,13 +104,13 @@ namespace Diligent std::array, 4> GenerateMipsVkHelper::CreatePSOs(TEXTURE_FORMAT Fmt) { - ShaderCreateInfo CSCreateAttribs; + ShaderCreateInfo CSCreateInfo; std::array, 4> PSOs; - CSCreateAttribs.Source = g_GenerateMipsCSSource; - CSCreateAttribs.EntryPoint = "main"; - CSCreateAttribs.SourceLanguage = SHADER_SOURCE_LANGUAGE_GLSL; - CSCreateAttribs.Desc.ShaderType = SHADER_TYPE_COMPUTE; + CSCreateInfo.Source = g_GenerateMipsCSSource; + CSCreateInfo.EntryPoint = "main"; + CSCreateInfo.SourceLanguage = SHADER_SOURCE_LANGUAGE_GLSL; + CSCreateInfo.Desc.ShaderType = SHADER_TYPE_COMPUTE; const auto& FmtAttribs = GetTextureFormatAttribs(Fmt); bool IsGamma = FmtAttribs.ComponentType == COMPONENT_TYPE_UNORM_SRGB; @@ -125,7 +125,7 @@ namespace Diligent Macros.AddShaderMacro("IMG_FORMAT", GlFmt.data()); Macros.Finalize(); - CSCreateAttribs.Macros = Macros; + CSCreateInfo.Macros = Macros; std::stringstream name_ss; name_ss << "Generate mips " << GlFmt.data(); @@ -138,10 +138,10 @@ namespace Diligent default: UNEXPECTED("Unexpected value"); } auto name = name_ss.str(); - CSCreateAttribs.Desc.Name = name.c_str(); + CSCreateInfo.Desc.Name = name.c_str(); RefCntAutoPtr pCS; - m_DeviceVkImpl.CreateShader(CSCreateAttribs, &pCS); + m_DeviceVkImpl.CreateShader(CSCreateInfo, &pCS); PipelineStateDesc PSODesc; PSODesc.IsComputePipeline = true; PSODesc.Name = name.c_str(); diff --git a/Graphics/GraphicsEngineVulkan/src/PipelineLayout.cpp b/Graphics/GraphicsEngineVulkan/src/PipelineLayout.cpp index 7ce29a6f..ef7fd8ec 100644 --- a/Graphics/GraphicsEngineVulkan/src/PipelineLayout.cpp +++ b/Graphics/GraphicsEngineVulkan/src/PipelineLayout.cpp @@ -373,6 +373,9 @@ void PipelineLayout::AllocateResourceSlot(const SPIRVShaderResourceAttribs& ResA Uint32& OffsetInCache, std::vector& SPIRV) { + VERIFY( (ResAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SampledImage || + ResAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler) || vkStaticSampler == VK_NULL_HANDLE, + "Immutable sampler should only be specified for combined image samplers or separate samplers"); m_LayoutMgr.AllocateResourceSlot(ResAttribs, VariableType,vkStaticSampler, ShaderType, DescriptorSet, Binding, OffsetInCache); SPIRV[ResAttribs.BindingDecorationOffset] = Binding; SPIRV[ResAttribs.DescriptorSetDecorationOffset] = DescriptorSet; diff --git a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp index 548441a7..fe05a3bd 100644 --- a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp @@ -663,8 +663,9 @@ void PipelineStateVkImpl::InitializeStaticSRBResources(ShaderResourceCacheVk& Re for (Uint32 s = 0; s < m_NumShaders; ++s) { const auto& StaticResLayout = GetStaticShaderResLayout(s); + const auto& StaticResCache = GetStaticResCache(s); #ifdef DEVELOPMENT - if (!StaticResLayout.dvpVerifyBindings(ResourceCache)) + if (!StaticResLayout.dvpVerifyBindings(StaticResCache)) { const auto* pShaderVk = GetShader(s); LOG_ERROR_MESSAGE("Static resources in SRB of PSO '", GetDesc().Name, "' will not be successfully initialized " @@ -673,7 +674,6 @@ void PipelineStateVkImpl::InitializeStaticSRBResources(ShaderResourceCacheVk& Re "directly or indirectly by passing InitStaticResources=true to CreateShaderResourceBinding() method."); } #endif - const auto& StaticResCache = GetStaticResCache(s); const auto& ShaderResourceLayouts = GetShaderResLayout(s); ShaderResourceLayouts.InitializeStaticResources(StaticResLayout, StaticResCache, ResourceCache); } diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceCacheVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceCacheVk.cpp index 98d4e424..85f835f8 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceCacheVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceCacheVk.cpp @@ -324,6 +324,8 @@ VkDescriptorImageInfo ShaderResourceCacheVk::Resource::GetImageDescriptorWriteIn VkDescriptorImageInfo DescrImgInfo; DescrImgInfo.sampler = VK_NULL_HANDLE; + VERIFY(Type == SPIRVShaderResourceAttribs::ResourceType::SampledImage || !IsImmutableSampler, + "Immutable sampler can't be assigned to separarate image or storage image"); if (Type == SPIRVShaderResourceAttribs::ResourceType::SampledImage && !IsImmutableSampler) { // Immutable samplers are permanently bound into the set layout; later binding a sampler @@ -340,7 +342,7 @@ VkDescriptorImageInfo ShaderResourceCacheVk::Resource::GetImageDescriptorWriteIn #ifdef DEVELOPMENT else { - LOG_ERROR_MESSAGE("No sampler assigned to texture view '", pTexViewVk->GetDesc().Name, "'"); + LOG_ERROR_MESSAGE("No sampler is assigned to texture view '", pTexViewVk->GetDesc().Name, "'"); } #endif } diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp index abd606b4..5b3578ba 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp @@ -44,7 +44,7 @@ static Int32 FindImmutableSampler(SHADER_TYPE ShaderType, const SPIRVShaderResourceAttribs& Attribs, const char* SamplerSuffix) { - if (Attribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateImage) + if (Attribs.Type == SPIRVShaderResourceAttribs::ResourceType::SampledImage) { SamplerSuffix = nullptr; } @@ -55,6 +55,7 @@ static Int32 FindImmutableSampler(SHADER_TYPE ShaderType, } else { + UNEXPECTED("Immutable sampler can only be assigned to a sampled image or separate sampler"); return -1; } @@ -182,6 +183,14 @@ void ShaderResourceLayoutVk::InitializeStaticResourceLayout(std::shared_ptr= 0); } ); @@ -227,7 +236,8 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* const auto& VarDesc = ResourceLayoutDesc.Variables[v]; if (VarDesc.ShaderStages == SHADER_TYPE_UNKNOWN) { - LOG_WARNING_MESSAGE("No allowed shader stages specified for variable '", VarDesc.Name, "' labeled as ", GetShaderVariableTypeLiteralName(VarDesc.Type), "."); + LOG_WARNING_MESSAGE("No allowed shader stages are specified for variable '", VarDesc.Name, "' labeled as ", GetShaderVariableTypeLiteralName(VarDesc.Type), "."); + continue; } for(Uint32 s=0; s < NumShaders && !VariableFound; ++s) @@ -253,7 +263,8 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* const auto& StSamDesc = ResourceLayoutDesc.StaticSamplers[sam]; if (StSamDesc.ShaderStages == SHADER_TYPE_UNKNOWN) { - LOG_WARNING_MESSAGE("No allowed shader stages specified for static sampler '", StSamDesc.SamplerOrTextureName, "."); + LOG_WARNING_MESSAGE("No allowed shader stages are specified for static sampler '", StSamDesc.SamplerOrTextureName, "."); + continue; } bool SamplerFound = false; @@ -333,17 +344,22 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* SamplerInd = ResLayout.FindAssignedSampler(Attribs, CurrResInd[ShaderInd][VarType], VarType); } - Int32 SrcImmutableSamplerInd = FindImmutableSampler(ShaderType, ResourceLayoutDesc, Attribs, Resources.GetCombinedSamplerSuffix()); VkSampler vkImmutableSampler = VK_NULL_HANDLE; - if (SrcImmutableSamplerInd >= 0) + if (Attribs.Type == SPIRVShaderResourceAttribs::ResourceType::SampledImage || + Attribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler) { - auto& ImmutableSampler = ResLayout.GetImmutableSampler(CurrImmutableSamplerInd[ShaderInd]++); - VERIFY(!ImmutableSampler, "Immutable sampler has already been initialized!"); - const auto& ImmutableSamplerDesc = ResourceLayoutDesc.StaticSamplers[SrcImmutableSamplerInd].Desc; - pRenderDevice->CreateSampler(ImmutableSamplerDesc, &ImmutableSampler); - vkImmutableSampler = ImmutableSampler.RawPtr()->GetVkSampler(); + // Only search for the immutable sampler for combined image samplers and separate samplers + Int32 SrcImmutableSamplerInd = FindImmutableSampler(ShaderType, ResourceLayoutDesc, Attribs, Resources.GetCombinedSamplerSuffix()); + if (SrcImmutableSamplerInd >= 0) + { + auto& ImmutableSampler = ResLayout.GetImmutableSampler(CurrImmutableSamplerInd[ShaderInd]++); + VERIFY(!ImmutableSampler, "Immutable sampler has already been initialized!"); + const auto& ImmutableSamplerDesc = ResourceLayoutDesc.StaticSamplers[SrcImmutableSamplerInd].Desc; + pRenderDevice->CreateSampler(ImmutableSamplerDesc, &ImmutableSampler); + vkImmutableSampler = ImmutableSampler.RawPtr()->GetVkSampler(); + } } - + auto& ShaderSPIRV = SPIRVs[ShaderInd]; PipelineLayout.AllocateResourceSlot(Attribs, VarType, vkImmutableSampler, Resources.GetShaderType(), DescriptorSet, Binding, CacheOffset, ShaderSPIRV); VERIFY(DescriptorSet <= std::numeric_limits::max(), "Descriptor set (", DescriptorSet, ") excceeds max representable value"); @@ -693,7 +709,7 @@ void ShaderResourceLayoutVk::VkResource::CacheImage(IDeviceObject* { if(pTexViewVk->GetSampler() == nullptr) { - LOG_RESOURCE_BINDING_ERROR("resource", pTexView, SpirvAttribs.GetPrintName(ArrayInd), ParentResLayout.GetShaderName(), "No sampler assigned to texture view '", pTexViewVk->GetDesc().Name, "'"); + LOG_RESOURCE_BINDING_ERROR("resource", pTexView, SpirvAttribs.GetPrintName(ArrayInd), ParentResLayout.GetShaderName(), "No sampler is assigned to texture view '", pTexViewVk->GetDesc().Name, "'"); } } #endif @@ -712,15 +728,19 @@ void ShaderResourceLayoutVk::VkResource::CacheImage(IDeviceObject* VERIFY_EXPR(!IsImmutableSamplerAssigned()); auto* pSampler = pTexViewVk->GetSampler(); const auto& SamplerAttribs = ParentResLayout.GetResource(GetVariableType(), SamplerInd); - if (pSampler != nullptr) + VERIFY_EXPR(SamplerAttribs.SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler); + if (!SamplerAttribs.IsImmutableSamplerAssigned()) { - CacheSampler(SamplerAttribs, pSampler); - } - else - { - LOG_ERROR_MESSAGE( "Failed to bind sampler to sampler variable '", SamplerAttribs.SpirvAttribs.Name, - "' assigned to separate image '", SpirvAttribs.GetPrintName(ArrayInd), "' in shader '", - ParentResLayout.GetShaderName(), "': no sampler is set in texture view '", pTexViewVk->GetDesc().Name, '\''); \ + if (pSampler != nullptr) + { + CacheSampler(SamplerAttribs, pSampler); + } + else + { + LOG_ERROR_MESSAGE( "Failed to bind sampler to sampler variable '", SamplerAttribs.SpirvAttribs.Name, + "' assigned to separate image '", SpirvAttribs.GetPrintName(ArrayInd), "' in shader '", + ParentResLayout.GetShaderName(), "': no sampler is set in texture view '", pTexViewVk->GetDesc().Name, '\''); \ + } } } } -- cgit v1.2.3 From 711d815460c97df8aa803393cd1e9414f71222b2 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Fri, 1 Mar 2019 19:28:08 -0800 Subject: Fixed ShaderResourceBinding.h --- Graphics/GraphicsEngine/interface/ShaderResourceBinding.h | 2 ++ 1 file changed, 2 insertions(+) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h b/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h index 970f1ff1..a216cfbe 100644 --- a/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h +++ b/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h @@ -27,7 +27,9 @@ /// Definition of the Diligent::IShaderResourceBinding interface and related data structures #include "../../../Primitives/interface/Object.h" +#include "Shader.h" #include "ShaderResourceVariable.h" +#include "ResourceMapping.h" namespace Diligent { -- cgit v1.2.3 From 9f3fd2c32f4736938695a254ee58cfc27ce40d14 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Fri, 1 Mar 2019 19:30:58 -0800 Subject: Fixed PipelineState.h --- Graphics/GraphicsEngine/interface/PipelineState.h | 1 + 1 file changed, 1 insertion(+) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngine/interface/PipelineState.h b/Graphics/GraphicsEngine/interface/PipelineState.h index 61a4e68e..7768daf8 100644 --- a/Graphics/GraphicsEngine/interface/PipelineState.h +++ b/Graphics/GraphicsEngine/interface/PipelineState.h @@ -36,6 +36,7 @@ #include "ShaderResourceBinding.h" #include "ShaderResourceVariable.h" #include "Shader.h" +#include "Sampler.h" namespace Diligent { -- cgit v1.2.3 From 604f72b4a00ca67b0b17d52ea31ddce5c746a29b Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Fri, 1 Mar 2019 20:52:29 -0800 Subject: Minor update --- Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp index 5b3578ba..bc6c0a54 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp @@ -263,7 +263,7 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* const auto& StSamDesc = ResourceLayoutDesc.StaticSamplers[sam]; if (StSamDesc.ShaderStages == SHADER_TYPE_UNKNOWN) { - LOG_WARNING_MESSAGE("No allowed shader stages are specified for static sampler '", StSamDesc.SamplerOrTextureName, "."); + LOG_WARNING_MESSAGE("No allowed shader stages are specified for static sampler '", StSamDesc.SamplerOrTextureName, "'."); continue; } -- cgit v1.2.3 From 95491dc230f022aca641e9fcc79e8e61b850cd3a Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sat, 2 Mar 2019 11:25:02 -0800 Subject: Some minor (mostly cosmetic) changes to SPIRVShaderResources --- Graphics/GLSLTools/include/SPIRVShaderResources.h | 20 ++++----- Graphics/GLSLTools/src/SPIRVShaderResources.cpp | 52 ++++++++++++----------- 2 files changed, 37 insertions(+), 35 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GLSLTools/include/SPIRVShaderResources.h b/Graphics/GLSLTools/include/SPIRVShaderResources.h index 4809bb71..523ccc29 100644 --- a/Graphics/GLSLTools/include/SPIRVShaderResources.h +++ b/Graphics/GLSLTools/include/SPIRVShaderResources.h @@ -70,18 +70,19 @@ struct SPIRVShaderResourceAttribs static constexpr const Uint32 InvalidSepSmplrOrImgInd = static_cast(-1); -/* 0 */const char* const Name; -/* 8 */const Uint16 ArraySize; -/*10 */const ResourceType Type; +/* 0 */const char* const Name; +/* 8 */const Uint16 ArraySize; +/* 10 */const ResourceType Type; +/* 11 */ // unused private: - // Defines mapping between separate samplers and seperate images when HLSL-style + // Defines the mapping between separate samplers and seperate images when HLSL-style // combined texture samplers are in use (i.e. texture2D g_Tex + sampler g_Tex_sampler). -/*12*/ Uint32 SepSmplrOrImgInd = InvalidSepSmplrOrImgInd; +/* 12 */ Uint32 SepSmplrOrImgInd = InvalidSepSmplrOrImgInd; public: // Offset in SPIRV words (uint32_t) of binding & descriptor set decorations in SPIRV binary -/*16*/const uint32_t BindingDecorationOffset; -/*20*/const uint32_t DescriptorSetDecorationOffset; - +/* 16 */const uint32_t BindingDecorationOffset; +/* 20 */const uint32_t DescriptorSetDecorationOffset; +/* 24 */ // End of structure SPIRVShaderResourceAttribs(const spirv_cross::Compiler& Compiler, const spirv_cross::Resource& Res, @@ -147,6 +148,7 @@ public: }; static_assert(sizeof(SPIRVShaderResourceAttribs) % sizeof(void*) == 0, "Size of SPIRVShaderResourceAttribs struct must be multiple of sizeof(void*)" ); +// sizeof(SPIRVShaderResourceAttribs) == 16, msvc x64 struct SPIRVShaderStageInputAttribs { SPIRVShaderStageInputAttribs(const char* _Semantic, uint32_t _LocationDecorationOffset) : @@ -290,8 +292,6 @@ public: bool IsCompatibleWith(const SPIRVShaderResources& Resources)const; - //size_t GetHash()const; - const char* GetCombinedSamplerSuffix() const { return m_CombinedSamplerSuffix; } const char* GetShaderName() const { return m_ShaderName; } bool IsUsingCombinedSamplers() const { return m_CombinedSamplerSuffix != nullptr; } diff --git a/Graphics/GLSLTools/src/SPIRVShaderResources.cpp b/Graphics/GLSLTools/src/SPIRVShaderResources.cpp index 50bebf47..7289e9fd 100644 --- a/Graphics/GLSLTools/src/SPIRVShaderResources.cpp +++ b/Graphics/GLSLTools/src/SPIRVShaderResources.cpp @@ -52,7 +52,7 @@ static uint32_t GetDecorationOffset(const spirv_cross::Compiler& Compiler, const spirv_cross::Resource& Res, spv::Decoration Decoration) { - VERIFY(Compiler.has_decoration(Res.id, Decoration), "Res \'", Res.name, "\' has no requested decoration"); + VERIFY(Compiler.has_decoration(Res.id, Decoration), "Resource \'", Res.name, "\' has no requested decoration"); uint32_t offset = 0; auto declared = Compiler.get_binary_offset_for_decoration(Res.id, Decoration, offset); VERIFY(declared, "Requested decoration is not declared"); (void)declared; @@ -71,8 +71,9 @@ SPIRVShaderResourceAttribs::SPIRVShaderResourceAttribs(const spirv_cross::Compil BindingDecorationOffset (GetDecorationOffset(Compiler, Res, spv::Decoration::DecorationBinding)), DescriptorSetDecorationOffset(GetDecorationOffset(Compiler, Res, spv::Decoration::DecorationDescriptorSet)) { - VERIFY(_SepSmplrOrImgInd == SPIRVShaderResourceAttribs::InvalidSepSmplrOrImgInd || _Type == ResourceType::SeparateSampler || - _Type == ResourceType::SeparateImage, "Only separate images or separate samplers can be assinged valid SepSmplrOrImgInd value"); + VERIFY(_SepSmplrOrImgInd == SPIRVShaderResourceAttribs::InvalidSepSmplrOrImgInd || + (_Type == ResourceType::SeparateSampler || _Type == ResourceType::SeparateImage), + "Only separate images or separate samplers can be assinged valid SepSmplrOrImgInd value"); } @@ -170,9 +171,9 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, spirv_cross::ShaderResources resources = Compiler.get_shader_resources(); size_t ResourceNamesPoolSize = 0; - for(const auto &ub : resources.uniform_buffers) + for (const auto& ub : resources.uniform_buffers) ResourceNamesPoolSize += GetUBName(Compiler, ub, ParsedIRSource).length() + 1; - for(auto *pResType : + for (auto* pResType : { &resources.storage_buffers, &resources.storage_images, @@ -182,7 +183,7 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, &resources.separate_samplers }) { - for(const auto &res : *pResType) + for(const auto& res : *pResType) ResourceNamesPoolSize += res.name.length() + 1; } @@ -191,6 +192,7 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, ResourceNamesPoolSize += strlen(CombinedSamplerSuffix) + 1; } + VERIFY_EXPR(shaderDesc.Name != nullptr); ResourceNamesPoolSize += strlen(shaderDesc.Name) + 1; Uint32 NumShaderStageInputs = 0; @@ -246,10 +248,10 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, { Uint32 CurrUB = 0; - for (const auto &UB : resources.uniform_buffers) + for (const auto& UB : resources.uniform_buffers) { const auto& name = GetUBName(Compiler, UB, ParsedIRSource); - new (&GetUB(CurrUB++)) + new (&GetUB(CurrUB++)) SPIRVShaderResourceAttribs(Compiler, UB, m_ResourceNames.CopyString(name), @@ -260,7 +262,7 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, { Uint32 CurrSB = 0; - for (const auto &SB : resources.storage_buffers) + for (const auto& SB : resources.storage_buffers) { new (&GetSB(CurrSB++)) SPIRVShaderResourceAttribs(Compiler, @@ -273,13 +275,13 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, { Uint32 CurrSmplImg = 0; - for (const auto &SmplImg : resources.sampled_images) + for (const auto& SmplImg : resources.sampled_images) { const auto& type = Compiler.get_type(SmplImg.type_id); auto ResType = type.image.dim == spv::DimBuffer ? SPIRVShaderResourceAttribs::ResourceType::UniformTexelBuffer : SPIRVShaderResourceAttribs::ResourceType::SampledImage; - new (&GetSmpldImg(CurrSmplImg++)) + new (&GetSmpldImg(CurrSmplImg++)) SPIRVShaderResourceAttribs(Compiler, SmplImg, m_ResourceNames.CopyString(SmplImg.name), @@ -296,7 +298,7 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, auto ResType = type.image.dim == spv::DimBuffer ? SPIRVShaderResourceAttribs::ResourceType::StorageTexelBuffer : SPIRVShaderResourceAttribs::ResourceType::StorageImage; - new (&GetImg(CurrImg++)) + new (&GetImg(CurrImg++)) SPIRVShaderResourceAttribs(Compiler, Img, m_ResourceNames.CopyString(Img.name), @@ -386,7 +388,7 @@ SPIRVShaderResources::SPIRVShaderResources(IMemoryAllocator& Allocator, if (Compiler.has_decoration(Input.id, spv::Decoration::DecorationHlslSemanticGOOGLE)) { const auto& Semantic = Compiler.get_decoration_string(Input.id, spv::Decoration::DecorationHlslSemanticGOOGLE); - new (&GetShaderStageInputAttribs(CurrStageInput++)) + new (&GetShaderStageInputAttribs(CurrStageInput++)) SPIRVShaderStageInputAttribs(m_ResourceNames.CopyString(Semantic), GetDecorationOffset(Compiler, Input, spv::Decoration::DecorationLocation)); } } @@ -419,7 +421,7 @@ void SPIRVShaderResources::Initialize(IMemoryAllocator& Allocator, constexpr Uint32 MaxOffset = std::numeric_limits::max(); auto AdvanceOffset = [&CurrentOffset, MaxOffset](Uint32 NumResources) { - VERIFY(CurrentOffset <= MaxOffset, "Current offser (", CurrentOffset, ") exceeds max allowed value (", MaxOffset, ")"); (void)MaxOffset; + VERIFY(CurrentOffset <= MaxOffset, "Current offset (", CurrentOffset, ") exceeds max allowed value (", MaxOffset, ")"); (void)MaxOffset; auto Offset = static_cast(CurrentOffset); CurrentOffset += NumResources; return Offset; @@ -493,10 +495,10 @@ SPIRVShaderResources::~SPIRVShaderResources() std::string SPIRVShaderResources::DumpResources() { std::stringstream ss; - ss << "Resource counters (" << GetTotalResources() << " total):" << std::endl << "UBs: " << GetNumUBs() << "; SBs: " - << GetNumSBs() << "; Imgs: " << GetNumImgs() << "; Smpl Imgs: " << GetNumSmpldImgs() << "; ACs: " << GetNumACs() - << "; Sep Imgs: " << GetNumSepImgs() << "; Sep Smpls: " << GetNumSepSmplrs() << '.' << std::endl - << "Resources:"; + ss << "Shader '" << m_ShaderName << "' resource stats: total resources: " << GetTotalResources() << ":" << std::endl + << "UBs: " << GetNumUBs() << "; SBs: " << GetNumSBs() << "; Imgs: " << GetNumImgs() << "; Smpl Imgs: " << GetNumSmpldImgs() + << "; ACs: " << GetNumACs() << "; Sep Imgs: " << GetNumSepImgs() << "; Sep Smpls: " << GetNumSepSmplrs() << '.' << std::endl + << "Resources:"; Uint32 ResNum = 0; auto DumpResource = [&ss, &ResNum](const SPIRVShaderResourceAttribs& Res) @@ -521,7 +523,7 @@ std::string SPIRVShaderResources::DumpResources() }; ProcessResources( - [&](const SPIRVShaderResourceAttribs &UB, Uint32) + [&](const SPIRVShaderResourceAttribs& UB, Uint32) { VERIFY(UB.Type == SPIRVShaderResourceAttribs::ResourceType::UniformBuffer, "Unexpected resource type"); ss << std::endl << std::setw(3) << ResNum << " Uniform Buffer "; @@ -533,9 +535,9 @@ std::string SPIRVShaderResources::DumpResources() ss << std::endl << std::setw(3) << ResNum << " Storage Buffer "; DumpResource(SB); }, - [&](const SPIRVShaderResourceAttribs &Img, Uint32) + [&](const SPIRVShaderResourceAttribs& Img, Uint32) { - if(Img.Type == SPIRVShaderResourceAttribs::ResourceType::StorageImage) + if (Img.Type == SPIRVShaderResourceAttribs::ResourceType::StorageImage) ss << std::endl << std::setw(3) << ResNum << " Storage Image "; else if(Img.Type == SPIRVShaderResourceAttribs::ResourceType::StorageTexelBuffer) ss << std::endl << std::setw(3) << ResNum << " Storage Txl Buff"; @@ -543,7 +545,7 @@ std::string SPIRVShaderResources::DumpResources() UNEXPECTED("Unexpected resource type"); DumpResource(Img); }, - [&](const SPIRVShaderResourceAttribs &SmplImg, Uint32) + [&](const SPIRVShaderResourceAttribs& SmplImg, Uint32) { if (SmplImg.Type == SPIRVShaderResourceAttribs::ResourceType::SampledImage) ss << std::endl << std::setw(3) << ResNum << " Sampled Image "; @@ -553,19 +555,19 @@ std::string SPIRVShaderResources::DumpResources() UNEXPECTED("Unexpected resource type"); DumpResource(SmplImg); }, - [&](const SPIRVShaderResourceAttribs &AC, Uint32) + [&](const SPIRVShaderResourceAttribs& AC, Uint32) { VERIFY(AC.Type == SPIRVShaderResourceAttribs::ResourceType::AtomicCounter, "Unexpected resource type"); ss << std::endl << std::setw(3) << ResNum << " Atomic Cntr "; DumpResource(AC); }, - [&](const SPIRVShaderResourceAttribs &SepSmpl, Uint32) + [&](const SPIRVShaderResourceAttribs& SepSmpl, Uint32) { VERIFY(SepSmpl.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler, "Unexpected resource type"); ss << std::endl << std::setw(3) << ResNum << " Separate Smpl "; DumpResource(SepSmpl); }, - [&](const SPIRVShaderResourceAttribs &SepImg, Uint32) + [&](const SPIRVShaderResourceAttribs& SepImg, Uint32) { VERIFY(SepImg.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateImage, "Unexpected resource type"); ss << std::endl << std::setw(3) << ResNum << " Separate Img "; -- cgit v1.2.3 From a643ee949f206c51d76432410e164f4f9810cbb8 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sat, 2 Mar 2019 12:53:29 -0800 Subject: Some minor changes to ShaderResourceCacheVk --- .../include/ShaderResourceCacheVk.h | 15 +++++++------ .../src/ShaderResourceCacheVk.cpp | 26 +++++++++++----------- 2 files changed, 21 insertions(+), 20 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderResourceCacheVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderResourceCacheVk.h index d9d1c07f..21f97b04 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderResourceCacheVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderResourceCacheVk.h @@ -83,7 +83,7 @@ public: ~ShaderResourceCacheVk(); static size_t GetRequiredMemorySize(Uint32 NumSets, Uint32 SetSizes[]); - void InitializeSets(IMemoryAllocator &MemAllocator, Uint32 NumSets, Uint32 SetSizes[]); + void InitializeSets(IMemoryAllocator& MemAllocator, Uint32 NumSets, Uint32 SetSizes[]); void InitializeResources(Uint32 Set, Uint32 Offset, Uint32 ArraySize, SPIRVShaderResourceAttribs::ResourceType Type); // sizeof(Resource) == 16 (x64, msvc, Release) @@ -93,13 +93,14 @@ public: Type(_Type) {} - Resource(const Resource&) = delete; - Resource(Resource&&) = delete; + Resource (const Resource&) = delete; + Resource (Resource&&) = delete; Resource& operator = (const Resource&) = delete; Resource& operator = (Resource&&) = delete; - const SPIRVShaderResourceAttribs::ResourceType Type; - RefCntAutoPtr pObject; +/* 0 */ const SPIRVShaderResourceAttribs::ResourceType Type; +/*1-7*/ // Unused +/* 8 */ RefCntAutoPtr pObject; VkDescriptorBufferInfo GetUniformBufferDescriptorWriteInfo () const; VkDescriptorBufferInfo GetStorageBufferDescriptorWriteInfo () const; @@ -117,8 +118,8 @@ public: m_pResources (pResources) {} - DescriptorSet(const DescriptorSet&) = delete; - DescriptorSet(DescriptorSet&&) = delete; + DescriptorSet (const DescriptorSet&) = delete; + DescriptorSet (DescriptorSet&&) = delete; DescriptorSet& operator = (const DescriptorSet&) = delete; DescriptorSet& operator = (DescriptorSet&&) = delete; diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceCacheVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceCacheVk.cpp index 85f835f8..47d098f9 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceCacheVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceCacheVk.cpp @@ -38,7 +38,7 @@ namespace Diligent size_t ShaderResourceCacheVk::GetRequiredMemorySize(Uint32 NumSets, Uint32 SetSizes[]) { Uint32 TotalResources = 0; - for(Uint32 t=0; t < NumSets; ++t) + for (Uint32 t=0; t < NumSets; ++t) TotalResources += SetSizes[t]; auto MemorySize = NumSets * sizeof(DescriptorSet) + TotalResources * sizeof(Resource); return MemorySize; @@ -60,15 +60,15 @@ void ShaderResourceCacheVk::InitializeSets(IMemoryAllocator& MemAllocator, Uint3 m_pAllocator = &MemAllocator; m_NumSets = NumSets; m_TotalResources = 0; - for(Uint32 t=0; t < NumSets; ++t) + for (Uint32 t=0; t < NumSets; ++t) m_TotalResources += SetSizes[t]; auto MemorySize = NumSets * sizeof(DescriptorSet) + m_TotalResources * sizeof(Resource); VERIFY_EXPR(MemorySize == GetRequiredMemorySize(NumSets, SetSizes)); if (MemorySize > 0) { m_pMemory = ALLOCATE( *m_pAllocator, "Memory for shader resource cache data", MemorySize); - auto *pSets = reinterpret_cast(m_pMemory); - auto *pCurrResPtr = reinterpret_cast(pSets + m_NumSets); + auto* pSets = reinterpret_cast(m_pMemory); + auto* pCurrResPtr = reinterpret_cast(pSets + m_NumSets); for (Uint32 t = 0; t < NumSets; ++t) { new(&GetDescriptorSet(t)) DescriptorSet(SetSizes[t], SetSizes[t] > 0 ? pCurrResPtr : nullptr); @@ -80,7 +80,7 @@ void ShaderResourceCacheVk::InitializeSets(IMemoryAllocator& MemAllocator, Uint3 void ShaderResourceCacheVk::InitializeResources(Uint32 Set, Uint32 Offset, Uint32 ArraySize, SPIRVShaderResourceAttribs::ResourceType Type) { - auto &DescrSet = GetDescriptorSet(Set); + auto& DescrSet = GetDescriptorSet(Set); for (Uint32 res = 0; res < ArraySize; ++res) new(&DescrSet.GetResource(Offset + res)) Resource{Type}; } @@ -89,8 +89,8 @@ ShaderResourceCacheVk::~ShaderResourceCacheVk() { if (m_pMemory) { - auto *pResources = GetFirstResourcePtr(); - for(Uint32 res=0; res < m_TotalResources; ++res) + auto* pResources = GetFirstResourcePtr(); + for (Uint32 res=0; res < m_TotalResources; ++res) pResources[res].~Resource(); for (Uint32 t = 0; t < m_NumSets; ++t) GetDescriptorSet(t).~DescriptorSet(); @@ -282,7 +282,7 @@ VkDescriptorBufferInfo ShaderResourceCacheVk::Resource::GetUniformBufferDescript // If descriptorType is VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER or VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, the offset member // of each element of pBufferInfo must be a multiple of VkPhysicalDeviceLimits::minUniformBufferOffsetAlignment (13.2.4) DescrBuffInfo.offset = 0; - DescrBuffInfo.range = pBuffVk->GetDesc().uiSizeInBytes; + DescrBuffInfo.range = pBuffVk->GetDesc().uiSizeInBytes; return DescrBuffInfo; } @@ -330,7 +330,7 @@ VkDescriptorImageInfo ShaderResourceCacheVk::Resource::GetImageDescriptorWriteIn { // Immutable samplers are permanently bound into the set layout; later binding a sampler // into an immutable sampler slot in a descriptor set is not allowed (13.2.1) - auto *pSamplerVk = ValidatedCast(pTexViewVk->GetSampler()); + auto* pSamplerVk = ValidatedCast(pTexViewVk->GetSampler()); if (pSamplerVk != nullptr) { // If descriptorType is VK_DESCRIPTOR_TYPE_SAMPLER or VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, @@ -386,8 +386,8 @@ VkDescriptorImageInfo ShaderResourceCacheVk::Resource::GetSamplerDescriptorWrite auto* pSamplerVk = pObject.RawPtr(); VkDescriptorImageInfo DescrImgInfo; // For VK_DESCRIPTOR_TYPE_SAMPLER, only the sample member of each element of VkWriteDescriptorSet::pImageInfo is accessed (13.2.4) - DescrImgInfo.sampler = pSamplerVk->GetVkSampler(); - DescrImgInfo.imageView = VK_NULL_HANDLE; + DescrImgInfo.sampler = pSamplerVk->GetVkSampler(); + DescrImgInfo.imageView = VK_NULL_HANDLE; DescrImgInfo.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED; return DescrImgInfo; } @@ -406,11 +406,11 @@ Uint32 ShaderResourceCacheVk::GetDynamicBufferOffsets(DeviceContextVkImpl *pCtxV // In each descriptor set, all uniform buffers for every shader stage come first, // followed by all storage buffers for every shader stage, followed by all other resources Uint32 OffsetInd = 0; - for(Uint32 set=0; set < m_NumSets; ++set) + for (Uint32 set=0; set < m_NumSets; ++set) { const auto& DescrSet = GetDescriptorSet(set); Uint32 res = 0; - while(res < DescrSet.GetSize()) + while (res < DescrSet.GetSize()) { const auto& Res = DescrSet.GetResource(res); if (Res.Type != SPIRVShaderResourceAttribs::ResourceType::UniformBuffer) -- cgit v1.2.3 From 876034c5e736200d471057b8cf555ded566345fa Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sat, 2 Mar 2019 13:33:32 -0800 Subject: Updated ShaderVariableVk: not creating variables for immutable samplers + code cleanup --- .../include/ShaderVariableVk.h | 14 ++-- .../GraphicsEngineVulkan/src/ShaderVariableVk.cpp | 83 ++++++++++++---------- 2 files changed, 51 insertions(+), 46 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h index 5f7a0628..bb555881 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h @@ -30,7 +30,7 @@ // * ShaderVariableManagerVk keeps list of variables of specific types // * Every ShaderVariableVkImpl references VkResource from ShaderResourceLayoutVk // * ShaderVariableManagerVk keeps pointer to ShaderResourceCacheVk -// * ShaderVariableManagerVk is used by ShaderVkImpl to manage static resources and by +// * ShaderVariableManagerVk is used by PipelineStateVkImpl to manage static resources and by // ShaderResourceBindingVkImpl to manage mutable and dynamic resources // // __________________________ __________________________________________________________________________ @@ -83,7 +83,7 @@ public: ShaderVariableVkImpl* GetVariable(const Char* Name); ShaderVariableVkImpl* GetVariable(Uint32 Index); - void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags); + void BindResources(IResourceMapping* pResourceMapping, Uint32 Flags); static size_t GetRequiredMemorySize(const ShaderResourceLayoutVk& Layout, const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, @@ -98,10 +98,10 @@ private: Uint32 GetVariableIndex(const ShaderVariableVkImpl& Variable); IObject& m_Owner; - // Variable mgr is owned by either Shader object (in which case m_pResourceLayout points to - // static resource layout owned by the same shader object), or by SRB object (in which case + // Variable mgr is owned by either Pipeline state object (in which case m_pResourceLayout points to + // static resource layout owned by the same PSO object), or by SRB object (in which case // m_pResourceLayout points to corresponding layout in pipeline state). Since SRB keeps strong - // reference to PSO, the layout is guaranteed be alive while SRB is alive + // reference to PSO, the layout is guaranteed to be alive while SRB is alive const ShaderResourceLayoutVk* m_pResourceLayout= nullptr; ShaderResourceCacheVk* m_pResourceCache = nullptr; @@ -147,7 +147,7 @@ public: 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; @@ -165,7 +165,7 @@ public: return m_Resource.GetVariableType(); } - virtual void Set(IDeviceObject *pObject)override final + virtual void Set(IDeviceObject* pObject)override final { VERIFY_EXPR(m_ParentManager.m_pResourceCache != nullptr); m_Resource.BindResource(pObject, 0, *m_ParentManager.m_pResourceCache); diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp index 22acaf5c..6698dd53 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp @@ -29,42 +29,43 @@ namespace Diligent { -size_t ShaderVariableManagerVk::GetRequiredMemorySize(const ShaderResourceLayoutVk& Layout, +size_t ShaderVariableManagerVk::GetRequiredMemorySize(const ShaderResourceLayoutVk& Layout, const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - Uint32& NumVariables) + Uint32 NumAllowedTypes, + Uint32& NumVariables) { 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)) + const Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); + const bool UsingSeparateSamplers = Layout.IsUsingSeparateSamplers(); + 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)) { auto NumResources = Layout.GetResourceCount(VarType); - if (Layout.IsUsingSeparateSamplers()) - NumVariables += NumResources; - else + for (Uint32 r=0; r < NumResources; ++r) { - // When using HLSL-style combined image samplers, we need to skip separate samplers - for( Uint32 r=0; r < NumResources; ++r ) - { - const auto& SrcRes = Layout.GetResource(VarType, r); - if (SrcRes.SpirvAttribs.Type != SPIRVShaderResourceAttribs::ResourceType::SeparateSampler) - ++NumVariables; - } + const auto& SrcRes = Layout.GetResource(VarType, r); + + // When using HLSL-style combined image samplers, we need to skip separate samplers. + // Also always skip immutable separate samplers. + if (SrcRes.SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler && + (!UsingSeparateSamplers || SrcRes.IsImmutableSamplerAssigned()) ) + continue; + + ++NumVariables; } } } - return NumVariables*sizeof(ShaderVariableVkImpl); + return NumVariables * sizeof(ShaderVariableVkImpl); } // Creates shader variable for every resource from SrcLayout whose type is one AllowedVarTypes -void ShaderVariableManagerVk::Initialize(const ShaderResourceLayoutVk& SrcLayout, - IMemoryAllocator& Allocator, +void ShaderVariableManagerVk::Initialize(const ShaderResourceLayoutVk& SrcLayout, + IMemoryAllocator& Allocator, const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - ShaderResourceCacheVk& ResourceCache) + Uint32 NumAllowedTypes, + ShaderResourceCacheVk& ResourceCache) { m_pResourceLayout = &SrcLayout; m_pResourceCache = &ResourceCache; @@ -79,23 +80,26 @@ void ShaderVariableManagerVk::Initialize(const ShaderResourceLayoutVk& SrcLayout if(m_NumVariables == 0) return; - auto *pRawMem = ALLOCATE(Allocator, "Raw memory buffer for shader variables", MemSize); + auto* pRawMem = ALLOCATE(Allocator, "Raw memory buffer for shader variables", MemSize); 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)) + const bool UsingSeparateSamplers = SrcLayout.IsUsingSeparateSamplers(); + 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.GetResourceCount(VarType); - for( Uint32 r=0; r < NumResources; ++r ) + for (Uint32 r=0; r < NumResources; ++r) { const auto& SrcRes = SrcLayout.GetResource(VarType, r); - if (!SrcLayout.IsUsingSeparateSamplers() && SrcRes.SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler) + // Skip separate samplers when using combined HLSL-style image samplers. Also always skip immutable separate samplers. + if (SrcRes.SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler && + (!UsingSeparateSamplers || SrcRes.IsImmutableSamplerAssigned()) ) continue; - ::new (m_pVariables + VarInd) ShaderVariableVkImpl(*this, SrcRes ); + ::new (m_pVariables + VarInd) ShaderVariableVkImpl(*this, SrcRes); ++VarInd; } } @@ -111,9 +115,9 @@ void ShaderVariableManagerVk::Destroy(IMemoryAllocator &Allocator) { VERIFY(m_pDbgAllocator == &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].~ShaderVariableVkImpl(); Allocator.Free(m_pVariables); m_pVariables = nullptr; @@ -125,7 +129,7 @@ ShaderVariableVkImpl* ShaderVariableManagerVk::GetVariable(const Char* Name) ShaderVariableVkImpl* pVar = nullptr; 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 (strcmp(Res.SpirvAttribs.Name, Name) == 0) { @@ -168,11 +172,11 @@ Uint32 ShaderVariableManagerVk::GetVariableIndex(const ShaderVariableVkImpl& Var } } -void ShaderVariableManagerVk::BindResources( IResourceMapping* pResourceMapping, Uint32 Flags) +void ShaderVariableManagerVk::BindResources(IResourceMapping* pResourceMapping, Uint32 Flags) { VERIFY_EXPR(m_pResourceCache != nullptr); - if( !pResourceMapping ) + if (!pResourceMapping) { LOG_ERROR_MESSAGE( "Failed to bind resources: resource mapping is null" ); return; @@ -181,34 +185,35 @@ void ShaderVariableManagerVk::BindResources( IResourceMapping* pResourceMapping, 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; - // Skip immutable separate samplers - if (Res.SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler && Res.IsImmutableSamplerAssigned()) - continue; + // There should be no immutable separate samplers + VERIFY(Res.SpirvAttribs.Type != SPIRVShaderResourceAttribs::ResourceType::SeparateSampler || !Res.IsImmutableSamplerAssigned(), + "There must be no shader resource variables for immutable separate samplers"); if ( (Flags & (1 << Res.GetVariableType())) == 0 ) continue; for (Uint32 ArrInd = 0; ArrInd < Res.SpirvAttribs.ArraySize; ++ArrInd) { - if( (Flags & BIND_SHADER_RESOURCES_KEEP_EXISTING) && Res.IsBound(ArrInd, *m_pResourceCache) ) + if ( (Flags & BIND_SHADER_RESOURCES_KEEP_EXISTING) && Res.IsBound(ArrInd, *m_pResourceCache) ) continue; const auto* VarName = Res.SpirvAttribs.Name; RefCntAutoPtr pObj; pResourceMapping->GetResource( VarName, &pObj, ArrInd ); - if( pObj ) + if (pObj) { Res.BindResource(pObj, ArrInd, *m_pResourceCache); } else { - if( (Flags & BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED) && !Res.IsBound(ArrInd, *m_pResourceCache) ) - LOG_ERROR_MESSAGE( "Unable to bind resource to shader variable '", Res.SpirvAttribs.GetPrintName(ArrInd), "': resource is not found in the resource mapping" ); + if ( (Flags & BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED) && !Res.IsBound(ArrInd, *m_pResourceCache) ) + LOG_ERROR_MESSAGE( "Unable to bind resource to shader variable '", Res.SpirvAttribs.GetPrintName(ArrInd), "': resource is not found in the resource mapping. " + "Do not use BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED flag to suppress the message if this is not an issue." ); } } } -- cgit v1.2.3 From a32b0a27713a7e5414923a7b50f31bb6830e45e8 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sat, 2 Mar 2019 14:16:17 -0800 Subject: Updated ShaderVariableVk and ShaderResourceBindingVkImpl --- .../include/DescriptorPoolManager.h | 1 + .../include/ShaderResourceBindingVkImpl.h | 5 ++- .../include/ShaderResourceCacheVk.h | 9 +++-- .../include/ShaderVariableVk.h | 29 +++++++-------- .../src/PipelineStateVkImpl.cpp | 5 +-- .../src/ShaderResourceBindingVkImpl.cpp | 43 +++++++++++----------- .../GraphicsEngineVulkan/src/ShaderVariableVk.cpp | 35 +++++++++--------- 7 files changed, 63 insertions(+), 64 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/include/DescriptorPoolManager.h b/Graphics/GraphicsEngineVulkan/include/DescriptorPoolManager.h index 24c3e157..bcb0a919 100644 --- a/Graphics/GraphicsEngineVulkan/include/DescriptorPoolManager.h +++ b/Graphics/GraphicsEngineVulkan/include/DescriptorPoolManager.h @@ -41,6 +41,7 @@ class RenderDeviceVkImpl; // This class manages descriptor set allocation. // The class destructor calls DescriptorSetAllocator::FreeDescriptorSet() that moves // the set into the release queue. +// sizeof(DescriptorSetAllocation) == 32 (x64) class DescriptorSetAllocation { public: diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderResourceBindingVkImpl.h b/Graphics/GraphicsEngineVulkan/include/ShaderResourceBindingVkImpl.h index b3933747..5719a1e4 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderResourceBindingVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderResourceBindingVkImpl.h @@ -48,7 +48,7 @@ public: ShaderResourceBindingVkImpl(IReferenceCounters* pRefCounters, class PipelineStateVkImpl* pPSO, bool IsPSOInternal); ~ShaderResourceBindingVkImpl(); - virtual void QueryInterface( const Diligent::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 final; @@ -66,8 +66,9 @@ public: private: - ShaderResourceCacheVk m_ShaderResourceCache; + ShaderResourceCacheVk m_ShaderResourceCache; ShaderVariableManagerVk* m_pShaderVarMgrs = nullptr; + // Shader variable manager index in m_pShaderVarMgrs[] array for every shader stage Int8 m_ResourceLayoutIndex[6] = {-1, -1, -1, -1, -1, -1}; bool m_bStaticResourcesInitialized = false; diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderResourceCacheVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderResourceCacheVk.h index 21f97b04..0843939f 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderResourceCacheVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderResourceCacheVk.h @@ -109,7 +109,7 @@ public: VkDescriptorImageInfo GetSamplerDescriptorWriteInfo() const; }; - // sizeof(DescriptorSet) == 40 (x64, msvc, Release) + // sizeof(DescriptorSet) == 48 (x64, msvc, Release) class DescriptorSet { public: @@ -147,11 +147,12 @@ public: m_DescriptorSetAllocation = std::move(Allocation); } - const Uint32 m_NumResources = 0; +/* 0 */ const Uint32 m_NumResources = 0; private: - Resource* const m_pResources = nullptr; - DescriptorSetAllocation m_DescriptorSetAllocation; +/* 8 */ Resource* const m_pResources = nullptr; +/*16 */ DescriptorSetAllocation m_DescriptorSetAllocation; +/*48 */ // End of structure }; inline DescriptorSet& GetDescriptorSet(Uint32 Index) diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h index bb555881..74dac81d 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h @@ -68,17 +68,16 @@ class ShaderVariableVkImpl; class ShaderVariableManagerVk { public: - ShaderVariableManagerVk(IObject &Owner) : - m_Owner(Owner) - {} + ShaderVariableManagerVk(IObject& Owner, + const ShaderResourceLayoutVk& SrcLayout, + IMemoryAllocator& Allocator, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes, + ShaderResourceCacheVk& ResourceCache); + ~ShaderVariableManagerVk(); - void Initialize(const ShaderResourceLayoutVk& Layout, - IMemoryAllocator& Allocator, - const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - ShaderResourceCacheVk& ResourceCache); - void Destroy(IMemoryAllocator& Allocator); + void DestroyVariables(IMemoryAllocator& Allocator); ShaderVariableVkImpl* GetVariable(const Char* Name); ShaderVariableVkImpl* GetVariable(Uint32 Index); @@ -102,8 +101,8 @@ private: // static resource layout owned by the same PSO object), or by SRB object (in which case // m_pResourceLayout points to corresponding layout in pipeline state). Since SRB keeps strong // reference to PSO, the layout is guaranteed to be alive while SRB is alive - const ShaderResourceLayoutVk* m_pResourceLayout= nullptr; - ShaderResourceCacheVk* m_pResourceCache = nullptr; + const ShaderResourceLayoutVk& m_ResourceLayout; + ShaderResourceCacheVk& m_ResourceCache; // Memory is allocated through the allocator provided by the pipeline state. If allocation granularity > 1, fixed block // memory allocator is used. This ensures that all resources from different shader resource bindings reside in @@ -112,7 +111,7 @@ private: Uint32 m_NumVariables = 0; #ifdef _DEBUG - IMemoryAllocator* m_pDbgAllocator = nullptr; + IMemoryAllocator& m_DbgAllocator; #endif }; @@ -167,15 +166,13 @@ public: virtual void Set(IDeviceObject* pObject)override final { - VERIFY_EXPR(m_ParentManager.m_pResourceCache != nullptr); - m_Resource.BindResource(pObject, 0, *m_ParentManager.m_pResourceCache); + m_Resource.BindResource(pObject, 0, m_ParentManager.m_ResourceCache); } virtual void SetArray(IDeviceObject* const* ppObjects, Uint32 FirstElement, Uint32 NumElements)override final { - VERIFY_EXPR(m_ParentManager.m_pResourceCache != nullptr); for (Uint32 Elem = 0; Elem < NumElements; ++Elem) - m_Resource.BindResource(ppObjects[Elem], FirstElement + Elem, *m_ParentManager.m_pResourceCache); + m_Resource.BindResource(ppObjects[Elem], FirstElement + Elem, m_ParentManager.m_ResourceCache); } virtual Uint32 GetArraySize()const override final diff --git a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp index fe05a3bd..5cb00c8a 100644 --- a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp @@ -176,8 +176,7 @@ PipelineStateVkImpl :: PipelineStateVkImpl(IReferenceCounters* pRefCounters auto* pStaticResCache = new (m_StaticResCaches + s) ShaderResourceCacheVk(ShaderResourceCacheVk::DbgCacheContentType::StaticShaderResources); pStaticResLayout->InitializeStaticResourceLayout(ShaderResources[s], ShaderResLayoutAllocator, PipelineDesc.ResourceLayout, m_StaticResCaches[s]); - auto* pStaticVarMgr = new (m_StaticVarsMgrs + s) ShaderVariableManagerVk(*this); - pStaticVarMgr->Initialize(*pStaticResLayout, GetRawAllocator(), nullptr, 0, *pStaticResCache); + new (m_StaticVarsMgrs + s) ShaderVariableManagerVk(*this, *pStaticResLayout, GetRawAllocator(), nullptr, 0, *pStaticResCache); } ShaderResourceLayoutVk::Initialize(pDeviceVk, m_NumShaders, m_ShaderResourceLayouts, ShaderResources.data(), GetRawAllocator(), PipelineDesc.ResourceLayout, ShaderSPIRVs.data(), m_PipelineLayout); @@ -461,7 +460,7 @@ PipelineStateVkImpl::~PipelineStateVkImpl() for (Uint32 s=0; s < m_NumShaders; ++s) { m_StaticResCaches[s].~ShaderResourceCacheVk(); - m_StaticVarsMgrs[s].Destroy(GetRawAllocator()); + m_StaticVarsMgrs[s].DestroyVariables(GetRawAllocator()); m_StaticVarsMgrs[s].~ShaderVariableManagerVk(); } RawAllocator.Free(m_ShaderResourceLayouts); diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp index 3077a5dd..e7f0ac89 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp @@ -21,7 +21,6 @@ * of the possibility of such damages. */ -#include #include "pch.h" #include "ShaderResourceBindingVkImpl.h" #include "PipelineStateVkImpl.h" @@ -31,8 +30,8 @@ namespace Diligent { -ShaderResourceBindingVkImpl::ShaderResourceBindingVkImpl( IReferenceCounters* pRefCounters, PipelineStateVkImpl* pPSO, bool IsPSOInternal) : - TBase( pRefCounters, pPSO, IsPSOInternal ), +ShaderResourceBindingVkImpl::ShaderResourceBindingVkImpl(IReferenceCounters* pRefCounters, PipelineStateVkImpl* pPSO, bool IsPSOInternal) : + TBase (pRefCounters, pPSO, IsPSOInternal), m_ShaderResourceCache(ShaderResourceCacheVk::DbgCacheContentType::SRBResources) { auto* ppShaders = pPSO->GetShaders(); @@ -44,30 +43,27 @@ ShaderResourceBindingVkImpl::ShaderResourceBindingVkImpl( IReferenceCounters* pR auto& ResourceCacheDataAllocator = pPSO->GetSRBMemoryAllocator().GetResourceCacheDataAllocator(0); pPSO->GetPipelineLayout().InitResourceCache(pRenderDeviceVkImpl, m_ShaderResourceCache, ResourceCacheDataAllocator, pPSO->GetDesc().Name); - auto *pVarMgrsRawMem = ALLOCATE(GetRawAllocator(), "Raw memory for ShaderVariableManagerVk", m_NumShaders * sizeof(ShaderVariableManagerVk)); + auto* pVarMgrsRawMem = ALLOCATE(GetRawAllocator(), "Raw memory for ShaderVariableManagerVk", m_NumShaders * sizeof(ShaderVariableManagerVk)); m_pShaderVarMgrs = reinterpret_cast(pVarMgrsRawMem); for (Uint32 s = 0; s < m_NumShaders; ++s) { - auto *pShader = ppShaders[s]; + auto* pShader = ppShaders[s]; auto ShaderType = pShader->GetDesc().ShaderType; auto ShaderInd = GetShaderTypeIndex(ShaderType); - - auto &VarDataAllocator = pPSO->GetSRBMemoryAllocator().GetShaderVariableDataAllocator(s); + m_ResourceLayoutIndex[ShaderInd] = static_cast(s); + + auto& VarDataAllocator = pPSO->GetSRBMemoryAllocator().GetShaderVariableDataAllocator(s); - const auto &SrcLayout = pPSO->GetShaderResLayout(s); + const auto& SrcLayout = pPSO->GetShaderResLayout(s); // Use source layout to initialize resource memory in the cache SrcLayout.InitializeResourceMemoryInCache(m_ShaderResourceCache); // Create shader variable manager in place - new (m_pShaderVarMgrs + s) ShaderVariableManagerVk(*this); - // Initialize vars manager to reference mutable and dynamic variables // Note that the cache has space for all variable types - std::array VarTypes = {{SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}}; - m_pShaderVarMgrs[s].Initialize(SrcLayout, VarDataAllocator, VarTypes.data(), static_cast(VarTypes.size()), m_ShaderResourceCache); - - m_ResourceLayoutIndex[ShaderInd] = static_cast(s); + SHADER_RESOURCE_VARIABLE_TYPE VarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; + new (m_pShaderVarMgrs + s) ShaderVariableManagerVk(*this, SrcLayout, VarDataAllocator, VarTypes, _countof(VarTypes), m_ShaderResourceCache); } } @@ -76,8 +72,8 @@ ShaderResourceBindingVkImpl::~ShaderResourceBindingVkImpl() PipelineStateVkImpl* pPSO = ValidatedCast(m_pPSO); for(Uint32 s = 0; s < m_NumShaders; ++s) { - auto &VarDataAllocator = pPSO->GetSRBMemoryAllocator().GetShaderVariableDataAllocator(s); - m_pShaderVarMgrs[s].Destroy(VarDataAllocator); + auto& VarDataAllocator = pPSO->GetSRBMemoryAllocator().GetShaderVariableDataAllocator(s); + m_pShaderVarMgrs[s].DestroyVariables(VarDataAllocator); m_pShaderVarMgrs[s].~ShaderVariableManagerVk(); } @@ -101,13 +97,14 @@ void ShaderResourceBindingVkImpl::BindResources(Uint32 ShaderFlags, IResourceMap } } -IShaderResourceVariable* ShaderResourceBindingVkImpl::GetVariable(SHADER_TYPE ShaderType, const char *Name) +IShaderResourceVariable* ShaderResourceBindingVkImpl::GetVariable(SHADER_TYPE ShaderType, const char* Name) { auto ShaderInd = GetShaderTypeIndex(ShaderType); auto ResLayoutInd = m_ResourceLayoutIndex[ShaderInd]; if (ResLayoutInd < 0) { - LOG_WARNING_MESSAGE("Unable to find mutable/dynamic variable '", Name, "': shader stage ", GetShaderTypeLiteralName(ShaderType), " is inactive"); + LOG_WARNING_MESSAGE("Unable to find mutable/dynamic variable '", Name, "': shader stage ", GetShaderTypeLiteralName(ShaderType), + " is inactive in Pipeline State '", m_pPSO->GetDesc().Name, "'."); return nullptr; } return m_pShaderVarMgrs[ResLayoutInd].GetVariable(Name); @@ -119,7 +116,8 @@ Uint32 ShaderResourceBindingVkImpl::GetVariableCount(SHADER_TYPE ShaderType) con auto ResLayoutInd = m_ResourceLayoutIndex[ShaderInd]; if (ResLayoutInd < 0) { - LOG_WARNING_MESSAGE("Unable to get the number of mutable/dynamic variables: shader stage ", GetShaderTypeLiteralName(ShaderType), " is inactive"); + LOG_WARNING_MESSAGE("Unable to get the number of mutable/dynamic variables: shader stage ", GetShaderTypeLiteralName(ShaderType), + " is inactive in Pipeline State '", m_pPSO->GetDesc().Name, "'."); return 0; } return m_pShaderVarMgrs[ResLayoutInd].GetVariableCount(); @@ -131,7 +129,8 @@ IShaderResourceVariable* ShaderResourceBindingVkImpl::GetVariable(SHADER_TYPE Sh auto ResLayoutInd = m_ResourceLayoutIndex[ShaderInd]; if (ResLayoutInd < 0) { - LOG_ERROR("Unable to get mutable/dynamic variable at index ", Index, ": shader stage ", GetShaderTypeLiteralName(ShaderType), " is inactive"); + LOG_WARNING_MESSAGE("Unable to get mutable/dynamic variable at index ", Index, ": shader stage ", GetShaderTypeLiteralName(ShaderType), + " is inactive in Pipeline State '", m_pPSO->GetDesc().Name, "'."); return nullptr; } return m_pShaderVarMgrs[ResLayoutInd].GetVariable(Index); @@ -151,7 +150,9 @@ void ShaderResourceBindingVkImpl::InitializeStaticResources(const IPipelineState } else { - DEV_CHECK_ERR(pPipelineState->IsCompatibleWith(GetPipelineState()), "The pipeline state is not compatible with this SRB"); + DEV_CHECK_ERR(pPipelineState->IsCompatibleWith(GetPipelineState()), "The pipeline state '", pPipelineState->GetDesc().Name, "' " + "is not compatible with the pipeline state '", m_pPSO->GetDesc().Name, "' this SRB was created from and cannot be " + "used to initialize static resources."); } auto* pPSOVK = ValidatedCast(pPipelineState); diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp index 6698dd53..d005dc26 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp @@ -61,18 +61,19 @@ size_t ShaderVariableManagerVk::GetRequiredMemorySize(const ShaderResourceLayout } // Creates shader variable for every resource from SrcLayout whose type is one AllowedVarTypes -void ShaderVariableManagerVk::Initialize(const ShaderResourceLayoutVk& SrcLayout, - IMemoryAllocator& Allocator, - const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - ShaderResourceCacheVk& ResourceCache) -{ - m_pResourceLayout = &SrcLayout; - m_pResourceCache = &ResourceCache; +ShaderVariableManagerVk::ShaderVariableManagerVk(IObject& Owner, + const ShaderResourceLayoutVk& SrcLayout, + IMemoryAllocator& Allocator, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes, + ShaderResourceCacheVk& ResourceCache) : + m_Owner(Owner), + m_ResourceLayout(SrcLayout), + m_ResourceCache(ResourceCache) #ifdef _DEBUG - m_pDbgAllocator = &Allocator; + , m_DbgAllocator(Allocator) #endif - +{ const Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); VERIFY_EXPR(m_NumVariables == 0); auto MemSize = GetRequiredMemorySize(SrcLayout, AllowedVarTypes, NumAllowedTypes, m_NumVariables); @@ -108,12 +109,12 @@ void ShaderVariableManagerVk::Initialize(const ShaderResourceLayoutVk& ShaderVariableManagerVk::~ShaderVariableManagerVk() { - VERIFY(m_pVariables == nullptr, "Destroy() has not been called"); + VERIFY(m_pVariables == nullptr, "DestroyVariables() has not been called"); } -void ShaderVariableManagerVk::Destroy(IMemoryAllocator &Allocator) +void ShaderVariableManagerVk::DestroyVariables(IMemoryAllocator& Allocator) { - VERIFY(m_pDbgAllocator == &Allocator, "Incosistent alloctor"); + VERIFY(&m_DbgAllocator == &Allocator, "Incosistent alloctor"); if (m_pVariables != nullptr) { @@ -174,8 +175,6 @@ Uint32 ShaderVariableManagerVk::GetVariableIndex(const ShaderVariableVkImpl& Var void ShaderVariableManagerVk::BindResources(IResourceMapping* pResourceMapping, Uint32 Flags) { - VERIFY_EXPR(m_pResourceCache != nullptr); - if (!pResourceMapping) { LOG_ERROR_MESSAGE( "Failed to bind resources: resource mapping is null" ); @@ -199,7 +198,7 @@ void ShaderVariableManagerVk::BindResources(IResourceMapping* pResourceMapping, for (Uint32 ArrInd = 0; ArrInd < Res.SpirvAttribs.ArraySize; ++ArrInd) { - if ( (Flags & BIND_SHADER_RESOURCES_KEEP_EXISTING) && Res.IsBound(ArrInd, *m_pResourceCache) ) + if ( (Flags & BIND_SHADER_RESOURCES_KEEP_EXISTING) && Res.IsBound(ArrInd, m_ResourceCache) ) continue; const auto* VarName = Res.SpirvAttribs.Name; @@ -207,11 +206,11 @@ void ShaderVariableManagerVk::BindResources(IResourceMapping* pResourceMapping, pResourceMapping->GetResource( VarName, &pObj, ArrInd ); if (pObj) { - Res.BindResource(pObj, ArrInd, *m_pResourceCache); + Res.BindResource(pObj, ArrInd, m_ResourceCache); } else { - if ( (Flags & BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED) && !Res.IsBound(ArrInd, *m_pResourceCache) ) + if ( (Flags & BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED) && !Res.IsBound(ArrInd, m_ResourceCache) ) LOG_ERROR_MESSAGE( "Unable to bind resource to shader variable '", Res.SpirvAttribs.GetPrintName(ArrInd), "': resource is not found in the resource mapping. " "Do not use BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED flag to suppress the message if this is not an issue." ); } -- cgit v1.2.3 From abb107753cc44317a2793884c25f90c732bc9b52 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sat, 2 Mar 2019 14:38:36 -0800 Subject: Some cosmetic updates to PipelineStateVkImpl & ShaderVkImpl --- .../include/PipelineStateVkImpl.h | 10 ++--- .../GraphicsEngineVulkan/include/ShaderVkImpl.h | 2 +- .../src/PipelineStateVkImpl.cpp | 51 +++++++++++----------- .../src/ShaderResourceBindingVkImpl.cpp | 2 +- 4 files changed, 33 insertions(+), 32 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/include/PipelineStateVkImpl.h b/Graphics/GraphicsEngineVulkan/include/PipelineStateVkImpl.h index 07b0f414..d03066fe 100644 --- a/Graphics/GraphicsEngineVulkan/include/PipelineStateVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/PipelineStateVkImpl.h @@ -53,7 +53,7 @@ class PipelineStateVkImpl final : public PipelineStateBase; - PipelineStateVkImpl( IReferenceCounters* pRefCounters, RenderDeviceVkImpl* pDeviceVk, const PipelineStateDesc &PipelineDesc ); + PipelineStateVkImpl(IReferenceCounters* pRefCounters, RenderDeviceVkImpl* pDeviceVk, const PipelineStateDesc& PipelineDesc); ~PipelineStateVkImpl(); virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; @@ -62,9 +62,9 @@ public: virtual bool IsCompatibleWith(const IPipelineState* pPSO)const override final; - virtual VkRenderPass GetVkRenderPass()const override final{return m_RenderPass;} + virtual VkRenderPass GetVkRenderPass()const override final { return m_RenderPass; } - virtual VkPipeline GetVkPipeline()const override final { return m_Pipeline; } + virtual VkPipeline GetVkPipeline() const override final { return m_Pipeline; } virtual void BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags)override final; @@ -143,8 +143,8 @@ private: PipelineLayout m_PipelineLayout; Int8 m_ResourceLayoutIndex[6] = {-1, -1, -1, -1, -1, -1}; - bool m_HasStaticResources = false; - bool m_HasNonStaticResources = false; + bool m_HasStaticResources = false; + bool m_HasNonStaticResources = false; }; } diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderVkImpl.h b/Graphics/GraphicsEngineVulkan/include/ShaderVkImpl.h index c646820c..041c7011 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderVkImpl.h @@ -44,7 +44,7 @@ class ShaderVkImpl final : public ShaderBase public: using TShaderBase = ShaderBase; - ShaderVkImpl(IReferenceCounters* pRefCounters, RenderDeviceVkImpl* pRenderDeviceVk, const ShaderCreateInfo &CreationAttribs); + ShaderVkImpl(IReferenceCounters* pRefCounters, RenderDeviceVkImpl* pRenderDeviceVk, const ShaderCreateInfo& CreationAttribs); ~ShaderVkImpl(); IMPLEMENT_QUERY_INTERFACE_IN_PLACE(IID_ShaderVk, TShaderBase); diff --git a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp index 5cb00c8a..f28b2068 100644 --- a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp @@ -49,11 +49,12 @@ VkRenderPassCreateInfo PipelineStateVkImpl::GetRenderPassCreateInfo( // Prepare render pass create info (7.1) VkRenderPassCreateInfo RenderPassCI = {}; - RenderPassCI.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; - RenderPassCI.pNext = nullptr; - RenderPassCI.flags = 0; // reserved for future use + RenderPassCI.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + RenderPassCI.pNext = nullptr; + RenderPassCI.flags = 0; // reserved for future use RenderPassCI.attachmentCount = (DSVFormat != TEX_FORMAT_UNKNOWN ? 1 : 0) + NumRenderTargets; - uint32_t AttachmentInd = 0; + + uint32_t AttachmentInd = 0; VkSampleCountFlagBits SampleCountFlags = static_cast(1 << (SampleCount - 1)); VkAttachmentReference* pDepthAttachmentReference = nullptr; if (DSVFormat != TEX_FORMAT_UNKNOWN) @@ -86,12 +87,12 @@ VkRenderPassCreateInfo PipelineStateVkImpl::GetRenderPassCreateInfo( { auto& ColorAttachment = Attachments[AttachmentInd]; - ColorAttachment.flags = 0; // Allowed value VK_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT - ColorAttachment.format = TexFormatToVkFormat(RTVFormats[rt]); + ColorAttachment.flags = 0; // Allowed value VK_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT + ColorAttachment.format = TexFormatToVkFormat(RTVFormats[rt]); ColorAttachment.samples = SampleCountFlags; - ColorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; // previous contents of the image within the render area - // will be preserved. For attachments with a depth/stencil format, - // this uses the access type VK_ACCESS_COLOR_ATTACHMENT_READ_BIT. + ColorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; // previous contents of the image within the render area + // will be preserved. For attachments with a depth/stencil format, + // this uses the access type VK_ACCESS_COLOR_ATTACHMENT_READ_BIT. ColorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; // the contents generated during the render pass and within the render // area are written to memory. For attachments with a color format, // this uses the access type VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT. @@ -102,15 +103,15 @@ VkRenderPassCreateInfo PipelineStateVkImpl::GetRenderPassCreateInfo( auto& ColorAttachmentRef = AttachmentReferences[AttachmentInd]; ColorAttachmentRef.attachment = AttachmentInd; - ColorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + ColorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; } - RenderPassCI.pAttachments = Attachments.data(); - RenderPassCI.subpassCount = 1; - RenderPassCI.pSubpasses = &SubpassDesc; + RenderPassCI.pAttachments = Attachments.data(); + RenderPassCI.subpassCount = 1; + RenderPassCI.pSubpasses = &SubpassDesc; RenderPassCI.dependencyCount = 0; // the number of dependencies between pairs of subpasses, or zero indicating no dependencies. - RenderPassCI.pDependencies = nullptr; // an array of dependencyCount number of VkSubpassDependency structures describing - // dependencies between pairs of subpasses, or NULL if dependencyCount is zero. + RenderPassCI.pDependencies = nullptr; // an array of dependencyCount number of VkSubpassDependency structures describing + // dependencies between pairs of subpasses, or NULL if dependencyCount is zero. SubpassDesc.flags = 0; // All bits for this type are defined by extensions @@ -166,7 +167,7 @@ PipelineStateVkImpl :: PipelineStateVkImpl(IReferenceCounters* pRefCounters new (m_ShaderResourceLayouts + s) ShaderResourceLayoutVk(LogicalDevice); auto* pShaderVk = GetShader(s); ShaderResources[s] = pShaderVk->GetShaderResources(); - ShaderSPIRVs[s] = pShaderVk->GetSPIRV(); + ShaderSPIRVs[s] = pShaderVk->GetSPIRV(); const auto ShaderType = pShaderVk->GetDesc().ShaderType; const auto ShaderTypeInd = GetShaderTypeIndex(ShaderType); @@ -187,9 +188,9 @@ PipelineStateVkImpl :: PipelineStateVkImpl(IReferenceCounters* pRefCounters std::array ShaderVariableDataSizes = {}; for (Uint32 s = 0; s < m_NumShaders; ++s) { - std::array AllowedVarTypes = { {SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC} }; + const SHADER_RESOURCE_VARIABLE_TYPE AllowedVarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; Uint32 UnusedNumVars = 0; - ShaderVariableDataSizes[s] = ShaderVariableManagerVk::GetRequiredMemorySize(m_ShaderResourceLayouts[s], AllowedVarTypes.data(), static_cast(AllowedVarTypes.size()), UnusedNumVars); + ShaderVariableDataSizes[s] = ShaderVariableManagerVk::GetRequiredMemorySize(m_ShaderResourceLayouts[s], AllowedVarTypes, _countof(AllowedVarTypes), UnusedNumVars); } Uint32 NumSets = 0; @@ -246,7 +247,7 @@ PipelineStateVkImpl :: PipelineStateVkImpl(IReferenceCounters* pRefCounters m_ShaderModules[s] = LogicalDevice.CreateShaderModule(ShaderModuleCI, pShaderVk->GetDesc().Name); StageCI.module = m_ShaderModules[s]; - StageCI.pName = pShaderVk->GetEntryPoint(); + StageCI.pName = pShaderVk->GetEntryPoint(); StageCI.pSpecializationInfo = nullptr; } @@ -265,9 +266,9 @@ PipelineStateVkImpl :: PipelineStateVkImpl(IReferenceCounters* pRefCounters PipelineCI.flags = VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT; #endif PipelineCI.basePipelineHandle = VK_NULL_HANDLE; // a pipeline to derive from - PipelineCI.basePipelineIndex = 0; // an index into the pCreateInfos parameter to use as a pipeline to derive from + PipelineCI.basePipelineIndex = 0; // an index into the pCreateInfos parameter to use as a pipeline to derive from - PipelineCI.stage = ShaderStages[0]; + PipelineCI.stage = ShaderStages[0]; PipelineCI.layout = m_PipelineLayout.GetVkPipelineLayout(); m_Pipeline = LogicalDevice.CreateComputePipeline(PipelineCI, VK_NULL_HANDLE, m_Desc.Name); @@ -294,11 +295,11 @@ PipelineStateVkImpl :: PipelineStateVkImpl(IReferenceCounters* pRefCounters #endif PipelineCI.stageCount = m_NumShaders; - PipelineCI.pStages = ShaderStages.data(); - PipelineCI.layout = m_PipelineLayout.GetVkPipelineLayout(); + PipelineCI.pStages = ShaderStages.data(); + PipelineCI.layout = m_PipelineLayout.GetVkPipelineLayout(); VkPipelineVertexInputStateCreateInfo VertexInputStateCI = {}; - std::array BindingDescriptions; + std::array BindingDescriptions; std::array AttributeDescription; InputLayoutDesc_To_VkVertexInputStateCI(GraphicsPipeline.InputLayout, VertexInputStateCI, BindingDescriptions, AttributeDescription); PipelineCI.pVertexInputState = &VertexInputStateCI; @@ -487,7 +488,7 @@ bool PipelineStateVkImpl::IsCompatibleWith(const IPipelineState *pPSO)const if (pPSO == this) return true; - const PipelineStateVkImpl *pPSOVk = ValidatedCast(pPSO); + const PipelineStateVkImpl* pPSOVk = ValidatedCast(pPSO); if (m_ShaderResourceLayoutHash != pPSOVk->m_ShaderResourceLayoutHash) return false; diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp index e7f0ac89..54b09c69 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp @@ -62,7 +62,7 @@ ShaderResourceBindingVkImpl::ShaderResourceBindingVkImpl(IReferenceCounters* pRe // Create shader variable manager in place // Initialize vars manager to reference mutable and dynamic variables // Note that the cache has space for all variable types - SHADER_RESOURCE_VARIABLE_TYPE VarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; + const SHADER_RESOURCE_VARIABLE_TYPE VarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; new (m_pShaderVarMgrs + s) ShaderVariableManagerVk(*this, SrcLayout, VarDataAllocator, VarTypes, _countof(VarTypes), m_ShaderResourceCache); } } -- cgit v1.2.3 From 11c5047df020d1dc814a3e252e0bd981e1b12218 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sat, 2 Mar 2019 19:32:10 -0800 Subject: Added debug checks to verify that all resources in ShaderResouceCacheVk have been initialized --- .../GraphicsEngineVulkan/include/PipelineLayout.h | 4 +-- .../include/ShaderResourceCacheVk.h | 6 ++++- .../include/ShaderResourceLayoutVk.h | 17 +++++++------ .../GraphicsEngineVulkan/src/PipelineLayout.cpp | 16 ++++++------ .../src/ShaderResourceBindingVkImpl.cpp | 4 +++ .../src/ShaderResourceCacheVk.cpp | 26 +++++++++++++++++-- .../src/ShaderResourceLayoutVk.cpp | 29 +++++++++++++--------- 7 files changed, 69 insertions(+), 33 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/include/PipelineLayout.h b/Graphics/GraphicsEngineVulkan/include/PipelineLayout.h index a875cb90..a5aec374 100644 --- a/Graphics/GraphicsEngineVulkan/include/PipelineLayout.h +++ b/Graphics/GraphicsEngineVulkan/include/PipelineLayout.h @@ -59,7 +59,7 @@ public: void AllocateResourceSlot(const SPIRVShaderResourceAttribs& ResAttribs, SHADER_RESOURCE_VARIABLE_TYPE VariableType, - VkSampler vkStaticSampler, + VkSampler vkImmutableSampler, SHADER_TYPE ShaderType, Uint32& DescriptorSet, Uint32& Binding, @@ -189,7 +189,7 @@ private: void AllocateResourceSlot(const SPIRVShaderResourceAttribs& ResAttribs, SHADER_RESOURCE_VARIABLE_TYPE VariableType, - VkSampler vkStaticSampler, + VkSampler vkImmutableSampler, SHADER_TYPE ShaderType, Uint32& DescriptorSet, Uint32& Binding, diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderResourceCacheVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderResourceCacheVk.h index 0843939f..1bedbcac 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderResourceCacheVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderResourceCacheVk.h @@ -49,6 +49,7 @@ // Descriptor set for static and mutable resources is assigned during cache initialization // Descriptor set for dynamic resources is assigned at every draw call +#include #include "DescriptorPoolManager.h" #include "SPIRVShaderResources.h" @@ -171,6 +172,7 @@ public: #ifdef _DEBUG // Only for debug purposes: indicates what types of resources are stored in the cache DbgCacheContentType DbgGetContentType()const{return m_DbgContentType;} + void DbgVerifyResourceInitialization()const; #endif template @@ -192,7 +194,9 @@ private: #ifdef _DEBUG // Only for debug purposes: indicates what types of resources are stored in the cache - const DbgCacheContentType m_DbgContentType; + const DbgCacheContentType m_DbgContentType; + // Debug array that stores flags indicating if resources in the cache have been initialized + std::vector> m_DbgInitializedResources; #endif }; diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h index b9f0ea10..a33f9841 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h @@ -107,7 +107,7 @@ namespace Diligent { /// Diligent::ShaderResourceLayoutVk class -// sizeof(ShaderResourceLayoutVk)==56 (MS compiler, x64) - TODO: verify +// sizeof(ShaderResourceLayoutVk)==56 (MS compiler, x64) class ShaderResourceLayoutVk { public: @@ -338,15 +338,16 @@ private: return reinterpret_cast(ResourceMemoryEnd)[n]; } - const VulkanUtilities::VulkanLogicalDevice& m_LogicalDevice; - std::unique_ptr > m_ResourceBuffer; +/* 0 */ const VulkanUtilities::VulkanLogicalDevice& m_LogicalDevice; +/* 8 */ std::unique_ptr > m_ResourceBuffer; - // We must use shared_ptr to reference ShaderResources instance, because - // there may be multiple objects referencing the same set of resources - std::shared_ptr m_pResources; + // We must use shared_ptr to reference ShaderResources instance, because + // there may be multiple objects referencing the same set of resources +/*24 */ std::shared_ptr m_pResources; - std::array m_NumResources = {}; - Uint32 m_NumImmutableSamplers = 0; +/*40 */ std::array m_NumResources = {}; +/*48 */ Uint32 m_NumImmutableSamplers = 0; +/*56*/ // End of class }; } diff --git a/Graphics/GraphicsEngineVulkan/src/PipelineLayout.cpp b/Graphics/GraphicsEngineVulkan/src/PipelineLayout.cpp index ef7fd8ec..d8383418 100644 --- a/Graphics/GraphicsEngineVulkan/src/PipelineLayout.cpp +++ b/Graphics/GraphicsEngineVulkan/src/PipelineLayout.cpp @@ -316,7 +316,7 @@ size_t PipelineLayout::DescriptorSetLayoutManager::GetHash()const void PipelineLayout::DescriptorSetLayoutManager::AllocateResourceSlot(const SPIRVShaderResourceAttribs& ResAttribs, SHADER_RESOURCE_VARIABLE_TYPE VariableType, - VkSampler vkStaticSampler, + VkSampler vkImmutableSampler, SHADER_TYPE ShaderType, Uint32& DescriptorSet, Uint32& Binding, @@ -336,15 +336,15 @@ void PipelineLayout::DescriptorSetLayoutManager::AllocateResourceSlot(const SPIR VkBinding.descriptorCount = ResAttribs.ArraySize; // There are no limitations on what combinations of stages can use a descriptor binding (13.2.1) VkBinding.stageFlags = ShaderTypeToVkShaderStageFlagBit(ShaderType); - if (vkStaticSampler != VK_NULL_HANDLE) + if (vkImmutableSampler != VK_NULL_HANDLE) { // If descriptorType is VK_DESCRIPTOR_TYPE_SAMPLER or VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, and // descriptorCount is not 0 and pImmutableSamplers is not NULL, pImmutableSamplers must be a valid pointer // to an array of descriptorCount valid VkSampler handles (13.2.1) - auto *pStaticSamplers = reinterpret_cast(ALLOCATE(m_MemAllocator, "Memory buffer for immutable samplers", sizeof(VkSampler) * VkBinding.descriptorCount)); + auto *pImmutableSamplers = reinterpret_cast(ALLOCATE(m_MemAllocator, "Memory buffer for immutable samplers", sizeof(VkSampler) * VkBinding.descriptorCount)); for(uint32_t s=0; s < VkBinding.descriptorCount; ++s) - pStaticSamplers[s] = vkStaticSampler; - VkBinding.pImmutableSamplers = pStaticSamplers; + pImmutableSamplers[s] = vkImmutableSampler; + VkBinding.pImmutableSamplers = pImmutableSamplers; } else VkBinding.pImmutableSamplers = nullptr; @@ -366,7 +366,7 @@ void PipelineLayout::Release(RenderDeviceVkImpl *pDeviceVkImpl, Uint64 CommandQu void PipelineLayout::AllocateResourceSlot(const SPIRVShaderResourceAttribs& ResAttribs, SHADER_RESOURCE_VARIABLE_TYPE VariableType, - VkSampler vkStaticSampler, + VkSampler vkImmutableSampler, SHADER_TYPE ShaderType, Uint32& DescriptorSet, // Output parameter Uint32& Binding, // Output parameter @@ -374,9 +374,9 @@ void PipelineLayout::AllocateResourceSlot(const SPIRVShaderResourceAttribs& ResA std::vector& SPIRV) { VERIFY( (ResAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SampledImage || - ResAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler) || vkStaticSampler == VK_NULL_HANDLE, + ResAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler) || vkImmutableSampler == VK_NULL_HANDLE, "Immutable sampler should only be specified for combined image samplers or separate samplers"); - m_LayoutMgr.AllocateResourceSlot(ResAttribs, VariableType,vkStaticSampler, ShaderType, DescriptorSet, Binding, OffsetInCache); + m_LayoutMgr.AllocateResourceSlot(ResAttribs, VariableType ,vkImmutableSampler, ShaderType, DescriptorSet, Binding, OffsetInCache); SPIRV[ResAttribs.BindingDecorationOffset] = Binding; SPIRV[ResAttribs.DescriptorSetDecorationOffset] = DescriptorSet; } diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp index 54b09c69..0193bb55 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceBindingVkImpl.cpp @@ -65,6 +65,10 @@ ShaderResourceBindingVkImpl::ShaderResourceBindingVkImpl(IReferenceCounters* pRe const SHADER_RESOURCE_VARIABLE_TYPE VarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; new (m_pShaderVarMgrs + s) ShaderVariableManagerVk(*this, SrcLayout, VarDataAllocator, VarTypes, _countof(VarTypes), m_ShaderResourceCache); } +#ifdef _DEBUG + m_ShaderResourceCache.DbgVerifyResourceInitialization(); +#endif + } ShaderResourceBindingVkImpl::~ShaderResourceBindingVkImpl() diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceCacheVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceCacheVk.cpp index 47d098f9..2bfa922e 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceCacheVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceCacheVk.cpp @@ -57,13 +57,16 @@ void ShaderResourceCacheVk::InitializeSets(IMemoryAllocator& MemAllocator, Uint3 // Ns = m_NumSets VERIFY(m_pAllocator == nullptr && m_pMemory == nullptr, "Cache already initialized"); - m_pAllocator = &MemAllocator; - m_NumSets = NumSets; + m_pAllocator = &MemAllocator; + m_NumSets = NumSets; m_TotalResources = 0; for (Uint32 t=0; t < NumSets; ++t) m_TotalResources += SetSizes[t]; auto MemorySize = NumSets * sizeof(DescriptorSet) + m_TotalResources * sizeof(Resource); VERIFY_EXPR(MemorySize == GetRequiredMemorySize(NumSets, SetSizes)); +#ifdef _DEBUG + m_DbgInitializedResources.resize(m_NumSets); +#endif if (MemorySize > 0) { m_pMemory = ALLOCATE( *m_pAllocator, "Memory for shader resource cache data", MemorySize); @@ -73,6 +76,9 @@ void ShaderResourceCacheVk::InitializeSets(IMemoryAllocator& MemAllocator, Uint3 { new(&GetDescriptorSet(t)) DescriptorSet(SetSizes[t], SetSizes[t] > 0 ? pCurrResPtr : nullptr); pCurrResPtr += SetSizes[t]; +#ifdef _DEBUG + m_DbgInitializedResources[t].resize(SetSizes[t]); +#endif } VERIFY_EXPR((char*)pCurrResPtr == (char*)m_pMemory + MemorySize); } @@ -82,9 +88,25 @@ void ShaderResourceCacheVk::InitializeResources(Uint32 Set, Uint32 Offset, Uint3 { auto& DescrSet = GetDescriptorSet(Set); for (Uint32 res = 0; res < ArraySize; ++res) + { new(&DescrSet.GetResource(Offset + res)) Resource{Type}; +#ifdef _DEBUG + m_DbgInitializedResources[Set][Offset + res] = true; +#endif + } } +#ifdef _DEBUG +void ShaderResourceCacheVk::DbgVerifyResourceInitialization()const +{ + for (const auto &SetFlags : m_DbgInitializedResources) + { + for (auto ResInitialized : SetFlags) + VERIFY(ResInitialized, "Not all resources in the cache have been initialized. This is a bug."); + } +} +#endif + ShaderResourceCacheVk::~ShaderResourceCacheVk() { if (m_pMemory) diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp index bc6c0a54..3e1aba42 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp @@ -93,9 +93,8 @@ static SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE ShaderResourceLayoutVk::~ShaderResourceLayoutVk() { - auto* Resources = reinterpret_cast(m_ResourceBuffer.get()); for (Uint32 r=0; r < GetTotalResourceCount(); ++r) - Resources[r].~VkResource(); + GetResource(r).~VkResource(); for(Uint32 s=0; s < m_NumImmutableSamplers; ++s) GetImmutableSampler(s).~ImmutableSamplerPtrType(); @@ -116,14 +115,17 @@ void ShaderResourceLayoutVk::AllocateMemory(std::shared_ptrGetShaderType(); const auto* CombinedSamplerSuffix = m_pResources->GetCombinedSamplerSuffix(); - // Count number of resources to allocate all needed memory + // Count the number of resources to allocate all needed memory m_pResources->ProcessResources( [&](const SPIRVShaderResourceAttribs& ResAttribs, Uint32) { auto VarType = GetShaderVariableType(ShaderType, ResAttribs, ResourceLayoutDesc, CombinedSamplerSuffix); if (IsAllowedType(VarType, AllowedTypeBits)) { - VERIFY( Uint32{m_NumResources[VarType]} + 1 <= Uint32{std::numeric_limits::max()}, "Number of resources exceeds max representable value"); + // For immutable separate samplers we still allocate VkResource instances, but they are never used + // or exposed to the app + + VERIFY( Uint32{m_NumResources[VarType]} + 1 <= Uint32{std::numeric_limits::max()}, "Number of resources exceeds maximum representable value"); ++m_NumResources[VarType]; } } @@ -134,11 +136,11 @@ void ShaderResourceLayoutVk::AllocateMemory(std::shared_ptr::max()}, "Total number of resources exceeds Uint16 max representable value" ); + VERIFY(TotalResources <= Uint32{std::numeric_limits::max()}, "Total number of resources exceeds Uint16 maximum representable value" ); m_NumResources[SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES] = static_cast(TotalResources); m_NumImmutableSamplers = 0; - for(Uint32 s=0; s < ResourceLayoutDesc.NumStaticSamplers; ++s) + for (Uint32 s=0; s < ResourceLayoutDesc.NumStaticSamplers; ++s) { const auto& StSamDesc = ResourceLayoutDesc.StaticSamplers[s]; if ((StSamDesc.ShaderStages & ShaderType) != 0) @@ -152,7 +154,7 @@ void ShaderResourceLayoutVk::AllocateMemory(std::shared_ptr >(pRawMem, Allocator); - for(Uint32 s=0; s < m_NumImmutableSamplers; ++s) + for (Uint32 s=0; s < m_NumImmutableSamplers; ++s) { // We need to initialize immutable samplers auto& UninitializedImmutableSampler = GetImmutableSampler(s); @@ -189,10 +191,10 @@ void ShaderResourceLayoutVk::InitializeStaticResourceLayout(std::shared_ptr::max(), "Descriptor set (", DescriptorSet, ") excceeds max representable value"); - VERIFY(Binding <= std::numeric_limits::max(), "Binding (", Binding, ") excceeds max representable value"); + VERIFY(DescriptorSet <= std::numeric_limits::max(), "Descriptor set (", DescriptorSet, ") excceeds maximum representable value"); + VERIFY(Binding <= std::numeric_limits ::max(), "Binding (", Binding, ") excceeds maximum representable value"); #ifdef _DEBUG // Verify that bindings and cache offsets monotonically increase in every descriptor set @@ -904,7 +909,7 @@ void ShaderResourceLayoutVk::InitializeStaticResources(const ShaderResourceLayou auto DstOffset = DstRes.CacheOffset + ArrInd; IDeviceObject* pCachedResource = DstResourceCache.GetDescriptorSet(DstRes.DescriptorSet).GetResource(DstOffset).pObject; - if(pCachedResource != pObject) + if (pCachedResource != pObject) { VERIFY(pCachedResource == nullptr, "Static resource has already been initialized, and the resource to be assigned from the shader does not match previously assigned resource"); DstRes.BindResource(pObject, ArrInd, DstResourceCache); -- cgit v1.2.3 From e4683811e233259f49552b77f1f037c475551815 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sat, 2 Mar 2019 21:33:11 -0800 Subject: A bunch of updates to ShaderResourceLayoutVk --- .../include/ShaderResourceLayoutVk.h | 6 +- .../src/ShaderResourceLayoutVk.cpp | 171 +++++++++++---------- 2 files changed, 98 insertions(+), 79 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h index a33f9841..729997f9 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h @@ -263,6 +263,9 @@ public: #ifdef DEVELOPMENT bool dvpVerifyBindings(const ShaderResourceCacheVk& ResourceCache)const; + static void dvpVerifyResourceLayoutDesc(Uint32 NumShaders, + const std::shared_ptr pShaderResources[], + const PipelineResourceLayoutDesc& ResourceLayoutDesc); #endif Uint32 GetResourceCount(SHADER_RESOURCE_VARIABLE_TYPE VarType)const @@ -324,7 +327,8 @@ private: IMemoryAllocator& Allocator, const PipelineResourceLayoutDesc& ResourceLayoutDesc, const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes); + Uint32 NumAllowedTypes, + bool AllocateImmutableSamplers); Uint32 FindAssignedSampler(const SPIRVShaderResourceAttribs& SepImg, Uint32 CurrResourceCount, diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp index 3e1aba42..48d117f6 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp @@ -104,7 +104,8 @@ void ShaderResourceLayoutVk::AllocateMemory(std::shared_ptrGetShaderType(); - const auto* CombinedSamplerSuffix = m_pResources->GetCombinedSamplerSuffix(); + const Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); + const auto ShaderType = m_pResources->GetShaderType(); + const auto* CombinedSamplerSuffix = m_pResources->GetCombinedSamplerSuffix(); // Count the number of resources to allocate all needed memory m_pResources->ProcessResources( [&](const SPIRVShaderResourceAttribs& ResAttribs, Uint32) @@ -122,10 +123,9 @@ void ShaderResourceLayoutVk::AllocateMemory(std::shared_ptr::max()}, "Number of resources exceeds maximum representable value"); + VERIFY( Uint32{m_NumResources[VarType]} + 1 <= Uint32{std::numeric_limits::max()}, "Number of resources exceeds Uint16 maximum representable value"); ++m_NumResources[VarType]; } } @@ -140,11 +140,14 @@ void ShaderResourceLayoutVk::AllocateMemory(std::shared_ptr(TotalResources); m_NumImmutableSamplers = 0; - for (Uint32 s=0; s < ResourceLayoutDesc.NumStaticSamplers; ++s) + if (AllocateImmutableSamplers) { - const auto& StSamDesc = ResourceLayoutDesc.StaticSamplers[s]; - if ((StSamDesc.ShaderStages & ShaderType) != 0) - ++m_NumImmutableSamplers; + for (Uint32 s=0; s < ResourceLayoutDesc.NumStaticSamplers; ++s) + { + const auto& StSamDesc = ResourceLayoutDesc.StaticSamplers[s]; + if ((StSamDesc.ShaderStages & ShaderType) != 0) + ++m_NumImmutableSamplers; + } } size_t MemSize = TotalResources * sizeof(VkResource) + m_NumImmutableSamplers * sizeof(ImmutableSamplerPtrType); @@ -168,15 +171,18 @@ void ShaderResourceLayoutVk::InitializeStaticResourceLayout(std::shared_ptr CurrResInd = {}; Uint32 StaticResCacheSize = 0; - const Uint32 AllowedTypeBits = GetAllowedTypeBits(&AllowedVarType, 1); - const auto ShaderType = m_pResources->GetShaderType(); - const auto* CombinedSamplerSuffix = m_pResources->GetCombinedSamplerSuffix(); + const Uint32 AllowedTypeBits = GetAllowedTypeBits(&AllowedVarType, 1); + const auto ShaderType = m_pResources->GetShaderType(); + const auto* CombinedSamplerSuffix = m_pResources->GetCombinedSamplerSuffix(); m_pResources->ProcessResources( [&](const SPIRVShaderResourceAttribs& Attribs, Uint32) @@ -191,8 +197,7 @@ void ShaderResourceLayoutVk::InitializeStaticResourceLayout(std::shared_ptr= 0); @@ -214,7 +219,7 @@ void ShaderResourceLayoutVk::InitializeStaticResourceLayout(std::shared_ptr(VarType + 1)) { - VERIFY(CurrResInd[VarType] == m_NumResources[VarType], "Not all resources are initialized, which will cause a crash when dtor is called"); + VERIFY(CurrResInd[VarType] == m_NumResources[VarType], "Not all resources have been initialized, which will cause a crash when dtor is called"); } #endif @@ -225,27 +230,22 @@ void ShaderResourceLayoutVk::InitializeStaticResourceLayout(std::shared_ptr pShaderResources[], - IMemoryAllocator& LayoutDataAllocator, - const PipelineResourceLayoutDesc& ResourceLayoutDesc, - std::vector SPIRVs[], - class PipelineLayout& PipelineLayout) -{ #ifdef DEVELOPMENT +void ShaderResourceLayoutVk::dvpVerifyResourceLayoutDesc(Uint32 NumShaders, + const std::shared_ptr pShaderResources[], + const PipelineResourceLayoutDesc& ResourceLayoutDesc) +{ for (Uint32 v = 0; v < ResourceLayoutDesc.NumVariables; ++v) { - bool VariableFound = false; const auto& VarDesc = ResourceLayoutDesc.Variables[v]; if (VarDesc.ShaderStages == SHADER_TYPE_UNKNOWN) { - LOG_WARNING_MESSAGE("No allowed shader stages are specified for variable '", VarDesc.Name, "' labeled as ", GetShaderVariableTypeLiteralName(VarDesc.Type), "."); + LOG_WARNING_MESSAGE("No allowed shader stages are specified for ", GetShaderVariableTypeLiteralName(VarDesc.Type), " variable '", VarDesc.Name, "'."); continue; } - for(Uint32 s=0; s < NumShaders && !VariableFound; ++s) + bool VariableFound = false; + for (Uint32 s=0; s < NumShaders && !VariableFound; ++s) { const auto& Resources = *pShaderResources[s]; if ( (VarDesc.ShaderStages & Resources.GetShaderType()) != 0 ) @@ -259,7 +259,7 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* } if (!VariableFound) { - LOG_WARNING_MESSAGE("Variable '", VarDesc.Name, "' labeled as ", GetShaderVariableTypeLiteralName(VarDesc.Type), " is not found in any of the specified shader stages: ", GetShaderStagesString(VarDesc.ShaderStages)); + LOG_WARNING_MESSAGE(GetShaderVariableTypeLiteralName(VarDesc.Type), " variable '", VarDesc.Name, "' is not found in any of the designated shader stages (", GetShaderStagesString(VarDesc.ShaderStages), ")"); } } @@ -273,7 +273,7 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* } bool SamplerFound = false; - for(Uint32 s=0; s < NumShaders && !SamplerFound; ++s) + for (Uint32 s=0; s < NumShaders && !SamplerFound; ++s) { const auto& Resources = *pShaderResources[s]; if ( (StSamDesc.ShaderStages & Resources.GetShaderType()) == 0 ) @@ -289,27 +289,38 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* if (!SamplerFound) { - // Check if static sampler is assigned to a separate sampler or - // separate image depending on whether HLSL-style combined samplers - // are used + // Check if static sampler is assigned to a separate sampler. + // In case HLSL-style combined image samplers are used, the condition is SepSmpl.Name == "g_Texture" + "_sampler". + // Otherwise the condition is SepSmpl.Name == "g_Texture_sampler" + "". const auto* CombinedSamplerSuffix = Resources.GetCombinedSamplerSuffix(); - for (Uint32 i = 0; i < Resources.GetNumSepSmplrs(); ++i) + for (Uint32 i = 0; i < Resources.GetNumSepSmplrs() && !SamplerFound; ++i) { const auto& SepSmpl = Resources.GetSepSmplr(i); SamplerFound = StreqSuff(SepSmpl.Name, StSamDesc.SamplerOrTextureName, CombinedSamplerSuffix); - if (SamplerFound) - break; } } } if (!SamplerFound) { - LOG_WARNING_MESSAGE("Static sampler '", StSamDesc.SamplerOrTextureName, "' is not found in any of the specified shader stages: ", GetShaderStagesString(StSamDesc.ShaderStages)); + LOG_WARNING_MESSAGE("Static sampler '", StSamDesc.SamplerOrTextureName, "' is not found in any of the designated shader stages (", GetShaderStagesString(StSamDesc.ShaderStages), ")"); } } +} #endif +void ShaderResourceLayoutVk::Initialize(IRenderDevice* pRenderDevice, + Uint32 NumShaders, + ShaderResourceLayoutVk Layouts[], + std::shared_ptr pShaderResources[], + IMemoryAllocator& LayoutDataAllocator, + const PipelineResourceLayoutDesc& ResourceLayoutDesc, + std::vector SPIRVs[], + class PipelineLayout& PipelineLayout) +{ +#ifdef DEVELOPMENT + dvpVerifyResourceLayoutDesc(NumShaders, pShaderResources, ResourceLayoutDesc); +#endif const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes = nullptr; const Uint32 NumAllowedTypes = 0; @@ -317,7 +328,8 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* for (Uint32 s=0; s < NumShaders; ++s) { - Layouts[s].AllocateMemory(std::move(pShaderResources[s]), LayoutDataAllocator, ResourceLayoutDesc, AllowedVarTypes, NumAllowedTypes); + constexpr bool AllocateImmutableSamplers = true; + Layouts[s].AllocateMemory(std::move(pShaderResources[s]), LayoutDataAllocator, ResourceLayoutDesc, AllowedVarTypes, NumAllowedTypes, AllocateImmutableSamplers); } VERIFY_EXPR(NumShaders <= MaxShadersInPipeline); @@ -332,15 +344,15 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* const SPIRVShaderResources& Resources, const SPIRVShaderResourceAttribs& Attribs) { - Uint32 Binding = 0; - Uint32 DescriptorSet = 0; - Uint32 CacheOffset = 0; const auto ShaderType = Resources.GetShaderType(); const SHADER_RESOURCE_VARIABLE_TYPE VarType = GetShaderVariableType(ShaderType, Attribs, ResourceLayoutDesc, Resources.GetCombinedSamplerSuffix()); if (!IsAllowedType(VarType, AllowedTypeBits)) return; - Uint32 SamplerInd = VkResource::InvalidSamplerInd; + Uint32 Binding = 0; + Uint32 DescriptorSet = 0; + Uint32 CacheOffset = 0; + Uint32 SamplerInd = VkResource::InvalidSamplerInd; if (Attribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateImage) { @@ -467,7 +479,7 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* auto& Layout = Layouts[s]; for (SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; VarType < SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType + 1)) { - VERIFY(CurrResInd[s][VarType] == Layout.m_NumResources[VarType], "Not all resources are initialized, which will cause a crash when dtor is called"); + VERIFY(CurrResInd[s][VarType] == Layout.m_NumResources[VarType], "Not all resources have been initialized, which will cause a crash when dtor is called. This is a bug."); } } #endif @@ -524,17 +536,17 @@ void ShaderResourceLayoutVk::VkResource::UpdateDescriptorHandle(VkDescriptorSet VERIFY_EXPR(vkDescrSet != VK_NULL_HANDLE); VkWriteDescriptorSet WriteDescrSet; - WriteDescrSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - WriteDescrSet.pNext = nullptr; - WriteDescrSet.dstSet = vkDescrSet; - WriteDescrSet.dstBinding = Binding; - WriteDescrSet.dstArrayElement = ArrayElement; - WriteDescrSet.descriptorCount = 1; + WriteDescrSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + WriteDescrSet.pNext = nullptr; + WriteDescrSet.dstSet = vkDescrSet; + WriteDescrSet.dstBinding = Binding; + WriteDescrSet.dstArrayElement = ArrayElement; + WriteDescrSet.descriptorCount = 1; // descriptorType must be the same type as that specified in VkDescriptorSetLayoutBinding for dstSet at dstBinding. // The type of the descriptor also controls which array the descriptors are taken from. (13.2.4) - WriteDescrSet.descriptorType = PipelineLayout::GetVkDescriptorType(SpirvAttribs); - WriteDescrSet.pImageInfo = pImageInfo; - WriteDescrSet.pBufferInfo = pBufferInfo; + WriteDescrSet.descriptorType = PipelineLayout::GetVkDescriptorType(SpirvAttribs); + WriteDescrSet.pImageInfo = pImageInfo; + WriteDescrSet.pBufferInfo = pBufferInfo; WriteDescrSet.pTexelBufferView = pTexelBufferView; ParentResLayout.m_LogicalDevice.UpdateDescriptorSets(1, &WriteDescrSet, 0, nullptr); @@ -729,13 +741,14 @@ void ShaderResourceLayoutVk::VkResource::CacheImage(IDeviceObject* if (SamplerInd != InvalidSamplerInd) { - VERIFY_EXPR(SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateImage); - VERIFY_EXPR(!IsImmutableSamplerAssigned()); - auto* pSampler = pTexViewVk->GetSampler(); + VERIFY(SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateImage, + "Only separate images can be assigned separate samplers when using HLSL-style combined samplers."); + VERIFY(!IsImmutableSamplerAssigned(), "Separate image can't be assigned an immutable sampler."); const auto& SamplerAttribs = ParentResLayout.GetResource(GetVariableType(), SamplerInd); VERIFY_EXPR(SamplerAttribs.SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler); if (!SamplerAttribs.IsImmutableSamplerAssigned()) { + auto* pSampler = pTexViewVk->GetSampler(); if (pSampler != nullptr) { CacheSampler(SamplerAttribs, pSampler); @@ -757,6 +770,7 @@ void ShaderResourceLayoutVk::VkResource::CacheSeparateSampler(IDeviceObject* Uint32 ArrayInd)const { VERIFY(SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler, "Separate sampler resource is expected"); + VERIFY(!IsImmutableSamplerAssigned(), "This separate sampler is assigned an immutable sampler"); if (UpdateCachedResource(DstRes, ArrayInd, pSampler, IID_Sampler, "sampler")) { @@ -821,6 +835,7 @@ void ShaderResourceLayoutVk::VkResource::BindResource(IDeviceObject* pObj, Uint3 CacheImage(pObj, DstRes, vkDescrSet, ArrayIndex, [&](const VkResource& SeparateSampler, ISampler* pSampler) { + VERIFY(!SeparateSampler.IsImmutableSamplerAssigned(), "This separate sampler is assigned an immutable sampler '", SeparateSampler.SpirvAttribs.Name, "'"); VERIFY_EXPR(SpirvAttribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateImage); DEV_CHECK_ERR(SeparateSampler.SpirvAttribs.ArraySize == 1 || SeparateSampler.SpirvAttribs.ArraySize == SpirvAttribs.ArraySize, "Array size (", SeparateSampler.SpirvAttribs.ArraySize,") of separate sampler variable '", @@ -865,10 +880,10 @@ bool ShaderResourceLayoutVk::VkResource::IsBound(Uint32 ArrayIndex, const Shader if (DescriptorSet < ResourceCache.GetNumDescriptorSets()) { - auto& Set = ResourceCache.GetDescriptorSet(DescriptorSet); + const auto& Set = ResourceCache.GetDescriptorSet(DescriptorSet); if (CacheOffset + ArrayIndex < Set.GetSize()) { - auto& CachedRes = Set.GetResource(CacheOffset + ArrayIndex); + const auto& CachedRes = Set.GetResource(CacheOffset + ArrayIndex); return CachedRes.pObject != nullptr; } } @@ -889,7 +904,7 @@ void ShaderResourceLayoutVk::InitializeStaticResources(const ShaderResourceLayou for (Uint32 r=0; r < NumStaticResources; ++r) { // Get resource attributes - auto& DstRes = GetResource(SHADER_RESOURCE_VARIABLE_TYPE_STATIC, r); + const auto& DstRes = GetResource(SHADER_RESOURCE_VARIABLE_TYPE_STATIC, r); const auto& SrcRes = SrcLayout.GetResource(SHADER_RESOURCE_VARIABLE_TYPE_STATIC, r); VERIFY(SrcRes.Binding == SrcRes.SpirvAttribs.Type, "Unexpected binding"); VERIFY(SrcRes.SpirvAttribs.ArraySize == DstRes.SpirvAttribs.ArraySize, "Inconsistent array size"); @@ -984,14 +999,14 @@ void ShaderResourceLayoutVk::CommitDynamicResources(const ShaderResourceCacheVk& VERIFY_EXPR(vkDynamicDescriptorSet != VK_NULL_HANDLE); #ifdef _DEBUG - static constexpr size_t ImgUpdateBatchSize = 4; - static constexpr size_t BuffUpdateBatchSize = 2; - static constexpr size_t TexelBuffUpdateBatchSize = 2; + static constexpr size_t ImgUpdateBatchSize = 4; + static constexpr size_t BuffUpdateBatchSize = 2; + static constexpr size_t TexelBuffUpdateBatchSize = 2; static constexpr size_t WriteDescriptorSetBatchSize = 2; #else - static constexpr size_t ImgUpdateBatchSize = 128; - static constexpr size_t BuffUpdateBatchSize = 64; - static constexpr size_t TexelBuffUpdateBatchSize = 32; + static constexpr size_t ImgUpdateBatchSize = 128; + static constexpr size_t BuffUpdateBatchSize = 64; + static constexpr size_t TexelBuffUpdateBatchSize = 32; static constexpr size_t WriteDescriptorSetBatchSize = 32; #endif @@ -1002,9 +1017,9 @@ void ShaderResourceLayoutVk::CommitDynamicResources(const ShaderResourceCacheVk& std::array WriteDescrSetArr; Uint32 ResNum = 0, ArrElem = 0; - auto DescrImgIt = DescrImgInfoArr.begin(); - auto DescrBuffIt = DescrBuffInfoArr.begin(); - auto BuffViewIt = DescrBuffViewArr.begin(); + auto DescrImgIt = DescrImgInfoArr.begin(); + auto DescrBuffIt = DescrBuffInfoArr.begin(); + auto BuffViewIt = DescrBuffViewArr.begin(); auto WriteDescrSetIt = WriteDescrSetArr.begin(); #ifdef _DEBUG @@ -1034,11 +1049,11 @@ void ShaderResourceLayoutVk::CommitDynamicResources(const ShaderResourceCacheVk& WriteDescrSetIt->descriptorType = PipelineLayout::GetVkDescriptorType(Res.SpirvAttribs); // For every resource type, try to batch as many descriptor updates as we can - switch(Res.SpirvAttribs.Type) + switch (Res.SpirvAttribs.Type) { case SPIRVShaderResourceAttribs::ResourceType::UniformBuffer: WriteDescrSetIt->pBufferInfo = &(*DescrBuffIt); - while(ArrElem < Res.SpirvAttribs.ArraySize && DescrBuffIt != DescrBuffInfoArr.end()) + while (ArrElem < Res.SpirvAttribs.ArraySize && DescrBuffIt != DescrBuffInfoArr.end()) { const auto& CachedRes = SetResources.GetResource(Res.CacheOffset + ArrElem); *DescrBuffIt = CachedRes.GetUniformBufferDescriptorWriteInfo(); @@ -1049,7 +1064,7 @@ void ShaderResourceLayoutVk::CommitDynamicResources(const ShaderResourceCacheVk& case SPIRVShaderResourceAttribs::ResourceType::StorageBuffer: WriteDescrSetIt->pBufferInfo = &(*DescrBuffIt); - while(ArrElem < Res.SpirvAttribs.ArraySize && DescrBuffIt != DescrBuffInfoArr.end()) + while (ArrElem < Res.SpirvAttribs.ArraySize && DescrBuffIt != DescrBuffInfoArr.end()) { const auto& CachedRes = SetResources.GetResource(Res.CacheOffset + ArrElem); *DescrBuffIt = CachedRes.GetStorageBufferDescriptorWriteInfo(); @@ -1061,7 +1076,7 @@ void ShaderResourceLayoutVk::CommitDynamicResources(const ShaderResourceCacheVk& case SPIRVShaderResourceAttribs::ResourceType::UniformTexelBuffer: case SPIRVShaderResourceAttribs::ResourceType::StorageTexelBuffer: WriteDescrSetIt->pTexelBufferView = &(*BuffViewIt); - while(ArrElem < Res.SpirvAttribs.ArraySize && BuffViewIt != DescrBuffViewArr.end()) + while (ArrElem < Res.SpirvAttribs.ArraySize && BuffViewIt != DescrBuffViewArr.end()) { const auto& CachedRes = SetResources.GetResource(Res.CacheOffset + ArrElem); *BuffViewIt = CachedRes.GetBufferViewWriteInfo(); @@ -1114,13 +1129,13 @@ void ShaderResourceLayoutVk::CommitDynamicResources(const ShaderResourceCacheVk& } WriteDescrSetIt->descriptorCount = ArrElem - WriteDescrSetIt->dstArrayElement; - if(ArrElem == Res.SpirvAttribs.ArraySize) + if (ArrElem == Res.SpirvAttribs.ArraySize) { ArrElem = 0; ++ResNum; } // descriptorCount == 0 for immutable separate samplers - if(WriteDescrSetIt->descriptorCount > 0) + if (WriteDescrSetIt->descriptorCount > 0) ++WriteDescrSetIt; // If we ran out of space in any of the arrays or if we processed all resources, @@ -1132,7 +1147,7 @@ void ShaderResourceLayoutVk::CommitDynamicResources(const ShaderResourceCacheVk& WriteDescrSetIt == WriteDescrSetArr.end()) { auto DescrWriteCount = static_cast(std::distance(WriteDescrSetArr.begin(), WriteDescrSetIt)); - if(DescrWriteCount > 0) + if (DescrWriteCount > 0) m_LogicalDevice.UpdateDescriptorSets(DescrWriteCount, WriteDescrSetArr.data(), 0, nullptr); DescrImgIt = DescrImgInfoArr.begin(); -- cgit v1.2.3 From c1470ef074418b5b238e0a461242f4c24b660ba2 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sat, 2 Mar 2019 22:31:12 -0800 Subject: Reworked ShaderD3DBase to comply with the updated API --- .../include/D3DShaderResourceLoader.h | 95 ++---------------- .../GraphicsEngineD3DBase/include/ShaderD3DBase.h | 3 +- .../include/ShaderResources.h | 110 ++++----------------- .../include/ShaderVariableD3DBase.h | 8 +- .../GraphicsEngineD3DBase/src/ShaderD3DBase.cpp | 70 ++++++------- .../GraphicsEngineD3DBase/src/ShaderResources.cpp | 54 ---------- 6 files changed, 66 insertions(+), 274 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineD3DBase/include/D3DShaderResourceLoader.h b/Graphics/GraphicsEngineD3DBase/include/D3DShaderResourceLoader.h index 511f436e..c2c6e402 100644 --- a/Graphics/GraphicsEngineD3DBase/include/D3DShaderResourceLoader.h +++ b/Graphics/GraphicsEngineD3DBase/include/D3DShaderResourceLoader.h @@ -57,17 +57,13 @@ namespace Diligent typename TOnNewSampler, typename TOnNewTexSRV> void LoadD3DShaderResources(ID3DBlob* pShaderByteCode, - TOnResourcesCounted OnResourcesCounted, TOnNewCB OnNewCB, TOnNewTexUAV OnNewTexUAV, TOnNewBuffUAV OnNewBuffUAV, TOnNewBuffSRV OnNewBuffSRV, TOnNewSampler OnNewSampler, - TOnNewTexSRV OnNewTexSRV, - - const ShaderDesc& ShdrDesc, - const Char* SamplerSuffix) + TOnNewTexSRV OnNewTexSRV) { CComPtr pShaderReflection; auto hr = D3DReflect( pShaderByteCode->GetBufferPointer(), pShaderByteCode->GetBufferSize(), __uuidof(pShaderReflection), reinterpret_cast(static_cast(&pShaderReflection))); @@ -80,13 +76,11 @@ namespace Diligent Resources.reserve(shaderDesc.BoundResources); std::unordered_set ResourceNamesTmpPool; - const bool UseCombinedTextureSamplers = SamplerSuffix != nullptr; - D3DShaderResourceCounters RC; size_t ResourceNamesPoolSize = 0; // Number of resources to skip (used for array resources) UINT SkipCount = 1; - for( UINT Res = 0; Res < shaderDesc.BoundResources; Res += SkipCount ) + for (UINT Res = 0; Res < shaderDesc.BoundResources; Res += SkipCount) { D3D_SHADER_INPUT_BIND_DESC BindingDesc = {}; pShaderReflection->GetResourceBindingDesc( Res, &BindingDesc ); @@ -128,7 +122,7 @@ namespace Diligent VERIFY(Name.compare(ExistingRes.Name) != 0, "Resource with the same name has already been enumerated. All array elements are expected to be enumerated one after another"); } #endif - for( UINT ArrElem = Res+1; ArrElem < shaderDesc.BoundResources; ++ArrElem) + for (UINT ArrElem = Res+1; ArrElem < shaderDesc.BoundResources; ++ArrElem) { D3D_SHADER_INPUT_BIND_DESC ArrElemBindingDesc = {}; pShaderReflection->GetResourceBindingDesc( ArrElem, &ArrElemBindingDesc ); @@ -156,32 +150,6 @@ namespace Diligent } } - - SHADER_VARIABLE_TYPE VarType = SHADER_VARIABLE_TYPE_NUM_TYPES; - bool IsStaticSampler = false; - if (BindingDesc.Type == D3D_SIT_SAMPLER) - { - for (Uint32 s = 0; s < ShdrDesc.NumStaticSamplers; ++s) - { - if (StreqSuff(Name.c_str(), ShdrDesc.StaticSamplers[s].SamplerOrTextureName, SamplerSuffix)) - { - IsStaticSampler = true; - break; - } - } - // Use texture or sampler name to derive sampler type - VarType = GetShaderVariableType(ShdrDesc.DefaultVariableType, ShdrDesc.VariableDesc, ShdrDesc.NumVariables, - [&](const char* VarName) - { - return StreqSuff(Name.c_str(), VarName, SamplerSuffix); - }); - } - else - { - VarType = GetShaderVariableType(Name, ShdrDesc.DefaultVariableType, ShdrDesc.VariableDesc, ShdrDesc.NumVariables); - } - - switch( BindingDesc.Type ) { case D3D_SIT_CBUFFER: ++RC.NumCBs; break; @@ -205,68 +173,17 @@ namespace Diligent BindingDesc.BindPoint, BindCount, BindingDesc.Type, - VarType, BindingDesc.Dimension, - D3DShaderResourceAttribs::InvalidSamplerId, - IsStaticSampler + D3DShaderResourceAttribs::InvalidSamplerId ); } - -#ifdef DEVELOPMENT - for (Uint32 v = 0; v < ShdrDesc.NumVariables; ++v) - { - bool VariableFound = false; - const auto* VarName = ShdrDesc.VariableDesc[v].Name; - - for (const auto& Res : Resources) - { - // Skip samplers if combined texture samplers are used as - // in this case they are not treated as independent variables - if (UseCombinedTextureSamplers && Res.GetInputType() == D3D_SIT_SAMPLER) - continue; - - VariableFound = (strcmp(Res.Name, VarName) == 0); - if (VariableFound) - break; - } - if(!VariableFound) - { - LOG_WARNING_MESSAGE("Variable '", VarName, "' is not found in shader '", ShdrDesc.Name, '\''); - } - } - - for (Uint32 s = 0; s < ShdrDesc.NumStaticSamplers; ++s) - { - const auto* TexOrSamName = ShdrDesc.StaticSamplers[s].SamplerOrTextureName; - - bool TextureOrSamplerFound = false; - for (const auto& Res : Resources) - { - if( UseCombinedTextureSamplers && Res.GetInputType() == D3D_SIT_TEXTURE && Res.GetSRVDimension() != D3D_SRV_DIMENSION_BUFFER || - !UseCombinedTextureSamplers && Res.GetInputType() == D3D_SIT_SAMPLER) - { - TextureOrSamplerFound = (strcmp(Res.Name, TexOrSamName) == 0); - if (TextureOrSamplerFound) - break; - } - } - if (!TextureOrSamplerFound) - { - if (UseCombinedTextureSamplers) - LOG_WARNING_MESSAGE("Static sampler specifies a texture '", TexOrSamName, "' that is not found in shader '", ShdrDesc.Name, '\''); - else - LOG_WARNING_MESSAGE("Static sampler '", TexOrSamName, "' is not found in shader '", ShdrDesc.Name, '\''); - } - } -#endif - OnResourcesCounted(RC, ResourceNamesPoolSize); std::vector > TexSRVInds( STD_ALLOCATOR_RAW_MEM(size_t, GetRawAllocator(), "Allocator for vector") ); TexSRVInds.reserve(RC.NumTexSRVs); - for(size_t ResInd = 0; ResInd < Resources.size(); ++ResInd) + for (size_t ResInd = 0; ResInd < Resources.size(); ++ResInd) { const auto& Res = Resources[ResInd]; switch (Res.GetInputType()) @@ -368,7 +285,7 @@ namespace Diligent // Process texture SRVs. We need to do this after all samplers are initialized for (auto TexSRVInd : TexSRVInds) { - OnNewTexSRV( Resources[TexSRVInd] ); + OnNewTexSRV(Resources[TexSRVInd]); } } } diff --git a/Graphics/GraphicsEngineD3DBase/include/ShaderD3DBase.h b/Graphics/GraphicsEngineD3DBase/include/ShaderD3DBase.h index e7b1d10f..7f2eda96 100644 --- a/Graphics/GraphicsEngineD3DBase/include/ShaderD3DBase.h +++ b/Graphics/GraphicsEngineD3DBase/include/ShaderD3DBase.h @@ -36,10 +36,9 @@ namespace Diligent class ShaderD3DBase { public: - ShaderD3DBase(const ShaderCreationAttribs &CreationAttribs); + ShaderD3DBase(const ShaderCreateInfo& ShaderCI); protected: - CComPtr m_pShaderByteCode; }; } diff --git a/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h b/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h index 3cc19fa7..aa3867f3 100644 --- a/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h +++ b/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h @@ -66,23 +66,6 @@ namespace Diligent { -inline bool IsAllowedType(SHADER_VARIABLE_TYPE VarType, Uint32 AllowedTypeBits)noexcept -{ - return ((1 << VarType) & AllowedTypeBits) != 0; -} - -inline Uint32 GetAllowedTypeBits(const SHADER_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes)noexcept -{ - if (AllowedVarTypes == nullptr) - return 0xFFFFFFFF; - - Uint32 AllowedTypeBits = 0; - for (Uint32 i=0; i < NumAllowedTypes; ++i) - AllowedTypeBits |= 1 << AllowedVarTypes[i]; - return AllowedTypeBits; -} - - struct D3DShaderResourceAttribs { const char* const Name; @@ -91,19 +74,16 @@ struct D3DShaderResourceAttribs const Uint16 BindCount; private: - // 4 3 4 20 1 - // bit | 0 1 2 3 | 4 5 6 | 7 8 9 10 | 11 12 13 ... 30 | 31 | - // | | | | | | - // | InputType | VariableType | SRV Dim | SamplerOrTexSRVIdBits | StaticSamplerFlag | + // 4 4 24 + // bit | 0 1 2 3 | 4 5 6 7 | 8 9 10 ... 31 | + // | | | | + // | InputType | SRV Dim | SamplerOrTexSRVIdBits | static constexpr const Uint32 ShaderInputTypeBits = 4; - static constexpr const Uint32 VariableTypeBits = 3; static constexpr const Uint32 SRVDimBits = 4; - static constexpr const Uint32 SamplerOrTexSRVIdBits = 20; - static constexpr const Uint32 StaticSamplerFlagBits = 1; - static_assert(ShaderInputTypeBits + VariableTypeBits + SRVDimBits + SamplerOrTexSRVIdBits + StaticSamplerFlagBits == 32, "Attributes are better be packed into 32 bits"); + static constexpr const Uint32 SamplerOrTexSRVIdBits = 24; + static_assert(ShaderInputTypeBits + SRVDimBits + SamplerOrTexSRVIdBits == 32, "Attributes are better be packed into 32 bits"); static_assert(D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER < (1 << ShaderInputTypeBits), "Not enough bits to represent D3D_SHADER_INPUT_TYPE"); - static_assert(SHADER_VARIABLE_TYPE_NUM_TYPES < (1 << VariableTypeBits), "Not enough bits to represent SHADER_VARIABLE_TYPE"); static_assert(D3D_SRV_DIMENSION_BUFFEREX < (1 << SRVDimBits), "Not enough bits to represent D3D_SRV_DIMENSION"); // We need to use Uint32 instead of the actual type for reliability and correctness. @@ -111,11 +91,8 @@ private: // the value of D3D_SIT_UAV_RWBYTEADDRESS (8) was interpreted as -8 (as the underlying enum type // is signed) causing errors const Uint32 InputType : ShaderInputTypeBits; // Max value: D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER == 11 - const Uint32 VariableType : VariableTypeBits; // Max value: SHADER_VARIABLE_TYPE_DYNAMIC == 2 const Uint32 SRVDimension : SRVDimBits; // Max value: D3D_SRV_DIMENSION_BUFFEREX == 11 Uint32 SamplerOrTexSRVId : SamplerOrTexSRVIdBits; // Max value: 1048575 - const Uint32 StaticSamplerFlag : StaticSamplerFlagBits; // Needs to be Uint32, otherwise sizeof(D3DShaderResourceAttribs)==24 - // (https://stackoverflow.com/questions/308364/c-bitfield-packing-with-bools) public: static constexpr const Uint32 InvalidSamplerId = (1 << SamplerOrTexSRVIdBits) - 1; @@ -129,39 +106,26 @@ public: UINT _BindPoint, UINT _BindCount, D3D_SHADER_INPUT_TYPE _InputType, - SHADER_VARIABLE_TYPE _VariableType, D3D_SRV_DIMENSION _SRVDimension, - Uint32 _SamplerId, - bool _IsStaticSampler)noexcept : + Uint32 _SamplerId)noexcept : Name (_Name), BindPoint (static_cast (_BindPoint)), BindCount (static_cast (_BindCount)), InputType (static_cast (_InputType)), - VariableType (static_cast(_VariableType)), SRVDimension (static_cast(_SRVDimension)), - SamplerOrTexSRVId (_SamplerId), - StaticSamplerFlag (_IsStaticSampler ? 1 : 0) + SamplerOrTexSRVId (_SamplerId) { #ifdef _DEBUG VERIFY(_BindPoint <= MaxBindPoint || _BindPoint == InvalidBindPoint, "Bind Point is out of allowed range"); VERIFY(_BindCount <= MaxBindCount, "Bind Count is out of allowed range"); VERIFY(_InputType < (1 << ShaderInputTypeBits), "Shader input type is out of expected range"); - VERIFY(_VariableType < (1 << VariableTypeBits), "Variable type is out of expected range"); VERIFY(_SRVDimension < (1 << SRVDimBits), "SRV dimensions is out of expected range"); VERIFY(_SamplerId < (1 << SamplerOrTexSRVIdBits), "SamplerOrTexSRVId is out of representable range"); - if (_InputType==D3D_SIT_SAMPLER) - VERIFY_EXPR(IsStaticSampler() == _IsStaticSampler); - else - VERIFY(!_IsStaticSampler, "Only samplers can be labeled as static"); - if (_InputType == D3D_SIT_TEXTURE && _SRVDimension != D3D_SRV_DIMENSION_BUFFER) VERIFY_EXPR(GetSamplerId() == _SamplerId); else VERIFY(_SamplerId == InvalidSamplerId, "Only texture SRV can be assigned a valid texture sampler"); - - if (_IsStaticSampler) - VERIFY( _InputType == D3D_SIT_SAMPLER, "Invalid input type: D3D_SIT_SAMPLER is expected" ); #endif } @@ -172,10 +136,8 @@ public: rhs.BindPoint, rhs.BindCount, rhs.GetInputType(), - rhs.GetVariableType(), rhs.GetSRVDimension(), - SamplerId, - false + SamplerId } { VERIFY(GetInputType() == D3D_SIT_TEXTURE && GetSRVDimension() != D3D_SRV_DIMENSION_BUFFER, "Only texture SRV can be assigned a texture sampler"); @@ -188,10 +150,8 @@ public: rhs.BindPoint, rhs.BindCount, rhs.GetInputType(), - rhs.GetVariableType(), rhs.GetSRVDimension(), - rhs.SamplerOrTexSRVId, - rhs.StaticSamplerFlag !=0 ? true : false + rhs.SamplerOrTexSRVId } { } @@ -206,11 +166,6 @@ public: return static_cast(InputType); } - SHADER_VARIABLE_TYPE GetVariableType()const - { - return static_cast(VariableType); - } - D3D_SRV_DIMENSION GetSRVDimension()const { return static_cast(SRVDimension); @@ -235,12 +190,6 @@ public: return SamplerOrTexSRVId; } - bool IsStaticSampler()const - { - VERIFY(GetInputType() == D3D_SIT_SAMPLER, "Invalid input type: D3D_SIT_SAMPLER is expected" ); - return StaticSamplerFlag != 0; - } - bool ValidSamplerAssigned()const { return GetSamplerId() != InvalidSamplerId; @@ -270,20 +219,13 @@ public: return BindPoint == Attribs.BindPoint && BindCount == Attribs.BindCount && InputType == Attribs.InputType && - VariableType == Attribs.VariableType && SRVDimension == Attribs.SRVDimension && - SamplerOrTexSRVId == Attribs.SamplerOrTexSRVId && - StaticSamplerFlag == Attribs.StaticSamplerFlag; + SamplerOrTexSRVId == Attribs.SamplerOrTexSRVId; } size_t GetHash()const { - return ComputeHash(BindPoint, BindCount, InputType, VariableType, SRVDimension, SamplerOrTexSRVId, StaticSamplerFlag); - } - - bool IsAllowedType(Uint32 AllowedTypeBits)const - { - return Diligent::IsAllowedType(GetVariableType(), AllowedTypeBits); + return ComputeHash(BindPoint, BindCount, InputType, SRVDimension, SamplerOrTexSRVId); } }; static_assert(sizeof(D3DShaderResourceAttribs) == sizeof(void*) + sizeof(Uint32)*2, "Unexpected sizeof(D3DShaderResourceAttribs)"); @@ -317,9 +259,6 @@ public: const D3DShaderResourceAttribs& GetBufUAV (Uint32 n)const noexcept{ return GetResAttribs(n, GetNumBufUAV(), m_BufUAVOffset); } const D3DShaderResourceAttribs& GetSampler(Uint32 n)const noexcept{ return GetResAttribs(n, GetNumSamplers(), m_SamplersOffset); } - D3DShaderResourceCounters CountResources(const SHADER_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes)const noexcept; - SHADER_TYPE GetShaderType()const noexcept{return m_ShaderType;} // Processes only resources listed in AllowedVarTypes @@ -329,57 +268,47 @@ public: typename THandleTexUAV, typename THandleBufSRV, typename THandleBufUAV> - void ProcessResources(const SHADER_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - THandleCB HandleCB, + void ProcessResources(THandleCB HandleCB, THandleSampler HandleSampler, THandleTexSRV HandleTexSRV, THandleTexUAV HandleTexUAV, THandleBufSRV HandleBufSRV, THandleBufUAV HandleBufUAV)const { - Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); - for(Uint32 n=0; n < GetNumCBs(); ++n) { const auto& CB = GetCB(n); - if( CB.IsAllowedType(AllowedTypeBits) ) - HandleCB(CB, n); + HandleCB(CB, n); } for(Uint32 n=0; n < GetNumSamplers(); ++n) { const auto& Sampler = GetSampler(n); - if( Sampler.IsAllowedType(AllowedTypeBits) ) - HandleSampler(Sampler, n); + HandleSampler(Sampler, n); } for(Uint32 n=0; n < GetNumTexSRV(); ++n) { const auto& TexSRV = GetTexSRV(n); - if( TexSRV.IsAllowedType(AllowedTypeBits) ) - HandleTexSRV(TexSRV, n); + HandleTexSRV(TexSRV, n); } for(Uint32 n=0; n < GetNumTexUAV(); ++n) { const auto& TexUAV = GetTexUAV(n); - if( TexUAV.IsAllowedType(AllowedTypeBits) ) - HandleTexUAV(TexUAV, n); + HandleTexUAV(TexUAV, n); } for(Uint32 n=0; n < GetNumBufSRV(); ++n) { const auto& BufSRV = GetBufSRV(n); - if( BufSRV.IsAllowedType(AllowedTypeBits) ) - HandleBufSRV(BufSRV, n); + HandleBufSRV(BufSRV, n); } for(Uint32 n=0; n < GetNumBufUAV(); ++n) { const auto& BufUAV = GetBufUAV(n); - if( BufUAV.IsAllowedType(AllowedTypeBits) ) - HandleBufUAV(BufUAV, n); + HandleBufUAV(BufUAV, n); } } @@ -567,3 +496,4 @@ namespace std } }; } + diff --git a/Graphics/GraphicsEngineD3DBase/include/ShaderVariableD3DBase.h b/Graphics/GraphicsEngineD3DBase/include/ShaderVariableD3DBase.h index 6c683aa2..48748a6c 100644 --- a/Graphics/GraphicsEngineD3DBase/include/ShaderVariableD3DBase.h +++ b/Graphics/GraphicsEngineD3DBase/include/ShaderVariableD3DBase.h @@ -23,7 +23,7 @@ #pragma once -#include "Shader.h" +#include "ShaderResourceVariable.h" /// \file /// Declaration of Diligent::ShaderVariableD3DBase class @@ -31,7 +31,7 @@ namespace Diligent { template - struct ShaderVariableD3DBase : public IShaderVariable + struct ShaderVariableD3DBase : public IShaderResourceVariable { ShaderVariableD3DBase(TShaderResourceLayout& ParentResLayout, const D3DShaderResourceAttribs& ResourcesAttribs) : m_ParentResLayout(ParentResLayout), @@ -54,7 +54,7 @@ namespace Diligent return m_ParentResLayout.GetOwner().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; @@ -67,7 +67,7 @@ namespace Diligent } } - virtual SHADER_VARIABLE_TYPE GetType()const override final + virtual SHADER_RESOURCE_VARIABLE_TYPE GetType()const override final { return Attribs.GetVariableType(); } diff --git a/Graphics/GraphicsEngineD3DBase/src/ShaderD3DBase.cpp b/Graphics/GraphicsEngineD3DBase/src/ShaderD3DBase.cpp index c1fbda20..e9f1144b 100644 --- a/Graphics/GraphicsEngineD3DBase/src/ShaderD3DBase.cpp +++ b/Graphics/GraphicsEngineD3DBase/src/ShaderD3DBase.cpp @@ -41,13 +41,13 @@ static const Char* g_HLSLDefinitions = class D3DIncludeImpl : public ID3DInclude { public: - D3DIncludeImpl(IShaderSourceInputStreamFactory *pStreamFactory) : + D3DIncludeImpl(IShaderSourceInputStreamFactory* pStreamFactory) : m_pStreamFactory(pStreamFactory) { } - STDMETHOD( Open )(THIS_ D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes) + STDMETHOD( Open )(THIS_ D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID* ppData, UINT* pBytes) { RefCntAutoPtr pSourceStream; m_pStreamFactory->CreateInputStream( pFileName, &pSourceStream ); @@ -78,13 +78,13 @@ private: std::unordered_map< LPCVOID, RefCntAutoPtr > m_DataBlobs; }; -HRESULT CompileShader( const char* Source, - LPCSTR strFunctionName, - const D3D_SHADER_MACRO* pDefines, - IShaderSourceInputStreamFactory *pIncludeStreamFactory, - LPCSTR profile, - ID3DBlob **ppBlobOut, - ID3DBlob **ppCompilerOutput) +static HRESULT CompileShader(const char* Source, + LPCSTR strFunctionName, + const D3D_SHADER_MACRO* pDefines, + IShaderSourceInputStreamFactory* pIncludeStreamFactory, + LPCSTR profile, + ID3DBlob** ppBlobOut, + ID3DBlob** ppCompilerOutput) { DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) @@ -133,15 +133,15 @@ const char* DXShaderProfileToString(SHADER_PROFILE DXProfile) } } -ShaderD3DBase::ShaderD3DBase(const ShaderCreationAttribs &CreationAttribs) +ShaderD3DBase::ShaderD3DBase(const ShaderCreateInfo& ShaderCI) { - if (CreationAttribs.Source || CreationAttribs.FilePath) + if (ShaderCI.Source || ShaderCI.FilePath) { - DEV_CHECK_ERR(CreationAttribs.ByteCode == nullptr, "'ByteCode' must be null when shader is created from the source code or a file"); - DEV_CHECK_ERR(CreationAttribs.ByteCodeSize == 0, "'ByteCodeSize' must be 0 when shader is created from the source code or a file"); + DEV_CHECK_ERR(ShaderCI.ByteCode == nullptr, "'ByteCode' must be null when shader is created from the source code or a file"); + DEV_CHECK_ERR(ShaderCI.ByteCodeSize == 0, "'ByteCodeSize' must be 0 when shader is created from the source code or a file"); std::string strShaderProfile; - switch(CreationAttribs.Desc.ShaderType) + switch (ShaderCI.Desc.ShaderType) { case SHADER_TYPE_VERTEX: strShaderProfile="vs"; break; case SHADER_TYPE_PIXEL: strShaderProfile="ps"; break; @@ -153,20 +153,20 @@ ShaderD3DBase::ShaderD3DBase(const ShaderCreationAttribs &CreationAttribs) default: UNEXPECTED( "Unknown shader type" ); } strShaderProfile += "_"; - auto *pProfileSuffix = DXShaderProfileToString(CreationAttribs.Desc.TargetProfile); + auto *pProfileSuffix = DXShaderProfileToString(ShaderCI.Desc.TargetProfile); strShaderProfile += pProfileSuffix; String ShaderSource(g_HLSLDefinitions); - if (CreationAttribs.Source) + if (ShaderCI.Source) { - DEV_CHECK_ERR(CreationAttribs.FilePath == nullptr, "'FilePath' is expected to be null when shader source code is provided"); - ShaderSource.append(CreationAttribs.Source); + DEV_CHECK_ERR(ShaderCI.FilePath == nullptr, "'FilePath' is expected to be null when shader source code is provided"); + ShaderSource.append(ShaderCI.Source); } else { - DEV_CHECK_ERR(CreationAttribs.pShaderSourceStreamFactory, "Input stream factory is null"); + DEV_CHECK_ERR(ShaderCI.pShaderSourceStreamFactory, "Input stream factory is null"); RefCntAutoPtr pSourceStream; - CreationAttribs.pShaderSourceStreamFactory->CreateInputStream(CreationAttribs.FilePath, &pSourceStream); + ShaderCI.pShaderSourceStreamFactory->CreateInputStream(ShaderCI.FilePath, &pSourceStream); RefCntAutoPtr pFileData(MakeNewRCObj()(0)); if (pSourceStream == nullptr) LOG_ERROR_AND_THROW("Failed to open shader source file"); @@ -179,9 +179,9 @@ ShaderD3DBase::ShaderD3DBase(const ShaderCreationAttribs &CreationAttribs) const D3D_SHADER_MACRO *pDefines = nullptr; std::vector D3DMacros; - if (CreationAttribs.Macros) + if (ShaderCI.Macros) { - for (auto* pCurrMacro = CreationAttribs.Macros; pCurrMacro->Name && pCurrMacro->Definition; ++pCurrMacro) + for (auto* pCurrMacro = ShaderCI.Macros; pCurrMacro->Name && pCurrMacro->Definition; ++pCurrMacro) { D3DMacros.push_back({ pCurrMacro->Name, pCurrMacro->Definition }); } @@ -189,39 +189,39 @@ ShaderD3DBase::ShaderD3DBase(const ShaderCreationAttribs &CreationAttribs) pDefines = D3DMacros.data(); } - DEV_CHECK_ERR(CreationAttribs.EntryPoint != nullptr, "Entry point must not be null"); + DEV_CHECK_ERR(ShaderCI.EntryPoint != nullptr, "Entry point must not be null"); CComPtr errors; - auto hr = CompileShader(ShaderSource.c_str(), CreationAttribs.EntryPoint, pDefines, CreationAttribs.pShaderSourceStreamFactory, strShaderProfile.c_str(), &m_pShaderByteCode, &errors); + auto hr = CompileShader(ShaderSource.c_str(), ShaderCI.EntryPoint, pDefines, ShaderCI.pShaderSourceStreamFactory, strShaderProfile.c_str(), &m_pShaderByteCode, &errors); - const char *CompilerMsg = errors ? reinterpret_cast(errors->GetBufferPointer()) : nullptr; - if(CompilerMsg != nullptr && CreationAttribs.ppCompilerOutput != nullptr) + const char* CompilerMsg = errors ? reinterpret_cast(errors->GetBufferPointer()) : nullptr; + if (CompilerMsg != nullptr && ShaderCI.ppCompilerOutput != nullptr) { auto ErrorMsgLen = strlen(CompilerMsg); auto *pOutputDataBlob = MakeNewRCObj()(ErrorMsgLen + 1 + ShaderSource.length() + 1); char* DataPtr = reinterpret_cast(pOutputDataBlob->GetDataPtr()); memcpy(DataPtr, CompilerMsg, ErrorMsgLen+1); memcpy(DataPtr + ErrorMsgLen + 1, ShaderSource.data(), ShaderSource.length() + 1); - pOutputDataBlob->QueryInterface(IID_DataBlob, reinterpret_cast(CreationAttribs.ppCompilerOutput)); + pOutputDataBlob->QueryInterface(IID_DataBlob, reinterpret_cast(ShaderCI.ppCompilerOutput)); } - if(FAILED(hr)) + if (FAILED(hr)) { ComErrorDesc ErrDesc(hr); - if(CreationAttribs.ppCompilerOutput != nullptr) + if(ShaderCI.ppCompilerOutput != nullptr) { - LOG_ERROR_AND_THROW("Failed to compile D3D shader \"", (CreationAttribs.Desc.Name != nullptr ? CreationAttribs.Desc.Name : ""), "\" (", ErrDesc.Get(), ")."); + LOG_ERROR_AND_THROW("Failed to compile D3D shader \"", (ShaderCI.Desc.Name != nullptr ? ShaderCI.Desc.Name : ""), "\" (", ErrDesc.Get(), ")."); } else { - LOG_ERROR_AND_THROW("Failed to compile D3D shader \"", (CreationAttribs.Desc.Name != nullptr ? CreationAttribs.Desc.Name : ""), "\" (", ErrDesc.Get(), "):\n", (CompilerMsg != nullptr ? CompilerMsg : "") ); + LOG_ERROR_AND_THROW("Failed to compile D3D shader \"", (ShaderCI.Desc.Name != nullptr ? ShaderCI.Desc.Name : ""), "\" (", ErrDesc.Get(), "):\n", (CompilerMsg != nullptr ? CompilerMsg : "") ); } } } - else if (CreationAttribs.ByteCode) + else if (ShaderCI.ByteCode) { - DEV_CHECK_ERR(CreationAttribs.ByteCodeSize != 0, "ByteCode size must be greater than 0"); - CHECK_D3D_RESULT_THROW(D3DCreateBlob(CreationAttribs.ByteCodeSize, &m_pShaderByteCode), "Failed to create D3D blob"); - memcpy(m_pShaderByteCode->GetBufferPointer(), CreationAttribs.ByteCode, CreationAttribs.ByteCodeSize); + DEV_CHECK_ERR(ShaderCI.ByteCodeSize != 0, "ByteCode size must be greater than 0"); + CHECK_D3D_RESULT_THROW(D3DCreateBlob(ShaderCI.ByteCodeSize, &m_pShaderByteCode), "Failed to create D3D blob"); + memcpy(m_pShaderByteCode->GetBufferPointer(), ShaderCI.ByteCode, ShaderCI.ByteCodeSize); } else { diff --git a/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp b/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp index 90b85286..847e2675 100644 --- a/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp +++ b/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp @@ -96,53 +96,6 @@ ShaderResources::ShaderResources(SHADER_TYPE ShaderType): { } -D3DShaderResourceCounters ShaderResources::CountResources(const SHADER_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes)const noexcept -{ - auto AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); - - D3DShaderResourceCounters Counters; - ProcessResources( - AllowedVarTypes, NumAllowedTypes, - - [&](const D3DShaderResourceAttribs& CB, Uint32) - { - VERIFY_EXPR(CB.IsAllowedType(AllowedTypeBits)); - ++Counters.NumCBs; - }, - [&](const D3DShaderResourceAttribs& Sam, Uint32) - { - VERIFY_EXPR(Sam.IsAllowedType(AllowedTypeBits)); - // Skip static samplers - if (!Sam.IsStaticSampler()) - ++Counters.NumSamplers; - }, - [&](const D3DShaderResourceAttribs& TexSRV, Uint32) - { - VERIFY_EXPR(TexSRV.IsAllowedType(AllowedTypeBits)); - ++Counters.NumTexSRVs; - }, - [&](const D3DShaderResourceAttribs& TexUAV, Uint32) - { - VERIFY_EXPR(TexUAV.IsAllowedType(AllowedTypeBits)); - ++Counters.NumTexUAVs; - }, - [&](const D3DShaderResourceAttribs& BufSRV, Uint32) - { - VERIFY_EXPR(BufSRV.IsAllowedType(AllowedTypeBits)); - ++Counters.NumBufSRVs; - }, - [&](const D3DShaderResourceAttribs& BufUAV, Uint32) - { - VERIFY_EXPR(BufUAV.IsAllowedType(AllowedTypeBits)); - ++Counters.NumBufUAVs; - } - ); - - return Counters; -} - - Uint32 ShaderResources::FindAssignedSamplerId(const D3DShaderResourceAttribs& TexSRV, const char* SamplerSuffix)const { VERIFY_EXPR(SamplerSuffix != nullptr && *SamplerSuffix != 0); @@ -153,10 +106,6 @@ Uint32 ShaderResources::FindAssignedSamplerId(const D3DShaderResourceAttribs& Te const auto& Sampler = GetSampler(s); if ( StreqSuff(Sampler.Name, TexSRV.Name, SamplerSuffix) ) { - DEV_CHECK_ERR(Sampler.GetVariableType() == TexSRV.GetVariableType(), - "The type (", GetShaderVariableTypeLiteralName(TexSRV.GetVariableType()),") of texture SRV variable '", TexSRV.Name, - "' is not consistent with the type (", GetShaderVariableTypeLiteralName(Sampler.GetVariableType()), - ") of the sampler '", Sampler.Name, "' that is assigned to it"); DEV_CHECK_ERR(Sampler.BindCount == TexSRV.BindCount || Sampler.BindCount == 1, "Sampler '", Sampler.Name, "' assigned to texture '", TexSRV.Name, "' must be scalar or have the same array dimension (", TexSRV.BindCount, "). Actual sampler array dimension : ", Sampler.BindCount); return s; } @@ -176,8 +125,6 @@ bool ShaderResources::IsCompatibleWith(const ShaderResources &Res)const bool IsCompatible = true; ProcessResources( - nullptr, 0, - [&](const D3DShaderResourceAttribs& CB, Uint32 n) { if (!CB.IsCompatibleWith(Res.GetCB(n))) @@ -216,7 +163,6 @@ size_t ShaderResources::GetHash()const { size_t hash = ComputeHash(GetNumCBs(), GetNumTexSRV(), GetNumTexUAV(), GetNumBufSRV(), GetNumBufUAV(), GetNumSamplers()); ProcessResources( - nullptr, 0, [&](const D3DShaderResourceAttribs& CB, Uint32) { HashCombine(hash, CB); -- cgit v1.2.3 From f57fc688a659087f5e85d8533f61c4a1fd914810 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sat, 2 Mar 2019 22:43:26 -0800 Subject: Reworked ShaderD3D11Impl to comply with the updated API --- .../include/RenderDeviceD3D11Impl.h | 3 +- .../GraphicsEngineD3D11/include/ShaderD3D11Impl.h | 33 ++---------------- .../include/ShaderResourceLayoutD3D11.h | 40 +++++++++++++--------- .../GraphicsEngineD3D11/src/ShaderD3D11Impl.cpp | 30 ++++------------ .../include/ShaderVariableD3DBase.h | 22 +++++++----- 5 files changed, 46 insertions(+), 82 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h index 95548464..0e7f66ad 100644 --- a/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h @@ -49,7 +49,7 @@ public: virtual void CreateBuffer(const BufferDesc& BuffDesc, const BufferData* pBuffData, IBuffer** ppBuffer)override final; - virtual void CreateShader(const ShaderCreationAttribs& ShaderCreationAttribs, IShader** ppShader)override final; + virtual void CreateShader(const ShaderCreateInfo& ShaderCI, IShader** ppShader)override final; virtual void CreateTexture(const TextureDesc& TexDesc, const TextureData* pData, ITexture** ppTexture)override final; @@ -81,3 +81,4 @@ private: }; } + diff --git a/Graphics/GraphicsEngineD3D11/include/ShaderD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/ShaderD3D11Impl.h index 5bafbb1f..c5005c4e 100644 --- a/Graphics/GraphicsEngineD3D11/include/ShaderD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/ShaderD3D11Impl.h @@ -50,31 +50,10 @@ public: ShaderD3D11Impl(IReferenceCounters* pRefCounters, class RenderDeviceD3D11Impl* pRenderDeviceD3D11, - const ShaderCreationAttribs& CreationAttribs); + const ShaderCreateInfo& ShaderCI); ~ShaderD3D11Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject** ppInterface )override final; - - virtual void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags )override final - { - m_StaticResLayout.BindResources(pResourceMapping, Flags, m_StaticResCache); - } - - virtual IShaderVariable* GetShaderVariable( const Char* Name )override final - { - return m_StaticResLayout.GetShaderVariable(Name); - } - - virtual Uint32 GetVariableCount() const override final - { - return m_StaticResLayout.GetTotalResourceCount(); - } - - virtual IShaderVariable* GetShaderVariable(Uint32 Index)override final - { - return m_StaticResLayout.GetShaderVariable(Index); - } - + IMPLEMENT_QUERY_INTERFACE_IN_PLACE(IID_ShaderD3D11, TShaderBase); virtual ID3D11DeviceChild* GetD3D11Shader()override final { @@ -83,20 +62,12 @@ public: ID3DBlob* GetBytecode(){return m_pShaderByteCode;} - ShaderResourceLayoutD3D11& GetStaticResourceLayout(){return m_StaticResLayout;} - const std::shared_ptr& GetResources()const{return m_pShaderResources;} Uint32 GetShaderTypeIndex()const{return m_ShaderTypeIndex;} private: /// D3D11 shader CComPtr m_pShader; - // ShaderResources class instance must be referenced through the shared pointer, because - // it is referenced by ShaderResourceLayoutD3D11 class instances - std::shared_ptr m_pShaderResources; - - ShaderResourceCacheD3D11 m_StaticResCache; - ShaderResourceLayoutD3D11 m_StaticResLayout; Uint32 m_ShaderTypeIndex; // VS == 0, PS == 1, GS == 2, HS == 3, DS == 4, CS == 5 }; diff --git a/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h b/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h index 61970f9d..b6079b0c 100644 --- a/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h +++ b/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h @@ -54,11 +54,11 @@ public: ShaderResourceLayoutD3D11& operator = ( ShaderResourceLayoutD3D11&&) = delete; static size_t GetRequiredMemorySize(const ShaderResourcesD3D11& SrcResources, - const SHADER_VARIABLE_TYPE* VarTypes, + const SHADER_RESOURCE_VARIABLE_TYPE* VarTypes, Uint32 NumVarTypes); void Initialize(std::shared_ptr pSrcResources, - const SHADER_VARIABLE_TYPE* VarTypes, + const SHADER_RESOURCE_VARIABLE_TYPE* VarTypes, Uint32 NumVarTypes, ShaderResourceCacheD3D11& ResourceCache, IMemoryAllocator& ResCacheDataAllocator, @@ -71,8 +71,9 @@ public: struct ConstBuffBindInfo final : ShaderVariableD3D11Base { ConstBuffBindInfo( const D3DShaderResourceAttribs& ResourceAttribs, - ShaderResourceLayoutD3D11& ParentResLayout ) : - ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs) + ShaderResourceLayoutD3D11& ParentResLayout, + SHADER_RESOURCE_VARIABLE_TYPE VariableType) : + ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs, VariableType) {} // Non-virtual function __forceinline void BindResource(IDeviceObject* pObject, Uint32 ArrayIndex); @@ -91,8 +92,9 @@ public: { TexSRVBindInfo( const D3DShaderResourceAttribs& _TextureAttribs, Uint32 _SamplerIndex, - ShaderResourceLayoutD3D11& ParentResLayout) : - ShaderVariableD3D11Base(ParentResLayout, _TextureAttribs), + ShaderResourceLayoutD3D11& ParentResLayout, + SHADER_RESOURCE_VARIABLE_TYPE VariableType) : + ShaderVariableD3D11Base(ParentResLayout, _TextureAttribs, VariableType), SamplerIndex(_SamplerIndex) {} @@ -117,8 +119,9 @@ public: struct TexUAVBindInfo final : ShaderVariableD3D11Base { TexUAVBindInfo( const D3DShaderResourceAttribs& ResourceAttribs, - ShaderResourceLayoutD3D11& ParentResLayout ) : - ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs) + ShaderResourceLayoutD3D11& ParentResLayout, + SHADER_RESOURCE_VARIABLE_TYPE VariableType ) : + ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs, VariableType) {} // Provide non-virtual function @@ -137,8 +140,9 @@ public: struct BuffUAVBindInfo final : ShaderVariableD3D11Base { BuffUAVBindInfo( const D3DShaderResourceAttribs& ResourceAttribs, - ShaderResourceLayoutD3D11& ParentResLayout ) : - ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs) + ShaderResourceLayoutD3D11& ParentResLayout, + SHADER_RESOURCE_VARIABLE_TYPE VariableType ) : + ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs, VariableType) {} // Non-virtual function @@ -157,8 +161,9 @@ public: struct BuffSRVBindInfo final : ShaderVariableD3D11Base { BuffSRVBindInfo( const D3DShaderResourceAttribs& ResourceAttribs, - ShaderResourceLayoutD3D11& ParentResLayout ) : - ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs) + ShaderResourceLayoutD3D11& ParentResLayout, + SHADER_RESOURCE_VARIABLE_TYPE VariableType ) : + ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs, VariableType) {} // Non-virtual function @@ -177,8 +182,9 @@ public: struct SamplerBindInfo final : ShaderVariableD3D11Base { SamplerBindInfo( const D3DShaderResourceAttribs& ResourceAttribs, - ShaderResourceLayoutD3D11& ParentResLayout ) : - ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs) + ShaderResourceLayoutD3D11& ParentResLayout, + SHADER_RESOURCE_VARIABLE_TYPE VariableType ) : + ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs, VariableType) {} // Non-virtual function @@ -202,8 +208,8 @@ public: bool dvpVerifyBindings()const; #endif - IShaderVariable* GetShaderVariable( const Char* Name ); - IShaderVariable* GetShaderVariable( Uint32 Index ); + IShaderResourceVariable* GetShaderVariable( const Char* Name ); + IShaderResourceVariable* GetShaderVariable( Uint32 Index ); __forceinline SHADER_TYPE GetShaderType()const{return m_pResources->GetShaderType();} IObject& GetOwner(){return m_Owner;} @@ -280,7 +286,7 @@ private: } template - IShaderVariable* GetResourceByName( const Char* Name ); + IShaderResourceVariable* GetResourceByName( const Char* Name ); templateGetD3D11Device(); - switch(CreationAttribs.Desc.ShaderType) + switch (ShaderCI.Desc.ShaderType) { #define CREATE_SHADER(SHADER_NAME, ShaderName)\ @@ -75,30 +74,13 @@ ShaderD3D11Impl::ShaderD3D11Impl(IReferenceCounters* pRefCounters, DEV_CHECK_ERR(SUCCEEDED(hr), "Failed to set shader name"); } - // Load shader resources - auto &Allocator = GetRawAllocator(); - auto *pRawMem = ALLOCATE(Allocator, "Allocator for ShaderResources", sizeof(ShaderResourcesD3D11)); - auto *pResources = new (pRawMem) ShaderResourcesD3D11(pRenderDeviceD3D11, m_pShaderByteCode, m_Desc, CreationAttribs.UseCombinedTextureSamplers ? CreationAttribs.CombinedSamplerSuffix : nullptr); - m_pShaderResources.reset(pResources, STDDeleterRawMem(Allocator)); - - // Clone only static resources that will be set directly in the shader - SHADER_VARIABLE_TYPE VarTypes[] = {SHADER_VARIABLE_TYPE_STATIC}; - // The method will also initialize resource cache to have enough space to hold static variables only! - m_StaticResLayout.Initialize(m_pShaderResources, VarTypes, _countof(VarTypes), m_StaticResCache, GetRawAllocator(), GetRawAllocator()); - - // This is not required, but still... - m_pShaderResources->SetStaticSamplers(m_StaticResCache); - // Byte code is only required for the vertex shader to create input layout - if( CreationAttribs.Desc.ShaderType != SHADER_TYPE_VERTEX ) + if( ShaderCI.Desc.ShaderType != SHADER_TYPE_VERTEX ) m_pShaderByteCode.Release(); } ShaderD3D11Impl::~ShaderD3D11Impl() { - m_StaticResCache.Destroy(GetRawAllocator()); } -IMPLEMENT_QUERY_INTERFACE( ShaderD3D11Impl, IID_ShaderD3D11, TShaderBase ) - } diff --git a/Graphics/GraphicsEngineD3DBase/include/ShaderVariableD3DBase.h b/Graphics/GraphicsEngineD3DBase/include/ShaderVariableD3DBase.h index 48748a6c..ae2d2728 100644 --- a/Graphics/GraphicsEngineD3DBase/include/ShaderVariableD3DBase.h +++ b/Graphics/GraphicsEngineD3DBase/include/ShaderVariableD3DBase.h @@ -33,9 +33,12 @@ namespace Diligent template struct ShaderVariableD3DBase : public IShaderResourceVariable { - ShaderVariableD3DBase(TShaderResourceLayout& ParentResLayout, const D3DShaderResourceAttribs& ResourcesAttribs) : - m_ParentResLayout(ParentResLayout), - Attribs(ResourcesAttribs) + ShaderVariableD3DBase(TShaderResourceLayout& ParentResLayout, + const D3DShaderResourceAttribs& Attribs, + SHADER_RESOURCE_VARIABLE_TYPE VariableType) : + m_ParentResLayout (ParentResLayout), + m_Attribs (Attribs), + m_VariableType (VariableType) { } @@ -60,7 +63,7 @@ namespace Diligent return; *ppInterface = nullptr; - if( IID == IID_ShaderVariable || IID == IID_Unknown ) + if( IID == IID_ShaderResourceVariable || IID == IID_Unknown ) { *ppInterface = this; (*ppInterface)->AddRef(); @@ -69,17 +72,17 @@ namespace Diligent virtual SHADER_RESOURCE_VARIABLE_TYPE GetType()const override final { - return Attribs.GetVariableType(); + return m_VariableType; } virtual Uint32 GetArraySize()const override final { - return Attribs.BindCount; + return m_Attribs.BindCount; } virtual const Char* GetName()const override final { - return Attribs.Name; + return m_Attribs.Name; } virtual Uint32 GetIndex()const override final @@ -87,9 +90,10 @@ namespace Diligent return m_ParentResLayout.GetVariableIndex(*this); } - const D3DShaderResourceAttribs& Attribs; + const D3DShaderResourceAttribs& m_Attribs; protected: - TShaderResourceLayout& m_ParentResLayout; + TShaderResourceLayout& m_ParentResLayout; + const SHADER_RESOURCE_VARIABLE_TYPE m_VariableType; }; } -- cgit v1.2.3 From 91dbc2c143a371bf0584e6c6a3cd2feb16535f8b Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sat, 2 Mar 2019 23:01:28 -0800 Subject: Reworked ShaderResourcesD3D11 to comply with the updated API --- .../include/ShaderResourcesD3D11.h | 8 ---- .../src/ShaderResourcesD3D11.cpp | 51 ++-------------------- .../include/ShaderResources.h | 13 +++--- 3 files changed, 8 insertions(+), 64 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineD3D11/include/ShaderResourcesD3D11.h b/Graphics/GraphicsEngineD3D11/include/ShaderResourcesD3D11.h index da8d4a34..a241b486 100644 --- a/Graphics/GraphicsEngineD3D11/include/ShaderResourcesD3D11.h +++ b/Graphics/GraphicsEngineD3D11/include/ShaderResourcesD3D11.h @@ -113,8 +113,6 @@ public: const Char* GetShaderName() const { return m_ShaderName; } - void SetStaticSamplers(class ShaderResourceCacheD3D11& ResourceCache)const; - private: using MaxBindPointType = Int8; @@ -132,12 +130,6 @@ private: // ShaderResourcesD3D11 is part of the ShaderD3D11Impl object, so we can simply // reference shader name without the need to copy it const Char* const m_ShaderName; - - using StaticSamplerAttribs = std::pair>; - using StaticSamplerVector = std::vector>; - void InitStaticSamplers(StaticSamplerVector&& StaticSamplers); - - StaticSamplerVector m_StaticSamplers; }; } diff --git a/Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp b/Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp index af72e1a0..78dfcf63 100755 --- a/Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp +++ b/Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp @@ -38,8 +38,7 @@ ShaderResourcesD3D11::ShaderResourcesD3D11(RenderDeviceD3D11Impl* pDeviceD3D11Im const ShaderDesc& ShdrDesc, const char* CombinedSamplerSuffix) : ShaderResources(ShdrDesc.ShaderType), - m_ShaderName(ShdrDesc.Name), - m_StaticSamplers(STD_ALLOCATOR_RAW_MEM(StaticSamplerAttribs, GetRawAllocator(), "Allocator for vector")) + m_ShaderName(ShdrDesc.Name) { class NewResourceHandler { @@ -51,8 +50,7 @@ ShaderResourcesD3D11::ShaderResourcesD3D11(RenderDeviceD3D11Impl* pDeviceD3D11Im pDeviceD3D11Impl (_pDeviceD3D11Impl), ShdrDesc (_ShdrDesc), CombinedSamplerSuffix(_CombinedSamplerSuffix), - Resources (_Resources), - m_StaticSamplers (STD_ALLOCATOR_RAW_MEM(StaticSamplerAttribs, GetRawAllocator(), "Allocator for vector")) + Resources (_Resources) {} void OnNewCB(const D3DShaderResourceAttribs& CBAttribs) @@ -83,24 +81,6 @@ ShaderResourcesD3D11::ShaderResourcesD3D11(RenderDeviceD3D11Impl* pDeviceD3D11Im { VERIFY( SamplerAttribs.BindPoint + SamplerAttribs.BindCount-1 <= MaxAllowedBindPoint, "Sampler bind point exceeds supported range" ); Resources.m_MaxSamplerBindPoint = std::max(Resources.m_MaxSamplerBindPoint, static_cast(SamplerAttribs.BindPoint + SamplerAttribs.BindCount-1)); - - if (SamplerAttribs.IsStaticSampler()) - { - // Find attributes of this static sampler - Uint32 ssd = 0; - for (; ssd < ShdrDesc.NumStaticSamplers; ++ssd) - { - const auto& StaticSamplerDesc = ShdrDesc.StaticSamplers[ssd]; - if (StreqSuff(SamplerAttribs.Name, StaticSamplerDesc.SamplerOrTextureName, CombinedSamplerSuffix)) - { - RefCntAutoPtr pSampler; - pDeviceD3D11Impl->CreateSampler(StaticSamplerDesc.Desc, &pSampler); - m_StaticSamplers.emplace_back(SamplerAttribs, std::move(pSampler)); - break; - } - } - VERIFY(ssd < ShdrDesc.NumStaticSamplers, "Unable to find sampler '", SamplerAttribs.Name, "' in the list of static samplers. This should never happen and likely indicates a bug in static sampler enumeration code."); - } } void OnNewTexSRV(const D3DShaderResourceAttribs& TexAttribs) @@ -111,7 +91,6 @@ ShaderResourcesD3D11::ShaderResourcesD3D11(RenderDeviceD3D11Impl* pDeviceD3D11Im ~NewResourceHandler() { - Resources.InitStaticSamplers(std::move(m_StaticSamplers)); } private: @@ -119,42 +98,20 @@ ShaderResourcesD3D11::ShaderResourcesD3D11(RenderDeviceD3D11Impl* pDeviceD3D11Im const ShaderDesc& ShdrDesc; const char* CombinedSamplerSuffix; ShaderResourcesD3D11& Resources; - - StaticSamplerVector m_StaticSamplers; }; Initialize( pShaderBytecode, NewResourceHandler{pDeviceD3D11Impl, ShdrDesc, CombinedSamplerSuffix, *this}, - ShdrDesc, + ShdrDesc.Name, CombinedSamplerSuffix); } -void ShaderResourcesD3D11::InitStaticSamplers(StaticSamplerVector&& StaticSamplers) -{ - m_StaticSamplers.reserve(StaticSamplers.size()); - for(auto& Sam : StaticSamplers) - m_StaticSamplers.emplace_back(std::move(Sam)); -} ShaderResourcesD3D11::~ShaderResourcesD3D11() { } -void ShaderResourcesD3D11::SetStaticSamplers(ShaderResourceCacheD3D11& ResourceCache)const -{ - auto NumCachedSamplers = ResourceCache.GetSamplerCount(); - for (const auto& SS : m_StaticSamplers) - { - const auto& SamAttribs = SS.first; - VERIFY_EXPR(SamAttribs.IsStaticSampler()); - auto* pSamplerD3D11Impl = const_cast(SS.second.RawPtr()); - // Limiting EndBindPoint is required when initializing static samplers in a Shader's static cache - auto EndBindPoint = std::min( static_cast(SamAttribs.BindPoint) + SamAttribs.BindCount, NumCachedSamplers); - for(Uint32 BindPoint = SamAttribs.BindPoint; BindPoint < EndBindPoint; ++BindPoint ) - ResourceCache.SetSampler(BindPoint, pSamplerD3D11Impl); - } -} #ifdef DEVELOPMENT static String DbgMakeResourceName(const D3DShaderResourceAttribs& Attr, Uint32 BindPoint) @@ -188,8 +145,6 @@ void ShaderResourcesD3D11::dvpVerifyCommittedResources(ID3D11Buffer* ResourceCache.GetUAVArrays (CachedUAVResources, d3d11UAVs); ProcessResources( - nullptr, 0, - [&](const D3DShaderResourceAttribs& cb, Uint32) { for (auto BindPoint = cb.BindPoint; BindPoint < cb.BindPoint + cb.BindCount; ++BindPoint) diff --git a/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h b/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h index aa3867f3..97fe7490 100644 --- a/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h +++ b/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h @@ -325,7 +325,7 @@ protected: typename TNewResourceHandler> void Initialize(ID3DBlob* pShaderByteCode, TNewResourceHandler NewResHandler, - const ShaderDesc& ShdrDesc, + const Char* ShaderName, const Char* SamplerSuffix); @@ -382,8 +382,8 @@ template void ShaderResources::Initialize(ID3DBlob* pShaderByteCode, - TNewResourceHandler NewResHandler, - const ShaderDesc& ShdrDesc, + TNewResourceHandler NewResHandler, + const Char* ShaderName, const Char* CombinedSamplerSuffix) { Uint32 CurrCB = 0, CurrTexSRV = 0, CurrTexUAV = 0, CurrBufSRV = 0, CurrBufUAV = 0, CurrSampler = 0; @@ -446,10 +446,7 @@ void ShaderResources::Initialize(ID3DBlob* pShaderByteCode, } ++CurrTexSRV; NewResHandler.OnNewTexSRV(*pNewTexSRV); - }, - - ShdrDesc, - CombinedSamplerSuffix); + }); if (CombinedSamplerSuffix != nullptr) { @@ -460,7 +457,7 @@ void ShaderResources::Initialize(ID3DBlob* pShaderByteCode, { const auto& Sampler = GetSampler(n); if (!Sampler.ValidTexSRVAssigned()) - LOG_ERROR_MESSAGE("Shader '", ShdrDesc.Name, "' uses combined texture samplers, but sampler '", Sampler.Name, "' is not assigned to any texture"); + LOG_ERROR_MESSAGE("Shader '", ShaderName, "' uses combined texture samplers, but sampler '", Sampler.Name, "' is not assigned to any texture"); } #endif } -- cgit v1.2.3 From 6f479d4aa4e49b1ac4b1a6fbfc8b52dbd3bf58d6 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sat, 2 Mar 2019 23:57:57 -0800 Subject: Partially reworked ShaderResourceLayoutD3D11 --- .../include/ShaderResourceLayoutD3D11.h | 13 +- .../src/ShaderResourceLayoutD3D11.cpp | 224 +++++++++++---------- .../include/ShaderResources.h | 11 + .../GraphicsEngineD3DBase/src/ShaderResources.cpp | 78 +++++++ 4 files changed, 213 insertions(+), 113 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h b/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h index b6079b0c..c6dd714b 100644 --- a/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h +++ b/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h @@ -53,9 +53,10 @@ public: ShaderResourceLayoutD3D11 ( ShaderResourceLayoutD3D11&&) = default; ShaderResourceLayoutD3D11& operator = ( ShaderResourceLayoutD3D11&&) = delete; - static size_t GetRequiredMemorySize(const ShaderResourcesD3D11& SrcResources, - const SHADER_RESOURCE_VARIABLE_TYPE* VarTypes, - Uint32 NumVarTypes); + static size_t GetRequiredMemorySize(const ShaderResourcesD3D11& SrcResources, + const PipelineResourceLayoutDesc& ResourceLayout, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes); void Initialize(std::shared_ptr pSrcResources, const SHADER_RESOURCE_VARIABLE_TYPE* VarTypes, @@ -198,6 +199,12 @@ public: } __forceinline bool IsBound(Uint32 ArrayIndex)const; + + bool IsStaticSampler()const + { + UNEXPECTED("Not implemented"); + return false; + } }; // dbgResourceCache is only used for sanity check and as a remainder that the resource cache must be alive diff --git a/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp b/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp index 5321d5e3..c6cf6f6b 100755 --- a/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp +++ b/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp @@ -77,11 +77,13 @@ ShaderResourceLayoutD3D11::~ShaderResourceLayoutD3D11() ); } -size_t ShaderResourceLayoutD3D11::GetRequiredMemorySize(const ShaderResourcesD3D11& SrcResources, - const SHADER_VARIABLE_TYPE* VarTypes, - Uint32 NumVarTypes) + +size_t ShaderResourceLayoutD3D11::GetRequiredMemorySize(const ShaderResourcesD3D11& SrcResources, + const PipelineResourceLayoutDesc& ResourceLayout, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes) { - auto ResCounters = SrcResources.CountResources(VarTypes, NumVarTypes); + auto ResCounters = SrcResources.CountResources(ResourceLayout, SrcResources.GetShaderType(), SrcResources.GetCombinedSamplerSuffix(), AllowedVarTypes, NumAllowedTypes); auto MemSize = ResCounters.NumCBs * sizeof(ConstBuffBindInfo) + ResCounters.NumTexSRVs * sizeof(TexSRVBindInfo) + ResCounters.NumTexUAVs * sizeof(TexUAVBindInfo) + @@ -91,6 +93,7 @@ size_t ShaderResourceLayoutD3D11::GetRequiredMemorySize(const ShaderResourcesD3D return MemSize; } +#if 0 void ShaderResourceLayoutD3D11::Initialize(std::shared_ptr pSrcResources, const SHADER_VARIABLE_TYPE* VarTypes, Uint32 NumVarTypes, @@ -199,7 +202,7 @@ void ShaderResourceLayoutD3D11::Initialize(std::shared_ptr(AssignedSamplerIndex); - if (strcmp(Sampler.Attribs.Name, AssignedSamplerAttribs.Name) == 0) + if (strcmp(Sampler.m_Attribs.Name, AssignedSamplerAttribs.Name) == 0) break; } VERIFY(AssignedSamplerIndex < NumSamplers, "Unable to find assigned sampler"); @@ -256,6 +259,7 @@ void ShaderResourceLayoutD3D11::Initialize(std::shared_ptrInitialize(NumCBSlots, NumSRVSlots, NumSamplerSlots, NumUAVSlots, ResCacheDataAllocator); } } +#endif void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache) { @@ -296,7 +300,7 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache HandleResources( [&](const ConstBuffBindInfo& cb) { - for(auto CBSlot = cb.Attribs.BindPoint; CBSlot < cb.Attribs.BindPoint+cb.Attribs.BindCount; ++CBSlot) + for(auto CBSlot = cb.m_Attribs.BindPoint; CBSlot < cb.m_Attribs.BindPoint+cb.m_Attribs.BindCount; ++CBSlot) { VERIFY_EXPR(CBSlot < m_pResourceCache->GetCBCount() && CBSlot < DstCache.GetCBCount()); DstCBs [CBSlot] = CachedCBs[CBSlot]; @@ -306,7 +310,7 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache [&](const TexSRVBindInfo& ts) { - for(auto SRVSlot = ts.Attribs.BindPoint; SRVSlot < ts.Attribs.BindPoint + ts.Attribs.BindCount; ++SRVSlot) + for(auto SRVSlot = ts.m_Attribs.BindPoint; SRVSlot < ts.m_Attribs.BindPoint + ts.m_Attribs.BindCount; ++SRVSlot) { VERIFY_EXPR(SRVSlot < m_pResourceCache->GetSRVCount() && SRVSlot < DstCache.GetSRVCount()); DstSRVResources[SRVSlot] = CachedSRVResources[SRVSlot]; @@ -316,7 +320,7 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache [&](const TexUAVBindInfo& uav) { - for(auto UAVSlot = uav.Attribs.BindPoint; UAVSlot < uav.Attribs.BindPoint + uav.Attribs.BindCount; ++UAVSlot) + for(auto UAVSlot = uav.m_Attribs.BindPoint; UAVSlot < uav.m_Attribs.BindPoint + uav.m_Attribs.BindCount; ++UAVSlot) { VERIFY_EXPR(UAVSlot < m_pResourceCache->GetUAVCount() && UAVSlot < DstCache.GetUAVCount()); DstUAVResources[UAVSlot] = CachedUAVResources[UAVSlot]; @@ -326,7 +330,7 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache [&](const BuffSRVBindInfo& srv) { - for(auto SRVSlot = srv.Attribs.BindPoint; SRVSlot < srv.Attribs.BindPoint + srv.Attribs.BindCount; ++SRVSlot) + for(auto SRVSlot = srv.m_Attribs.BindPoint; SRVSlot < srv.m_Attribs.BindPoint + srv.m_Attribs.BindCount; ++SRVSlot) { VERIFY_EXPR(SRVSlot < m_pResourceCache->GetSRVCount() && SRVSlot < DstCache.GetSRVCount()); DstSRVResources[SRVSlot] = CachedSRVResources[SRVSlot]; @@ -336,7 +340,7 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache [&](const BuffUAVBindInfo& uav) { - for(auto UAVSlot = uav.Attribs.BindPoint; UAVSlot < uav.Attribs.BindPoint + uav.Attribs.BindCount; ++UAVSlot) + for(auto UAVSlot = uav.m_Attribs.BindPoint; UAVSlot < uav.m_Attribs.BindPoint + uav.m_Attribs.BindCount; ++UAVSlot) { VERIFY_EXPR(UAVSlot < m_pResourceCache->GetUAVCount() && UAVSlot < DstCache.GetUAVCount()); DstUAVResources[UAVSlot] = CachedUAVResources[UAVSlot]; @@ -346,8 +350,8 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache [&](const SamplerBindInfo& sam) { - VERIFY(!sam.Attribs.IsStaticSampler(), "Variables are not created for static samplers"); - for(auto SamSlot = sam.Attribs.BindPoint; SamSlot < sam.Attribs.BindPoint + sam.Attribs.BindCount; ++SamSlot) + VERIFY(!sam.IsStaticSampler(), "Variables are not created for static samplers"); + for(auto SamSlot = sam.m_Attribs.BindPoint; SamSlot < sam.m_Attribs.BindPoint + sam.m_Attribs.BindCount; ++SamSlot) { VERIFY_EXPR(SamSlot < m_pResourceCache->GetSamplerCount() && SamSlot < DstCache.GetSamplerCount()); DstSamplers [SamSlot] = CachedSamplers[SamSlot]; @@ -360,7 +364,7 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache #define LOG_RESOURCE_BINDING_ERROR(ResType, pResource, Attribs, ArrayInd, ShaderName, ...)\ do{ \ const auto* ResName = pResource->GetDesc().Name; \ - if(Attribs.BindCount>1) \ + if (Attribs.BindCount>1) \ LOG_ERROR_MESSAGE( "Failed to bind ", ResType, " '", ResName, "' to variable '", Attribs.Name,\ "[", ArrayInd, "]' in shader '", ShaderName, "'. ", __VA_ARGS__ ); \ else \ @@ -372,7 +376,7 @@ void ShaderResourceLayoutD3D11::ConstBuffBindInfo::BindResource(IDeviceObject* p Uint32 ArrayIndex) { VERIFY(m_ParentResLayout.m_pResourceCache != nullptr, "Resource cache is null"); - DEV_CHECK_ERR(ArrayIndex < Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", Attribs.Name, "'. Max allowed index: ", Attribs.BindCount); + DEV_CHECK_ERR(ArrayIndex < m_Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", m_Attribs.Name, "'. Max allowed index: ", m_Attribs.BindCount); auto& ResourceCache = *m_ParentResLayout.m_pResourceCache; // We cannot use ValidatedCast<> here as the resource retrieved from the @@ -380,26 +384,26 @@ void ShaderResourceLayoutD3D11::ConstBuffBindInfo::BindResource(IDeviceObject* p RefCntAutoPtr pBuffD3D11Impl(pBuffer, IID_BufferD3D11); #ifdef DEVELOPMENT if (pBuffer && !pBuffD3D11Impl) - LOG_RESOURCE_BINDING_ERROR("buffer", pBuffer, Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Incorrect resource type: buffer is expected."); + LOG_RESOURCE_BINDING_ERROR("buffer", pBuffer, m_Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Incorrect resource type: buffer is expected."); if (pBuffD3D11Impl && (pBuffD3D11Impl->GetDesc().BindFlags & BIND_UNIFORM_BUFFER) == 0) { - LOG_RESOURCE_BINDING_ERROR("buffer", pBuffer, Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Buffer was not created with BIND_UNIFORM_BUFFER flag."); + LOG_RESOURCE_BINDING_ERROR("buffer", pBuffer, m_Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Buffer was not created with BIND_UNIFORM_BUFFER flag."); pBuffD3D11Impl.Release(); } - if (Attribs.GetVariableType() != SHADER_VARIABLE_TYPE_DYNAMIC) + if (GetType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) { - auto& CachedCB = ResourceCache.GetCB(Attribs.BindPoint + ArrayIndex); + auto& CachedCB = ResourceCache.GetCB(m_Attribs.BindPoint + ArrayIndex); if (CachedCB.pBuff != nullptr && CachedCB.pBuff != pBuffD3D11Impl) { - auto VarTypeStr = GetShaderVariableTypeLiteralName(Attribs.GetVariableType()); - LOG_ERROR_MESSAGE( "Non-null constant buffer is already bound to ", VarTypeStr, " shader variable '", Attribs.GetPrintName(ArrayIndex), "' in shader '", m_ParentResLayout.GetShaderName(), "'. Attempting to bind another resource or null is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic." ); + auto VarTypeStr = GetShaderVariableTypeLiteralName(GetType()); + LOG_ERROR_MESSAGE( "Non-null constant buffer is already bound to ", VarTypeStr, " shader variable '", m_Attribs.GetPrintName(ArrayIndex), "' in shader '", m_ParentResLayout.GetShaderName(), "'. Attempting to bind another resource or null is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic." ); } } #endif - ResourceCache.SetCB(Attribs.BindPoint + ArrayIndex, std::move(pBuffD3D11Impl) ); + ResourceCache.SetCB(m_Attribs.BindPoint + ArrayIndex, std::move(pBuffD3D11Impl) ); } @@ -408,9 +412,9 @@ bool ShaderResourceLayoutD3D11::ConstBuffBindInfo::IsBound(Uint32 ArrayIndex) { auto* pResourceCache = m_ParentResLayout.m_pResourceCache; VERIFY(pResourceCache, "Resource cache is null"); - VERIFY_EXPR(ArrayIndex < Attribs.BindCount); + VERIFY_EXPR(ArrayIndex < m_Attribs.BindCount); - return pResourceCache->IsCBBound(Attribs.BindPoint + ArrayIndex); + return pResourceCache->IsCBBound(m_Attribs.BindPoint + ArrayIndex); } @@ -446,7 +450,7 @@ void ShaderResourceLayoutD3D11::TexSRVBindInfo::BindResource(IDeviceObject* pVie Uint32 ArrayIndex) { VERIFY(m_ParentResLayout.m_pResourceCache, "Resource cache is null"); - DEV_CHECK_ERR(ArrayIndex < Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", Attribs.Name, "'. Max allowed index: ", Attribs.BindCount); + DEV_CHECK_ERR(ArrayIndex < m_Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", m_Attribs.Name, "'. Max allowed index: ", m_Attribs.BindCount); auto& ResourceCache = *m_ParentResLayout.m_pResourceCache; // We cannot use ValidatedCast<> here as the resource retrieved from the @@ -454,17 +458,17 @@ void ShaderResourceLayoutD3D11::TexSRVBindInfo::BindResource(IDeviceObject* pVie RefCntAutoPtr pViewD3D11(pView, IID_TextureViewD3D11); #ifdef DEVELOPMENT if (pView && !pViewD3D11) - LOG_RESOURCE_BINDING_ERROR("resource", pView, Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Incorect resource type: texture view is expected."); - if (pViewD3D11 && !dbgVerifyViewType("texture view", pViewD3D11.RawPtr(), Attribs, ArrayIndex, TEXTURE_VIEW_SHADER_RESOURCE, m_ParentResLayout.GetShaderName())) + LOG_RESOURCE_BINDING_ERROR("resource", pView, m_Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Incorect resource type: texture view is expected."); + if (pViewD3D11 && !dbgVerifyViewType("texture view", pViewD3D11.RawPtr(), m_Attribs, ArrayIndex, TEXTURE_VIEW_SHADER_RESOURCE, m_ParentResLayout.GetShaderName())) pViewD3D11.Release(); - if( Attribs.GetVariableType() != SHADER_VARIABLE_TYPE_DYNAMIC) + if( GetType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) { - auto& CachedSRV = ResourceCache.GetSRV(Attribs.BindPoint + ArrayIndex); + auto& CachedSRV = ResourceCache.GetSRV(m_Attribs.BindPoint + ArrayIndex); if (CachedSRV.pView != nullptr && CachedSRV.pView != pViewD3D11) { - auto VarTypeStr = GetShaderVariableTypeLiteralName(Attribs.GetVariableType()); - LOG_ERROR_MESSAGE( "Non-null texture SRV is already bound to ", VarTypeStr, " shader variable '", Attribs.GetPrintName(ArrayIndex), "' in shader '", m_ParentResLayout.GetShaderName(), "'. Attempting to bind another resource or null is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic." ); + auto VarTypeStr = GetShaderVariableTypeLiteralName(GetType()); + LOG_ERROR_MESSAGE( "Non-null texture SRV is already bound to ", VarTypeStr, " shader variable '", m_Attribs.GetPrintName(ArrayIndex), "' in shader '", m_ParentResLayout.GetShaderName(), "'. Attempting to bind another resource or null is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic." ); } } #endif @@ -472,9 +476,9 @@ void ShaderResourceLayoutD3D11::TexSRVBindInfo::BindResource(IDeviceObject* pVie if (ValidSamplerAssigned()) { auto& Sampler = m_ParentResLayout.GetResource(SamplerIndex); - VERIFY(!Sampler.Attribs.IsStaticSampler(), "Static samplers are not assigned to texture SRVs as they are initialized directly in the shader resource cache"); - VERIFY_EXPR(Sampler.Attribs.BindCount == Attribs.BindCount || Sampler.Attribs.BindCount == 1); - auto SamplerBindPoint = Sampler.Attribs.BindPoint + (Sampler.Attribs.BindCount != 1 ? ArrayIndex : 0); + VERIFY(!Sampler.IsStaticSampler(), "Static samplers are not assigned to texture SRVs as they are initialized directly in the shader resource cache"); + VERIFY_EXPR(Sampler.m_Attribs.BindCount == m_Attribs.BindCount || Sampler.m_Attribs.BindCount == 1); + auto SamplerBindPoint = Sampler.m_Attribs.BindPoint + (Sampler.m_Attribs.BindCount != 1 ? ArrayIndex : 0); SamplerD3D11Impl* pSamplerD3D11Impl = nullptr; if (pViewD3D11) @@ -483,37 +487,37 @@ void ShaderResourceLayoutD3D11::TexSRVBindInfo::BindResource(IDeviceObject* pVie #ifdef DEVELOPMENT if (pSamplerD3D11Impl == nullptr) { - if(Sampler.Attribs.BindCount > 1) - LOG_ERROR_MESSAGE( "Failed to bind sampler to variable '", Sampler.Attribs.Name, "[", ArrayIndex,"]'. Sampler is not set in the texture view '", pViewD3D11->GetDesc().Name, "'" ); + if(Sampler.m_Attribs.BindCount > 1) + LOG_ERROR_MESSAGE( "Failed to bind sampler to variable '", Sampler.m_Attribs.Name, "[", ArrayIndex,"]'. Sampler is not set in the texture view '", pViewD3D11->GetDesc().Name, "'" ); else - LOG_ERROR_MESSAGE( "Failed to bind sampler to variable '", Sampler.Attribs.Name, "'. Sampler is not set in the texture view '", pViewD3D11->GetDesc().Name, "'" ); + LOG_ERROR_MESSAGE( "Failed to bind sampler to variable '", Sampler.m_Attribs.Name, "'. Sampler is not set in the texture view '", pViewD3D11->GetDesc().Name, "'" ); } #endif } #ifdef DEVELOPMENT - if (Sampler.Attribs.GetVariableType() != SHADER_VARIABLE_TYPE_DYNAMIC) + if (Sampler.GetType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) { auto& CachedSampler = ResourceCache.GetSampler(SamplerBindPoint); if (CachedSampler.pSampler != nullptr && CachedSampler.pSampler != pSamplerD3D11Impl) { - auto VarTypeStr = GetShaderVariableTypeLiteralName(Attribs.GetVariableType()); - LOG_ERROR_MESSAGE( "Non-null sampler is already bound to ", VarTypeStr, " shader variable '", Sampler.Attribs.GetPrintName(ArrayIndex), "' in shader '", m_ParentResLayout.GetShaderName(), "'. Attempting to bind another sampler or null is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic." ); + auto VarTypeStr = GetShaderVariableTypeLiteralName(GetType()); + LOG_ERROR_MESSAGE( "Non-null sampler is already bound to ", VarTypeStr, " shader variable '", Sampler.m_Attribs.GetPrintName(ArrayIndex), "' in shader '", m_ParentResLayout.GetShaderName(), "'. Attempting to bind another sampler or null is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic." ); } } #endif ResourceCache.SetSampler(SamplerBindPoint, pSamplerD3D11Impl); } - ResourceCache.SetTexSRV(Attribs.BindPoint + ArrayIndex, std::move(pViewD3D11)); + ResourceCache.SetTexSRV(m_Attribs.BindPoint + ArrayIndex, std::move(pViewD3D11)); } void ShaderResourceLayoutD3D11::SamplerBindInfo::BindResource(IDeviceObject* pSampler, Uint32 ArrayIndex) { VERIFY(m_ParentResLayout.m_pResourceCache != nullptr, "Resource cache is null"); - DEV_CHECK_ERR(ArrayIndex < Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", Attribs.Name, "'. Max allowed index: ", Attribs.BindCount); + DEV_CHECK_ERR(ArrayIndex < m_Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", m_Attribs.Name, "'. Max allowed index: ", m_Attribs.BindCount); auto& ResourceCache = *m_ParentResLayout.m_pResourceCache; - VERIFY(!Attribs.IsStaticSampler(), "Cannot bind sampler to a static sampler"); + VERIFY(!IsStaticSampler(), "Cannot bind sampler to a static sampler"); // We cannot use ValidatedCast<> here as the resource retrieved from the // resource mapping can be of wrong type @@ -521,33 +525,33 @@ void ShaderResourceLayoutD3D11::SamplerBindInfo::BindResource(IDeviceObject* pSa #ifdef DEVELOPMENT if (pSampler && !pSamplerD3D11) - LOG_RESOURCE_BINDING_ERROR("sampler", pSampler, Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Incorect resource type: sampler is expected."); + LOG_RESOURCE_BINDING_ERROR("sampler", pSampler, m_Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Incorect resource type: sampler is expected."); - if (Attribs.ValidTexSRVAssigned()) + if (m_Attribs.ValidTexSRVAssigned()) { - auto* TexSRVName = m_ParentResLayout.m_pResources->GetTexSRV(Attribs.GetTexSRVId()).Name; - LOG_WARNING_MESSAGE("Texture sampler sampler '", Attribs.Name, "' is assigned to texture SRV '", TexSRVName, "' and should not be accessed directly. The sampler is initialized when texture SRV is set to '", TexSRVName, "' variable."); + auto* TexSRVName = m_ParentResLayout.m_pResources->GetTexSRV(m_Attribs.GetTexSRVId()).Name; + LOG_WARNING_MESSAGE("Texture sampler sampler '", m_Attribs.Name, "' is assigned to texture SRV '", TexSRVName, "' and should not be accessed directly. The sampler is initialized when texture SRV is set to '", TexSRVName, "' variable."); } - if (Attribs.GetVariableType() != SHADER_VARIABLE_TYPE_DYNAMIC) + if (GetType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) { - auto& CachedSampler = ResourceCache.GetSampler(Attribs.BindPoint + ArrayIndex); + auto& CachedSampler = ResourceCache.GetSampler(m_Attribs.BindPoint + ArrayIndex); if( CachedSampler.pSampler != nullptr && CachedSampler.pSampler != pSamplerD3D11) { - auto VarTypeStr = GetShaderVariableTypeLiteralName(Attribs.GetVariableType()); - LOG_ERROR_MESSAGE( "Non-null sampler is already bound to ", VarTypeStr, " shader variable '", Attribs.GetPrintName(ArrayIndex), "' in shader '", m_ParentResLayout.GetShaderName(), "'. Attempting to bind another sampler or null is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic." ); + auto VarTypeStr = GetShaderVariableTypeLiteralName(GetType()); + LOG_ERROR_MESSAGE( "Non-null sampler is already bound to ", VarTypeStr, " shader variable '", m_Attribs.GetPrintName(ArrayIndex), "' in shader '", m_ParentResLayout.GetShaderName(), "'. Attempting to bind another sampler or null is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic." ); } } #endif - ResourceCache.SetSampler(Attribs.BindPoint + ArrayIndex, std::move(pSamplerD3D11)); + ResourceCache.SetSampler(m_Attribs.BindPoint + ArrayIndex, std::move(pSamplerD3D11)); } void ShaderResourceLayoutD3D11::BuffSRVBindInfo::BindResource(IDeviceObject* pView, Uint32 ArrayIndex) { VERIFY(m_ParentResLayout.m_pResourceCache != nullptr, "Resource cache is null"); - DEV_CHECK_ERR(ArrayIndex < Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", Attribs.Name, "'. Max allowed index: ", Attribs.BindCount); + DEV_CHECK_ERR(ArrayIndex < m_Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", m_Attribs.Name, "'. Max allowed index: ", m_Attribs.BindCount); auto& ResourceCache = *m_ParentResLayout.m_pResourceCache; // We cannot use ValidatedCast<> here as the resource retrieved from the @@ -555,22 +559,22 @@ void ShaderResourceLayoutD3D11::BuffSRVBindInfo::BindResource(IDeviceObject* pVi RefCntAutoPtr pViewD3D11(pView, IID_BufferViewD3D11); #ifdef DEVELOPMENT if (pView && !pViewD3D11) - LOG_RESOURCE_BINDING_ERROR("resource", pView, Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Incorect resource type: buffer view is expected."); - if (pViewD3D11 && !dbgVerifyViewType("buffer view", pViewD3D11.RawPtr(), Attribs, ArrayIndex, BUFFER_VIEW_SHADER_RESOURCE, m_ParentResLayout.GetShaderName())) + LOG_RESOURCE_BINDING_ERROR("resource", pView, m_Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Incorect resource type: buffer view is expected."); + if (pViewD3D11 && !dbgVerifyViewType("buffer view", pViewD3D11.RawPtr(), m_Attribs, ArrayIndex, BUFFER_VIEW_SHADER_RESOURCE, m_ParentResLayout.GetShaderName())) pViewD3D11.Release(); - if (Attribs.GetVariableType() != SHADER_VARIABLE_TYPE_DYNAMIC) + if (GetType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) { - auto& CachedSRV = ResourceCache.GetSRV(Attribs.BindPoint + ArrayIndex); + auto& CachedSRV = ResourceCache.GetSRV(m_Attribs.BindPoint + ArrayIndex); if (CachedSRV.pView != nullptr && CachedSRV.pView != pViewD3D11) { - auto VarTypeStr = GetShaderVariableTypeLiteralName(Attribs.GetVariableType()); - LOG_ERROR_MESSAGE( "Non-null buffer SRV is already bound to ", VarTypeStr, " shader variable '", Attribs.GetPrintName(ArrayIndex), "' in shader '", m_ParentResLayout.GetShaderName(), "'. Attempting to bind another resource or null is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic." ); + auto VarTypeStr = GetShaderVariableTypeLiteralName(GetType()); + LOG_ERROR_MESSAGE( "Non-null buffer SRV is already bound to ", VarTypeStr, " shader variable '", m_Attribs.GetPrintName(ArrayIndex), "' in shader '", m_ParentResLayout.GetShaderName(), "'. Attempting to bind another resource or null is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic." ); } } #endif - ResourceCache.SetBufSRV(Attribs.BindPoint + ArrayIndex, std::move(pViewD3D11)); + ResourceCache.SetBufSRV(m_Attribs.BindPoint + ArrayIndex, std::move(pViewD3D11)); } @@ -578,7 +582,7 @@ void ShaderResourceLayoutD3D11::TexUAVBindInfo::BindResource(IDeviceObject* pVie Uint32 ArrayIndex) { VERIFY(m_ParentResLayout.m_pResourceCache != nullptr, "Resource cache is null"); - DEV_CHECK_ERR(ArrayIndex < Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", Attribs.Name, "'. Max allowed index: ", Attribs.BindCount); + DEV_CHECK_ERR(ArrayIndex < m_Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", m_Attribs.Name, "'. Max allowed index: ", m_Attribs.BindCount); auto& ResourceCache = *m_ParentResLayout.m_pResourceCache; // We cannot use ValidatedCast<> here as the resource retrieved from the @@ -586,22 +590,22 @@ void ShaderResourceLayoutD3D11::TexUAVBindInfo::BindResource(IDeviceObject* pVie RefCntAutoPtr pViewD3D11(pView, IID_TextureViewD3D11); #ifdef DEVELOPMENT if (pView && !pViewD3D11) - LOG_RESOURCE_BINDING_ERROR("resource", pView, Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Incorect resource type: texture view is expected."); - if (pViewD3D11 && !dbgVerifyViewType("texture view", pViewD3D11.RawPtr(), Attribs, ArrayIndex, TEXTURE_VIEW_UNORDERED_ACCESS, m_ParentResLayout.GetShaderName())) + LOG_RESOURCE_BINDING_ERROR("resource", pView, m_Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Incorect resource type: texture view is expected."); + if (pViewD3D11 && !dbgVerifyViewType("texture view", pViewD3D11.RawPtr(), m_Attribs, ArrayIndex, TEXTURE_VIEW_UNORDERED_ACCESS, m_ParentResLayout.GetShaderName())) pViewD3D11.Release(); - if (Attribs.GetVariableType() != SHADER_VARIABLE_TYPE_DYNAMIC) + if (GetType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) { - auto& CachedUAV = ResourceCache.GetUAV(Attribs.BindPoint + ArrayIndex); + auto& CachedUAV = ResourceCache.GetUAV(m_Attribs.BindPoint + ArrayIndex); if (CachedUAV.pView != nullptr && CachedUAV.pView != pViewD3D11) { - auto VarTypeStr = GetShaderVariableTypeLiteralName(Attribs.GetVariableType()); - LOG_ERROR_MESSAGE( "Non-null texture UAV is already bound to ", VarTypeStr, " shader variable '", Attribs.GetPrintName(ArrayIndex), "' in shader '", m_ParentResLayout.GetShaderName(), "'. Attempting to bind another resource or null is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic." ); + auto VarTypeStr = GetShaderVariableTypeLiteralName(GetType()); + LOG_ERROR_MESSAGE( "Non-null texture UAV is already bound to ", VarTypeStr, " shader variable '", m_Attribs.GetPrintName(ArrayIndex), "' in shader '", m_ParentResLayout.GetShaderName(), "'. Attempting to bind another resource or null is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic." ); } } #endif - ResourceCache.SetTexUAV(Attribs.BindPoint + ArrayIndex, std::move(pViewD3D11)); + ResourceCache.SetTexUAV(m_Attribs.BindPoint + ArrayIndex, std::move(pViewD3D11)); } @@ -609,7 +613,7 @@ void ShaderResourceLayoutD3D11::BuffUAVBindInfo::BindResource(IDeviceObject* pVi Uint32 ArrayIndex) { VERIFY(m_ParentResLayout.m_pResourceCache != nullptr, "Resource cache is null"); - DEV_CHECK_ERR(ArrayIndex < Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", Attribs.Name, "'. Max allowed index: ", Attribs.BindCount); + DEV_CHECK_ERR(ArrayIndex < m_Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", m_Attribs.Name, "'. Max allowed index: ", m_Attribs.BindCount); auto& ResourceCache = *m_ParentResLayout.m_pResourceCache; // We cannot use ValidatedCast<> here as the resource retrieved from the @@ -617,22 +621,22 @@ void ShaderResourceLayoutD3D11::BuffUAVBindInfo::BindResource(IDeviceObject* pVi RefCntAutoPtr pViewD3D11(pView, IID_BufferViewD3D11); #ifdef DEVELOPMENT if (pView && !pViewD3D11) - LOG_RESOURCE_BINDING_ERROR("resource", pView, Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Incorect resource type: buffer view is expected."); - if (pViewD3D11 && !dbgVerifyViewType("buffer view", pViewD3D11.RawPtr(), Attribs, ArrayIndex, BUFFER_VIEW_UNORDERED_ACCESS, m_ParentResLayout.GetShaderName()) ) + LOG_RESOURCE_BINDING_ERROR("resource", pView, m_Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Incorect resource type: buffer view is expected."); + if (pViewD3D11 && !dbgVerifyViewType("buffer view", pViewD3D11.RawPtr(), m_Attribs, ArrayIndex, BUFFER_VIEW_UNORDERED_ACCESS, m_ParentResLayout.GetShaderName()) ) pViewD3D11.Release(); - if (Attribs.GetVariableType() != SHADER_VARIABLE_TYPE_DYNAMIC) + if (GetType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) { - auto& CachedUAV = ResourceCache.GetUAV(Attribs.BindPoint + ArrayIndex); + auto& CachedUAV = ResourceCache.GetUAV(m_Attribs.BindPoint + ArrayIndex); if (CachedUAV.pView != nullptr && CachedUAV.pView != pViewD3D11) { - auto VarTypeStr = GetShaderVariableTypeLiteralName(Attribs.GetVariableType()); - LOG_ERROR_MESSAGE( "Non-null buffer UAV is already bound to ", VarTypeStr, " shader variable '", Attribs.GetPrintName(ArrayIndex), "' in shader '", m_ParentResLayout.GetShaderName(), "'. Attempting to bind another resource or null is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic." ); + auto VarTypeStr = GetShaderVariableTypeLiteralName(GetType()); + LOG_ERROR_MESSAGE( "Non-null buffer UAV is already bound to ", VarTypeStr, " shader variable '", m_Attribs.GetPrintName(ArrayIndex), "' in shader '", m_ParentResLayout.GetShaderName(), "'. Attempting to bind another resource or null is an error and may cause unpredicted behavior. Use another shader resource binding instance or label the variable as dynamic." ); } } #endif - ResourceCache.SetBufUAV(Attribs.BindPoint + ArrayIndex, std::move(pViewD3D11)); + ResourceCache.SetBufUAV(m_Attribs.BindPoint + ArrayIndex, std::move(pViewD3D11)); } @@ -640,9 +644,9 @@ bool ShaderResourceLayoutD3D11::TexSRVBindInfo::IsBound(Uint32 ArrayIndex)const { auto* pResourceCache = m_ParentResLayout.m_pResourceCache; VERIFY(pResourceCache != nullptr, "Resource cache is null"); - VERIFY_EXPR(ArrayIndex < Attribs.BindCount); + VERIFY_EXPR(ArrayIndex < m_Attribs.BindCount); - return pResourceCache->IsSRVBound(Attribs.BindPoint + ArrayIndex, true); + return pResourceCache->IsSRVBound(m_Attribs.BindPoint + ArrayIndex, true); } @@ -650,36 +654,36 @@ bool ShaderResourceLayoutD3D11::BuffSRVBindInfo::IsBound(Uint32 ArrayIndex)const { auto* pResourceCache = m_ParentResLayout.m_pResourceCache; VERIFY(pResourceCache, "Resource cache is null"); - VERIFY_EXPR(ArrayIndex < Attribs.BindCount); + VERIFY_EXPR(ArrayIndex < m_Attribs.BindCount); - return pResourceCache->IsSRVBound(Attribs.BindPoint + ArrayIndex, false); + return pResourceCache->IsSRVBound(m_Attribs.BindPoint + ArrayIndex, false); } bool ShaderResourceLayoutD3D11::TexUAVBindInfo::IsBound(Uint32 ArrayIndex)const { auto* pResourceCache = m_ParentResLayout.m_pResourceCache; VERIFY(pResourceCache, "Resource cache is null"); - VERIFY_EXPR(ArrayIndex < Attribs.BindCount); + VERIFY_EXPR(ArrayIndex < m_Attribs.BindCount); - return pResourceCache->IsUAVBound(Attribs.BindPoint + ArrayIndex, true); + return pResourceCache->IsUAVBound(m_Attribs.BindPoint + ArrayIndex, true); } bool ShaderResourceLayoutD3D11::BuffUAVBindInfo::IsBound(Uint32 ArrayIndex)const { auto* pResourceCache = m_ParentResLayout.m_pResourceCache; VERIFY(pResourceCache, "Resource cache is null"); - VERIFY_EXPR(ArrayIndex < Attribs.BindCount); + VERIFY_EXPR(ArrayIndex < m_Attribs.BindCount); - return pResourceCache->IsUAVBound(Attribs.BindPoint + ArrayIndex, false); + return pResourceCache->IsUAVBound(m_Attribs.BindPoint + ArrayIndex, false); } bool ShaderResourceLayoutD3D11::SamplerBindInfo::IsBound(Uint32 ArrayIndex)const { auto* pResourceCache = m_ParentResLayout.m_pResourceCache; VERIFY(pResourceCache, "Resource cache is null"); - VERIFY_EXPR(ArrayIndex < Attribs.BindCount); + VERIFY_EXPR(ArrayIndex < m_Attribs.BindCount); - return pResourceCache->IsSamplerBound(Attribs.BindPoint + ArrayIndex); + return pResourceCache->IsSamplerBound(m_Attribs.BindPoint + ArrayIndex); } @@ -697,15 +701,15 @@ public: template void Bind( ResourceType &Res) { - if ( (Flags & (1 << Res.Attribs.GetVariableType())) == 0 ) + if ( (Flags & (1 << Res.GetType())) == 0 ) return; - for (Uint16 elem=0; elem < Res.Attribs.BindCount; ++elem) + for (Uint16 elem=0; elem < Res.m_Attribs.BindCount; ++elem) { if ( (Flags & BIND_SHADER_RESOURCES_KEEP_EXISTING) && Res.IsBound(elem) ) continue; - const auto* VarName = Res.Attribs.Name; + const auto* VarName = Res.m_Attribs.Name; RefCntAutoPtr pRes; ResourceMapping.GetResource( VarName, &pRes, elem ); if (pRes) @@ -776,20 +780,20 @@ void ShaderResourceLayoutD3D11::BindResources( IResourceMapping* pResourceMappin } template -IShaderVariable* ShaderResourceLayoutD3D11::GetResourceByName( const Char* Name ) +IShaderResourceVariable* ShaderResourceLayoutD3D11::GetResourceByName( const Char* Name ) { auto NumResources = GetNumResources(); for (Uint32 res = 0; res < NumResources; ++res) { auto& Resource = GetResource(res); - if (strcmp(Resource.Attribs.Name, Name) == 0) + if (strcmp(Resource.m_Attribs.Name, Name) == 0) return &Resource; } return nullptr; } -IShaderVariable* ShaderResourceLayoutD3D11::GetShaderVariable(const Char* Name) +IShaderResourceVariable* ShaderResourceLayoutD3D11::GetShaderVariable(const Char* Name) { if(auto* pCB = GetResourceByName(Name)) return pCB; @@ -900,7 +904,7 @@ public: } template - IShaderVariable* TryResource() + IShaderResourceVariable* TryResource() { #ifdef _DEBUG VERIFY(Layout.GetResourceOffset() >= dbgPreviousResourceOffset, "Resource types are processed out of order!"); @@ -924,7 +928,7 @@ private: #endif }; -IShaderVariable* ShaderResourceLayoutD3D11::GetShaderVariable( Uint32 Index ) +IShaderResourceVariable* ShaderResourceLayoutD3D11::GetShaderVariable( Uint32 Index ) { ShaderVariableLocator VarLocator(*this, Index); @@ -975,11 +979,11 @@ do{ \ const_cast(this)->HandleResources( [&](const ConstBuffBindInfo& cb) { - for (Uint32 BindPoint = cb.Attribs.BindPoint; BindPoint < Uint32{cb.Attribs.BindPoint} + cb.Attribs.BindCount; ++BindPoint) + for (Uint32 BindPoint = cb.m_Attribs.BindPoint; BindPoint < Uint32{cb.m_Attribs.BindPoint} + cb.m_Attribs.BindCount; ++BindPoint) { if (!m_pResourceCache->IsCBBound(BindPoint)) { - LOG_MISSING_BINDING("constant buffer", cb.Attribs, BindPoint); + LOG_MISSING_BINDING("constant buffer", cb.m_Attribs, BindPoint); BindingsOK = false; } } @@ -987,27 +991,27 @@ do{ \ [&](const TexSRVBindInfo& ts) { - for (Uint32 BindPoint = ts.Attribs.BindPoint; BindPoint < Uint32{ts.Attribs.BindPoint} + ts.Attribs.BindCount; ++BindPoint) + for (Uint32 BindPoint = ts.m_Attribs.BindPoint; BindPoint < Uint32{ts.m_Attribs.BindPoint} + ts.m_Attribs.BindCount; ++BindPoint) { if (!m_pResourceCache->IsSRVBound(BindPoint, true)) { - LOG_MISSING_BINDING("texture", ts.Attribs, BindPoint); + LOG_MISSING_BINDING("texture", ts.m_Attribs, BindPoint); BindingsOK = false; } if (ts.ValidSamplerAssigned()) { const auto& Sampler = GetConstResource(ts.SamplerIndex); - VERIFY_EXPR(Sampler.Attribs.BindCount == ts.Attribs.BindCount || Sampler.Attribs.BindCount == 1); + VERIFY_EXPR(Sampler.m_Attribs.BindCount == ts.m_Attribs.BindCount || Sampler.m_Attribs.BindCount == 1); // Verify that if single sampler is used for all texture array elements, all samplers set in the resource views are consistent - if (ts.Attribs.BindCount > 1 && Sampler.Attribs.BindCount == 1) + if (ts.m_Attribs.BindCount > 1 && Sampler.m_Attribs.BindCount == 1) { ShaderResourceCacheD3D11::CachedSampler* pCachedSamplers = nullptr; ID3D11SamplerState** ppCachedD3D11Samplers = nullptr; m_pResourceCache->GetSamplerArrays(pCachedSamplers, ppCachedD3D11Samplers); - VERIFY_EXPR(Sampler.Attribs.BindPoint < m_pResourceCache->GetSamplerCount()); - const auto& CachedSampler = pCachedSamplers[Sampler.Attribs.BindPoint]; + VERIFY_EXPR(Sampler.m_Attribs.BindPoint < m_pResourceCache->GetSamplerCount()); + const auto& CachedSampler = pCachedSamplers[Sampler.m_Attribs.BindPoint]; ShaderResourceCacheD3D11::CachedResource* pCachedResources = nullptr; ID3D11ShaderResourceView** ppCachedD3D11Resources = nullptr; @@ -1020,7 +1024,7 @@ do{ \ auto* pSampler = pTexView->GetSampler(); if (pSampler != nullptr && pSampler != CachedSampler.pSampler.RawPtr()) { - LOG_ERROR_MESSAGE( "All elements of texture array '", ts.Attribs.Name, "' in shader '", GetShaderName(), "' share the same sampler. However, the sampler set in view for element ", BindPoint - ts.Attribs.BindPoint, " does not match bound sampler. This may cause incorrect behavior on GL platform." ); + LOG_ERROR_MESSAGE( "All elements of texture array '", ts.m_Attribs.Name, "' in shader '", GetShaderName(), "' share the same sampler. However, the sampler set in view for element ", BindPoint - ts.m_Attribs.BindPoint, " does not match bound sampler. This may cause incorrect behavior on GL platform." ); } } } @@ -1030,11 +1034,11 @@ do{ \ [&](const TexUAVBindInfo& uav) { - for (Uint32 BindPoint = uav.Attribs.BindPoint; BindPoint < Uint32{uav.Attribs.BindPoint} + uav.Attribs.BindCount; ++BindPoint) + for (Uint32 BindPoint = uav.m_Attribs.BindPoint; BindPoint < Uint32{uav.m_Attribs.BindPoint} + uav.m_Attribs.BindCount; ++BindPoint) { if (!m_pResourceCache->IsUAVBound(BindPoint, true)) { - LOG_MISSING_BINDING("texture UAV", uav.Attribs, BindPoint); + LOG_MISSING_BINDING("texture UAV", uav.m_Attribs, BindPoint); BindingsOK = false; } } @@ -1042,11 +1046,11 @@ do{ \ [&](const BuffSRVBindInfo& buf) { - for (Uint32 BindPoint = buf.Attribs.BindPoint; BindPoint < Uint32{buf.Attribs.BindPoint} + buf.Attribs.BindCount; ++BindPoint) + for (Uint32 BindPoint = buf.m_Attribs.BindPoint; BindPoint < Uint32{buf.m_Attribs.BindPoint} + buf.m_Attribs.BindCount; ++BindPoint) { if (!m_pResourceCache->IsSRVBound(BindPoint, false)) { - LOG_MISSING_BINDING("buffer", buf.Attribs, BindPoint); + LOG_MISSING_BINDING("buffer", buf.m_Attribs, BindPoint); BindingsOK = false; } } @@ -1054,11 +1058,11 @@ do{ \ [&](const BuffUAVBindInfo& uav) { - for (Uint32 BindPoint = uav.Attribs.BindPoint; BindPoint < Uint32{uav.Attribs.BindPoint} + uav.Attribs.BindCount; ++BindPoint) + for (Uint32 BindPoint = uav.m_Attribs.BindPoint; BindPoint < Uint32{uav.m_Attribs.BindPoint} + uav.m_Attribs.BindCount; ++BindPoint) { if (!m_pResourceCache->IsUAVBound(BindPoint, false)) { - LOG_MISSING_BINDING("buffer UAV", uav.Attribs, BindPoint); + LOG_MISSING_BINDING("buffer UAV", uav.m_Attribs, BindPoint); BindingsOK = false; } } @@ -1066,11 +1070,11 @@ do{ \ [&](const SamplerBindInfo& sam) { - for (Uint32 BindPoint = sam.Attribs.BindPoint; BindPoint < Uint32{sam.Attribs.BindPoint} + sam.Attribs.BindCount; ++BindPoint) + for (Uint32 BindPoint = sam.m_Attribs.BindPoint; BindPoint < Uint32{sam.m_Attribs.BindPoint} + sam.m_Attribs.BindCount; ++BindPoint) { if (!m_pResourceCache->IsSamplerBound(BindPoint)) { - LOG_MISSING_BINDING("sampler", sam.Attribs, BindPoint); + LOG_MISSING_BINDING("sampler", sam.m_Attribs, BindPoint); BindingsOK = false; } } diff --git a/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h b/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h index 97fe7490..64c8fe61 100644 --- a/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h +++ b/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h @@ -62,6 +62,7 @@ #include "HashUtils.h" #include "StringPool.h" #include "D3DShaderResourceLoader.h" +#include "PipelineState.h" namespace Diligent { @@ -223,6 +224,10 @@ public: SamplerOrTexSRVId == Attribs.SamplerOrTexSRVId; } + SHADER_RESOURCE_VARIABLE_TYPE FindVariableType(SHADER_TYPE ShaderType, + const PipelineResourceLayoutDesc& ResourceLayoutDesc, + const char* CombinedSamplerSuffix)const; + size_t GetHash()const { return ComputeHash(BindPoint, BindCount, InputType, SRVDimension, SamplerOrTexSRVId); @@ -318,6 +323,12 @@ public: size_t GetHash()const; + D3DShaderResourceCounters CountResources(const PipelineResourceLayoutDesc& ResourceLayout, + SHADER_TYPE ShaderStage, + const char* CombinedSamplerSuffix, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes)const noexcept; + protected: template Date: Sat, 2 Mar 2019 23:59:59 -0800 Subject: Minor update to ShaderResourceLayoutVk --- .../GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp index 48d117f6..9f212fd4 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp @@ -69,10 +69,10 @@ static Int32 FindImmutableSampler(SHADER_TYPE ShaderType, return -1; } -static SHADER_RESOURCE_VARIABLE_TYPE GetShaderVariableType(SHADER_TYPE ShaderType, - const SPIRVShaderResourceAttribs& Attribs, - const PipelineResourceLayoutDesc& ResourceLayoutDesc, - const char* CombinedSamplerSuffix) +static SHADER_RESOURCE_VARIABLE_TYPE FindShaderVariableType(SHADER_TYPE ShaderType, + const SPIRVShaderResourceAttribs& Attribs, + const PipelineResourceLayoutDesc& ResourceLayoutDesc, + const char* CombinedSamplerSuffix) { if (Attribs.Type == SPIRVShaderResourceAttribs::ResourceType::SeparateSampler) { @@ -120,7 +120,7 @@ void ShaderResourceLayoutVk::AllocateMemory(std::shared_ptrProcessResources( [&](const SPIRVShaderResourceAttribs& ResAttribs, Uint32) { - auto VarType = GetShaderVariableType(ShaderType, ResAttribs, ResourceLayoutDesc, CombinedSamplerSuffix); + auto VarType = FindShaderVariableType(ShaderType, ResAttribs, ResourceLayoutDesc, CombinedSamplerSuffix); if (IsAllowedType(VarType, AllowedTypeBits)) { // For immutable separate samplers we still allocate VkResource instances, but they are never exposed to the app @@ -187,7 +187,7 @@ void ShaderResourceLayoutVk::InitializeStaticResourceLayout(std::shared_ptrProcessResources( [&](const SPIRVShaderResourceAttribs& Attribs, Uint32) { - auto VarType = GetShaderVariableType(ShaderType, Attribs, ResourceLayoutDesc, CombinedSamplerSuffix); + auto VarType = FindShaderVariableType(ShaderType, Attribs, ResourceLayoutDesc, CombinedSamplerSuffix); if (!IsAllowedType(VarType, AllowedTypeBits)) return; @@ -345,7 +345,7 @@ void ShaderResourceLayoutVk::Initialize(IRenderDevice* const SPIRVShaderResourceAttribs& Attribs) { const auto ShaderType = Resources.GetShaderType(); - const SHADER_RESOURCE_VARIABLE_TYPE VarType = GetShaderVariableType(ShaderType, Attribs, ResourceLayoutDesc, Resources.GetCombinedSamplerSuffix()); + const SHADER_RESOURCE_VARIABLE_TYPE VarType = FindShaderVariableType(ShaderType, Attribs, ResourceLayoutDesc, Resources.GetCombinedSamplerSuffix()); if (!IsAllowedType(VarType, AllowedTypeBits)) return; -- cgit v1.2.3 From 04330a7e1d0198e721fd8d10379ab751b6826a35 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sun, 3 Mar 2019 13:16:34 -0800 Subject: Cleaned up QueryInterface declarations --- Graphics/GraphicsEngine/include/ResourceMappingImpl.h | 2 +- Graphics/GraphicsEngine/interface/Buffer.h | 2 +- Graphics/GraphicsEngine/interface/BufferView.h | 2 +- Graphics/GraphicsEngine/interface/DeviceContext.h | 2 +- Graphics/GraphicsEngine/interface/Fence.h | 2 +- Graphics/GraphicsEngine/interface/Sampler.h | 2 +- .../GraphicsEngineD3D11/include/BufferD3D11Impl.h | 2 +- .../GraphicsEngineD3D11/include/BufferViewD3D11Impl.h | 2 +- .../include/DeviceContextD3D11Impl.h | 2 +- .../include/PipelineStateD3D11Impl.h | 19 ++++++++++++++++++- .../include/RenderDeviceD3D11Impl.h | 2 +- .../GraphicsEngineD3D11/include/SamplerD3D11Impl.h | 2 +- .../GraphicsEngineD3D11/include/SwapChainD3D11Impl.h | 2 +- .../GraphicsEngineD3D11/include/TextureBaseD3D11.h | 2 +- .../include/TextureViewD3D11Impl.h | 2 +- .../src/DeviceContextD3D11Impl.cpp | 4 ++-- .../GraphicsEngineVulkan/include/CommandQueueVkImpl.h | 2 +- .../GraphicsEngineVulkan/include/SwapChainVkImpl.h | 2 +- .../GraphicsEngineVulkan/include/TextureViewVkImpl.h | 2 +- Graphics/GraphicsEngineVulkan/include/TextureVkImpl.h | 2 +- 20 files changed, 38 insertions(+), 21 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngine/include/ResourceMappingImpl.h b/Graphics/GraphicsEngine/include/ResourceMappingImpl.h index ae0b4734..8630d764 100644 --- a/Graphics/GraphicsEngine/include/ResourceMappingImpl.h +++ b/Graphics/GraphicsEngine/include/ResourceMappingImpl.h @@ -104,7 +104,7 @@ namespace Diligent ~ResourceMappingImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID& IID, IObject** ppInterface )override final; + virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface )override final; /// Implementation of IResourceMapping::AddResource() virtual void AddResource( const Char* Name, IDeviceObject* pObject, bool bIsUnique )override final; diff --git a/Graphics/GraphicsEngine/interface/Buffer.h b/Graphics/GraphicsEngine/interface/Buffer.h index 3bf17e94..7729df8d 100644 --- a/Graphics/GraphicsEngine/interface/Buffer.h +++ b/Graphics/GraphicsEngine/interface/Buffer.h @@ -171,7 +171,7 @@ class IBuffer : public IDeviceObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface( const Diligent::INTERFACE_ID& IID, IObject** ppInterface ) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; /// Returns the buffer description used to create the object virtual const BufferDesc& GetDesc()const = 0; diff --git a/Graphics/GraphicsEngine/interface/BufferView.h b/Graphics/GraphicsEngine/interface/BufferView.h index 0f396dd4..37162724 100644 --- a/Graphics/GraphicsEngine/interface/BufferView.h +++ b/Graphics/GraphicsEngine/interface/BufferView.h @@ -138,7 +138,7 @@ class IBufferView : public IDeviceObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface( const Diligent::INTERFACE_ID& IID, IObject** ppInterface ) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; /// Returns the buffer view description used to create the object virtual const BufferViewDesc& GetDesc()const = 0; diff --git a/Graphics/GraphicsEngine/interface/DeviceContext.h b/Graphics/GraphicsEngine/interface/DeviceContext.h index ed9aa996..32b4ac59 100644 --- a/Graphics/GraphicsEngine/interface/DeviceContext.h +++ b/Graphics/GraphicsEngine/interface/DeviceContext.h @@ -450,7 +450,7 @@ class IDeviceContext : public IObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details. - virtual void QueryInterface(const Diligent::INTERFACE_ID& IID, IObject** ppInterface) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; /// Sets the pipeline state. diff --git a/Graphics/GraphicsEngine/interface/Fence.h b/Graphics/GraphicsEngine/interface/Fence.h index 06708e5d..0d72985f 100644 --- a/Graphics/GraphicsEngine/interface/Fence.h +++ b/Graphics/GraphicsEngine/interface/Fence.h @@ -48,7 +48,7 @@ class IFence : public IDeviceObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface( const Diligent::INTERFACE_ID& IID, IObject** ppInterface ) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; /// Returns the fence description used to create the object virtual const FenceDesc& GetDesc()const = 0; diff --git a/Graphics/GraphicsEngine/interface/Sampler.h b/Graphics/GraphicsEngine/interface/Sampler.h index c8b3c540..65579f5e 100644 --- a/Graphics/GraphicsEngine/interface/Sampler.h +++ b/Graphics/GraphicsEngine/interface/Sampler.h @@ -170,7 +170,7 @@ class ISampler : public IDeviceObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface( const Diligent::INTERFACE_ID& IID, IObject** ppInterface ) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; /// Returns the sampler description used to create the object virtual const SamplerDesc& GetDesc()const = 0; diff --git a/Graphics/GraphicsEngineD3D11/include/BufferD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/BufferD3D11Impl.h index 8b39f607..71b91345 100644 --- a/Graphics/GraphicsEngineD3D11/include/BufferD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/BufferD3D11Impl.h @@ -58,7 +58,7 @@ public: ~BufferD3D11Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual ID3D11Buffer* GetD3D11Buffer()override final{ return m_pd3d11Buffer; } diff --git a/Graphics/GraphicsEngineD3D11/include/BufferViewD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/BufferViewD3D11Impl.h index 208dd1ee..d705536e 100644 --- a/Graphics/GraphicsEngineD3D11/include/BufferViewD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/BufferViewD3D11Impl.h @@ -48,7 +48,7 @@ public: ID3D11View* pD3D11View, bool bIsDefaultView); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ) final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject **ppInterface) final; virtual ID3D11View* GetD3D11View()override final { diff --git a/Graphics/GraphicsEngineD3D11/include/DeviceContextD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/DeviceContextD3D11Impl.h index df013869..d9a0e44d 100755 --- a/Graphics/GraphicsEngineD3D11/include/DeviceContextD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/DeviceContextD3D11Impl.h @@ -59,7 +59,7 @@ public: ID3D11DeviceContext* pd3d11DeviceContext, const struct EngineD3D11Attribs& EngineAttribs, bool bIsDeferred); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual void SetPipelineState(IPipelineState* pPipelineState)override final; diff --git a/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h index af93c8eb..04e0edc0 100644 --- a/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h @@ -48,7 +48,7 @@ public: const PipelineStateDesc& PipelineDesc); ~PipelineStateD3D11Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; /// Implementation of the IPipelineStateD3D11::GetD3D11BlendState() method. virtual ID3D11BlendState* GetD3D11BlendState()override final; @@ -77,12 +77,29 @@ public: return m_SRBMemAllocator; } + const ShaderResourceLayoutD3D11& GetStaticResourceLayout(Uint32 s)const + { + VERIFY_EXPR(s < m_NumShaders); + return m_pStaticResourceLayouts[s]; + } + + ShaderResourceCacheD3D11& GetStaticResourceCache(Uint32 s) + { + VERIFY_EXPR(s < m_NumShaders); + return m_pStaticResourceCaches[s]; + } + + private: CComPtr m_pd3d11BlendState; CComPtr m_pd3d11RasterizerState; CComPtr m_pd3d11DepthStencilState; CComPtr m_pd3d11InputLayout; + // The caches are indexed by the shader order in the PSO, not shader index + ShaderResourceCacheD3D11* m_pStaticResourceCaches = nullptr; + ShaderResourceLayoutD3D11* m_pStaticResourceLayouts= nullptr; + // SRB memory allocator must be defined before the default shader res binding SRBMemoryAllocator m_SRBMemAllocator; }; diff --git a/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h index 0e7f66ad..87189352 100644 --- a/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h @@ -45,7 +45,7 @@ public: const EngineD3D11Attribs& EngineAttribs, ID3D11Device* pd3d11Device, Uint32 NumDeferredContexts ); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual void CreateBuffer(const BufferDesc& BuffDesc, const BufferData* pBuffData, IBuffer** ppBuffer)override final; diff --git a/Graphics/GraphicsEngineD3D11/include/SamplerD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/SamplerD3D11Impl.h index 5745bf18..4cac7884 100644 --- a/Graphics/GraphicsEngineD3D11/include/SamplerD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/SamplerD3D11Impl.h @@ -46,7 +46,7 @@ public: const SamplerDesc& SamplerDesc); ~SamplerD3D11Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject** ppInterface ) final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override final; virtual ID3D11SamplerState* GetD3D11SamplerState()override final{ return m_pd3dSampler; } diff --git a/Graphics/GraphicsEngineD3D11/include/SwapChainD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/SwapChainD3D11Impl.h index 7dd8680e..98d92676 100644 --- a/Graphics/GraphicsEngineD3D11/include/SwapChainD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/SwapChainD3D11Impl.h @@ -47,7 +47,7 @@ public: void* pNativeWndHandle); ~SwapChainD3D11Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual void Present(Uint32 SyncInterval)override final; virtual void Resize( Uint32 NewWidth, Uint32 NewHeight )override final; diff --git a/Graphics/GraphicsEngineD3D11/include/TextureBaseD3D11.h b/Graphics/GraphicsEngineD3D11/include/TextureBaseD3D11.h index 56ef5bc3..1333bd8e 100644 --- a/Graphics/GraphicsEngineD3D11/include/TextureBaseD3D11.h +++ b/Graphics/GraphicsEngineD3D11/include/TextureBaseD3D11.h @@ -51,7 +51,7 @@ public: const TextureData* pInitData = nullptr); ~TextureBaseD3D11(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual ID3D11Resource* GetD3D11Texture()override final{ return m_pd3d11Texture; } diff --git a/Graphics/GraphicsEngineD3D11/include/TextureViewD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/TextureViewD3D11Impl.h index 3fcea2da..423b6dee 100644 --- a/Graphics/GraphicsEngineD3D11/include/TextureViewD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/TextureViewD3D11Impl.h @@ -49,7 +49,7 @@ public: ID3D11View* pD3D11View, bool bIsDefaultView); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual ID3D11View* GetD3D11View()override final { diff --git a/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp index 03327e15..0c205533 100755 --- a/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp @@ -214,7 +214,7 @@ namespace Diligent #ifdef DEVELOPMENT auto* pShaderD3D11 = ValidatedCast(ppdbgShaders[s]); - VERIFY_EXPR( ShaderTypeInd == static_cast(pShaderD3D11->GetShaderTypeIndex()) ); + VERIFY_EXPR( ShaderTypeInd == static_cast(GetShaderTypeIndex(pShaderD3D11->GetDesc().ShaderType)) ); #endif auto& Cache = pShaderResBindingD3D11->GetResourceCache(s); @@ -360,7 +360,7 @@ namespace Diligent #ifdef DEVELOPMENT auto* pShaderD3D11 = ValidatedCast(ppdbgShaders[s]); - VERIFY_EXPR( ShaderTypeInd == static_cast(pShaderD3D11->GetShaderTypeIndex()) ); + VERIFY_EXPR( ShaderTypeInd == static_cast(GetShaderTypeIndex(pShaderD3D11->GetDesc().ShaderType)) ); #endif auto& Cache = pShaderResBindingD3D11->GetResourceCache(s); diff --git a/Graphics/GraphicsEngineVulkan/include/CommandQueueVkImpl.h b/Graphics/GraphicsEngineVulkan/include/CommandQueueVkImpl.h index a5669f6c..3c649ab1 100644 --- a/Graphics/GraphicsEngineVulkan/include/CommandQueueVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/CommandQueueVkImpl.h @@ -48,7 +48,7 @@ public: uint32_t QueueFamilyIndex); ~CommandQueueVkImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID& IID, IObject** ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; // Returns the fence value that will be signaled next time virtual Uint64 GetNextFenceValue()override final { return m_NextFenceValue; } diff --git a/Graphics/GraphicsEngineVulkan/include/SwapChainVkImpl.h b/Graphics/GraphicsEngineVulkan/include/SwapChainVkImpl.h index aada3ab5..d309c638 100644 --- a/Graphics/GraphicsEngineVulkan/include/SwapChainVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/SwapChainVkImpl.h @@ -49,7 +49,7 @@ public: void* pNativeWndHandle); ~SwapChainVkImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID& IID, IObject** ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual void Present(Uint32 SyncInterval)override final; virtual void Resize( Uint32 NewWidth, Uint32 NewHeight )override final; diff --git a/Graphics/GraphicsEngineVulkan/include/TextureViewVkImpl.h b/Graphics/GraphicsEngineVulkan/include/TextureViewVkImpl.h index 650829e1..8989c245 100644 --- a/Graphics/GraphicsEngineVulkan/include/TextureViewVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/TextureViewVkImpl.h @@ -50,7 +50,7 @@ public: bool bIsDefaultView); ~TextureViewVkImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID& IID, IObject** ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; VkImageView GetVulkanImageView()const override final{return m_ImageView;} diff --git a/Graphics/GraphicsEngineVulkan/include/TextureVkImpl.h b/Graphics/GraphicsEngineVulkan/include/TextureVkImpl.h index 4d040a0e..4d19fe91 100644 --- a/Graphics/GraphicsEngineVulkan/include/TextureVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/TextureVkImpl.h @@ -62,7 +62,7 @@ public: ~TextureVkImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID& IID, IObject** ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual VkImage GetVkImage()const override final{ return m_VulkanImage; } virtual void* GetNativeHandle()override final -- cgit v1.2.3 From a407080d12bc2b762f84131cfa62c1f3069c4a09 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sun, 3 Mar 2019 13:18:12 -0800 Subject: Minor change to DeviceContextVkImpl.h --- Graphics/GraphicsEngineVulkan/include/DeviceContextVkImpl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/include/DeviceContextVkImpl.h b/Graphics/GraphicsEngineVulkan/include/DeviceContextVkImpl.h index bc8c42ac..84e8bfdd 100644 --- a/Graphics/GraphicsEngineVulkan/include/DeviceContextVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/DeviceContextVkImpl.h @@ -68,7 +68,7 @@ public: std::shared_ptr GenerateMipsHelper); ~DeviceContextVkImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID& IID, IObject** ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual void SetPipelineState(IPipelineState* pPipelineState)override final; -- cgit v1.2.3 From b21f54c63be0e81a26f505ea019049d4f663bf3b Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sun, 3 Mar 2019 14:01:58 -0800 Subject: Implemented shader resource reflectio API in Vk backend --- .../GraphicsEngineVulkan/include/ShaderVkImpl.h | 11 ++--- Graphics/GraphicsEngineVulkan/src/ShaderVkImpl.cpp | 57 ++++++++++++++++++++++ 2 files changed, 60 insertions(+), 8 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderVkImpl.h b/Graphics/GraphicsEngineVulkan/include/ShaderVkImpl.h index 041c7011..03fc2189 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderVkImpl.h @@ -49,17 +49,12 @@ public: IMPLEMENT_QUERY_INTERFACE_IN_PLACE(IID_ShaderVk, TShaderBase); - virtual Uint32 GetResourceCount()const + virtual Uint32 GetResourceCount()const override final { - UNSUPPORTED("Not yet implemented"); - return 0; + return m_pShaderResources->GetTotalResources(); } - virtual const ShaderResourceDesc* GetResources()const - { - UNSUPPORTED("Not yet implemented"); - return nullptr; - } + virtual ShaderResourceDesc GetResource(Uint32 Index)const override final; virtual const std::vector& GetSPIRV()const override final { diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderVkImpl.cpp index 3cf4c3f0..9ec51af6 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderVkImpl.cpp @@ -129,4 +129,61 @@ ShaderVkImpl::~ShaderVkImpl() { } +ShaderResourceDesc ShaderVkImpl::GetResource(Uint32 Index)const +{ + auto ResCount = GetResourceCount(); + DEV_CHECK_ERR(Index < ResCount, "Resource index (", Index, ") is out of range"); + ShaderResourceDesc ResourceDesc; + if (Index < ResCount) + { + const auto& SPIRVResource = m_pShaderResources->GetResource(Index); + ResourceDesc.Name = SPIRVResource.Name; + ResourceDesc.ArraySize = SPIRVResource.ArraySize; + static_assert(SPIRVShaderResourceAttribs::ResourceType::NumResourceTypes == 9, "Please update switch statement below"); + switch (SPIRVResource.Type) + { + case SPIRVShaderResourceAttribs::ResourceType::UniformBuffer: + ResourceDesc.Type = SHADER_RESOURCE_TYPE_CONSTANT_BUFFER; + break; + + case SPIRVShaderResourceAttribs::ResourceType::StorageBuffer: + ResourceDesc.Type = SHADER_RESOURCE_TYPE_BUFFER_UAV; + break; + + case SPIRVShaderResourceAttribs::ResourceType::UniformTexelBuffer: + ResourceDesc.Type = SHADER_RESOURCE_TYPE_BUFFER_SRV; + break; + + case SPIRVShaderResourceAttribs::ResourceType::StorageTexelBuffer: + ResourceDesc.Type = SHADER_RESOURCE_TYPE_BUFFER_UAV; + break; + + case SPIRVShaderResourceAttribs::ResourceType::StorageImage: + ResourceDesc.Type = SHADER_RESOURCE_TYPE_TEXTURE_UAV; + break; + + case SPIRVShaderResourceAttribs::ResourceType::SampledImage: + ResourceDesc.Type = SHADER_RESOURCE_TYPE_TEXTURE_SRV; + break; + + case SPIRVShaderResourceAttribs::ResourceType::AtomicCounter: + LOG_WARNING_MESSAGE("There is no appropriate shader resource type for atomic counter resource '", SPIRVResource.Name, "'"); + ResourceDesc.Type = SHADER_RESOURCE_TYPE_BUFFER_UAV; + break; + + case SPIRVShaderResourceAttribs::ResourceType::SeparateImage: + ResourceDesc.Type = SHADER_RESOURCE_TYPE_TEXTURE_SRV; + break; + + case SPIRVShaderResourceAttribs::ResourceType::SeparateSampler: + ResourceDesc.Type = SHADER_RESOURCE_TYPE_SAMPLER; + break; + + default: + UNEXPECTED("Unknown SPIRV resource type"); + } + } + return ResourceDesc; +} + } -- cgit v1.2.3 From 2808b9f671e29e27a4d04f6c8ea21c40d8c573eb Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sun, 3 Mar 2019 18:09:24 -0800 Subject: Almost completed refactoring d3d11 backend to comply with the new API --- Graphics/GraphicsEngine/interface/Shader.h | 2 +- .../include/PipelineStateD3D11Impl.h | 10 + .../GraphicsEngineD3D11/include/ShaderD3D11Impl.h | 16 +- .../include/ShaderResourceBindingD3D11Impl.h | 16 +- .../include/ShaderResourceCacheD3D11.h | 4 +- .../include/ShaderResourceLayoutD3D11.h | 105 +++++--- .../include/ShaderResourcesD3D11.h | 21 +- .../src/DeviceContextD3D11Impl.cpp | 27 +- .../src/PipelineStateD3D11Impl.cpp | 109 +++++++- .../src/RenderDeviceD3D11Impl.cpp | 6 +- .../GraphicsEngineD3D11/src/ShaderD3D11Impl.cpp | 9 +- .../src/ShaderResourceBindingD3D11Impl.cpp | 56 ++-- .../src/ShaderResourceLayoutD3D11.cpp | 292 +++++++++++---------- .../src/ShaderResourcesD3D11.cpp | 3 +- .../include/ShaderResources.h | 99 ++++--- .../GraphicsEngineD3DBase/src/ShaderResources.cpp | 230 +++++++++++----- 16 files changed, 649 insertions(+), 356 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngine/interface/Shader.h b/Graphics/GraphicsEngine/interface/Shader.h index 2ac6a2c6..e877ce17 100644 --- a/Graphics/GraphicsEngine/interface/Shader.h +++ b/Graphics/GraphicsEngine/interface/Shader.h @@ -241,7 +241,7 @@ public: virtual Uint32 GetResourceCount()const = 0; /// Returns the pointer to the array of shader resources - virtual const ShaderResourceDesc* GetResources()const = 0; + virtual ShaderResourceDesc GetResource(Uint32 Index)const = 0; }; } diff --git a/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h index 04e0edc0..583190aa 100644 --- a/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h @@ -72,6 +72,14 @@ public: virtual bool IsCompatibleWith(const IPipelineState *pPSO)const override final; + virtual void BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags)override final; + + virtual Uint32 GetStaticVariableCount(SHADER_TYPE ShaderType) const override final; + + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) override final; + + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) override final; + SRBMemoryAllocator& GetSRBMemoryAllocator() { return m_SRBMemAllocator; @@ -102,6 +110,8 @@ private: // SRB memory allocator must be defined before the default shader res binding SRBMemoryAllocator m_SRBMemAllocator; + + Int8 m_ResourceLayoutIndex[6] = {-1, -1, -1, -1, -1, -1}; }; } diff --git a/Graphics/GraphicsEngineD3D11/include/ShaderD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/ShaderD3D11Impl.h index c5005c4e..35a50a08 100644 --- a/Graphics/GraphicsEngineD3D11/include/ShaderD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/ShaderD3D11Impl.h @@ -55,6 +55,16 @@ public: IMPLEMENT_QUERY_INTERFACE_IN_PLACE(IID_ShaderD3D11, TShaderBase); + virtual Uint32 GetResourceCount()const override final + { + return m_pShaderResources->GetTotalResources(); + } + + virtual ShaderResourceDesc GetResource(Uint32 Index)const override final + { + return m_pShaderResources->GetShaderResourceDesc(Index); + } + virtual ID3D11DeviceChild* GetD3D11Shader()override final { return m_pShader; @@ -62,13 +72,15 @@ public: ID3DBlob* GetBytecode(){return m_pShaderByteCode;} - Uint32 GetShaderTypeIndex()const{return m_ShaderTypeIndex;} + const std::shared_ptr& GetD3D11Resources()const{return m_pShaderResources;} private: /// D3D11 shader CComPtr m_pShader; - Uint32 m_ShaderTypeIndex; // VS == 0, PS == 1, GS == 2, HS == 3, DS == 4, CS == 5 + // ShaderResources class instance must be referenced through the shared pointer, because + // it is referenced by ShaderResourceLayoutD3D11 class instances + std::shared_ptr m_pShaderResources; }; } diff --git a/Graphics/GraphicsEngineD3D11/include/ShaderResourceBindingD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/ShaderResourceBindingD3D11Impl.h index 9f175f1d..b3274b21 100755 --- a/Graphics/GraphicsEngineD3D11/include/ShaderResourceBindingD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/ShaderResourceBindingD3D11Impl.h @@ -48,15 +48,15 @@ public: bool IsInternal); ~ShaderResourceBindingD3D11Impl(); - virtual void QueryInterface( const Diligent::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 final; - virtual IShaderVariable* GetVariable(SHADER_TYPE ShaderType, const char *Name)override final; + virtual IShaderResourceVariable* GetVariable(SHADER_TYPE ShaderType, const char *Name)override final; virtual Uint32 GetVariableCount(SHADER_TYPE ShaderType) const override final; - virtual IShaderVariable* GetVariable(SHADER_TYPE ShaderType, Uint32 Index)override final; + virtual IShaderResourceVariable* GetVariable(SHADER_TYPE ShaderType, Uint32 Index)override final; virtual void InitializeStaticResources(const IPipelineState* pPipelineState)override final; @@ -74,14 +74,14 @@ public: private: // The caches are indexed by the shader order in the PSO, not shader index - ShaderResourceCacheD3D11* m_pBoundResourceCaches = nullptr; - ShaderResourceLayoutD3D11* m_pResourceLayouts = nullptr; + ShaderResourceCacheD3D11* m_pBoundResourceCaches = nullptr; + ShaderResourceLayoutD3D11* m_pResourceLayouts = nullptr; - Int8 m_ShaderTypeIndex[6] = {}; + Int8 m_ShaderTypeIndex[6] = {}; // Resource layout index in m_ResourceLayouts[] array for every shader stage - Int8 m_ResourceLayoutIndex[6]; - Uint8 m_NumActiveShaders = 0; + Int8 m_ResourceLayoutIndex[6] = {-1, -1, -1, -1, -1, -1}; + Uint8 m_NumActiveShaders = 0; bool m_bIsStaticResourcesBound = false; }; diff --git a/Graphics/GraphicsEngineD3D11/include/ShaderResourceCacheD3D11.h b/Graphics/GraphicsEngineD3D11/include/ShaderResourceCacheD3D11.h index 02cde863..f25dff7c 100755 --- a/Graphics/GraphicsEngineD3D11/include/ShaderResourceCacheD3D11.h +++ b/Graphics/GraphicsEngineD3D11/include/ShaderResourceCacheD3D11.h @@ -117,8 +117,8 @@ public: static size_t GetRequriedMemorySize(const class ShaderResourcesD3D11& Resources); - void Initialize(const class ShaderResourcesD3D11& Resources, class IMemoryAllocator &MemAllocator); - void Initialize(Uint32 CBCount, Uint32 SRVCount, Uint32 SamplerCount, Uint32 UAVCount, class IMemoryAllocator &MemAllocator); + void Initialize(const class ShaderResourcesD3D11& Resources, class IMemoryAllocator& MemAllocator); + void Initialize(Uint32 CBCount, Uint32 SRVCount, Uint32 SamplerCount, Uint32 UAVCount, class IMemoryAllocator& MemAllocator); void Destroy(class IMemoryAllocator& MemAllocator); diff --git a/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h b/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h index c6dd714b..6666777b 100644 --- a/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h +++ b/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h @@ -41,10 +41,19 @@ class IMemoryAllocator; /// Diligent::ShaderResourceLayoutD3D11 class /// http://diligentgraphics.com/diligent-engine/architecture/d3d11/shader-resource-layout/ +// sizeof(ShaderResourceLayoutD3D11) == 64 (x64) class ShaderResourceLayoutD3D11 { public: - ShaderResourceLayoutD3D11(IObject& Owner); + ShaderResourceLayoutD3D11(IObject& Owner, + IRenderDevice* pRenderDevice, + std::shared_ptr pSrcResources, + const PipelineResourceLayoutDesc& ResourceLayout, + const SHADER_RESOURCE_VARIABLE_TYPE* VarTypes, + Uint32 NumVarTypes, + ShaderResourceCacheD3D11& ResourceCache, + IMemoryAllocator& ResCacheDataAllocator, + IMemoryAllocator& ResLayoutDataAllocator); ~ShaderResourceLayoutD3D11(); // No copies, only moves are allowed @@ -58,14 +67,7 @@ public: const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes); - void Initialize(std::shared_ptr pSrcResources, - const SHADER_RESOURCE_VARIABLE_TYPE* VarTypes, - Uint32 NumVarTypes, - ShaderResourceCacheD3D11& ResourceCache, - IMemoryAllocator& ResCacheDataAllocator, - IMemoryAllocator& ResLayoutDataAllocator); - - void CopyResources(ShaderResourceCacheD3D11& DstCache); + void CopyResources(ShaderResourceCacheD3D11& DstCache)const; using ShaderVariableD3D11Base = ShaderVariableD3DBase; @@ -86,7 +88,7 @@ public: BindResource(ppObjects[elem], FirstElement+elem); } - __forceinline bool IsBound(Uint32 ArrayIndex); + __forceinline bool IsBound(Uint32 ArrayIndex)const; }; struct TexSRVBindInfo final : ShaderVariableD3D11Base @@ -184,8 +186,10 @@ public: { SamplerBindInfo( const D3DShaderResourceAttribs& ResourceAttribs, ShaderResourceLayoutD3D11& ParentResLayout, - SHADER_RESOURCE_VARIABLE_TYPE VariableType ) : - ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs, VariableType) + SHADER_RESOURCE_VARIABLE_TYPE VariableType, + RefCntAutoPtr _pStaticSampler) : + ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs, VariableType), + pStaticSampler(std::move(_pStaticSampler)) {} // Non-virtual function @@ -199,17 +203,15 @@ public: } __forceinline bool IsBound(Uint32 ArrayIndex)const; - - bool IsStaticSampler()const - { - UNEXPECTED("Not implemented"); - return false; - } + + RefCntAutoPtr pStaticSampler; }; // dbgResourceCache is only used for sanity check and as a remainder that the resource cache must be alive // while Layout is alive void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags, const ShaderResourceCacheD3D11& dbgResourceCache ); + + void SetStaticSamplers(ShaderResourceCacheD3D11& ResourceCache)const; #ifdef DEVELOPMENT bool dvpVerifyBindings()const; @@ -246,28 +248,34 @@ public: template<> Uint32 GetNumResources () const { return GetNumBufUAVs(); } template<> Uint32 GetNumResources () const { return GetNumSamplers(); } -private: - const Char* GetShaderName()const { return m_pResources->GetShaderName(); } - // No need to use shared pointer, as the resource cache is either part of the same - // ShaderD3D11Impl object, or ShaderResourceBindingD3D11Impl object - ShaderResourceCacheD3D11* m_pResourceCache = nullptr; +private: + +/* 0 */ IObject& m_Owner; +/* 8 */ std::shared_ptr m_pResources; - std::unique_ptr > m_ResourceBuffer; + // No need to use shared pointer, as the resource cache is either part of the same + // ShaderD3D11Impl object, or ShaderResourceBindingD3D11Impl object +/*24*/ ShaderResourceCacheD3D11& m_ResourceCache; - // Offsets in bytes - using OffsetType = Uint16; - OffsetType m_TexSRVsOffset = 0; - OffsetType m_TexUAVsOffset = 0; - OffsetType m_BuffSRVsOffset = 0; - OffsetType m_BuffUAVsOffset = 0; - OffsetType m_SamplerOffset = 0; - OffsetType m_MemorySize = 0; +/*32*/ std::unique_ptr > m_ResourceBuffer; + // Offsets in bytes + using OffsetType = Uint16; +/*48*/ OffsetType m_TexSRVsOffset = 0; +/*50*/ OffsetType m_TexUAVsOffset = 0; +/*52*/ OffsetType m_BuffSRVsOffset = 0; +/*54*/ OffsetType m_BuffUAVsOffset = 0; +/*56*/ OffsetType m_SamplerOffset = 0; +/*58*/ OffsetType m_MemorySize = 0; +/*60 - 64*/ +/*64*/ // End of data + + template OffsetType GetResourceOffset()const; template<> OffsetType GetResourceOffset() const { return 0; } template<> OffsetType GetResourceOffset () const { return m_TexSRVsOffset; } @@ -327,8 +335,37 @@ private: HandleSampler(GetResource(s)); } - std::shared_ptr m_pResources; - IObject& m_Owner; + template + void HandleConstResources(THandleCB HandleCB, + THandleTexSRV HandleTexSRV, + THandleTexUAV HandleTexUAV, + THandleBufSRV HandleBufSRV, + THandleBufUAV HandleBufUAV, + THandleSampler HandleSampler)const + { + for (Uint32 cb = 0; cb < GetNumResources(); ++cb) + HandleCB(GetConstResource(cb)); + + for (Uint32 t = 0; t < GetNumResources(); ++t) + HandleTexSRV(GetConstResource(t)); + + for (Uint32 u = 0; u < GetNumResources(); ++u) + HandleTexUAV(GetConstResource(u)); + + for (Uint32 s = 0; s < GetNumResources(); ++s) + HandleBufSRV(GetConstResource(s)); + + for (Uint32 u = 0; u < GetNumResources(); ++u) + HandleBufUAV(GetConstResource(u)); + + for (Uint32 s = 0; s < GetNumResources(); ++s) + HandleSampler(GetConstResource(s)); + } friend class ShaderVariableIndexLocator; friend class ShaderVariableLocator; diff --git a/Graphics/GraphicsEngineD3D11/include/ShaderResourcesD3D11.h b/Graphics/GraphicsEngineD3D11/include/ShaderResourcesD3D11.h index a241b486..c2c3a34d 100644 --- a/Graphics/GraphicsEngineD3D11/include/ShaderResourcesD3D11.h +++ b/Graphics/GraphicsEngineD3D11/include/ShaderResourcesD3D11.h @@ -28,7 +28,7 @@ // ShaderResourcesD3D11 are created by ShaderD3D11Impl instances. They are then referenced by ShaderResourceLayoutD3D11 objects, which are in turn -// created by instances of ShaderResourceBindingsD3D11Impl (and ShaderD3D11Impl too) +// created by instances of ShaderResourceBindingsD3D11Impl and PipelineStateD3D11Impl // // _________________ // | | @@ -64,13 +64,17 @@ // | | shared_ptr | | shared_ptr| | | | | // | ShaderD3D11Impl |--------------->| ShaderResourcesD3D11 |<---------------| ShaderResourceLayoutD3D11 |<-----| ShaderResourceBindingD3D11Impl | // |_________________| |______________________| | |___________________________| |________________________________| -// | A | -// V | | -// ________ | | _______ ________________________________ +// A | +// | | +// __________ | | _______ ________________________________ // | | shared_ptr | | | | | | // | ShaderResourceLayoutD3D11 |------------------- ----| ShaderResourceLayoutD3D11 |<-----| ShaderResourceBindingD3D11Impl | // |___________________________| |___________________________| |________________________________| -// +// A +// ___________|______________ +// | | +// | PipelineStateD3D11Impl | +// |__________________________| // #include @@ -111,8 +115,7 @@ public: class ShaderResourceCacheD3D11& ResourceCache)const; #endif - const Char* GetShaderName() const { return m_ShaderName; } - + private: using MaxBindPointType = Int8; @@ -126,10 +129,6 @@ private: static_assert(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT-1 <= MaxAllowedBindPoint, "Not enough bits to represent max SRV slot"); static_assert(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT-1 <= MaxAllowedBindPoint, "Not enough bits to represent max Sampler slot"); static_assert(D3D11_PS_CS_UAV_REGISTER_COUNT-1 <= MaxAllowedBindPoint, "Not enough bits to represent max UAV slot"); - - // ShaderResourcesD3D11 is part of the ShaderD3D11Impl object, so we can simply - // reference shader name without the need to copy it - const Char* const m_ShaderName; }; } diff --git a/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp index 0c205533..f531ab9a 100755 --- a/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp @@ -151,19 +151,16 @@ namespace Diligent VERIFY_EXPR(pPSO != nullptr); static_assert(TransitionResources || CommitResources, "At least one of TransitionResources or CommitResources flags is expected to be true"); -#ifdef DEVELOPMENT - auto pdbgPipelineStateD3D11 = ValidatedCast( pPSO ); - auto ppdbgShaders = pdbgPipelineStateD3D11->GetShaders(); -#endif + auto* pPipelineStateD3D11 = ValidatedCast(pPSO); if (pShaderResourceBinding == nullptr) { #ifdef DEVELOPMENT bool ResourcesPresent = false; - for (Uint32 s = 0; s < pdbgPipelineStateD3D11->GetNumShaders(); ++s) + for (Uint32 s = 0; s < pPipelineStateD3D11->GetNumShaders(); ++s) { - auto* pShaderD3D11 = ValidatedCast(ppdbgShaders[s]); - if (pShaderD3D11->GetResources()->GetTotalResources() > 0) + auto* pShaderD3D11 = pPipelineStateD3D11->GetShader(s); + if (pShaderD3D11->GetD3D11Resources()->GetTotalResources() > 0) ResourcesPresent = true; } @@ -179,7 +176,7 @@ namespace Diligent auto pShaderResBindingD3D11 = ValidatedCast(pShaderResourceBinding); #ifdef DEVELOPMENT - if (pdbgPipelineStateD3D11->IsIncompatibleWith(pShaderResourceBinding->GetPipelineState())) + if (pPipelineStateD3D11->IsIncompatibleWith(pShaderResourceBinding->GetPipelineState())) { LOG_ERROR_MESSAGE("Shader resource binding does not match Pipeline State"); return; @@ -187,16 +184,14 @@ namespace Diligent #endif auto NumShaders = pShaderResBindingD3D11->GetNumActiveShaders(); - VERIFY(NumShaders == pdbgPipelineStateD3D11->GetNumShaders(), "Number of active shaders in shader resource binding is not consistent with the number of shaders in the pipeline state"); + VERIFY(NumShaders == pPipelineStateD3D11->GetNumShaders(), "Number of active shaders in shader resource binding is not consistent with the number of shaders in the pipeline state"); #ifdef DEVELOPMENT bool StaticResourcesPresent = false; for (Uint32 s = 0; s < NumShaders; ++s) { - pShaderResBindingD3D11->GetResourceLayout(s).dvpVerifyBindings(); - // Static resource bindings are verified in BindStaticShaderResources() - auto* pShaderD3D11 = ValidatedCast(ppdbgShaders[s]); - if (pShaderD3D11->GetStaticResourceLayout().GetTotalResourceCount() > 0) + const auto& StaticResLayout = pPipelineStateD3D11->GetStaticResourceLayout(s); + if (StaticResLayout.GetTotalResourceCount() > 0) StaticResourcesPresent = true; } // Static resource bindings are verified in BindStaticShaderResources() @@ -213,7 +208,7 @@ namespace Diligent auto ShaderTypeInd = pShaderResBindingD3D11->GetActiveShaderTypeIndex(s); #ifdef DEVELOPMENT - auto* pShaderD3D11 = ValidatedCast(ppdbgShaders[s]); + auto* pShaderD3D11 = pPipelineStateD3D11->GetShader(s); VERIFY_EXPR( ShaderTypeInd == static_cast(GetShaderTypeIndex(pShaderD3D11->GetDesc().ShaderType)) ); #endif @@ -359,7 +354,7 @@ namespace Diligent auto ShaderTypeInd = pShaderResBindingD3D11->GetActiveShaderTypeIndex(s); #ifdef DEVELOPMENT - auto* pShaderD3D11 = ValidatedCast(ppdbgShaders[s]); + auto* pShaderD3D11 = pPipelineStateD3D11->GetShader(s); VERIFY_EXPR( ShaderTypeInd == static_cast(GetShaderTypeIndex(pShaderD3D11->GetDesc().ShaderType)) ); #endif @@ -595,7 +590,7 @@ namespace Diligent if (CommitResources && (m_DebugFlags & (Uint32)EngineD3D11DebugFlags::VerifyCommittedShaderResources) != 0) { // Use full resource layout to verify that all required resources are committed - pShaderD3D11->GetResources()->dvpVerifyCommittedResources( + pShaderD3D11->GetD3D11Resources()->dvpVerifyCommittedResources( m_CommittedD3D11CBs[ShaderTypeInd], m_CommittedD3D11SRVs[ShaderTypeInd], m_CommittedD3D11SRVResources[ShaderTypeInd], diff --git a/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp index 90828884..eec91b20 100644 --- a/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp @@ -27,6 +27,7 @@ #include "RenderDeviceD3D11Impl.h" #include "ShaderResourceBindingD3D11Impl.h" #include "EngineMemory.h" +#include "ShaderD3D11Impl.h" namespace Diligent { @@ -50,7 +51,7 @@ PipelineStateD3D11Impl::PipelineStateD3D11Impl(IReferenceCounters* pRefCoun { LOG_ERROR_AND_THROW(GetShaderTypeLiteralName(SHADER_TYPE_COMPUTE), " shader is expeceted while ", GetShaderTypeLiteralName(m_pCS->GetDesc().ShaderType), " provided"); } - m_ShaderResourceLayoutHash = pCS->GetResources()->GetHash(); + m_ShaderResourceLayoutHash = pCS->GetD3D11Resources()->GetHash(); } else { @@ -64,7 +65,7 @@ PipelineStateD3D11Impl::PipelineStateD3D11Impl(IReferenceCounters* pRefCoun LOG_ERROR_AND_THROW( GetShaderTypeLiteralName(ExpectedType), " shader is expeceted while ", GetShaderTypeLiteralName(m_p##ShortName->GetDesc().ShaderType)," provided" ); \ } \ if(pShader!=nullptr) \ - HashCombine(m_ShaderResourceLayoutHash, pShader->GetResources()->GetHash() ); \ + HashCombine(m_ShaderResourceLayoutHash, pShader->GetD3D11Resources()->GetHash() ); \ } INIT_SHADER(VS, SHADER_TYPE_VERTEX); @@ -110,19 +111,51 @@ PipelineStateD3D11Impl::PipelineStateD3D11Impl(IReferenceCounters* pRefCoun } } - if(PipelineDesc.SRBAllocationGranularity > 1) + auto* pStaticResLayoutRawMem = ALLOCATE(GetRawAllocator(), "Raw memory for ShaderResourceLayoutD3D11", m_NumShaders * sizeof(ShaderResourceLayoutD3D11)); + m_pStaticResourceLayouts = reinterpret_cast(pStaticResLayoutRawMem); + + auto* pResCacheRawMem = ALLOCATE(GetRawAllocator(), "Raw memory for ShaderResourceCacheD3D11", m_NumShaders * sizeof(ShaderResourceCacheD3D11)); + m_pStaticResourceCaches = reinterpret_cast(pResCacheRawMem); + + const auto& ResourceLayout = PipelineDesc.ResourceLayout; + std::array ShaderResLayoutDataSizes = {}; + std::array ShaderResCacheDataSizes = {}; + for (Uint32 s = 0; s < m_NumShaders; ++s) { - std::array ShaderResLayoutDataSizes = {}; - std::array ShaderResCacheDataSizes = {}; - for (Uint32 s = 0; s < m_NumShaders; ++s) + auto* pShader = GetShader(s); + const auto& ShaderResources = *pShader->GetD3D11Resources(); + + new (m_pStaticResourceCaches+s) ShaderResourceCacheD3D11; + // Do not initialize the cache as this will be performed by the resource layout + + // Shader resource layout will only contain dynamic and mutable variables + const SHADER_RESOURCE_VARIABLE_TYPE StaticVarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_STATIC}; + new (m_pStaticResourceLayouts + s) + ShaderResourceLayoutD3D11 + { + *this, + pRenderDeviceD3D11, + pShader->GetD3D11Resources(), + m_Desc.ResourceLayout, + StaticVarTypes, + _countof(StaticVarTypes), + m_pStaticResourceCaches[s], + GetRawAllocator(), + GetRawAllocator() + }; + + m_pStaticResourceLayouts[s].SetStaticSamplers(m_pStaticResourceCaches[s]); + + if (PipelineDesc.SRBAllocationGranularity > 1) { - auto* pShader = GetShader(s); - const auto& ShaderResources = *pShader->GetResources(); - std::array AllowedVarTypes = { SHADER_VARIABLE_TYPE_MUTABLE, SHADER_VARIABLE_TYPE_DYNAMIC }; - ShaderResLayoutDataSizes[s] = ShaderResourceLayoutD3D11::GetRequiredMemorySize(ShaderResources, AllowedVarTypes.data(), static_cast(AllowedVarTypes.size())); + const SHADER_RESOURCE_VARIABLE_TYPE SRBVarTypes[] = { SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC }; + ShaderResLayoutDataSizes[s] = ShaderResourceLayoutD3D11::GetRequiredMemorySize(ShaderResources, ResourceLayout, SRBVarTypes, _countof(SRBVarTypes)); ShaderResCacheDataSizes[s] = ShaderResourceCacheD3D11::GetRequriedMemorySize(ShaderResources); } + } + if (PipelineDesc.SRBAllocationGranularity > 1) + { m_SRBMemAllocator.Initialize(PipelineDesc.SRBAllocationGranularity, m_NumShaders, ShaderResLayoutDataSizes.data(), m_NumShaders, ShaderResCacheDataSizes.data()); } } @@ -130,6 +163,18 @@ PipelineStateD3D11Impl::PipelineStateD3D11Impl(IReferenceCounters* pRefCoun PipelineStateD3D11Impl::~PipelineStateD3D11Impl() { + for (Uint32 s = 0; s < m_NumShaders; ++s) + { + m_pStaticResourceCaches[s].Destroy(GetRawAllocator()); + m_pStaticResourceCaches[s].~ShaderResourceCacheD3D11(); + } + GetRawAllocator().Free(m_pStaticResourceCaches); + + for (Uint32 l = 0; l < m_NumShaders; ++l) + { + m_pStaticResourceLayouts[l].~ShaderResourceLayoutD3D11(); + } + GetRawAllocator().Free(m_pStaticResourceLayouts); } IMPLEMENT_QUERY_INTERFACE( PipelineStateD3D11Impl, IID_PipelineStateD3D11, TPipelineStateBase ) @@ -183,11 +228,11 @@ bool PipelineStateD3D11Impl::IsCompatibleWith(const IPipelineState* pPSO)const { auto* pShader0 = GetShader(s); auto* pShader1 = pPSOD3D11->GetShader(s); - if (pShader0->GetShaderTypeIndex() != pShader1->GetShaderTypeIndex()) + if (pShader0->GetDesc().ShaderType != pShader1->GetDesc().ShaderType) return false; - const ShaderResourcesD3D11* pRes0 = pShader0->GetResources().get(); - const ShaderResourcesD3D11* pRes1 = pShader1->GetResources().get(); - if (!pRes0->IsCompatibleWith(*pRes1)) + const auto& Res0 = *pShader0->GetD3D11Resources(); + const auto& Res1 = *pShader1->GetD3D11Resources(); + if (!Res0.IsCompatibleWith(Res1)) return false; } @@ -236,4 +281,40 @@ ID3D11ComputeShader* PipelineStateD3D11Impl::GetD3D11ComputeShader() return static_cast(pCSD3D11->GetD3D11Shader()); } + +void PipelineStateD3D11Impl::BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags) +{ + for (Uint32 s=0; s < m_NumShaders; ++s) + { + m_pStaticResourceLayouts[s].BindResources(pResourceMapping, Flags, m_pStaticResourceCaches[s]); + } +} + +Uint32 PipelineStateD3D11Impl::GetStaticVariableCount(SHADER_TYPE ShaderType) const +{ + const auto LayoutInd = m_ResourceLayoutIndex[GetShaderTypeIndex(ShaderType)]; + if (LayoutInd < 0) + return 0; + + return m_pStaticResourceLayouts[LayoutInd].GetTotalResourceCount(); +} + +IShaderResourceVariable* PipelineStateD3D11Impl::GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) +{ + const auto LayoutInd = m_ResourceLayoutIndex[GetShaderTypeIndex(ShaderType)]; + if (LayoutInd < 0) + return nullptr; + + return m_pStaticResourceLayouts[LayoutInd].GetShaderVariable(Name); +} + +IShaderResourceVariable* PipelineStateD3D11Impl::GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) +{ + const auto LayoutInd = m_ResourceLayoutIndex[GetShaderTypeIndex(ShaderType)]; + if (LayoutInd < 0) + return nullptr; + + return m_pStaticResourceLayouts[LayoutInd].GetShaderVariable(Index); +} + } diff --git a/Graphics/GraphicsEngineD3D11/src/RenderDeviceD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/RenderDeviceD3D11Impl.cpp index 2d08f430..86eae24a 100644 --- a/Graphics/GraphicsEngineD3D11/src/RenderDeviceD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/RenderDeviceD3D11Impl.cpp @@ -134,13 +134,13 @@ void RenderDeviceD3D11Impl :: CreateBuffer(const BufferDesc& BuffDesc, const Buf ); } -void RenderDeviceD3D11Impl :: CreateShader(const ShaderCreationAttribs& ShaderCreationAttribs, IShader** ppShader) +void RenderDeviceD3D11Impl :: CreateShader(const ShaderCreateInfo& ShaderCI, IShader** ppShader) { - CreateDeviceObject( "shader", ShaderCreationAttribs.Desc, ppShader, + CreateDeviceObject( "shader", ShaderCI.Desc, ppShader, [&]() { ShaderD3D11Impl* pShaderD3D11( NEW_RC_OBJ(m_ShaderObjAllocator, "ShaderD3D11Impl instance", ShaderD3D11Impl) - (this, ShaderCreationAttribs ) ); + (this, ShaderCI) ); pShaderD3D11->QueryInterface( IID_Shader, reinterpret_cast(ppShader) ); OnCreateDeviceObject( pShaderD3D11 ); diff --git a/Graphics/GraphicsEngineD3D11/src/ShaderD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/ShaderD3D11Impl.cpp index 3af91c50..677cd40c 100644 --- a/Graphics/GraphicsEngineD3D11/src/ShaderD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/ShaderD3D11Impl.cpp @@ -34,8 +34,7 @@ ShaderD3D11Impl::ShaderD3D11Impl(IReferenceCounters* pRefCounters, RenderDeviceD3D11Impl* pRenderDeviceD3D11, const ShaderCreateInfo& ShaderCI) : TShaderBase(pRefCounters, pRenderDeviceD3D11, ShaderCI.Desc), - ShaderD3DBase(ShaderCI), - m_ShaderTypeIndex(Diligent::GetShaderTypeIndex(ShaderCI.Desc.ShaderType)) + ShaderD3DBase(ShaderCI) { auto *pDeviceD3D11 = pRenderDeviceD3D11->GetD3D11Device(); switch (ShaderCI.Desc.ShaderType) @@ -74,6 +73,12 @@ ShaderD3D11Impl::ShaderD3D11Impl(IReferenceCounters* pRefCounters, DEV_CHECK_ERR(SUCCEEDED(hr), "Failed to set shader name"); } + // Load shader resources + auto& Allocator = GetRawAllocator(); + auto* pRawMem = ALLOCATE(Allocator, "Allocator for ShaderResources", sizeof(ShaderResourcesD3D11)); + auto* pResources = new (pRawMem) ShaderResourcesD3D11(pRenderDeviceD3D11, m_pShaderByteCode, m_Desc, ShaderCI.UseCombinedTextureSamplers ? ShaderCI.CombinedSamplerSuffix : nullptr); + m_pShaderResources.reset(pResources, STDDeleterRawMem(Allocator)); + // Byte code is only required for the vertex shader to create input layout if( ShaderCI.Desc.ShaderType != SHADER_TYPE_VERTEX ) m_pShaderByteCode.Release(); diff --git a/Graphics/GraphicsEngineD3D11/src/ShaderResourceBindingD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/ShaderResourceBindingD3D11Impl.cpp index 3cce0055..0091cc54 100644 --- a/Graphics/GraphicsEngineD3D11/src/ShaderResourceBindingD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/ShaderResourceBindingD3D11Impl.cpp @@ -37,24 +37,22 @@ ShaderResourceBindingD3D11Impl::ShaderResourceBindingD3D11Impl( IReferenceCounte TBase( pRefCounters, pPSO, IsInternal ), m_bIsStaticResourcesBound(false) { - for(size_t s=0; s < _countof(m_ResourceLayoutIndex); ++s) - m_ResourceLayoutIndex[s] = -1; + m_NumActiveShaders = static_cast(pPSO->GetNumShaders()); - auto ppShaders = pPSO->GetShaders(); - m_NumActiveShaders = static_cast( pPSO->GetNumShaders() ); - - auto *pResLayoutRawMem = ALLOCATE(GetRawAllocator(), "Raw memory for ShaderResourceLayoutD3D11", m_NumActiveShaders * sizeof(ShaderResourceLayoutD3D11)); + auto* pResLayoutRawMem = ALLOCATE(GetRawAllocator(), "Raw memory for ShaderResourceLayoutD3D11", m_NumActiveShaders * sizeof(ShaderResourceLayoutD3D11)); m_pResourceLayouts = reinterpret_cast(pResLayoutRawMem); - auto *pResCacheRawMem = ALLOCATE(GetRawAllocator(), "Raw memory for ShaderResourceCacheD3D11", m_NumActiveShaders * sizeof(ShaderResourceCacheD3D11)); + auto* pResCacheRawMem = ALLOCATE(GetRawAllocator(), "Raw memory for ShaderResourceCacheD3D11", m_NumActiveShaders * sizeof(ShaderResourceCacheD3D11)); m_pBoundResourceCaches = reinterpret_cast(pResCacheRawMem); + + auto* pRenderDevice = pPSO->GetDevice(); + const auto& PSODesc = pPSO->GetDesc(); // Reserve memory for resource layouts for (Uint8 s = 0; s < m_NumActiveShaders; ++s) { - auto *pShaderD3D11 = ValidatedCast(ppShaders[s]); - auto ShaderInd = pShaderD3D11->GetShaderTypeIndex(); - VERIFY_EXPR(static_cast(ShaderInd) == GetShaderTypeIndex(pShaderD3D11->GetDesc().ShaderType)); + auto* pShaderD3D11 = pPSO->GetShader(s); + auto ShaderInd = GetShaderTypeIndex(pShaderD3D11->GetDesc().ShaderType); auto& SRBMemAllocator = pPSO->GetSRBMemoryAllocator(); auto& ResCacheDataAllocator = SRBMemAllocator.GetResourceCacheDataAllocator(s); @@ -62,17 +60,29 @@ ShaderResourceBindingD3D11Impl::ShaderResourceBindingD3D11Impl( IReferenceCounte // Initialize resource cache to have enough space to contain all shader resources, including static ones // Static resources are copied before resources are committed - const auto& Resources = *pShaderD3D11->GetResources(); + const auto& Resources = *pShaderD3D11->GetD3D11Resources(); new (m_pBoundResourceCaches+s) ShaderResourceCacheD3D11; m_pBoundResourceCaches[s].Initialize(Resources, ResCacheDataAllocator); // Shader resource layout will only contain dynamic and mutable variables // http://diligentgraphics.com/diligent-engine/architecture/d3d11/shader-resource-cache#Shader-Resource-Cache-Initialization - SHADER_VARIABLE_TYPE VarTypes[] = {SHADER_VARIABLE_TYPE_MUTABLE, SHADER_VARIABLE_TYPE_DYNAMIC}; - new (m_pResourceLayouts + s) ShaderResourceLayoutD3D11(*this); - m_pResourceLayouts[s].Initialize(pShaderD3D11->GetResources(), VarTypes, _countof(VarTypes), m_pBoundResourceCaches[s], ResCacheDataAllocator, ResLayoutDataAllocator); - - Resources.SetStaticSamplers(m_pBoundResourceCaches[s]); + SHADER_RESOURCE_VARIABLE_TYPE VarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; + new (m_pResourceLayouts + s) + ShaderResourceLayoutD3D11 + { + *this, + pRenderDevice, + pShaderD3D11->GetD3D11Resources(), + PSODesc.ResourceLayout, + VarTypes, + _countof(VarTypes), + m_pBoundResourceCaches[s], + ResCacheDataAllocator, + ResLayoutDataAllocator + }; + + m_pResourceLayouts[s].SetStaticSamplers(m_pBoundResourceCaches[s]); + pPSO->GetStaticResourceLayout(s).SetStaticSamplers(m_pBoundResourceCaches[s]); m_ResourceLayoutIndex[ShaderInd] = s; m_ShaderTypeIndex[s] = static_cast(ShaderInd); @@ -99,7 +109,7 @@ ShaderResourceBindingD3D11Impl::~ShaderResourceBindingD3D11Impl() IMPLEMENT_QUERY_INTERFACE( ShaderResourceBindingD3D11Impl, IID_ShaderResourceBindingD3D11, TBase ) -void ShaderResourceBindingD3D11Impl::BindResources(Uint32 ShaderFlags, IResourceMapping *pResMapping, Uint32 Flags) +void ShaderResourceBindingD3D11Impl::BindResources(Uint32 ShaderFlags, IResourceMapping* pResMapping, Uint32 Flags) { for(Uint32 ResLayoutInd = 0; ResLayoutInd < m_NumActiveShaders; ++ResLayoutInd) { @@ -135,9 +145,10 @@ void ShaderResourceBindingD3D11Impl::InitializeStaticResources(const IPipelineSt for (Uint32 shader = 0; shader < NumShaders; ++shader) { + const auto& StaticResLayout = pPSOD3D11->GetStaticResourceLayout(shader); auto* pShaderD3D11 = ValidatedCast(ppShaders[shader]); #ifdef DEVELOPMENT - if (!pShaderD3D11->GetStaticResourceLayout().dvpVerifyBindings()) + if (!StaticResLayout.dvpVerifyBindings()) { LOG_ERROR_MESSAGE("Static resources in SRB of PSO '", pPSOD3D11->GetDesc().Name, "' will not be successfully initialized " "because not all static resource bindings in shader '", pShaderD3D11->GetDesc().Name, "' are valid. " @@ -147,17 +158,18 @@ void ShaderResourceBindingD3D11Impl::InitializeStaticResources(const IPipelineSt #endif #ifdef _DEBUG - auto ShaderTypeInd = pShaderD3D11->GetShaderTypeIndex(); + auto ShaderTypeInd = GetShaderTypeIndex(pShaderD3D11->GetDesc().ShaderType); auto ResourceLayoutInd = m_ResourceLayoutIndex[ShaderTypeInd]; VERIFY_EXPR(ResourceLayoutInd == static_cast(shader) ); #endif - pShaderD3D11->GetStaticResourceLayout().CopyResources( m_pBoundResourceCaches[shader] ); + StaticResLayout.CopyResources(m_pBoundResourceCaches[shader]); + //StaticResLayout.SetStaticSamplers(m_pBoundResourceCaches[shader]); } m_bIsStaticResourcesBound = true; } -IShaderVariable* ShaderResourceBindingD3D11Impl::GetVariable(SHADER_TYPE ShaderType, const char* Name) +IShaderResourceVariable* ShaderResourceBindingD3D11Impl::GetVariable(SHADER_TYPE ShaderType, const char* Name) { auto Ind = GetShaderTypeIndex(ShaderType); VERIFY_EXPR(Ind >= 0 && Ind < _countof(m_ResourceLayoutIndex)); @@ -185,7 +197,7 @@ Uint32 ShaderResourceBindingD3D11Impl::GetVariableCount(SHADER_TYPE ShaderType) return m_pResourceLayouts[ResLayoutIndex].GetTotalResourceCount(); } -IShaderVariable* ShaderResourceBindingD3D11Impl::GetVariable(SHADER_TYPE ShaderType, Uint32 Index) +IShaderResourceVariable* ShaderResourceBindingD3D11Impl::GetVariable(SHADER_TYPE ShaderType, Uint32 Index) { auto Ind = GetShaderTypeIndex(ShaderType); VERIFY_EXPR(Ind >= 0 && Ind < _countof(m_ResourceLayoutIndex)); diff --git a/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp b/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp index c6cf6f6b..6839e29d 100755 --- a/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp +++ b/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp @@ -33,14 +33,11 @@ #include "TextureViewD3D11.h" #include "SamplerD3D11Impl.h" #include "ShaderD3D11Impl.h" +#include "ShaderResourceVariableBase.h" namespace Diligent { -ShaderResourceLayoutD3D11::ShaderResourceLayoutD3D11(IObject& Owner) : - m_Owner(Owner) -{ -} ShaderResourceLayoutD3D11::~ShaderResourceLayoutD3D11() { @@ -83,7 +80,7 @@ size_t ShaderResourceLayoutD3D11::GetRequiredMemorySize(const ShaderResourcesD3D const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes) { - auto ResCounters = SrcResources.CountResources(ResourceLayout, SrcResources.GetShaderType(), SrcResources.GetCombinedSamplerSuffix(), AllowedVarTypes, NumAllowedTypes); + auto ResCounters = SrcResources.CountResources(ResourceLayout, AllowedVarTypes, NumAllowedTypes); auto MemSize = ResCounters.NumCBs * sizeof(ConstBuffBindInfo) + ResCounters.NumTexSRVs * sizeof(TexSRVBindInfo) + ResCounters.NumTexUAVs * sizeof(TexUAVBindInfo) + @@ -93,23 +90,26 @@ size_t ShaderResourceLayoutD3D11::GetRequiredMemorySize(const ShaderResourcesD3D return MemSize; } -#if 0 -void ShaderResourceLayoutD3D11::Initialize(std::shared_ptr pSrcResources, - const SHADER_VARIABLE_TYPE* VarTypes, - Uint32 NumVarTypes, - ShaderResourceCacheD3D11& ResourceCache, - IMemoryAllocator& ResCacheDataAllocator, - IMemoryAllocator& ResLayoutDataAllocator) + +ShaderResourceLayoutD3D11::ShaderResourceLayoutD3D11(IObject& Owner, + IRenderDevice* pRenderDevice, + std::shared_ptr pSrcResources, + const PipelineResourceLayoutDesc& ResourceLayout, + const SHADER_RESOURCE_VARIABLE_TYPE* VarTypes, + Uint32 NumVarTypes, + ShaderResourceCacheD3D11& ResourceCache, + IMemoryAllocator& ResCacheDataAllocator, + IMemoryAllocator& ResLayoutDataAllocator) : + m_Owner (Owner), + m_pResources (std::move(pSrcResources)), + m_ResourceCache (ResourceCache) { // http://diligentgraphics.com/diligent-engine/architecture/d3d11/shader-resource-layout#Shader-Resource-Layout-Initialization - m_pResources = std::move(pSrcResources); - m_pResourceCache = &ResourceCache; - - auto AllowedTypeBits = GetAllowedTypeBits(VarTypes, NumVarTypes); + const auto AllowedTypeBits = GetAllowedTypeBits(VarTypes, NumVarTypes); // Count total number of resources of allowed types - auto ResCounters = m_pResources->CountResources(VarTypes, NumVarTypes); + auto ResCounters = m_pResources->CountResources(ResourceLayout, VarTypes, NumVarTypes); // Initialize offsets size_t CurrentOffset = 0; @@ -122,7 +122,7 @@ void ShaderResourceLayoutD3D11::Initialize(std::shared_ptr >(pRawMem, ResLayoutDataAllocator); } @@ -158,33 +158,41 @@ void ShaderResourceLayoutD3D11::Initialize(std::shared_ptrProcessResources( - VarTypes, NumVarTypes, - [&](const D3DShaderResourceAttribs& CB, Uint32) { - VERIFY_EXPR( CB.IsAllowedType(AllowedTypeBits) ); - - // Initialize current CB in place, increment CB counter - new (&GetResource(cb++)) ConstBuffBindInfo( CB, *this ); - NumCBSlots = std::max(NumCBSlots, Uint32{CB.BindPoint} + Uint32{CB.BindCount}); + auto VarType = m_pResources->FindVariableType(CB, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) + { + // Initialize current CB in place, increment CB counter + new (&GetResource(cb++)) ConstBuffBindInfo(CB, *this, VarType); + NumCBSlots = std::max(NumCBSlots, Uint32{CB.BindPoint} + Uint32{CB.BindCount}); + } }, [&](const D3DShaderResourceAttribs& Sampler, Uint32) { - VERIFY_EXPR(Sampler.IsAllowedType(AllowedTypeBits)); - - // Skip static samplers as they are initialized in the resource cache - if (!Sampler.IsStaticSampler()) + auto VarType = m_pResources->FindVariableType(Sampler, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) { + auto StaticSamplerInd = m_pResources->FindStaticSampler(Sampler, ResourceLayout); + RefCntAutoPtr pStaticSampler; + if (StaticSamplerInd >= 0) + { + const auto& StaticSamplerDesc = ResourceLayout.StaticSamplers[StaticSamplerInd]; + pRenderDevice->CreateSampler(StaticSamplerDesc.Desc, &pStaticSampler); + } // Initialize current sampler in place, increment sampler counter - new (&GetResource(sam++)) SamplerBindInfo( Sampler, *this ); + new (&GetResource(sam++)) SamplerBindInfo(Sampler, *this, VarType, std::move(pStaticSampler)); NumSamplerSlots = std::max(NumSamplerSlots, Uint32{Sampler.BindPoint} + Uint32{Sampler.BindCount}); } }, [&](const D3DShaderResourceAttribs& TexSRV, Uint32) { - VERIFY_EXPR( TexSRV.IsAllowedType(AllowedTypeBits) ); + auto VarType = m_pResources->FindVariableType(TexSRV, ResourceLayout); + if (!IsAllowedType(VarType, AllowedTypeBits)) + return; + auto NumSamplers = GetNumSamplers(); VERIFY(sam == NumSamplers, "All samplers must be initialized before texture SRVs"); @@ -192,53 +200,66 @@ void ShaderResourceLayoutD3D11::Initialize(std::shared_ptrGetSampler(TexSRV.GetSamplerId()); - DEV_CHECK_ERR(AssignedSamplerAttribs.GetVariableType() == TexSRV.GetVariableType(), - "The type (", GetShaderVariableTypeLiteralName(TexSRV.GetVariableType()),") of texture SRV variable '", TexSRV.Name, - "' is not consistent with the type (", GetShaderVariableTypeLiteralName(AssignedSamplerAttribs.GetVariableType()), + auto AssignedSamplerType = m_pResources->FindVariableType(AssignedSamplerAttribs, ResourceLayout); + DEV_CHECK_ERR(AssignedSamplerType == VarType, + "The type (", GetShaderVariableTypeLiteralName(VarType),") of texture SRV variable '", TexSRV.Name, + "' is not consistent with the type (", GetShaderVariableTypeLiteralName(AssignedSamplerType), ") of the sampler '", AssignedSamplerAttribs.Name, "' that is assigned to it"); - // Do not assign static sampler to texture SRV as it is initialized directly in the shader resource cache - if (!AssignedSamplerAttribs.IsStaticSampler()) + + bool SamplerFound = false; + for (AssignedSamplerIndex = 0; AssignedSamplerIndex < NumSamplers && !SamplerFound; ++AssignedSamplerIndex) { - for (AssignedSamplerIndex = 0; AssignedSamplerIndex < NumSamplers; ++AssignedSamplerIndex) + const auto& Sampler = GetResource(AssignedSamplerIndex); + SamplerFound = strcmp(Sampler.m_Attribs.Name, AssignedSamplerAttribs.Name) == 0; + if (SamplerFound) { - const auto& Sampler = GetResource(AssignedSamplerIndex); - if (strcmp(Sampler.m_Attribs.Name, AssignedSamplerAttribs.Name) == 0) + if (Sampler.pStaticSampler) + { + // Do not assign static samplers to texture SRV + AssignedSamplerIndex = TexSRVBindInfo::InvalidSamplerIndex; break; + } } - VERIFY(AssignedSamplerIndex < NumSamplers, "Unable to find assigned sampler"); } + VERIFY(SamplerFound, "Unable to find sampler assigned to texture SRV '", TexSRV.Name, "'"); } // Initialize tex SRV in place, increment counter of tex SRVs - new (&GetResource(texSrv++)) TexSRVBindInfo( TexSRV, AssignedSamplerIndex, *this ); + new (&GetResource(texSrv++)) TexSRVBindInfo(TexSRV, AssignedSamplerIndex, *this, VarType); NumSRVSlots = std::max(NumSRVSlots, Uint32{TexSRV.BindPoint} + Uint32{TexSRV.BindCount}); }, [&](const D3DShaderResourceAttribs& TexUAV, Uint32) { - VERIFY_EXPR( TexUAV.IsAllowedType(AllowedTypeBits) ); - - // Initialize tex UAV in place, increment counter of tex UAVs - new (&GetResource(texUav++)) TexUAVBindInfo( TexUAV, *this ); - NumUAVSlots = std::max(NumUAVSlots, Uint32{TexUAV.BindPoint} + Uint32{TexUAV.BindCount}); + auto VarType = m_pResources->FindVariableType(TexUAV, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) + { + // Initialize tex UAV in place, increment counter of tex UAVs + new (&GetResource(texUav++)) TexUAVBindInfo(TexUAV, *this, VarType); + NumUAVSlots = std::max(NumUAVSlots, Uint32{TexUAV.BindPoint} + Uint32{TexUAV.BindCount}); + } }, [&](const D3DShaderResourceAttribs& BuffSRV, Uint32) { - VERIFY_EXPR(BuffSRV.IsAllowedType(AllowedTypeBits)); - - // Initialize buff SRV in place, increment counter of buff SRVs - new (&GetResource(bufSrv++)) BuffSRVBindInfo( BuffSRV, *this ); - NumSRVSlots = std::max(NumSRVSlots, Uint32{BuffSRV.BindPoint} + Uint32{BuffSRV.BindCount}); + auto VarType = m_pResources->FindVariableType(BuffSRV, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) + { + // Initialize buff SRV in place, increment counter of buff SRVs + new (&GetResource(bufSrv++)) BuffSRVBindInfo(BuffSRV, *this, VarType); + NumSRVSlots = std::max(NumSRVSlots, Uint32{BuffSRV.BindPoint} + Uint32{BuffSRV.BindCount}); + } }, [&](const D3DShaderResourceAttribs& BuffUAV, Uint32) { - VERIFY_EXPR(BuffUAV.IsAllowedType(AllowedTypeBits)); - - // Initialize buff UAV in place, increment counter of buff UAVs - new (&GetResource(bufUav++)) BuffUAVBindInfo( BuffUAV, *this ); - NumUAVSlots = std::max(NumUAVSlots, Uint32{BuffUAV.BindPoint} + Uint32{BuffUAV.BindCount}); + auto VarType = m_pResources->FindVariableType(BuffUAV, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) + { + // Initialize buff UAV in place, increment counter of buff UAVs + new (&GetResource(bufUav++)) BuffUAVBindInfo(BuffUAV, *this, VarType); + NumUAVSlots = std::max(NumUAVSlots, Uint32{BuffUAV.BindPoint} + Uint32{BuffUAV.BindCount}); + } } ); @@ -253,22 +274,19 @@ void ShaderResourceLayoutD3D11::Initialize(std::shared_ptrIsInitialized()) + if (!m_ResourceCache.IsInitialized()) { // NOTE that here we are using max bind points required to cache only the shader variables of allowed types! - m_pResourceCache->Initialize(NumCBSlots, NumSRVSlots, NumSamplerSlots, NumUAVSlots, ResCacheDataAllocator); + m_ResourceCache.Initialize(NumCBSlots, NumSRVSlots, NumSamplerSlots, NumUAVSlots, ResCacheDataAllocator); } } -#endif -void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache) +void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache)const { - VERIFY(m_pResourceCache, "Resource cache must not be null"); - - VERIFY( DstCache.GetCBCount() >= m_pResourceCache->GetCBCount(), "Dst cache is not large enough to contain all CBs" ); - VERIFY( DstCache.GetSRVCount() >= m_pResourceCache->GetSRVCount(), "Dst cache is not large enough to contain all SRVs" ); - VERIFY( DstCache.GetSamplerCount() >= m_pResourceCache->GetSamplerCount(), "Dst cache is not large enough to contain all samplers" ); - VERIFY( DstCache.GetUAVCount() >= m_pResourceCache->GetUAVCount(), "Dst cache is not large enough to contain all UAVs" ); + VERIFY( DstCache.GetCBCount() >= m_ResourceCache.GetCBCount(), "Dst cache is not large enough to contain all CBs" ); + VERIFY( DstCache.GetSRVCount() >= m_ResourceCache.GetSRVCount(), "Dst cache is not large enough to contain all SRVs" ); + VERIFY( DstCache.GetSamplerCount() >= m_ResourceCache.GetSamplerCount(), "Dst cache is not large enough to contain all samplers" ); + VERIFY( DstCache.GetUAVCount() >= m_ResourceCache.GetUAVCount(), "Dst cache is not large enough to contain all UAVs" ); ShaderResourceCacheD3D11::CachedCB* CachedCBs = nullptr; ID3D11Buffer** d3d11CBs = nullptr; @@ -278,10 +296,10 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache ID3D11SamplerState** d3d11Samplers = nullptr; ShaderResourceCacheD3D11::CachedResource* CachedUAVResources = nullptr; ID3D11UnorderedAccessView** d3d11UAVs = nullptr; - m_pResourceCache->GetCBArrays (CachedCBs, d3d11CBs); - m_pResourceCache->GetSRVArrays (CachedSRVResources, d3d11SRVs); - m_pResourceCache->GetSamplerArrays(CachedSamplers, d3d11Samplers); - m_pResourceCache->GetUAVArrays (CachedUAVResources, d3d11UAVs); + m_ResourceCache.GetCBArrays (CachedCBs, d3d11CBs); + m_ResourceCache.GetSRVArrays (CachedSRVResources, d3d11SRVs); + m_ResourceCache.GetSamplerArrays(CachedSamplers, d3d11Samplers); + m_ResourceCache.GetUAVArrays (CachedUAVResources, d3d11UAVs); ShaderResourceCacheD3D11::CachedCB* DstCBs = nullptr; @@ -297,12 +315,12 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache DstCache.GetSamplerArrays(DstSamplers, DstD3D11Samplers); DstCache.GetUAVArrays (DstUAVResources, DstD3D11UAVs); - HandleResources( + HandleConstResources( [&](const ConstBuffBindInfo& cb) { for(auto CBSlot = cb.m_Attribs.BindPoint; CBSlot < cb.m_Attribs.BindPoint+cb.m_Attribs.BindCount; ++CBSlot) { - VERIFY_EXPR(CBSlot < m_pResourceCache->GetCBCount() && CBSlot < DstCache.GetCBCount()); + VERIFY_EXPR(CBSlot < m_ResourceCache.GetCBCount() && CBSlot < DstCache.GetCBCount()); DstCBs [CBSlot] = CachedCBs[CBSlot]; DstD3D11CBs[CBSlot] = d3d11CBs [CBSlot]; } @@ -312,7 +330,7 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache { for(auto SRVSlot = ts.m_Attribs.BindPoint; SRVSlot < ts.m_Attribs.BindPoint + ts.m_Attribs.BindCount; ++SRVSlot) { - VERIFY_EXPR(SRVSlot < m_pResourceCache->GetSRVCount() && SRVSlot < DstCache.GetSRVCount()); + VERIFY_EXPR(SRVSlot < m_ResourceCache.GetSRVCount() && SRVSlot < DstCache.GetSRVCount()); DstSRVResources[SRVSlot] = CachedSRVResources[SRVSlot]; DstD3D11SRVs [SRVSlot] = d3d11SRVs [SRVSlot]; } @@ -322,7 +340,7 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache { for(auto UAVSlot = uav.m_Attribs.BindPoint; UAVSlot < uav.m_Attribs.BindPoint + uav.m_Attribs.BindCount; ++UAVSlot) { - VERIFY_EXPR(UAVSlot < m_pResourceCache->GetUAVCount() && UAVSlot < DstCache.GetUAVCount()); + VERIFY_EXPR(UAVSlot < m_ResourceCache.GetUAVCount() && UAVSlot < DstCache.GetUAVCount()); DstUAVResources[UAVSlot] = CachedUAVResources[UAVSlot]; DstD3D11UAVs [UAVSlot] = d3d11UAVs [UAVSlot]; } @@ -332,7 +350,7 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache { for(auto SRVSlot = srv.m_Attribs.BindPoint; SRVSlot < srv.m_Attribs.BindPoint + srv.m_Attribs.BindCount; ++SRVSlot) { - VERIFY_EXPR(SRVSlot < m_pResourceCache->GetSRVCount() && SRVSlot < DstCache.GetSRVCount()); + VERIFY_EXPR(SRVSlot < m_ResourceCache.GetSRVCount() && SRVSlot < DstCache.GetSRVCount()); DstSRVResources[SRVSlot] = CachedSRVResources[SRVSlot]; DstD3D11SRVs [SRVSlot] = d3d11SRVs [SRVSlot]; } @@ -342,7 +360,7 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache { for(auto UAVSlot = uav.m_Attribs.BindPoint; UAVSlot < uav.m_Attribs.BindPoint + uav.m_Attribs.BindCount; ++UAVSlot) { - VERIFY_EXPR(UAVSlot < m_pResourceCache->GetUAVCount() && UAVSlot < DstCache.GetUAVCount()); + VERIFY_EXPR(UAVSlot < m_ResourceCache.GetUAVCount() && UAVSlot < DstCache.GetUAVCount()); DstUAVResources[UAVSlot] = CachedUAVResources[UAVSlot]; DstD3D11UAVs [UAVSlot] = d3d11UAVs [UAVSlot]; } @@ -350,10 +368,10 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache [&](const SamplerBindInfo& sam) { - VERIFY(!sam.IsStaticSampler(), "Variables are not created for static samplers"); + VERIFY(!sam.pStaticSampler, "Variables are not created for static samplers"); for(auto SamSlot = sam.m_Attribs.BindPoint; SamSlot < sam.m_Attribs.BindPoint + sam.m_Attribs.BindCount; ++SamSlot) { - VERIFY_EXPR(SamSlot < m_pResourceCache->GetSamplerCount() && SamSlot < DstCache.GetSamplerCount()); + VERIFY_EXPR(SamSlot < m_ResourceCache.GetSamplerCount() && SamSlot < DstCache.GetSamplerCount()); DstSamplers [SamSlot] = CachedSamplers[SamSlot]; DstD3D11Samplers[SamSlot] = d3d11Samplers [SamSlot]; } @@ -361,6 +379,24 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache ); } +void ShaderResourceLayoutD3D11::SetStaticSamplers(ShaderResourceCacheD3D11& ResourceCache)const +{ + auto NumCachedSamplers = ResourceCache.GetSamplerCount(); + for (Uint32 s = 0; s < GetNumResources(); ++s) + { + auto& Sampler = GetConstResource(s); + if (Sampler.pStaticSampler) + { + const auto& SamAttribs = Sampler.m_Attribs; + auto* pSamplerD3D11Impl = const_cast(Sampler.pStaticSampler.RawPtr()); + // Limiting EndBindPoint is required when initializing static samplers in a Shader's static cache + auto EndBindPoint = std::min( static_cast(SamAttribs.BindPoint) + SamAttribs.BindCount, NumCachedSamplers); + for (Uint32 BindPoint = SamAttribs.BindPoint; BindPoint < EndBindPoint; ++BindPoint ) + ResourceCache.SetSampler(BindPoint, pSamplerD3D11Impl); + } + } +} + #define LOG_RESOURCE_BINDING_ERROR(ResType, pResource, Attribs, ArrayInd, ShaderName, ...)\ do{ \ const auto* ResName = pResource->GetDesc().Name; \ @@ -375,9 +411,8 @@ do{ void ShaderResourceLayoutD3D11::ConstBuffBindInfo::BindResource(IDeviceObject* pBuffer, Uint32 ArrayIndex) { - VERIFY(m_ParentResLayout.m_pResourceCache != nullptr, "Resource cache is null"); DEV_CHECK_ERR(ArrayIndex < m_Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", m_Attribs.Name, "'. Max allowed index: ", m_Attribs.BindCount); - auto& ResourceCache = *m_ParentResLayout.m_pResourceCache; + auto& ResourceCache = m_ParentResLayout.m_ResourceCache; // We cannot use ValidatedCast<> here as the resource retrieved from the // resource mapping can be of wrong type @@ -408,13 +443,10 @@ void ShaderResourceLayoutD3D11::ConstBuffBindInfo::BindResource(IDeviceObject* p -bool ShaderResourceLayoutD3D11::ConstBuffBindInfo::IsBound(Uint32 ArrayIndex) +bool ShaderResourceLayoutD3D11::ConstBuffBindInfo::IsBound(Uint32 ArrayIndex)const { - auto* pResourceCache = m_ParentResLayout.m_pResourceCache; - VERIFY(pResourceCache, "Resource cache is null"); VERIFY_EXPR(ArrayIndex < m_Attribs.BindCount); - - return pResourceCache->IsCBBound(m_Attribs.BindPoint + ArrayIndex); + return m_ParentResLayout.m_ResourceCache.IsCBBound(m_Attribs.BindPoint + ArrayIndex); } @@ -449,9 +481,8 @@ bool dbgVerifyViewType( const char* ViewTypeName, void ShaderResourceLayoutD3D11::TexSRVBindInfo::BindResource(IDeviceObject* pView, Uint32 ArrayIndex) { - VERIFY(m_ParentResLayout.m_pResourceCache, "Resource cache is null"); DEV_CHECK_ERR(ArrayIndex < m_Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", m_Attribs.Name, "'. Max allowed index: ", m_Attribs.BindCount); - auto& ResourceCache = *m_ParentResLayout.m_pResourceCache; + auto& ResourceCache = m_ParentResLayout.m_ResourceCache; // We cannot use ValidatedCast<> here as the resource retrieved from the // resource mapping can be of wrong type @@ -476,7 +507,7 @@ void ShaderResourceLayoutD3D11::TexSRVBindInfo::BindResource(IDeviceObject* pVie if (ValidSamplerAssigned()) { auto& Sampler = m_ParentResLayout.GetResource(SamplerIndex); - VERIFY(!Sampler.IsStaticSampler(), "Static samplers are not assigned to texture SRVs as they are initialized directly in the shader resource cache"); + VERIFY(!Sampler.pStaticSampler, "Static samplers are not assigned to texture SRVs as they are initialized directly in the shader resource cache"); VERIFY_EXPR(Sampler.m_Attribs.BindCount == m_Attribs.BindCount || Sampler.m_Attribs.BindCount == 1); auto SamplerBindPoint = Sampler.m_Attribs.BindPoint + (Sampler.m_Attribs.BindCount != 1 ? ArrayIndex : 0); @@ -514,10 +545,9 @@ void ShaderResourceLayoutD3D11::TexSRVBindInfo::BindResource(IDeviceObject* pVie void ShaderResourceLayoutD3D11::SamplerBindInfo::BindResource(IDeviceObject* pSampler, Uint32 ArrayIndex) { - VERIFY(m_ParentResLayout.m_pResourceCache != nullptr, "Resource cache is null"); DEV_CHECK_ERR(ArrayIndex < m_Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", m_Attribs.Name, "'. Max allowed index: ", m_Attribs.BindCount); - auto& ResourceCache = *m_ParentResLayout.m_pResourceCache; - VERIFY(!IsStaticSampler(), "Cannot bind sampler to a static sampler"); + auto& ResourceCache = m_ParentResLayout.m_ResourceCache; + VERIFY(!pStaticSampler, "Cannot bind sampler to a static sampler"); // We cannot use ValidatedCast<> here as the resource retrieved from the // resource mapping can be of wrong type @@ -550,9 +580,8 @@ void ShaderResourceLayoutD3D11::SamplerBindInfo::BindResource(IDeviceObject* pSa void ShaderResourceLayoutD3D11::BuffSRVBindInfo::BindResource(IDeviceObject* pView, Uint32 ArrayIndex) { - VERIFY(m_ParentResLayout.m_pResourceCache != nullptr, "Resource cache is null"); DEV_CHECK_ERR(ArrayIndex < m_Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", m_Attribs.Name, "'. Max allowed index: ", m_Attribs.BindCount); - auto& ResourceCache = *m_ParentResLayout.m_pResourceCache; + auto& ResourceCache = m_ParentResLayout.m_ResourceCache; // We cannot use ValidatedCast<> here as the resource retrieved from the // resource mapping can be of wrong type @@ -581,9 +610,8 @@ void ShaderResourceLayoutD3D11::BuffSRVBindInfo::BindResource(IDeviceObject* pVi void ShaderResourceLayoutD3D11::TexUAVBindInfo::BindResource(IDeviceObject* pView, Uint32 ArrayIndex) { - VERIFY(m_ParentResLayout.m_pResourceCache != nullptr, "Resource cache is null"); DEV_CHECK_ERR(ArrayIndex < m_Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", m_Attribs.Name, "'. Max allowed index: ", m_Attribs.BindCount); - auto& ResourceCache = *m_ParentResLayout.m_pResourceCache; + auto& ResourceCache = m_ParentResLayout.m_ResourceCache; // We cannot use ValidatedCast<> here as the resource retrieved from the // resource mapping can be of wrong type @@ -612,9 +640,8 @@ void ShaderResourceLayoutD3D11::TexUAVBindInfo::BindResource(IDeviceObject* pVie void ShaderResourceLayoutD3D11::BuffUAVBindInfo::BindResource(IDeviceObject* pView, Uint32 ArrayIndex) { - VERIFY(m_ParentResLayout.m_pResourceCache != nullptr, "Resource cache is null"); DEV_CHECK_ERR(ArrayIndex < m_Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", m_Attribs.Name, "'. Max allowed index: ", m_Attribs.BindCount); - auto& ResourceCache = *m_ParentResLayout.m_pResourceCache; + auto& ResourceCache = m_ParentResLayout.m_ResourceCache; // We cannot use ValidatedCast<> here as the resource retrieved from the // resource mapping can be of wrong type @@ -642,48 +669,33 @@ void ShaderResourceLayoutD3D11::BuffUAVBindInfo::BindResource(IDeviceObject* pVi bool ShaderResourceLayoutD3D11::TexSRVBindInfo::IsBound(Uint32 ArrayIndex)const { - auto* pResourceCache = m_ParentResLayout.m_pResourceCache; - VERIFY(pResourceCache != nullptr, "Resource cache is null"); VERIFY_EXPR(ArrayIndex < m_Attribs.BindCount); - - return pResourceCache->IsSRVBound(m_Attribs.BindPoint + ArrayIndex, true); + return m_ParentResLayout.m_ResourceCache.IsSRVBound(m_Attribs.BindPoint + ArrayIndex, true); } bool ShaderResourceLayoutD3D11::BuffSRVBindInfo::IsBound(Uint32 ArrayIndex)const { - auto* pResourceCache = m_ParentResLayout.m_pResourceCache; - VERIFY(pResourceCache, "Resource cache is null"); VERIFY_EXPR(ArrayIndex < m_Attribs.BindCount); - - return pResourceCache->IsSRVBound(m_Attribs.BindPoint + ArrayIndex, false); + return m_ParentResLayout.m_ResourceCache.IsSRVBound(m_Attribs.BindPoint + ArrayIndex, false); } bool ShaderResourceLayoutD3D11::TexUAVBindInfo::IsBound(Uint32 ArrayIndex)const { - auto* pResourceCache = m_ParentResLayout.m_pResourceCache; - VERIFY(pResourceCache, "Resource cache is null"); VERIFY_EXPR(ArrayIndex < m_Attribs.BindCount); - - return pResourceCache->IsUAVBound(m_Attribs.BindPoint + ArrayIndex, true); + return m_ParentResLayout.m_ResourceCache.IsUAVBound(m_Attribs.BindPoint + ArrayIndex, true); } bool ShaderResourceLayoutD3D11::BuffUAVBindInfo::IsBound(Uint32 ArrayIndex)const { - auto* pResourceCache = m_ParentResLayout.m_pResourceCache; - VERIFY(pResourceCache, "Resource cache is null"); VERIFY_EXPR(ArrayIndex < m_Attribs.BindCount); - - return pResourceCache->IsUAVBound(m_Attribs.BindPoint + ArrayIndex, false); + return m_ParentResLayout.m_ResourceCache.IsUAVBound(m_Attribs.BindPoint + ArrayIndex, false); } bool ShaderResourceLayoutD3D11::SamplerBindInfo::IsBound(Uint32 ArrayIndex)const { - auto* pResourceCache = m_ParentResLayout.m_pResourceCache; - VERIFY(pResourceCache, "Resource cache is null"); VERIFY_EXPR(ArrayIndex < m_Attribs.BindCount); - - return pResourceCache->IsSamplerBound(m_Attribs.BindPoint + ArrayIndex); + return m_ParentResLayout.m_ResourceCache.IsSamplerBound(m_Attribs.BindPoint + ArrayIndex); } @@ -699,7 +711,7 @@ public: } template - void Bind( ResourceType &Res) + void Bind( ResourceType& Res) { if ( (Flags & (1 << Res.GetType())) == 0 ) return; @@ -732,7 +744,7 @@ private: void ShaderResourceLayoutD3D11::BindResources( IResourceMapping* pResourceMapping, Uint32 Flags, const ShaderResourceCacheD3D11& dbgResourceCache ) { - VERIFY(&dbgResourceCache == m_pResourceCache, "Resource cache does not match the cache provided at initialization"); + VERIFY(&dbgResourceCache == &m_ResourceCache, "Resource cache does not match the cache provided at initialization"); if (pResourceMapping == nullptr) { @@ -812,8 +824,16 @@ IShaderResourceVariable* ShaderResourceLayoutD3D11::GetShaderVariable(const Char if (!m_pResources->IsUsingCombinedTextureSamplers()) { - if(auto* pSampler = GetResourceByName(Name)) - return pSampler; + auto NumSamplers = GetNumResources(); + for (Uint32 s = 0; s < NumSamplers; ++s) + { + auto& Sampler = GetResource(s); + if (strcmp(Sampler.m_Attribs.Name, Name) == 0) + { + // Do not return static samplers + return Sampler.pStaticSampler ? nullptr : &Sampler; + } + } } return nullptr; @@ -971,17 +991,15 @@ do{ \ LOG_ERROR_MESSAGE( "No resource is bound to ", VarType, " variable '", Attrs.Name, "[", BindPt-Attrs.BindPoint, "]' in shader '", GetShaderName(), "'" );\ }while(false) - m_pResourceCache->dbgVerifyCacheConsistency(); + m_ResourceCache.dbgVerifyCacheConsistency(); bool BindingsOK = true; - // Use const_cast to avoid duplication of the HandleResources() function - // The function actually changes nothing - const_cast(this)->HandleResources( + HandleConstResources( [&](const ConstBuffBindInfo& cb) { for (Uint32 BindPoint = cb.m_Attribs.BindPoint; BindPoint < Uint32{cb.m_Attribs.BindPoint} + cb.m_Attribs.BindCount; ++BindPoint) { - if (!m_pResourceCache->IsCBBound(BindPoint)) + if (!m_ResourceCache.IsCBBound(BindPoint)) { LOG_MISSING_BINDING("constant buffer", cb.m_Attribs, BindPoint); BindingsOK = false; @@ -993,7 +1011,7 @@ do{ \ { for (Uint32 BindPoint = ts.m_Attribs.BindPoint; BindPoint < Uint32{ts.m_Attribs.BindPoint} + ts.m_Attribs.BindCount; ++BindPoint) { - if (!m_pResourceCache->IsSRVBound(BindPoint, true)) + if (!m_ResourceCache.IsSRVBound(BindPoint, true)) { LOG_MISSING_BINDING("texture", ts.m_Attribs, BindPoint); BindingsOK = false; @@ -1009,14 +1027,14 @@ do{ \ { ShaderResourceCacheD3D11::CachedSampler* pCachedSamplers = nullptr; ID3D11SamplerState** ppCachedD3D11Samplers = nullptr; - m_pResourceCache->GetSamplerArrays(pCachedSamplers, ppCachedD3D11Samplers); - VERIFY_EXPR(Sampler.m_Attribs.BindPoint < m_pResourceCache->GetSamplerCount()); + m_ResourceCache.GetSamplerArrays(pCachedSamplers, ppCachedD3D11Samplers); + VERIFY_EXPR(Sampler.m_Attribs.BindPoint < m_ResourceCache.GetSamplerCount()); const auto& CachedSampler = pCachedSamplers[Sampler.m_Attribs.BindPoint]; ShaderResourceCacheD3D11::CachedResource* pCachedResources = nullptr; ID3D11ShaderResourceView** ppCachedD3D11Resources = nullptr; - m_pResourceCache->GetSRVArrays(pCachedResources, ppCachedD3D11Resources); - VERIFY_EXPR(BindPoint < m_pResourceCache->GetSRVCount()); + m_ResourceCache.GetSRVArrays(pCachedResources, ppCachedD3D11Resources); + VERIFY_EXPR(BindPoint < m_ResourceCache.GetSRVCount()); auto& CachedResource = pCachedResources[BindPoint]; if (CachedResource.pView) { @@ -1036,7 +1054,7 @@ do{ \ { for (Uint32 BindPoint = uav.m_Attribs.BindPoint; BindPoint < Uint32{uav.m_Attribs.BindPoint} + uav.m_Attribs.BindCount; ++BindPoint) { - if (!m_pResourceCache->IsUAVBound(BindPoint, true)) + if (!m_ResourceCache.IsUAVBound(BindPoint, true)) { LOG_MISSING_BINDING("texture UAV", uav.m_Attribs, BindPoint); BindingsOK = false; @@ -1048,7 +1066,7 @@ do{ \ { for (Uint32 BindPoint = buf.m_Attribs.BindPoint; BindPoint < Uint32{buf.m_Attribs.BindPoint} + buf.m_Attribs.BindCount; ++BindPoint) { - if (!m_pResourceCache->IsSRVBound(BindPoint, false)) + if (!m_ResourceCache.IsSRVBound(BindPoint, false)) { LOG_MISSING_BINDING("buffer", buf.m_Attribs, BindPoint); BindingsOK = false; @@ -1060,7 +1078,7 @@ do{ \ { for (Uint32 BindPoint = uav.m_Attribs.BindPoint; BindPoint < Uint32{uav.m_Attribs.BindPoint} + uav.m_Attribs.BindCount; ++BindPoint) { - if (!m_pResourceCache->IsUAVBound(BindPoint, false)) + if (!m_ResourceCache.IsUAVBound(BindPoint, false)) { LOG_MISSING_BINDING("buffer UAV", uav.m_Attribs, BindPoint); BindingsOK = false; @@ -1072,7 +1090,7 @@ do{ \ { for (Uint32 BindPoint = sam.m_Attribs.BindPoint; BindPoint < Uint32{sam.m_Attribs.BindPoint} + sam.m_Attribs.BindCount; ++BindPoint) { - if (!m_pResourceCache->IsSamplerBound(BindPoint)) + if (!m_ResourceCache.IsSamplerBound(BindPoint)) { LOG_MISSING_BINDING("sampler", sam.m_Attribs, BindPoint); BindingsOK = false; diff --git a/Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp b/Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp index 78dfcf63..a12a8ff6 100755 --- a/Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp +++ b/Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp @@ -37,8 +37,7 @@ ShaderResourcesD3D11::ShaderResourcesD3D11(RenderDeviceD3D11Impl* pDeviceD3D11Im ID3DBlob* pShaderBytecode, const ShaderDesc& ShdrDesc, const char* CombinedSamplerSuffix) : - ShaderResources(ShdrDesc.ShaderType), - m_ShaderName(ShdrDesc.Name) + ShaderResources(ShdrDesc.ShaderType) { class NewResourceHandler { diff --git a/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h b/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h index 64c8fe61..4c38c4f5 100644 --- a/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h +++ b/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h @@ -67,33 +67,35 @@ namespace Diligent { +// sizeof(D3DShaderResourceAttribs) == 16 (x64) struct D3DShaderResourceAttribs { - const char* const Name; +/* 0 */ const char* const Name; - const Uint16 BindPoint; - const Uint16 BindCount; +/* 8 */ const Uint16 BindPoint; +/*10 */ const Uint16 BindCount; private: // 4 4 24 // bit | 0 1 2 3 | 4 5 6 7 | 8 9 10 ... 31 | // | | | | // | InputType | SRV Dim | SamplerOrTexSRVIdBits | - static constexpr const Uint32 ShaderInputTypeBits = 4; - static constexpr const Uint32 SRVDimBits = 4; - static constexpr const Uint32 SamplerOrTexSRVIdBits = 24; + static constexpr const Uint32 ShaderInputTypeBits = 4; + static constexpr const Uint32 SRVDimBits = 4; + static constexpr const Uint32 SamplerOrTexSRVIdBits = 24; static_assert(ShaderInputTypeBits + SRVDimBits + SamplerOrTexSRVIdBits == 32, "Attributes are better be packed into 32 bits"); static_assert(D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER < (1 << ShaderInputTypeBits), "Not enough bits to represent D3D_SHADER_INPUT_TYPE"); static_assert(D3D_SRV_DIMENSION_BUFFEREX < (1 << SRVDimBits), "Not enough bits to represent D3D_SRV_DIMENSION"); - // We need to use Uint32 instead of the actual type for reliability and correctness. - // There originally was a problem when the type of InputType was D3D_SHADER_INPUT_TYPE: - // the value of D3D_SIT_UAV_RWBYTEADDRESS (8) was interpreted as -8 (as the underlying enum type - // is signed) causing errors - const Uint32 InputType : ShaderInputTypeBits; // Max value: D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER == 11 - const Uint32 SRVDimension : SRVDimBits; // Max value: D3D_SRV_DIMENSION_BUFFEREX == 11 - Uint32 SamplerOrTexSRVId : SamplerOrTexSRVIdBits; // Max value: 1048575 + // We need to use Uint32 instead of the actual type for reliability and correctness. + // There originally was a problem when the type of InputType was D3D_SHADER_INPUT_TYPE: + // the value of D3D_SIT_UAV_RWBYTEADDRESS (8) was interpreted as -8 (as the underlying enum type + // is signed) causing errors +/*12.0*/ const Uint32 InputType : ShaderInputTypeBits; // Max value: D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER == 11 +/*12.4*/ const Uint32 SRVDimension : SRVDimBits; // Max value: D3D_SRV_DIMENSION_BUFFEREX == 11 +/*13.0*/ Uint32 SamplerOrTexSRVId : SamplerOrTexSRVIdBits; // Max value: 2^24-1 +/*16 */ // End of structure public: static constexpr const Uint32 InvalidSamplerId = (1 << SamplerOrTexSRVIdBits) - 1; @@ -224,10 +226,6 @@ public: SamplerOrTexSRVId == Attribs.SamplerOrTexSRVId; } - SHADER_RESOURCE_VARIABLE_TYPE FindVariableType(SHADER_TYPE ShaderType, - const PipelineResourceLayoutDesc& ResourceLayoutDesc, - const char* CombinedSamplerSuffix)const; - size_t GetHash()const { return ComputeHash(BindPoint, BindCount, InputType, SRVDimension, SamplerOrTexSRVId); @@ -240,33 +238,37 @@ static_assert(sizeof(D3DShaderResourceAttribs) == sizeof(void*) + sizeof(Uint32) class ShaderResources { public: - ShaderResources(SHADER_TYPE ShaderType); + ShaderResources(SHADER_TYPE ShaderType)noexcept : + m_ShaderType(ShaderType) + { + } - ShaderResources (const ShaderResources&) = delete; - ShaderResources (ShaderResources&&) = delete; - ShaderResources& operator = (const ShaderResources&) = delete; - ShaderResources& operator = (ShaderResources&&) = delete; + ShaderResources (const ShaderResources&) = delete; + ShaderResources ( ShaderResources&&) = delete; + ShaderResources& operator = (const ShaderResources&) = delete; + ShaderResources& operator = ( ShaderResources&&) = delete; ~ShaderResources(); - Uint32 GetNumCBs() const noexcept{ return (m_TexSRVOffset - 0); } - Uint32 GetNumTexSRV() const noexcept{ return (m_TexUAVOffset - m_TexSRVOffset); } - Uint32 GetNumTexUAV() const noexcept{ return (m_BufSRVOffset - m_TexUAVOffset); } - Uint32 GetNumBufSRV() const noexcept{ return (m_BufUAVOffset - m_BufSRVOffset); } - Uint32 GetNumBufUAV() const noexcept{ return (m_SamplersOffset - m_BufUAVOffset); } - Uint32 GetNumSamplers() const noexcept{ return (m_TotalResources - m_SamplersOffset); } - Uint32 GetTotalResources()const noexcept{ return m_TotalResources; } - - const D3DShaderResourceAttribs& GetCB (Uint32 n)const noexcept{ return GetResAttribs(n, GetNumCBs(), 0); } - const D3DShaderResourceAttribs& GetTexSRV (Uint32 n)const noexcept{ return GetResAttribs(n, GetNumTexSRV(), m_TexSRVOffset); } - const D3DShaderResourceAttribs& GetTexUAV (Uint32 n)const noexcept{ return GetResAttribs(n, GetNumTexUAV(), m_TexUAVOffset); } - const D3DShaderResourceAttribs& GetBufSRV (Uint32 n)const noexcept{ return GetResAttribs(n, GetNumBufSRV(), m_BufSRVOffset); } - const D3DShaderResourceAttribs& GetBufUAV (Uint32 n)const noexcept{ return GetResAttribs(n, GetNumBufUAV(), m_BufUAVOffset); } - const D3DShaderResourceAttribs& GetSampler(Uint32 n)const noexcept{ return GetResAttribs(n, GetNumSamplers(), m_SamplersOffset); } + Uint32 GetNumCBs() const noexcept { return (m_TexSRVOffset - 0); } + Uint32 GetNumTexSRV() const noexcept { return (m_TexUAVOffset - m_TexSRVOffset); } + Uint32 GetNumTexUAV() const noexcept { return (m_BufSRVOffset - m_TexUAVOffset); } + Uint32 GetNumBufSRV() const noexcept { return (m_BufUAVOffset - m_BufSRVOffset); } + Uint32 GetNumBufUAV() const noexcept { return (m_SamplersOffset - m_BufUAVOffset); } + Uint32 GetNumSamplers() const noexcept { return (m_TotalResources - m_SamplersOffset); } + Uint32 GetTotalResources()const noexcept { return m_TotalResources; } + + const D3DShaderResourceAttribs& GetCB (Uint32 n)const noexcept { return GetResAttribs(n, GetNumCBs(), 0); } + const D3DShaderResourceAttribs& GetTexSRV (Uint32 n)const noexcept { return GetResAttribs(n, GetNumTexSRV(), m_TexSRVOffset); } + const D3DShaderResourceAttribs& GetTexUAV (Uint32 n)const noexcept { return GetResAttribs(n, GetNumTexUAV(), m_TexUAVOffset); } + const D3DShaderResourceAttribs& GetBufSRV (Uint32 n)const noexcept { return GetResAttribs(n, GetNumBufSRV(), m_BufSRVOffset); } + const D3DShaderResourceAttribs& GetBufUAV (Uint32 n)const noexcept { return GetResAttribs(n, GetNumBufUAV(), m_BufUAVOffset); } + const D3DShaderResourceAttribs& GetSampler(Uint32 n)const noexcept { return GetResAttribs(n, GetNumSamplers(), m_SamplersOffset); } SHADER_TYPE GetShaderType()const noexcept{return m_ShaderType;} - // Processes only resources listed in AllowedVarTypes + ShaderResourceDesc GetShaderResourceDesc(Uint32 Index)const; + template > m_MemoryBuffer; StringPool m_ResourceNames; - const char* m_SamplerSuffix = nullptr; // The suffix is put into the m_ResourceNames + const char* m_SamplerSuffix = nullptr; // The suffix and the shader name + const char* m_ShaderName = nullptr; // are put into the m_ResourceNames // Offsets in elements of D3DShaderResourceAttribs typedef Uint16 OffsetType; @@ -384,7 +395,7 @@ private: OffsetType m_SamplersOffset = 0; OffsetType m_TotalResources = 0; - SHADER_TYPE m_ShaderType = SHADER_TYPE_UNKNOWN; + const SHADER_TYPE m_ShaderType; }; @@ -403,6 +414,9 @@ void ShaderResources::Initialize(ID3DBlob* pShaderByteCode, [&](const D3DShaderResourceCounters& ResCounters, size_t ResourceNamesPoolSize) { + VERIFY_EXPR(ShaderName != nullptr); + ResourceNamesPoolSize += strlen(ShaderName)+1; + if (CombinedSamplerSuffix != nullptr) ResourceNamesPoolSize += strlen(CombinedSamplerSuffix)+1; @@ -459,6 +473,8 @@ void ShaderResources::Initialize(ID3DBlob* pShaderByteCode, NewResHandler.OnNewTexSRV(*pNewTexSRV); }); + m_ShaderName = m_ResourceNames.CopyString(ShaderName); + if (CombinedSamplerSuffix != nullptr) { m_SamplerSuffix = m_ResourceNames.CopyString(CombinedSamplerSuffix); @@ -504,4 +520,3 @@ namespace std } }; } - diff --git a/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp b/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp index 97107560..613cd96a 100644 --- a/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp +++ b/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp @@ -31,25 +31,6 @@ namespace Diligent { -SHADER_RESOURCE_VARIABLE_TYPE D3DShaderResourceAttribs::FindVariableType(SHADER_TYPE ShaderType, - const PipelineResourceLayoutDesc& ResourceLayoutDesc, - const char* CombinedSamplerSuffix)const -{ - if (GetInputType() == D3D_SIT_SAMPLER) - { - // Only use CombinedSamplerSuffix when looking for the sampler variable type - return GetShaderVariableType(ShaderType, ResourceLayoutDesc.DefaultVariableType, ResourceLayoutDesc.Variables, ResourceLayoutDesc.NumVariables, - [&](const char* VarName) - { - return StreqSuff(Name, VarName, CombinedSamplerSuffix); - }); - } - else - { - return GetShaderVariableType(ShaderType, Name, ResourceLayoutDesc); - } -} - ShaderResources::~ShaderResources() { for(Uint32 n=0; n < GetNumCBs(); ++n) @@ -85,7 +66,7 @@ void ShaderResources::AllocateMemory(IMemoryAllocator& Allocator, return Offset; }; - auto CBOffset = AdvanceOffset(ResCounters.NumCBs); CBOffset; // To suppress warning + auto CBOffset = AdvanceOffset(ResCounters.NumCBs); (void)CBOffset; // To suppress warning m_TexSRVOffset = AdvanceOffset(ResCounters.NumTexSRVs); m_TexUAVOffset = AdvanceOffset(ResCounters.NumTexUAVs); m_BufSRVOffset = AdvanceOffset(ResCounters.NumBufSRVs); @@ -111,15 +92,41 @@ void ShaderResources::AllocateMemory(IMemoryAllocator& Allocator, } } -ShaderResources::ShaderResources(SHADER_TYPE ShaderType): - m_ShaderType(ShaderType) +SHADER_RESOURCE_VARIABLE_TYPE ShaderResources::FindVariableType(const D3DShaderResourceAttribs& ResourceAttribs, + const PipelineResourceLayoutDesc& ResourceLayout)const { + if (ResourceAttribs.GetInputType() == D3D_SIT_SAMPLER) + { + // Only use CombinedSamplerSuffix when looking for the sampler variable type + return GetShaderVariableType(m_ShaderType, ResourceLayout.DefaultVariableType, ResourceLayout.Variables, ResourceLayout.NumVariables, + [&](const char* VarName) + { + return StreqSuff(ResourceAttribs.Name, VarName, m_SamplerSuffix); + }); + } + else + { + return GetShaderVariableType(m_ShaderType, ResourceAttribs.Name, ResourceLayout); + } +} + +Int32 ShaderResources::FindStaticSampler(const D3DShaderResourceAttribs& ResourceAttribs, + const PipelineResourceLayoutDesc& ResourceLayoutDesc)const +{ + VERIFY(ResourceAttribs.GetInputType() == D3D_SIT_SAMPLER, "Sampler is expected"); + + for (Uint32 s=0; s < ResourceLayoutDesc.NumStaticSamplers; ++s) + { + const auto& StSam = ResourceLayoutDesc.StaticSamplers[s]; + if ( ((StSam.ShaderStages & m_ShaderType) != 0) && StreqSuff(ResourceAttribs.Name, StSam.SamplerOrTextureName, m_SamplerSuffix) ) + return s; + } + + return -1; } D3DShaderResourceCounters ShaderResources::CountResources(const PipelineResourceLayoutDesc& ResourceLayout, - SHADER_TYPE ShaderStage, - const char* CombinedSamplerSuffix, const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes)const noexcept { @@ -129,41 +136,37 @@ D3DShaderResourceCounters ShaderResources::CountResources(const PipelineResource ProcessResources( [&](const D3DShaderResourceAttribs& CB, Uint32) { - auto VarType = CB.FindVariableType(ShaderStage, ResourceLayout, CombinedSamplerSuffix); + auto VarType = FindVariableType(CB, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) ++Counters.NumCBs; }, [&](const D3DShaderResourceAttribs& Sam, Uint32) { - auto VarType = Sam.FindVariableType(ShaderStage, ResourceLayout, CombinedSamplerSuffix); + auto VarType = FindVariableType(Sam, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) - { - // Skip static samplers - //if (!Sam.IsStaticSampler()) ++Counters.NumSamplers; - } }, [&](const D3DShaderResourceAttribs& TexSRV, Uint32) { - auto VarType = TexSRV.FindVariableType(ShaderStage, ResourceLayout, CombinedSamplerSuffix); + auto VarType = FindVariableType(TexSRV, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) ++Counters.NumTexSRVs; }, [&](const D3DShaderResourceAttribs& TexUAV, Uint32) { - auto VarType = TexUAV.FindVariableType(ShaderStage, ResourceLayout, CombinedSamplerSuffix); + auto VarType = FindVariableType(TexUAV, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) ++Counters.NumTexUAVs; }, [&](const D3DShaderResourceAttribs& BufSRV, Uint32) { - auto VarType = BufSRV.FindVariableType(ShaderStage, ResourceLayout, CombinedSamplerSuffix); + auto VarType = FindVariableType(BufSRV, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) ++Counters.NumBufSRVs; }, [&](const D3DShaderResourceAttribs& BufUAV, Uint32) { - auto VarType = BufUAV.FindVariableType(ShaderStage, ResourceLayout, CombinedSamplerSuffix); + auto VarType = FindVariableType(BufUAV, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) ++Counters.NumBufUAVs; } @@ -172,6 +175,82 @@ D3DShaderResourceCounters ShaderResources::CountResources(const PipelineResource return Counters; } +#ifdef DEVELOPMENT +void ShaderResources::DvpVerifyResourceLayout(const PipelineResourceLayoutDesc& ResourceLayout)const +{ + const auto UseCombinedTextureSamplers = IsUsingCombinedTextureSamplers(); + for (Uint32 v = 0; v < ResourceLayout.NumVariables; ++v) + { + const auto& VarDesc = ResourceLayout.Variables[v]; + if (VarDesc.ShaderStages == SHADER_TYPE_UNKNOWN) + { + LOG_WARNING_MESSAGE("No allowed shader stages are specified for ", GetShaderVariableTypeLiteralName(VarDesc.Type), " variable '", VarDesc.Name, "'."); + continue; + } + + if( (VarDesc.ShaderStages & m_ShaderType) == 0) + continue; + + bool VariableFound = false; + for (Uint32 n=0; n < m_TotalResources && !VariableFound; ++n) + { + const auto& Res = GetResAttribs(n, m_TotalResources, 0); + + // Skip samplers if combined texture samplers are used as + // in this case they are not treated as independent variables + if (UseCombinedTextureSamplers && Res.GetInputType() == D3D_SIT_SAMPLER) + continue; + + VariableFound = (strcmp(Res.Name, VarDesc.Name) == 0); + } + + if(!VariableFound) + { + LOG_WARNING_MESSAGE("Variable '", VarDesc.Name, "' is not found in shader '", m_ShaderName, '\''); + } + } + + for (Uint32 s = 0; s < ResourceLayout.NumStaticSamplers; ++s) + { + const auto& StSamDesc = ResourceLayout.StaticSamplers[s]; + if (StSamDesc.ShaderStages == SHADER_TYPE_UNKNOWN) + { + LOG_WARNING_MESSAGE("No allowed shader stages are specified for static sampler '", StSamDesc.SamplerOrTextureName, "'."); + continue; + } + + if ( (StSamDesc.ShaderStages & m_ShaderType) == 0) + continue; + + const auto* TexOrSamName = StSamDesc.SamplerOrTextureName; + + if (UseCombinedTextureSamplers) + { + bool TextureFound = false; + for(Uint32 n=0; n < GetNumTexSRV() && !TextureFound; ++n) + { + const auto& TexSRV = GetTexSRV(n); + TextureFound = (strcmp(TexSRV.Name, TexOrSamName) == 0); + } + if (!TextureFound) + { + LOG_WARNING_MESSAGE("Static sampler specifies a texture '", TexOrSamName, "' that is not found in shader '", m_ShaderName, '\''); + } + } + else + { + bool SamplerFound = false; + for(Uint32 n=0; n < GetNumSamplers() && !SamplerFound; ++n) + { + const auto& Sampler = GetSampler(n); + SamplerFound = (strcmp(Sampler.Name, TexOrSamName) == 0); + } + if (!SamplerFound) + LOG_WARNING_MESSAGE("Static sampler '", TexOrSamName, "' is not found in shader '", m_ShaderName, '\''); + } + } +} +#endif Uint32 ShaderResources::FindAssignedSamplerId(const D3DShaderResourceAttribs& TexSRV, const char* SamplerSuffix)const @@ -237,35 +316,66 @@ bool ShaderResources::IsCompatibleWith(const ShaderResources &Res)const return IsCompatible; } -size_t ShaderResources::GetHash()const +ShaderResourceDesc ShaderResources::GetShaderResourceDesc(Uint32 Index)const { - size_t hash = ComputeHash(GetNumCBs(), GetNumTexSRV(), GetNumTexUAV(), GetNumBufSRV(), GetNumBufUAV(), GetNumSamplers()); - ProcessResources( - [&](const D3DShaderResourceAttribs& CB, Uint32) - { - HashCombine(hash, CB); - }, - [&](const D3DShaderResourceAttribs& Sam, Uint32) - { - HashCombine(hash, Sam); - }, - [&](const D3DShaderResourceAttribs& TexSRV, Uint32) - { - HashCombine(hash, TexSRV); - }, - [&](const D3DShaderResourceAttribs& TexUAV, Uint32) - { - HashCombine(hash, TexUAV); - }, - [&](const D3DShaderResourceAttribs& BufSRV, Uint32) - { - HashCombine(hash, BufSRV); - }, - [&](const D3DShaderResourceAttribs& BufUAV, Uint32) + DEV_CHECK_ERR(Index < m_TotalResources, "Resource index (", Index, ") is out of range"); + ShaderResourceDesc ResourceDesc; + if (Index < m_TotalResources) + { + const auto& Res = GetResAttribs(Index, 0, m_TotalResources); + ResourceDesc.Name = Res.Name; + ResourceDesc.ArraySize = Res.BindCount; + switch(Res.GetInputType()) { - HashCombine(hash, BufUAV); + case D3D_SIT_CBUFFER: + ResourceDesc.Type = SHADER_RESOURCE_TYPE_CONSTANT_BUFFER; + break; + + case D3D_SIT_TBUFFER: + UNSUPPORTED( "TBuffers are not supported" ); + ResourceDesc.Type = SHADER_RESOURCE_TYPE_UNKNOWN; + break; + + case D3D_SIT_TEXTURE: + ResourceDesc.Type = (Res.GetSRVDimension() == D3D_SRV_DIMENSION_BUFFER ? SHADER_RESOURCE_TYPE_BUFFER_SRV : SHADER_RESOURCE_TYPE_TEXTURE_SRV); + break; + + case D3D_SIT_SAMPLER: + ResourceDesc.Type = SHADER_RESOURCE_TYPE_SAMPLER; + break; + + case D3D_SIT_UAV_RWTYPED: + ResourceDesc.Type = (Res.GetSRVDimension() == D3D_SRV_DIMENSION_BUFFER ? SHADER_RESOURCE_TYPE_BUFFER_UAV : SHADER_RESOURCE_TYPE_TEXTURE_UAV); + break; + + case D3D_SIT_STRUCTURED: + case D3D_SIT_BYTEADDRESS: + ResourceDesc.Type = SHADER_RESOURCE_TYPE_BUFFER_SRV; + break; + + case D3D_SIT_UAV_RWSTRUCTURED: + case D3D_SIT_UAV_RWBYTEADDRESS: + case D3D_SIT_UAV_APPEND_STRUCTURED: + case D3D_SIT_UAV_CONSUME_STRUCTURED: + case D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER: + ResourceDesc.Type = SHADER_RESOURCE_TYPE_BUFFER_UAV; + break; + + default: + UNEXPECTED("Unknown input type"); } - ); + } + return ResourceDesc; +} + +size_t ShaderResources::GetHash()const +{ + size_t hash = ComputeHash(GetNumCBs(), GetNumTexSRV(), GetNumTexUAV(), GetNumBufSRV(), GetNumBufUAV(), GetNumSamplers()); + for (Uint32 n=0; n < m_TotalResources; ++n) + { + const auto& Res = GetResAttribs(n, m_TotalResources, 0); + HashCombine(hash, Res); + } return hash; } -- cgit v1.2.3 From c3ce1b6cc0214c0c67ac6c75b742b92b18af30d8 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sun, 3 Mar 2019 20:50:04 -0800 Subject: Final changes to complete d3d11 backend refactor --- .../include/PipelineStateD3D11Impl.h | 5 + .../include/ShaderResourceLayoutD3D11.h | 11 +-- .../src/PipelineStateD3D11Impl.cpp | 58 +++++++++++- .../src/ShaderResourceBindingD3D11Impl.cpp | 7 +- .../src/ShaderResourceLayoutD3D11.cpp | 103 +++++++++------------ .../include/ShaderResources.h | 7 +- .../GraphicsEngineD3DBase/src/ShaderResources.cpp | 95 +++++++++++-------- 7 files changed, 172 insertions(+), 114 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h index 583190aa..2cbe0ebc 100644 --- a/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h @@ -97,8 +97,10 @@ public: return m_pStaticResourceCaches[s]; } + void SetStaticSamplers(ShaderResourceCacheD3D11& ResourceCache, Uint32 ShaderInd)const; private: + CComPtr m_pd3d11BlendState; CComPtr m_pd3d11RasterizerState; CComPtr m_pd3d11DepthStencilState; @@ -112,6 +114,9 @@ private: SRBMemoryAllocator m_SRBMemAllocator; Int8 m_ResourceLayoutIndex[6] = {-1, -1, -1, -1, -1, -1}; + + Uint16 m_StaticSamplerOffsets[MaxShadersInPipeline+1] = {}; + std::vector< std::pair< const D3DShaderResourceAttribs&, RefCntAutoPtr > > m_StaticSamplers; }; } diff --git a/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h b/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h index 6666777b..bfc39727 100644 --- a/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h +++ b/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h @@ -46,7 +46,6 @@ class ShaderResourceLayoutD3D11 { public: ShaderResourceLayoutD3D11(IObject& Owner, - IRenderDevice* pRenderDevice, std::shared_ptr pSrcResources, const PipelineResourceLayoutDesc& ResourceLayout, const SHADER_RESOURCE_VARIABLE_TYPE* VarTypes, @@ -186,10 +185,8 @@ public: { SamplerBindInfo( const D3DShaderResourceAttribs& ResourceAttribs, ShaderResourceLayoutD3D11& ParentResLayout, - SHADER_RESOURCE_VARIABLE_TYPE VariableType, - RefCntAutoPtr _pStaticSampler) : - ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs, VariableType), - pStaticSampler(std::move(_pStaticSampler)) + SHADER_RESOURCE_VARIABLE_TYPE VariableType) : + ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs, VariableType) {} // Non-virtual function @@ -203,16 +200,12 @@ public: } __forceinline bool IsBound(Uint32 ArrayIndex)const; - - RefCntAutoPtr pStaticSampler; }; // dbgResourceCache is only used for sanity check and as a remainder that the resource cache must be alive // while Layout is alive void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags, const ShaderResourceCacheD3D11& dbgResourceCache ); - void SetStaticSamplers(ShaderResourceCacheD3D11& ResourceCache)const; - #ifdef DEVELOPMENT bool dvpVerifyBindings()const; #endif diff --git a/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp index eec91b20..09754861 100644 --- a/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp @@ -118,6 +118,20 @@ PipelineStateD3D11Impl::PipelineStateD3D11Impl(IReferenceCounters* pRefCoun m_pStaticResourceCaches = reinterpret_cast(pResCacheRawMem); const auto& ResourceLayout = PipelineDesc.ResourceLayout; + +#ifdef DEVELOPMENT + { + const ShaderResources* pResources[MaxShadersInPipeline] = {}; + for (Uint32 s = 0; s < m_NumShaders; ++s) + { + auto* pShader = GetShader(s); + pResources[s] = &(*pShader->GetD3D11Resources()); + } + ShaderResources::DvpVerifyResourceLayout(ResourceLayout, pResources, m_NumShaders); + } +#endif + + decltype(m_StaticSamplers) StaticSamplers; std::array ShaderResLayoutDataSizes = {}; std::array ShaderResCacheDataSizes = {}; for (Uint32 s = 0; s < m_NumShaders; ++s) @@ -134,7 +148,6 @@ PipelineStateD3D11Impl::PipelineStateD3D11Impl(IReferenceCounters* pRefCoun ShaderResourceLayoutD3D11 { *this, - pRenderDeviceD3D11, pShader->GetD3D11Resources(), m_Desc.ResourceLayout, StaticVarTypes, @@ -144,7 +157,20 @@ PipelineStateD3D11Impl::PipelineStateD3D11Impl(IReferenceCounters* pRefCoun GetRawAllocator() }; - m_pStaticResourceLayouts[s].SetStaticSamplers(m_pStaticResourceCaches[s]); + // Initialize static samplers + for(Uint32 sam = 0; sam < ShaderResources.GetNumSamplers(); ++sam) + { + const auto& SamplerAttribs = ShaderResources.GetSampler(sam); + auto SrcStaticSamplerInd = ShaderResources.FindStaticSampler(SamplerAttribs, ResourceLayout); + if (SrcStaticSamplerInd >= 0) + { + const auto& SrcStaticSamplerInfo = ResourceLayout.StaticSamplers[SrcStaticSamplerInd]; + RefCntAutoPtr pStaticSampler; + pRenderDeviceD3D11->CreateSampler(SrcStaticSamplerInfo.Desc, &pStaticSampler); + StaticSamplers.emplace_back(SamplerAttribs, std::move(pStaticSampler)); + } + } + m_StaticSamplerOffsets[s + 1] = static_cast(StaticSamplers.size()); if (PipelineDesc.SRBAllocationGranularity > 1) { @@ -152,12 +178,25 @@ PipelineStateD3D11Impl::PipelineStateD3D11Impl(IReferenceCounters* pRefCoun ShaderResLayoutDataSizes[s] = ShaderResourceLayoutD3D11::GetRequiredMemorySize(ShaderResources, ResourceLayout, SRBVarTypes, _countof(SRBVarTypes)); ShaderResCacheDataSizes[s] = ShaderResourceCacheD3D11::GetRequriedMemorySize(ShaderResources); } + + auto ShaderInd = GetShaderTypeIndex(pShader->GetDesc().ShaderType); + m_ResourceLayoutIndex[ShaderInd] = static_cast(s); } if (PipelineDesc.SRBAllocationGranularity > 1) { m_SRBMemAllocator.Initialize(PipelineDesc.SRBAllocationGranularity, m_NumShaders, ShaderResLayoutDataSizes.data(), m_NumShaders, ShaderResCacheDataSizes.data()); } + + m_StaticSamplers.reserve(StaticSamplers.size()); + for(auto& Sam : StaticSamplers) + m_StaticSamplers.emplace_back(std::move(Sam)); + + for (Uint32 s = 0; s < m_NumShaders; ++s) + { + // Initialize static samplers in the static resource cache to avoid warning messages + SetStaticSamplers(m_pStaticResourceCaches[s], s); + } } @@ -317,4 +356,19 @@ IShaderResourceVariable* PipelineStateD3D11Impl::GetStaticShaderVariable(SHADER_ return m_pStaticResourceLayouts[LayoutInd].GetShaderVariable(Index); } +void PipelineStateD3D11Impl::SetStaticSamplers(ShaderResourceCacheD3D11& ResourceCache, Uint32 ShaderInd)const +{ + auto NumCachedSamplers = ResourceCache.GetSamplerCount(); + for (Uint32 s = m_StaticSamplerOffsets[ShaderInd]; s < m_StaticSamplerOffsets[ShaderInd+1]; ++s) + { + auto& SamplerInfo = m_StaticSamplers[s]; + const auto& SamAttribs = SamplerInfo.first; + auto* pSamplerD3D11Impl = SamplerInfo.second.RawPtr(); + // Limiting EndBindPoint is required when initializing static samplers in a Shader's static cache + auto EndBindPoint = std::min( static_cast(SamAttribs.BindPoint) + SamAttribs.BindCount, NumCachedSamplers); + for (Uint32 BindPoint = SamAttribs.BindPoint; BindPoint < EndBindPoint; ++BindPoint ) + ResourceCache.SetSampler(BindPoint, pSamplerD3D11Impl); + } +} + } diff --git a/Graphics/GraphicsEngineD3D11/src/ShaderResourceBindingD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/ShaderResourceBindingD3D11Impl.cpp index 0091cc54..a99da5de 100644 --- a/Graphics/GraphicsEngineD3D11/src/ShaderResourceBindingD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/ShaderResourceBindingD3D11Impl.cpp @@ -45,7 +45,6 @@ ShaderResourceBindingD3D11Impl::ShaderResourceBindingD3D11Impl( IReferenceCounte auto* pResCacheRawMem = ALLOCATE(GetRawAllocator(), "Raw memory for ShaderResourceCacheD3D11", m_NumActiveShaders * sizeof(ShaderResourceCacheD3D11)); m_pBoundResourceCaches = reinterpret_cast(pResCacheRawMem); - auto* pRenderDevice = pPSO->GetDevice(); const auto& PSODesc = pPSO->GetDesc(); // Reserve memory for resource layouts @@ -71,7 +70,6 @@ ShaderResourceBindingD3D11Impl::ShaderResourceBindingD3D11Impl( IReferenceCounte ShaderResourceLayoutD3D11 { *this, - pRenderDevice, pShaderD3D11->GetD3D11Resources(), PSODesc.ResourceLayout, VarTypes, @@ -81,9 +79,6 @@ ShaderResourceBindingD3D11Impl::ShaderResourceBindingD3D11Impl( IReferenceCounte ResLayoutDataAllocator }; - m_pResourceLayouts[s].SetStaticSamplers(m_pBoundResourceCaches[s]); - pPSO->GetStaticResourceLayout(s).SetStaticSamplers(m_pBoundResourceCaches[s]); - m_ResourceLayoutIndex[ShaderInd] = s; m_ShaderTypeIndex[s] = static_cast(ShaderInd); } @@ -163,7 +158,7 @@ void ShaderResourceBindingD3D11Impl::InitializeStaticResources(const IPipelineSt VERIFY_EXPR(ResourceLayoutInd == static_cast(shader) ); #endif StaticResLayout.CopyResources(m_pBoundResourceCaches[shader]); - //StaticResLayout.SetStaticSamplers(m_pBoundResourceCaches[shader]); + pPSOD3D11->SetStaticSamplers(m_pBoundResourceCaches[shader], shader); } m_bIsStaticResourcesBound = true; diff --git a/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp b/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp index 6839e29d..12ca400a 100755 --- a/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp +++ b/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp @@ -80,7 +80,9 @@ size_t ShaderResourceLayoutD3D11::GetRequiredMemorySize(const ShaderResourcesD3D const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes) { - auto ResCounters = SrcResources.CountResources(ResourceLayout, AllowedVarTypes, NumAllowedTypes); + // Skip static samplers as they are initialized directly in the resource cache by the PSO + constexpr bool CountStaticSamplers = false; + auto ResCounters = SrcResources.CountResources(ResourceLayout, AllowedVarTypes, NumAllowedTypes, CountStaticSamplers); auto MemSize = ResCounters.NumCBs * sizeof(ConstBuffBindInfo) + ResCounters.NumTexSRVs * sizeof(TexSRVBindInfo) + ResCounters.NumTexUAVs * sizeof(TexUAVBindInfo) + @@ -92,7 +94,6 @@ size_t ShaderResourceLayoutD3D11::GetRequiredMemorySize(const ShaderResourcesD3D ShaderResourceLayoutD3D11::ShaderResourceLayoutD3D11(IObject& Owner, - IRenderDevice* pRenderDevice, std::shared_ptr pSrcResources, const PipelineResourceLayoutDesc& ResourceLayout, const SHADER_RESOURCE_VARIABLE_TYPE* VarTypes, @@ -109,7 +110,9 @@ ShaderResourceLayoutD3D11::ShaderResourceLayoutD3D11(IObject& const auto AllowedTypeBits = GetAllowedTypeBits(VarTypes, NumVarTypes); // Count total number of resources of allowed types - auto ResCounters = m_pResources->CountResources(ResourceLayout, VarTypes, NumVarTypes); + // Skip static samplers as they are initialized directly in the resource cache by the PSO + constexpr bool CountStaticSamplers = false; + auto ResCounters = m_pResources->CountResources(ResourceLayout, VarTypes, NumVarTypes, CountStaticSamplers); // Initialize offsets size_t CurrentOffset = 0; @@ -175,14 +178,13 @@ ShaderResourceLayoutD3D11::ShaderResourceLayoutD3D11(IObject& if (IsAllowedType(VarType, AllowedTypeBits)) { auto StaticSamplerInd = m_pResources->FindStaticSampler(Sampler, ResourceLayout); - RefCntAutoPtr pStaticSampler; if (StaticSamplerInd >= 0) { - const auto& StaticSamplerDesc = ResourceLayout.StaticSamplers[StaticSamplerInd]; - pRenderDevice->CreateSampler(StaticSamplerDesc.Desc, &pStaticSampler); + // Skip static samplers as they are initialized directly in the resource cache by the PSO + return; } // Initialize current sampler in place, increment sampler counter - new (&GetResource(sam++)) SamplerBindInfo(Sampler, *this, VarType, std::move(pStaticSampler)); + new (&GetResource(sam++)) SamplerBindInfo(Sampler, *this, VarType); NumSamplerSlots = std::max(NumSamplerSlots, Uint32{Sampler.BindPoint} + Uint32{Sampler.BindCount}); } }, @@ -207,21 +209,33 @@ ShaderResourceLayoutD3D11::ShaderResourceLayoutD3D11(IObject& ") of the sampler '", AssignedSamplerAttribs.Name, "' that is assigned to it"); bool SamplerFound = false; - for (AssignedSamplerIndex = 0; AssignedSamplerIndex < NumSamplers && !SamplerFound; ++AssignedSamplerIndex) + for (AssignedSamplerIndex = 0; AssignedSamplerIndex < NumSamplers; ++AssignedSamplerIndex) { const auto& Sampler = GetResource(AssignedSamplerIndex); SamplerFound = strcmp(Sampler.m_Attribs.Name, AssignedSamplerAttribs.Name) == 0; if (SamplerFound) + break; // Otherwise AssignedSamplerIndex will be incremented + } + + if (!SamplerFound) + { + AssignedSamplerIndex = TexSRVBindInfo::InvalidSamplerIndex; +#ifdef _DEBUG + if (m_pResources->FindStaticSampler(AssignedSamplerAttribs, ResourceLayout) < 0) { - if (Sampler.pStaticSampler) - { - // Do not assign static samplers to texture SRV - AssignedSamplerIndex = TexSRVBindInfo::InvalidSamplerIndex; - break; - } + LOG_ERROR("Unable to find non-static sampler assigned to texture SRV '", TexSRV.Name, "'. This seems to be a bug."); + } +#endif + } + else + { +#ifdef _DEBUG + if (m_pResources->FindStaticSampler(AssignedSamplerAttribs, ResourceLayout) >= 0) + { + LOG_ERROR("Static sampler '", AssignedSamplerAttribs.Name, "' is assigned to texture SRV '", TexSRV.Name, "'. This seems to be a bug."); } +#endif } - VERIFY(SamplerFound, "Unable to find sampler assigned to texture SRV '", TexSRV.Name, "'"); } // Initialize tex SRV in place, increment counter of tex SRVs @@ -318,7 +332,7 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache HandleConstResources( [&](const ConstBuffBindInfo& cb) { - for(auto CBSlot = cb.m_Attribs.BindPoint; CBSlot < cb.m_Attribs.BindPoint+cb.m_Attribs.BindCount; ++CBSlot) + for (auto CBSlot = cb.m_Attribs.BindPoint; CBSlot < cb.m_Attribs.BindPoint+cb.m_Attribs.BindCount; ++CBSlot) { VERIFY_EXPR(CBSlot < m_ResourceCache.GetCBCount() && CBSlot < DstCache.GetCBCount()); DstCBs [CBSlot] = CachedCBs[CBSlot]; @@ -328,7 +342,7 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache [&](const TexSRVBindInfo& ts) { - for(auto SRVSlot = ts.m_Attribs.BindPoint; SRVSlot < ts.m_Attribs.BindPoint + ts.m_Attribs.BindCount; ++SRVSlot) + for (auto SRVSlot = ts.m_Attribs.BindPoint; SRVSlot < ts.m_Attribs.BindPoint + ts.m_Attribs.BindCount; ++SRVSlot) { VERIFY_EXPR(SRVSlot < m_ResourceCache.GetSRVCount() && SRVSlot < DstCache.GetSRVCount()); DstSRVResources[SRVSlot] = CachedSRVResources[SRVSlot]; @@ -338,7 +352,7 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache [&](const TexUAVBindInfo& uav) { - for(auto UAVSlot = uav.m_Attribs.BindPoint; UAVSlot < uav.m_Attribs.BindPoint + uav.m_Attribs.BindCount; ++UAVSlot) + for (auto UAVSlot = uav.m_Attribs.BindPoint; UAVSlot < uav.m_Attribs.BindPoint + uav.m_Attribs.BindCount; ++UAVSlot) { VERIFY_EXPR(UAVSlot < m_ResourceCache.GetUAVCount() && UAVSlot < DstCache.GetUAVCount()); DstUAVResources[UAVSlot] = CachedUAVResources[UAVSlot]; @@ -348,7 +362,7 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache [&](const BuffSRVBindInfo& srv) { - for(auto SRVSlot = srv.m_Attribs.BindPoint; SRVSlot < srv.m_Attribs.BindPoint + srv.m_Attribs.BindCount; ++SRVSlot) + for (auto SRVSlot = srv.m_Attribs.BindPoint; SRVSlot < srv.m_Attribs.BindPoint + srv.m_Attribs.BindCount; ++SRVSlot) { VERIFY_EXPR(SRVSlot < m_ResourceCache.GetSRVCount() && SRVSlot < DstCache.GetSRVCount()); DstSRVResources[SRVSlot] = CachedSRVResources[SRVSlot]; @@ -358,7 +372,7 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache [&](const BuffUAVBindInfo& uav) { - for(auto UAVSlot = uav.m_Attribs.BindPoint; UAVSlot < uav.m_Attribs.BindPoint + uav.m_Attribs.BindCount; ++UAVSlot) + for (auto UAVSlot = uav.m_Attribs.BindPoint; UAVSlot < uav.m_Attribs.BindPoint + uav.m_Attribs.BindCount; ++UAVSlot) { VERIFY_EXPR(UAVSlot < m_ResourceCache.GetUAVCount() && UAVSlot < DstCache.GetUAVCount()); DstUAVResources[UAVSlot] = CachedUAVResources[UAVSlot]; @@ -368,8 +382,8 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache [&](const SamplerBindInfo& sam) { - VERIFY(!sam.pStaticSampler, "Variables are not created for static samplers"); - for(auto SamSlot = sam.m_Attribs.BindPoint; SamSlot < sam.m_Attribs.BindPoint + sam.m_Attribs.BindCount; ++SamSlot) + //VERIFY(!sam.IsStaticSampler, "Variables are not created for static samplers"); + for (auto SamSlot = sam.m_Attribs.BindPoint; SamSlot < sam.m_Attribs.BindPoint + sam.m_Attribs.BindCount; ++SamSlot) { VERIFY_EXPR(SamSlot < m_ResourceCache.GetSamplerCount() && SamSlot < DstCache.GetSamplerCount()); DstSamplers [SamSlot] = CachedSamplers[SamSlot]; @@ -379,24 +393,6 @@ void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11& DstCache ); } -void ShaderResourceLayoutD3D11::SetStaticSamplers(ShaderResourceCacheD3D11& ResourceCache)const -{ - auto NumCachedSamplers = ResourceCache.GetSamplerCount(); - for (Uint32 s = 0; s < GetNumResources(); ++s) - { - auto& Sampler = GetConstResource(s); - if (Sampler.pStaticSampler) - { - const auto& SamAttribs = Sampler.m_Attribs; - auto* pSamplerD3D11Impl = const_cast(Sampler.pStaticSampler.RawPtr()); - // Limiting EndBindPoint is required when initializing static samplers in a Shader's static cache - auto EndBindPoint = std::min( static_cast(SamAttribs.BindPoint) + SamAttribs.BindCount, NumCachedSamplers); - for (Uint32 BindPoint = SamAttribs.BindPoint; BindPoint < EndBindPoint; ++BindPoint ) - ResourceCache.SetSampler(BindPoint, pSamplerD3D11Impl); - } - } -} - #define LOG_RESOURCE_BINDING_ERROR(ResType, pResource, Attribs, ArrayInd, ShaderName, ...)\ do{ \ const auto* ResName = pResource->GetDesc().Name; \ @@ -507,7 +503,7 @@ void ShaderResourceLayoutD3D11::TexSRVBindInfo::BindResource(IDeviceObject* pVie if (ValidSamplerAssigned()) { auto& Sampler = m_ParentResLayout.GetResource(SamplerIndex); - VERIFY(!Sampler.pStaticSampler, "Static samplers are not assigned to texture SRVs as they are initialized directly in the shader resource cache"); + //VERIFY(!Sampler.IsStaticSampler, "Static samplers are not assigned to texture SRVs as they are initialized directly in the shader resource cache"); VERIFY_EXPR(Sampler.m_Attribs.BindCount == m_Attribs.BindCount || Sampler.m_Attribs.BindCount == 1); auto SamplerBindPoint = Sampler.m_Attribs.BindPoint + (Sampler.m_Attribs.BindCount != 1 ? ArrayIndex : 0); @@ -547,7 +543,7 @@ void ShaderResourceLayoutD3D11::SamplerBindInfo::BindResource(IDeviceObject* pSa { DEV_CHECK_ERR(ArrayIndex < m_Attribs.BindCount, "Array index (", ArrayIndex, ") is out of range for variable '", m_Attribs.Name, "'. Max allowed index: ", m_Attribs.BindCount); auto& ResourceCache = m_ParentResLayout.m_ResourceCache; - VERIFY(!pStaticSampler, "Cannot bind sampler to a static sampler"); + //VERIFY(!IsStaticSampler, "Cannot bind sampler to a static sampler"); // We cannot use ValidatedCast<> here as the resource retrieved from the // resource mapping can be of wrong type @@ -807,33 +803,26 @@ IShaderResourceVariable* ShaderResourceLayoutD3D11::GetResourceByName( const Cha IShaderResourceVariable* ShaderResourceLayoutD3D11::GetShaderVariable(const Char* Name) { - if(auto* pCB = GetResourceByName(Name)) + if (auto* pCB = GetResourceByName(Name)) return pCB; - if(auto* pTexSRV = GetResourceByName(Name)) + if (auto* pTexSRV = GetResourceByName(Name)) return pTexSRV; - if(auto* pTexUAV = GetResourceByName(Name)) + if (auto* pTexUAV = GetResourceByName(Name)) return pTexUAV; - if(auto* pBuffSRV = GetResourceByName(Name)) + if (auto* pBuffSRV = GetResourceByName(Name)) return pBuffSRV; - if(auto* pBuffUAV = GetResourceByName(Name)) + if (auto* pBuffUAV = GetResourceByName(Name)) return pBuffUAV; if (!m_pResources->IsUsingCombinedTextureSamplers()) { - auto NumSamplers = GetNumResources(); - for (Uint32 s = 0; s < NumSamplers; ++s) - { - auto& Sampler = GetResource(s); - if (strcmp(Sampler.m_Attribs.Name, Name) == 0) - { - // Do not return static samplers - return Sampler.pStaticSampler ? nullptr : &Sampler; - } - } + // Static samplers are never created in the resource layout + if (auto* pSampler = GetResourceByName(Name)) + return pSampler; } return nullptr; diff --git a/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h b/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h index 4c38c4f5..7bfd2cfd 100644 --- a/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h +++ b/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h @@ -334,9 +334,12 @@ public: D3DShaderResourceCounters CountResources(const PipelineResourceLayoutDesc& ResourceLayout, const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes)const noexcept; + Uint32 NumAllowedTypes, + bool CountStaticSamplers)const noexcept; #ifdef DEVELOPMENT - void DvpVerifyResourceLayout(const PipelineResourceLayoutDesc& ResourceLayout)const; + static void DvpVerifyResourceLayout(const PipelineResourceLayoutDesc& ResourceLayout, + const ShaderResources* const pShaderResources[], + Uint32 NumShaders); #endif protected: diff --git a/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp b/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp index 613cd96a..a3efe9f3 100644 --- a/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp +++ b/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp @@ -128,7 +128,8 @@ Int32 ShaderResources::FindStaticSampler(const D3DShaderResourceAttribs& Resou D3DShaderResourceCounters ShaderResources::CountResources(const PipelineResourceLayoutDesc& ResourceLayout, const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes)const noexcept + Uint32 NumAllowedTypes, + bool CountStaticSamplers)const noexcept { auto AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); @@ -144,7 +145,14 @@ D3DShaderResourceCounters ShaderResources::CountResources(const PipelineResource { auto VarType = FindVariableType(Sam, ResourceLayout); if (IsAllowedType(VarType, AllowedTypeBits)) - ++Counters.NumSamplers; + { + if (!CountStaticSamplers) + { + if (FindStaticSampler(Sam, ResourceLayout) >= 0) + return; // Skip static sampler if requested + } + ++Counters.NumSamplers; + } }, [&](const D3DShaderResourceAttribs& TexSRV, Uint32) { @@ -176,9 +184,10 @@ D3DShaderResourceCounters ShaderResources::CountResources(const PipelineResource } #ifdef DEVELOPMENT -void ShaderResources::DvpVerifyResourceLayout(const PipelineResourceLayoutDesc& ResourceLayout)const +void ShaderResources::DvpVerifyResourceLayout(const PipelineResourceLayoutDesc& ResourceLayout, + const ShaderResources* const pShaderResources[], + Uint32 NumShaders) { - const auto UseCombinedTextureSamplers = IsUsingCombinedTextureSamplers(); for (Uint32 v = 0; v < ResourceLayout.NumVariables; ++v) { const auto& VarDesc = ResourceLayout.Variables[v]; @@ -188,65 +197,75 @@ void ShaderResources::DvpVerifyResourceLayout(const PipelineResourceLayoutDesc& continue; } - if( (VarDesc.ShaderStages & m_ShaderType) == 0) - continue; - bool VariableFound = false; - for (Uint32 n=0; n < m_TotalResources && !VariableFound; ++n) + for (Uint32 s = 0; s < NumShaders && !VariableFound; ++s) { - const auto& Res = GetResAttribs(n, m_TotalResources, 0); - - // Skip samplers if combined texture samplers are used as - // in this case they are not treated as independent variables - if (UseCombinedTextureSamplers && Res.GetInputType() == D3D_SIT_SAMPLER) + const auto& Resources = *pShaderResources[s]; + if( (VarDesc.ShaderStages & Resources.GetShaderType()) == 0) continue; + + const auto UseCombinedTextureSamplers = Resources.IsUsingCombinedTextureSamplers(); + for (Uint32 n=0; n < Resources.m_TotalResources && !VariableFound; ++n) + { + const auto& Res = Resources.GetResAttribs(n, Resources.m_TotalResources, 0); - VariableFound = (strcmp(Res.Name, VarDesc.Name) == 0); + // Skip samplers if combined texture samplers are used as + // in this case they are not treated as independent variables + if (UseCombinedTextureSamplers && Res.GetInputType() == D3D_SIT_SAMPLER) + continue; + + VariableFound = (strcmp(Res.Name, VarDesc.Name) == 0); + } } - if(!VariableFound) + if (!VariableFound) { - LOG_WARNING_MESSAGE("Variable '", VarDesc.Name, "' is not found in shader '", m_ShaderName, '\''); + LOG_WARNING_MESSAGE("Variable '", VarDesc.Name, "' is not found in of the designated shader stages " + "(", GetShaderStagesString(VarDesc.ShaderStages), ")"); } } - for (Uint32 s = 0; s < ResourceLayout.NumStaticSamplers; ++s) + for (Uint32 sam = 0; sam < ResourceLayout.NumStaticSamplers; ++sam) { - const auto& StSamDesc = ResourceLayout.StaticSamplers[s]; + const auto& StSamDesc = ResourceLayout.StaticSamplers[sam]; if (StSamDesc.ShaderStages == SHADER_TYPE_UNKNOWN) { LOG_WARNING_MESSAGE("No allowed shader stages are specified for static sampler '", StSamDesc.SamplerOrTextureName, "'."); continue; } - if ( (StSamDesc.ShaderStages & m_ShaderType) == 0) - continue; - const auto* TexOrSamName = StSamDesc.SamplerOrTextureName; - - if (UseCombinedTextureSamplers) + + bool TextureOrSamplerFound = false; + for (Uint32 s = 0; s < NumShaders && !TextureOrSamplerFound; ++s) { - bool TextureFound = false; - for(Uint32 n=0; n < GetNumTexSRV() && !TextureFound; ++n) + const auto& Resources = *pShaderResources[s]; + if ( (StSamDesc.ShaderStages & Resources.GetShaderType()) == 0) + continue; + + const auto UseCombinedTextureSamplers = Resources.IsUsingCombinedTextureSamplers(); + if (UseCombinedTextureSamplers) { - const auto& TexSRV = GetTexSRV(n); - TextureFound = (strcmp(TexSRV.Name, TexOrSamName) == 0); + for(Uint32 n=0; n < Resources.GetNumTexSRV() && !TextureOrSamplerFound; ++n) + { + const auto& TexSRV = Resources.GetTexSRV(n); + TextureOrSamplerFound = (strcmp(TexSRV.Name, TexOrSamName) == 0); + } } - if (!TextureFound) + else { - LOG_WARNING_MESSAGE("Static sampler specifies a texture '", TexOrSamName, "' that is not found in shader '", m_ShaderName, '\''); + for(Uint32 n=0; n < Resources.GetNumSamplers() && !TextureOrSamplerFound; ++n) + { + const auto& Sampler = Resources.GetSampler(n); + TextureOrSamplerFound = (strcmp(Sampler.Name, TexOrSamName) == 0); + } } } - else + + if (!TextureOrSamplerFound) { - bool SamplerFound = false; - for(Uint32 n=0; n < GetNumSamplers() && !SamplerFound; ++n) - { - const auto& Sampler = GetSampler(n); - SamplerFound = (strcmp(Sampler.Name, TexOrSamName) == 0); - } - if (!SamplerFound) - LOG_WARNING_MESSAGE("Static sampler '", TexOrSamName, "' is not found in shader '", m_ShaderName, '\''); + LOG_WARNING_MESSAGE("Static sampler '", TexOrSamName, "' is not found in any of the designated shader stages " + "(", GetShaderStagesString(StSamDesc.ShaderStages), ")"); } } } -- cgit v1.2.3 From 05aa92315c10fe7e3a2bb84d69026933e1831f95 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sun, 3 Mar 2019 20:59:33 -0800 Subject: Updated static sampler array in PipelineStateD3D11Impl to use raw allocator --- .../GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h | 12 +++++++++++- Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp | 9 +++++---- 2 files changed, 16 insertions(+), 5 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h index 2cbe0ebc..71830432 100644 --- a/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h @@ -116,7 +116,17 @@ private: Int8 m_ResourceLayoutIndex[6] = {-1, -1, -1, -1, -1, -1}; Uint16 m_StaticSamplerOffsets[MaxShadersInPipeline+1] = {}; - std::vector< std::pair< const D3DShaderResourceAttribs&, RefCntAutoPtr > > m_StaticSamplers; + struct StaticSamplerInfo + { + const D3DShaderResourceAttribs& Attribs; + RefCntAutoPtr pSampler; + StaticSamplerInfo(const D3DShaderResourceAttribs& _Attribs, + RefCntAutoPtr _pSampler) : + Attribs (_Attribs), + pSampler (std::move(_pSampler)) + {} + }; + std::vector< StaticSamplerInfo, STDAllocatorRawMem > m_StaticSamplers; }; } diff --git a/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp index 09754861..84bc1ef5 100644 --- a/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp @@ -36,7 +36,8 @@ PipelineStateD3D11Impl::PipelineStateD3D11Impl(IReferenceCounters* pRefCoun RenderDeviceD3D11Impl* pRenderDeviceD3D11, const PipelineStateDesc& PipelineDesc) : TPipelineStateBase(pRefCounters, pRenderDeviceD3D11, PipelineDesc), - m_SRBMemAllocator(GetRawAllocator()) + m_SRBMemAllocator(GetRawAllocator()), + m_StaticSamplers(STD_ALLOCATOR_RAW_MEM(StaticSamplerInfo, GetRawAllocator(), "Allocator for vector")) { if (PipelineDesc.IsComputePipeline) { @@ -131,7 +132,7 @@ PipelineStateD3D11Impl::PipelineStateD3D11Impl(IReferenceCounters* pRefCoun } #endif - decltype(m_StaticSamplers) StaticSamplers; + decltype(m_StaticSamplers) StaticSamplers(STD_ALLOCATOR_RAW_MEM(StaticSamplerInfo, GetRawAllocator(), "Allocator for vector")); std::array ShaderResLayoutDataSizes = {}; std::array ShaderResCacheDataSizes = {}; for (Uint32 s = 0; s < m_NumShaders; ++s) @@ -362,8 +363,8 @@ void PipelineStateD3D11Impl::SetStaticSamplers(ShaderResourceCacheD3D11& Resourc for (Uint32 s = m_StaticSamplerOffsets[ShaderInd]; s < m_StaticSamplerOffsets[ShaderInd+1]; ++s) { auto& SamplerInfo = m_StaticSamplers[s]; - const auto& SamAttribs = SamplerInfo.first; - auto* pSamplerD3D11Impl = SamplerInfo.second.RawPtr(); + const auto& SamAttribs = SamplerInfo.Attribs; + auto* pSamplerD3D11Impl = SamplerInfo.pSampler.RawPtr(); // Limiting EndBindPoint is required when initializing static samplers in a Shader's static cache auto EndBindPoint = std::min( static_cast(SamAttribs.BindPoint) + SamAttribs.BindCount, NumCachedSamplers); for (Uint32 BindPoint = SamAttribs.BindPoint; BindPoint < EndBindPoint; ++BindPoint ) -- cgit v1.2.3 From 5b22be322244bc4368bffd4c34ba2516d638282e Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sun, 3 Mar 2019 21:56:38 -0800 Subject: Cleaned up QueryInterface declaration in D3D12 backend --- Graphics/GraphicsEngineD3D12/include/BufferD3D12Impl.h | 2 +- Graphics/GraphicsEngineD3D12/include/BufferViewD3D12Impl.h | 2 +- Graphics/GraphicsEngineD3D12/include/CommandQueueD3D12Impl.h | 2 +- Graphics/GraphicsEngineD3D12/include/DeviceContextD3D12Impl.h | 2 +- Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h | 2 +- Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.h | 4 ++-- Graphics/GraphicsEngineD3D12/include/SamplerD3D12Impl.h | 2 +- Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h | 2 +- Graphics/GraphicsEngineD3D12/include/SwapChainD3D12Impl.h | 2 +- Graphics/GraphicsEngineD3D12/include/TextureD3D12Impl.h | 2 +- Graphics/GraphicsEngineD3D12/include/TextureViewD3D12Impl.h | 2 +- 11 files changed, 12 insertions(+), 12 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineD3D12/include/BufferD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/BufferD3D12Impl.h index 708a65ea..0bdd87ac 100644 --- a/Graphics/GraphicsEngineD3D12/include/BufferD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/BufferD3D12Impl.h @@ -58,7 +58,7 @@ public: ID3D12Resource* pd3d12Buffer); ~BufferD3D12Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; #ifdef DEVELOPMENT void DvpVerifyDynamicAllocation(class DeviceContextD3D12Impl* pCtx)const; diff --git a/Graphics/GraphicsEngineD3D12/include/BufferViewD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/BufferViewD3D12Impl.h index cf8b403c..0d375eb3 100644 --- a/Graphics/GraphicsEngineD3D12/include/BufferViewD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/BufferViewD3D12Impl.h @@ -49,7 +49,7 @@ public: DescriptorHeapAllocation&& HandleAlloc, bool bIsDefaultView); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ); + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle()override final{return m_DescriptorHandle.GetCpuHandle();} diff --git a/Graphics/GraphicsEngineD3D12/include/CommandQueueD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/CommandQueueD3D12Impl.h index 31f248bb..4089663c 100644 --- a/Graphics/GraphicsEngineD3D12/include/CommandQueueD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/CommandQueueD3D12Impl.h @@ -42,7 +42,7 @@ public: CommandQueueD3D12Impl(IReferenceCounters *pRefCounters, ID3D12CommandQueue *pd3d12NativeCmdQueue, ID3D12Fence *pd3d12Fence); ~CommandQueueD3D12Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; // Returns the fence value that will be signaled next time virtual Uint64 GetNextFenceValue()override final { return m_NextFenceValue; } diff --git a/Graphics/GraphicsEngineD3D12/include/DeviceContextD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/DeviceContextD3D12Impl.h index dfdfa760..438014e3 100644 --- a/Graphics/GraphicsEngineD3D12/include/DeviceContextD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/DeviceContextD3D12Impl.h @@ -60,7 +60,7 @@ public: Uint32 CommandQueueId); ~DeviceContextD3D12Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual void SetPipelineState(IPipelineState* pPipelineState)override final; diff --git a/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h index 43b2c12d..35cd4e7e 100644 --- a/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h @@ -47,7 +47,7 @@ public: PipelineStateD3D12Impl( IReferenceCounters *pRefCounters, RenderDeviceD3D12Impl *pDeviceD3D12, const PipelineStateDesc &PipelineDesc ); ~PipelineStateD3D12Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ); + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual ID3D12PipelineState *GetD3D12PipelineState()const override final{return m_pd3d12PSO;} diff --git a/Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.h index 7f53cb26..f9e4d3aa 100644 --- a/Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.h @@ -54,13 +54,13 @@ public: Uint32 NumDeferredContexts ); ~RenderDeviceD3D12Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual void CreatePipelineState( const PipelineStateDesc &PipelineDesc, IPipelineState **ppPipelineState )override final; virtual void CreateBuffer(const BufferDesc& BuffDesc, const BufferData* pBuffData, IBuffer **ppBuffer)override final; - virtual void CreateShader(const ShaderCreationAttribs& ShaderCreationAttribs, IShader **ppShader)override final; + virtual void CreateShader(const ShaderCreateInfo& ShaderCreateInfo, IShader **ppShader)override final; virtual void CreateTexture(const TextureDesc& TexDesc, const TextureData* pData, ITexture **ppTexture)override final; diff --git a/Graphics/GraphicsEngineD3D12/include/SamplerD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/SamplerD3D12Impl.h index c34e2417..2cc34633 100644 --- a/Graphics/GraphicsEngineD3D12/include/SamplerD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/SamplerD3D12Impl.h @@ -47,7 +47,7 @@ public: const SamplerDesc& SamplerDesc); ~SamplerD3D12Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle()override{ return m_Descriptor.GetCpuHandle(); } diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h index 4f2cdef5..aed47701 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h @@ -49,7 +49,7 @@ public: bool IsPSOInternal); ~ShaderResourceBindingD3D12Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject** ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual void BindResources(Uint32 ShaderFlags, IResourceMapping* pResMapping, Uint32 Flags)override; diff --git a/Graphics/GraphicsEngineD3D12/include/SwapChainD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/SwapChainD3D12Impl.h index 50d80511..61d8cfb8 100644 --- a/Graphics/GraphicsEngineD3D12/include/SwapChainD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/SwapChainD3D12Impl.h @@ -49,7 +49,7 @@ public: void* pNativeWndHandle); ~SwapChainD3D12Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ); + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual void Present(Uint32 SyncInterval)override final; virtual void Resize( Uint32 NewWidth, Uint32 NewHeight )override final; diff --git a/Graphics/GraphicsEngineD3D12/include/TextureD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/TextureD3D12Impl.h index b205f843..92e3333e 100644 --- a/Graphics/GraphicsEngineD3D12/include/TextureD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/TextureD3D12Impl.h @@ -60,7 +60,7 @@ public: ID3D12Resource* pTexture); ~TextureD3D12Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual ID3D12Resource* GetD3D12Texture(){ return GetD3D12Resource(); } diff --git a/Graphics/GraphicsEngineD3D12/include/TextureViewD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/TextureViewD3D12Impl.h index 5f68724d..41c17980 100644 --- a/Graphics/GraphicsEngineD3D12/include/TextureViewD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/TextureViewD3D12Impl.h @@ -49,7 +49,7 @@ public: DescriptorHeapAllocation&& HandleAlloc, bool bIsDefaultView); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle()override{return m_Descriptor.GetCpuHandle();} -- cgit v1.2.3 From 2f468cbac64474c16a87c2fd6f8c8bb06f3f7d0f Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Sun, 3 Mar 2019 22:41:15 -0800 Subject: Updated ShaderResourceLayoutD3D12 and few other objects in D3D12 backend to comply with the new API --- .../GraphicsEngineD3D12/include/RootSignature.h | 82 +++--- .../GraphicsEngineD3D12/include/ShaderD3D12Impl.h | 37 +-- .../include/ShaderResourceBindingD3D12Impl.h | 4 +- .../include/ShaderResourceLayoutD3D12.h | 87 +++--- .../include/ShaderVariableD3D12.h | 28 +- .../src/PipelineStateD3D12Impl.cpp | 8 +- Graphics/GraphicsEngineD3D12/src/RootSignature.cpp | 54 ++-- .../GraphicsEngineD3D12/src/ShaderD3D12Impl.cpp | 29 +- .../src/ShaderResourceBindingD3D12Impl.cpp | 6 +- .../src/ShaderResourceLayoutD3D12.cpp | 301 +++++++++++---------- .../src/ShaderResourcesD3D12.cpp | 2 +- .../src/ShaderVariableD3D12.cpp | 25 +- 12 files changed, 317 insertions(+), 346 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineD3D12/include/RootSignature.h b/Graphics/GraphicsEngineD3D12/include/RootSignature.h index fbf17f4d..ebe2083e 100644 --- a/Graphics/GraphicsEngineD3D12/include/RootSignature.h +++ b/Graphics/GraphicsEngineD3D12/include/RootSignature.h @@ -40,12 +40,12 @@ class RootParameter { public: - RootParameter(D3D12_ROOT_PARAMETER_TYPE ParameterType, - Uint32 RootIndex, - UINT Register, - UINT RegisterSpace, - D3D12_SHADER_VISIBILITY Visibility, - SHADER_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 : m_RootIndex (RootIndex), m_ShaderVarType(VarType) { @@ -56,13 +56,13 @@ public: m_RootParam.Descriptor.RegisterSpace = RegisterSpace; } - RootParameter(D3D12_ROOT_PARAMETER_TYPE ParameterType, - Uint32 RootIndex, - UINT Register, - UINT RegisterSpace, - UINT NumDwords, - D3D12_SHADER_VISIBILITY Visibility, - SHADER_VARIABLE_TYPE VarType)noexcept : + 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_RootIndex (RootIndex), m_ShaderVarType(VarType) { @@ -74,12 +74,12 @@ public: m_RootParam.Constants.RegisterSpace = RegisterSpace; } - RootParameter(D3D12_ROOT_PARAMETER_TYPE ParameterType, - Uint32 RootIndex, - UINT NumRanges, - D3D12_DESCRIPTOR_RANGE* pRanges, - D3D12_SHADER_VISIBILITY Visibility, - SHADER_VARIABLE_TYPE VarType)noexcept : + 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_RootIndex (RootIndex), m_ShaderVarType(VarType) { @@ -158,7 +158,7 @@ public: m_DescriptorTableSize = std::max(m_DescriptorTableSize, OffsetFromTableStart + Count); } - SHADER_VARIABLE_TYPE GetShaderVariableType()const{ return m_ShaderVarType; } + 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"); @@ -274,10 +274,10 @@ public: private: - SHADER_VARIABLE_TYPE m_ShaderVarType = static_cast(-1); - D3D12_ROOT_PARAMETER m_RootParam = {}; - Uint32 m_DescriptorTableSize = 0; - Uint32 m_RootIndex = static_cast(-1); + SHADER_RESOURCE_VARIABLE_TYPE m_ShaderVarType = static_cast(-1); + D3D12_ROOT_PARAMETER m_RootParam = {}; + Uint32 m_DescriptorTableSize = 0; + Uint32 m_RootIndex = static_cast(-1); }; @@ -330,15 +330,15 @@ public: bool IsCompute, class DeviceContextD3D12Impl* pCtx)const; - Uint32 GetTotalSrvCbvUavSlots(SHADER_VARIABLE_TYPE VarType)const + Uint32 GetTotalSrvCbvUavSlots(SHADER_RESOURCE_VARIABLE_TYPE VarType)const { return m_TotalSrvCbvUavSlots[VarType]; } - Uint32 GetTotalSamplerSlots(SHADER_VARIABLE_TYPE VarType)const + Uint32 GetTotalSamplerSlots(SHADER_RESOURCE_VARIABLE_TYPE VarType)const { return m_TotalSamplerSlots[VarType]; } - Uint32 GetTotalRootViews(SHADER_VARIABLE_TYPE VarType)const + Uint32 GetTotalRootViews(SHADER_RESOURCE_VARIABLE_TYPE VarType)const { return m_TotalRootViews[VarType]; } @@ -359,9 +359,9 @@ private: std::vector > GetCacheTableSizes()const; - std::array m_TotalSrvCbvUavSlots = {}; - std::array m_TotalSamplerSlots = {}; - std::array m_TotalRootViews = {}; + std::array m_TotalSrvCbvUavSlots = {}; + std::array m_TotalSamplerSlots = {}; + std::array m_TotalRootViews = {}; CComPtr m_pd3d12RootSignature; @@ -402,16 +402,16 @@ private: return m_pRootViews[ViewInd]; } - void AddRootView(D3D12_ROOT_PARAMETER_TYPE ParameterType, - Uint32 RootIndex, - UINT Register, - D3D12_SHADER_VISIBILITY Visibility, - SHADER_VARIABLE_TYPE VarType); + void AddRootView(D3D12_ROOT_PARAMETER_TYPE ParameterType, + Uint32 RootIndex, + UINT Register, + D3D12_SHADER_VISIBILITY Visibility, + SHADER_RESOURCE_VARIABLE_TYPE VarType); - void AddRootTable(Uint32 RootIndex, - D3D12_SHADER_VISIBILITY Visibility, - SHADER_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); @@ -446,9 +446,9 @@ private: // 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; + std::array m_SrvCbvUavRootTablesMap; // This array contains the same data for Sampler root table - std::array m_SamplerRootTablesMap; + std::array m_SamplerRootTablesMap; RootParamsManager m_RootParams; diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/ShaderD3D12Impl.h index 8f80e54b..674beafb 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderD3D12Impl.h @@ -45,49 +45,20 @@ class ShaderD3D12Impl final : public ShaderBase; - ShaderD3D12Impl(IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pRenderDeviceD3D12, - const ShaderCreationAttribs& ShaderCreationAttribs); + ShaderD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl* pRenderDeviceD3D12, + const ShaderCreateInfo& ShaderCI); ~ShaderD3D12Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override; - - virtual void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags )override final - { - m_StaticVarsMgr.BindResources(pResourceMapping, Flags); - } - - virtual IShaderVariable* GetShaderVariable(const Char* Name)override final - { - return m_StaticVarsMgr.GetVariable(Name); - } - - virtual Uint32 GetVariableCount() const override final - { - return m_StaticVarsMgr.GetVariableCount(); - } - - virtual IShaderVariable* GetShaderVariable(Uint32 Index)override final - { - return m_StaticVarsMgr.GetVariable(Index); - } + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; ID3DBlob* GetShaderByteCode(){return m_pShaderByteCode;} const std::shared_ptr& GetShaderResources()const { return m_pShaderResources; } - const ShaderResourceLayoutD3D12& GetStaticResLayout()const { return m_StaticResLayout; } - const ShaderResourceCacheD3D12& GetStaticResCache() const { return m_StaticResCache; } - -#ifdef DEVELOPMENT - bool DvpVerifyStaticResourceBindings()const; -#endif private: // ShaderResources class instance must be referenced through the shared pointer, because // it is referenced by ShaderResourceLayoutD3D12 class instances std::shared_ptr m_pShaderResources; - ShaderResourceLayoutD3D12 m_StaticResLayout; - ShaderResourceCacheD3D12 m_StaticResCache; - ShaderVariableManagerD3D12 m_StaticVarsMgr; }; } diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h index aed47701..b45514da 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h @@ -53,11 +53,11 @@ public: virtual void BindResources(Uint32 ShaderFlags, IResourceMapping* pResMapping, Uint32 Flags)override; - virtual IShaderVariable* GetVariable(SHADER_TYPE ShaderType, const char* Name)override; + virtual IShaderResourceVariable* GetVariable(SHADER_TYPE ShaderType, const char* Name)override; virtual Uint32 GetVariableCount(SHADER_TYPE ShaderType) const override final; - virtual IShaderVariable* GetVariable(SHADER_TYPE ShaderType, Uint32 Index)override final; + virtual IShaderResourceVariable* GetVariable(SHADER_TYPE ShaderType, Uint32 Index)override final; virtual void InitializeStaticResources(const IPipelineState* pPipelineState)override final; diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h b/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h index e734cf5c..2ae5c927 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h @@ -37,14 +37,14 @@ // | SRV/CBV/UAV - STATIC | SRV/CBV/UAV - MUTABLE | SRV/CBV/UAV - DYNAMIC | Samplers - STATIC | Samplers - MUTABLE | Samplers - DYNAMIC || // | | | | // -// s == NumCbvSrvUav[SHADER_VARIABLE_TYPE_STATIC] -// m == NumCbvSrvUav[SHADER_VARIABLE_TYPE_MUTABLE] -// d == NumCbvSrvUav[SHADER_VARIABLE_TYPE_DYNAMIC] +// s == NumCbvSrvUav[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] +// m == NumCbvSrvUav[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE] +// d == NumCbvSrvUav[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC] // smd = s+m+d // -// s' == NumSamplers[SHADER_VARIABLE_TYPE_STATIC] -// m' == NumSamplers[SHADER_VARIABLE_TYPE_MUTABLE] -// d' == NumSamplers[SHADER_VARIABLE_TYPE_DYNAMIC] +// s' == NumSamplers[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] +// m' == NumSamplers[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE] +// 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 @@ -86,14 +86,13 @@ // ** These resource layouts are used as reference layouts for shader resource binding objects // ** All variable types are preserved // ** Root indices and descriptor table offsets are assigned during the initialization -// * Every shader object (ShaderD3D12Impl) contains shader resource layout that facilitates management of static shader resources +// * Every pipeline state object also contains shader resource layout that facilitates management of static shader resources // ** 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 // manager (ShaderVariableManagerD3D12) for every active shader stage in the parent pipeline state that // handles mutable and dynamic resources -// * Every shader object (ShaderD3D12Impl) constains shader variable manager that handles static resources #include @@ -118,16 +117,16 @@ public: ~ShaderResourceLayoutD3D12(); - // The method is called by - // - ShaderD3D12Impl class instance to initialize static resource layout and initialize shader resource cache - // to hold static resources - // - PipelineStateD3D12Impl class instance to reference all types of resources (static, mutable, dynamic). + // The method is called to + // - 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; // no shader resource cache is provided void Initialize(ID3D12Device* pd3d12Device, + const PipelineResourceLayoutDesc& ResourceLayout, std::shared_ptr pSrcResources, IMemoryAllocator& LayoutDataAllocator, - const SHADER_VARIABLE_TYPE* VarTypes, + const SHADER_RESOURCE_VARIABLE_TYPE* const VarTypes, Uint32 NumAllowedTypes, ShaderResourceCacheD3D12* pResourceCache, class RootSignature* pRootSig); @@ -141,7 +140,8 @@ public: D3D12Resource& operator = ( D3D12Resource&&) = delete; static constexpr const Uint32 ResourceTypeBits = 3; - static constexpr const Uint32 RootIndexBits = 16 - ResourceTypeBits; + static constexpr const Uint32 VariableTypeBits = 2; + static constexpr const Uint32 RootIndexBits = 16 - ResourceTypeBits - VariableTypeBits; static constexpr const Uint32 InvalidRootIndex = (1 << RootIndexBits) - 1; static constexpr const Uint32 MaxRootIndex = InvalidRootIndex - 1; @@ -150,24 +150,29 @@ public: static constexpr const Uint32 MaxSamplerId = InvalidSamplerId-1; static constexpr const Uint32 InvalidOffset = static_cast(-1); + static_assert( SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES < (1 << VariableTypeBits), "2 bits is not enough to store SHADER_RESOURCE_VARIABLE_TYPE"); static_assert( static_cast(CachedResourceType::NumTypes) < (1 << ResourceTypeBits), "3 bits is not enough to store CachedResourceType"); - const ShaderResourceLayoutD3D12& ParentResLayout; - const D3DShaderResourceAttribs& Attribs; - const Uint32 OffsetFromTableStart; - const Uint16 ResourceType : ResourceTypeBits; // | 0 1 2 | - const Uint16 RootIndex : RootIndexBits; // | 3 4 5 ... 15 | - const Uint16 SamplerId; +/* 0 */ const ShaderResourceLayoutD3D12& ParentResLayout; +/* 8 */ const D3DShaderResourceAttribs& Attribs; +/*16 */ const Uint32 OffsetFromTableStart; +/*20.0*/ const Uint16 ResourceType : ResourceTypeBits; // | 0 1 2 | +/*20.3*/ const Uint16 VariableType : VariableTypeBits; // | 3 4 | +/*20.5*/ const Uint16 RootIndex : RootIndexBits; // | 5 6 7 ... 15 | +/*22 */ const Uint16 SamplerId; +/*24 */ // End of data D3D12Resource(const ShaderResourceLayoutD3D12& _ParentLayout, - const D3DShaderResourceAttribs& _Attribs, - CachedResourceType _ResType, + const D3DShaderResourceAttribs& _Attribs, + SHADER_RESOURCE_VARIABLE_TYPE _VariableType, + CachedResourceType _ResType, Uint32 _RootIndex, Uint32 _OffsetFromTableStart, Uint32 _SamplerId)noexcept : ParentResLayout (_ParentLayout), Attribs (_Attribs), ResourceType (static_cast(_ResType)), + VariableType (static_cast(_VariableType)), RootIndex (static_cast(_RootIndex)), SamplerId (static_cast(_SamplerId)), OffsetFromTableStart( _OffsetFromTableStart ) @@ -175,6 +180,7 @@ public: 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(_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 || GetResType() == CachedResourceType::TexSRV, "A sampler can only be assigned to a Texture SRV"); } @@ -191,6 +197,7 @@ public: bool IsValidOffset() const { return OffsetFromTableStart != InvalidOffset; } CachedResourceType GetResType() const { return static_cast( ResourceType ); } + SHADER_RESOURCE_VARIABLE_TYPE GetVariableType() const { return static_cast(VariableType); } private: void CacheCB(IDeviceObject* pBuffer, @@ -224,21 +231,21 @@ public: IObject& GetOwner(){return m_Owner;} - Uint32 GetCbvSrvUavCount(SHADER_VARIABLE_TYPE VarType)const + Uint32 GetCbvSrvUavCount(SHADER_RESOURCE_VARIABLE_TYPE VarType)const { return m_CbvSrvUavOffsets[VarType + 1] - m_CbvSrvUavOffsets[VarType]; } - Uint32 GetSamplerCount(SHADER_VARIABLE_TYPE VarType)const + Uint32 GetSamplerCount(SHADER_RESOURCE_VARIABLE_TYPE VarType)const { return m_SamplersOffsets[VarType + 1] - m_SamplersOffsets[VarType]; } - const D3D12Resource& GetSrvCbvUav(SHADER_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)); } - const D3D12Resource& GetSampler(SHADER_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)); @@ -250,20 +257,24 @@ private: 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 { VERIFY_EXPR(m_CbvSrvUavOffsets[0] == 0); - return m_CbvSrvUavOffsets[SHADER_VARIABLE_TYPE_NUM_TYPES]; + return m_CbvSrvUavOffsets[SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES]; } Uint32 GetTotalSamplerCount()const { - return m_SamplersOffsets[SHADER_VARIABLE_TYPE_NUM_TYPES] - m_SamplersOffsets[0]; + return m_SamplersOffsets[SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES] - m_SamplersOffsets[0]; } Uint32 GetTotalResourceCount()const { - return m_SamplersOffsets[SHADER_VARIABLE_TYPE_NUM_TYPES]; + return m_SamplersOffsets[SHADER_RESOURCE_VARIABLE_TYPE_NUM_TYPES]; } D3D12Resource& GetResource(Uint32 r) @@ -279,25 +290,25 @@ private: return Resource[r]; } - Uint32 GetSrvCbvUavOffset(SHADER_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] ); return Offset; } - D3D12Resource& GetSrvCbvUav(SHADER_VARIABLE_TYPE VarType, Uint32 r) + D3D12Resource& GetSrvCbvUav(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 r) { VERIFY_EXPR( r < GetCbvSrvUavCount(VarType) ); return GetResource(GetSrvCbvUavOffset(VarType,r)); } - Uint32 GetSamplerOffset(SHADER_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] ); return Offset; } - D3D12Resource& GetSampler(SHADER_VARIABLE_TYPE VarType, Uint32 s) + D3D12Resource& GetSampler(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 s) { VERIFY_EXPR( s < GetSamplerCount(VarType) ); return GetResource(GetSamplerOffset(VarType,s)); @@ -309,12 +320,12 @@ private: } void AllocateMemory(IMemoryAllocator& Allocator, - const std::array& CbvSrvUavCount, - const std::array& SamplerCount); + const std::array& CbvSrvUavCount, + const std::array& SamplerCount); std::unique_ptr > m_ResourceBuffer; - std::array m_CbvSrvUavOffsets = {}; - std::array m_SamplersOffsets = {}; + std::array m_CbvSrvUavOffsets = {}; + std::array m_SamplersOffsets = {}; CComPtr m_pd3d12Device; IObject& m_Owner; diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h b/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h index 0c1127d2..0b6d2762 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h @@ -30,7 +30,7 @@ // * ShaderVariableManagerD3D12 keeps list of variables of specific types // * Every ShaderVariableD3D12Impl references D3D12Resource from ShaderResourceLayoutD3D12 // * ShaderVariableManagerD3D12 keeps pointer to ShaderResourceCacheD3D12 -// * ShaderVariableManagerD3D12 is used by ShaderD3D12Impl to manage static resources and by +// * ShaderVariableManagerD3D12 is used by PipelineStateD3D12Impl to manage static resources and by // ShaderResourceBindingD3D12Impl to manage mutable and dynamic resources // // _____________________________ ________________________________________________________________________________ @@ -75,11 +75,11 @@ public: {} ~ShaderVariableManagerD3D12(); - void Initialize(const ShaderResourceLayoutD3D12& Layout, - IMemoryAllocator& Allocator, - const SHADER_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - ShaderResourceCacheD3D12& ResourceCache); + void Initialize(const ShaderResourceLayoutD3D12& Layout, + IMemoryAllocator& Allocator, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes, + ShaderResourceCacheD3D12& ResourceCache); void Destroy(IMemoryAllocator& Allocator); ShaderVariableD3D12Impl* GetVariable(const Char* Name); @@ -87,10 +87,10 @@ public: void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags); - static size_t GetRequiredMemorySize(const ShaderResourceLayoutD3D12& Layout, - const SHADER_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; } @@ -119,7 +119,7 @@ private: }; // sizeof(ShaderVariableD3D12Impl) == 24 (x64) -class ShaderVariableD3D12Impl final : public IShaderVariable +class ShaderVariableD3D12Impl final : public IShaderResourceVariable { public: ShaderVariableD3D12Impl(ShaderVariableManagerD3D12& ParentManager, @@ -154,16 +154,16 @@ public: return; *ppInterface = nullptr; - if (IID == IID_ShaderVariable || IID == IID_Unknown) + if (IID == IID_ShaderResourceVariable || IID == IID_Unknown) { *ppInterface = this; (*ppInterface)->AddRef(); } } - virtual SHADER_VARIABLE_TYPE GetType()const override final + virtual SHADER_RESOURCE_VARIABLE_TYPE GetType()const override final { - return m_Resource.Attribs.GetVariableType(); + return m_Resource.GetVariableType(); } virtual void Set(IDeviceObject *pObject)override final diff --git a/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp index 8d5f1ba4..82c3f587 100644 --- a/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp @@ -204,7 +204,7 @@ PipelineStateD3D12Impl :: PipelineStateD3D12Impl(IReferenceCounters* pRefCo std::array ShaderVarMgrDataSizes = {}; for (Uint32 s = 0; s < m_NumShaders; ++s) { - std::array AllowedVarTypes = { SHADER_VARIABLE_TYPE_MUTABLE, SHADER_VARIABLE_TYPE_DYNAMIC }; + 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); } @@ -324,8 +324,8 @@ ShaderResourceCacheD3D12* PipelineStateD3D12Impl::CommitAndTransitionShaderResou } - if( (m_RootSig.GetTotalSrvCbvUavSlots(SHADER_VARIABLE_TYPE_STATIC) != 0 || - m_RootSig.GetTotalRootViews(SHADER_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()."); } @@ -357,7 +357,7 @@ ShaderResourceCacheD3D12* PipelineStateD3D12Impl::CommitAndTransitionShaderResou bool PipelineStateD3D12Impl::dbgContainsShaderResources()const { - for(auto VarType = SHADER_VARIABLE_TYPE_STATIC; VarType < SHADER_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) diff --git a/Graphics/GraphicsEngineD3D12/src/RootSignature.cpp b/Graphics/GraphicsEngineD3D12/src/RootSignature.cpp index 82bf20dd..64da64c9 100644 --- a/Graphics/GraphicsEngineD3D12/src/RootSignature.cpp +++ b/Graphics/GraphicsEngineD3D12/src/RootSignature.cpp @@ -100,17 +100,17 @@ void RootSignature::RootParamsManager::AddRootView(D3D12_ROOT_PARAMETER_TYPE Par Uint32 RootIndex, UINT Register, D3D12_SHADER_VISIBILITY Visibility, - SHADER_VARIABLE_TYPE VarType) + SHADER_RESOURCE_VARIABLE_TYPE VarType) { 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); } -void RootSignature::RootParamsManager::AddRootTable(Uint32 RootIndex, - D3D12_SHADER_VISIBILITY Visibility, - SHADER_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)); @@ -304,8 +304,8 @@ void RootSignature::AllocateResourceSlot(SHADER_TYPE ShaderT else { // Use the same table for static and mutable resources. Treat both as static - auto RootTableType = (ShaderResAttribs.GetVariableType() == SHADER_VARIABLE_TYPE_DYNAMIC) ? SHADER_VARIABLE_TYPE_DYNAMIC : SHADER_VARIABLE_TYPE_STATIC; - auto TableIndKey = ShaderInd * SHADER_VARIABLE_TYPE_NUM_TYPES + RootTableType; + auto RootTableType = (ShaderResAttribs.GetVariableType() == 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; // Get the table array index (this is not the root index!) auto& RootTableArrayInd = (( RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER ) ? m_SamplerRootTablesMap : m_SrvCbvUavRootTablesMap)[ TableIndKey ]; if (RootTableArrayInd == InvalidRootTableIndex) @@ -397,17 +397,17 @@ void RootSignature::dbgVerifyRootParameters()const } VERIFY(dbgTotalSrvCbvUavSlots == - m_TotalSrvCbvUavSlots[SHADER_VARIABLE_TYPE_STATIC] + - m_TotalSrvCbvUavSlots[SHADER_VARIABLE_TYPE_MUTABLE] + - m_TotalSrvCbvUavSlots[SHADER_VARIABLE_TYPE_DYNAMIC], "Unexpected number of SRV CBV UAV resource slots"); + m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] + + m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE] + + m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC], "Unexpected number of SRV CBV UAV resource slots"); VERIFY(dbgTotalSamplerSlots == - m_TotalSamplerSlots[SHADER_VARIABLE_TYPE_STATIC] + - m_TotalSamplerSlots[SHADER_VARIABLE_TYPE_MUTABLE] + - m_TotalSamplerSlots[SHADER_VARIABLE_TYPE_DYNAMIC], "Unexpected number of sampler slots"); + m_TotalSamplerSlots[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] + + m_TotalSamplerSlots[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE] + + m_TotalSamplerSlots[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC], "Unexpected number of sampler slots"); VERIFY(dbgTotalRootViews == - m_TotalRootViews[SHADER_VARIABLE_TYPE_STATIC] + - m_TotalRootViews[SHADER_VARIABLE_TYPE_MUTABLE] + - m_TotalRootViews[SHADER_VARIABLE_TYPE_DYNAMIC], "Unexpected number of root views"); + 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"); } #endif @@ -530,7 +530,7 @@ void RootSignature::Finalize(ID3D12Device* pd3d12Device) 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_VARIABLE_TYPE_DYNAMIC] != 0 || m_TotalSamplerSlots[SHADER_VARIABLE_TYPE_DYNAMIC] != 0; + bool bHasDynamicDescriptors = m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC] != 0 || m_TotalSamplerSlots[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC] != 0; if(bHasDynamicDescriptors) { CommitDescriptorHandles = &RootSignature::CommitDescriptorHandlesInternal_SMD; @@ -581,11 +581,11 @@ void RootSignature::InitResourceCache(RenderDeviceD3D12Impl* pDeviceD3D12Impl // Allocate space in GPU-visible descriptor heap for static and mutable variables only Uint32 TotalSrvCbvUavDescriptors = - m_TotalSrvCbvUavSlots[SHADER_VARIABLE_TYPE_STATIC] + - m_TotalSrvCbvUavSlots[SHADER_VARIABLE_TYPE_MUTABLE]; + m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] + + m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE]; Uint32 TotalSamplerDescriptors = - m_TotalSamplerSlots[SHADER_VARIABLE_TYPE_STATIC] + - m_TotalSamplerSlots[SHADER_VARIABLE_TYPE_MUTABLE]; + m_TotalSamplerSlots[SHADER_RESOURCE_VARIABLE_TYPE_STATIC] + + m_TotalSamplerSlots[SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE]; DescriptorHeapAllocation CbcSrvUavHeapSpace, SamplerHeapSpace; if(TotalSrvCbvUavDescriptors) @@ -624,7 +624,7 @@ void RootSignature::InitResourceCache(RenderDeviceD3D12Impl* pDeviceD3D12Impl #endif // Space for dynamic variables is allocated at every draw call - if( RootParam.GetShaderVariableType() != SHADER_VARIABLE_TYPE_DYNAMIC ) + if( RootParam.GetShaderVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC ) { if( HeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ) { @@ -886,8 +886,8 @@ void RootSignature::CommitDescriptorHandlesInternal_SMD(RenderDeviceD3D12Impl* { auto *pd3d12Device = pRenderDeviceD3D12->GetD3D12Device(); - Uint32 NumDynamicCbvSrvUavDescriptors = m_TotalSrvCbvUavSlots[SHADER_VARIABLE_TYPE_DYNAMIC]; - Uint32 NumDynamicSamplerDescriptors = m_TotalSamplerSlots [SHADER_VARIABLE_TYPE_DYNAMIC]; + Uint32 NumDynamicCbvSrvUavDescriptors = m_TotalSrvCbvUavSlots[SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC]; + Uint32 NumDynamicSamplerDescriptors = m_TotalSamplerSlots [SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC]; VERIFY_EXPR(NumDynamicCbvSrvUavDescriptors > 0 || NumDynamicSamplerDescriptors > 0); DescriptorHeapAllocation DynamicCbvSrvUavDescriptors, DynamicSamplerDescriptors; @@ -920,7 +920,7 @@ void RootSignature::CommitDescriptorHandlesInternal_SMD(RenderDeviceD3D12Impl* [&](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_VARIABLE_TYPE_DYNAMIC; + bool IsDynamicTable = RootTable.GetShaderVariableType() == SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; if (IsDynamicTable) { if( IsResourceTable ) @@ -1008,7 +1008,7 @@ void RootSignature::CommitDescriptorHandlesInternal_SM(RenderDeviceD3D12Impl* bool IsCompute, bool ValidateStates)const { - VERIFY_EXPR(m_TotalSrvCbvUavSlots[SHADER_VARIABLE_TYPE_DYNAMIC] == 0 && m_TotalSamplerSlots[SHADER_VARIABLE_TYPE_DYNAMIC] == 0); + 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) @@ -1017,7 +1017,7 @@ void RootSignature::CommitDescriptorHandlesInternal_SM(RenderDeviceD3D12Impl* m_RootParams.ProcessRootTables( [&](Uint32 RootInd, const RootParameter& RootTable, const D3D12_ROOT_PARAMETER& D3D12Param, bool IsResourceTable, D3D12_DESCRIPTOR_HEAP_TYPE dbgHeapType ) { - VERIFY(RootTable.GetShaderVariableType() != SHADER_VARIABLE_TYPE_DYNAMIC, "Unexpected dynamic resource"); + VERIFY(RootTable.GetShaderVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC, "Unexpected dynamic resource"); D3D12_GPU_DESCRIPTOR_HANDLE RootTableGPUDescriptorHandle = IsResourceTable ? ResourceCache.GetShaderVisibleTableGPUDescriptorHandle(RootInd) : diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderD3D12Impl.cpp index bdaf41b0..ba069332 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderD3D12Impl.cpp @@ -32,40 +32,23 @@ namespace Diligent { -ShaderD3D12Impl::ShaderD3D12Impl(IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pRenderDeviceD3D12, - const ShaderCreationAttribs& ShaderCreationAttribs) : - TShaderBase(pRefCounters, pRenderDeviceD3D12, ShaderCreationAttribs.Desc), - ShaderD3DBase(ShaderCreationAttribs), - m_StaticResLayout(*this), - m_StaticResCache(ShaderResourceCacheD3D12::DbgCacheContentType::StaticShaderResources), - m_StaticVarsMgr(*this) +ShaderD3D12Impl::ShaderD3D12Impl(IReferenceCounters* pRefCounters, + RenderDeviceD3D12Impl* pRenderDeviceD3D12, + const ShaderCreateInfo& ShaderCI) : + TShaderBase(pRefCounters, pRenderDeviceD3D12, ShaderCI.Desc), + ShaderD3DBase(ShaderCI) { // Load shader resources auto& Allocator = GetRawAllocator(); auto* pRawMem = ALLOCATE(Allocator, "Allocator for ShaderResources", sizeof(ShaderResourcesD3D12)); - auto* pResources = new (pRawMem) ShaderResourcesD3D12(m_pShaderByteCode, m_Desc, ShaderCreationAttribs.UseCombinedTextureSamplers ? ShaderCreationAttribs.CombinedSamplerSuffix : nullptr); + auto* pResources = new (pRawMem) ShaderResourcesD3D12(m_pShaderByteCode, m_Desc, ShaderCI.UseCombinedTextureSamplers ? ShaderCI.CombinedSamplerSuffix : nullptr); m_pShaderResources.reset(pResources, STDDeleterRawMem(Allocator)); - - // Clone only static resources that will be set directly in the shader - // http://diligentgraphics.com/diligent-engine/architecture/d3d12/shader-resource-layout#Initializing-Special-Resource-Layout-for-Managing-Static-Shader-Resources - SHADER_VARIABLE_TYPE VarTypes[] = {SHADER_VARIABLE_TYPE_STATIC}; - m_StaticResLayout.Initialize(pRenderDeviceD3D12->GetD3D12Device(), m_pShaderResources, GetRawAllocator(), VarTypes, _countof(VarTypes), &m_StaticResCache, nullptr); - m_StaticVarsMgr.Initialize(m_StaticResLayout, GetRawAllocator(), nullptr, 0, m_StaticResCache); } ShaderD3D12Impl::~ShaderD3D12Impl() { - m_StaticVarsMgr.Destroy(GetRawAllocator()); } IMPLEMENT_QUERY_INTERFACE( ShaderD3D12Impl, IID_ShaderD3D12, TShaderBase ) -#ifdef DEVELOPMENT -bool ShaderD3D12Impl::DvpVerifyStaticResourceBindings()const -{ - return m_StaticResLayout.dvpVerifyBindings(m_StaticResCache); -} -#endif - } diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderResourceBindingD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderResourceBindingD3D12Impl.cpp index c8fbaeca..b8d46dbb 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderResourceBindingD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderResourceBindingD3D12Impl.cpp @@ -58,7 +58,7 @@ ShaderResourceBindingD3D12Impl::ShaderResourceBindingD3D12Impl(IReferenceCounter 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 - std::array AllowedVarTypes = { SHADER_VARIABLE_TYPE_MUTABLE, SHADER_VARIABLE_TYPE_DYNAMIC }; + std::array AllowedVarTypes = { SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC }; const auto& SrcLayout = pPSO->GetShaderResLayout(s); m_pShaderVarMgrs[s].Initialize(SrcLayout, VarDataAllocator, AllowedVarTypes.data(), static_cast(AllowedVarTypes.size()), m_ShaderResourceCache); @@ -96,7 +96,7 @@ void ShaderResourceBindingD3D12Impl::BindResources(Uint32 ShaderFlags, IResource } } -IShaderVariable *ShaderResourceBindingD3D12Impl::GetVariable(SHADER_TYPE ShaderType, const char *Name) +IShaderResourceVariable *ShaderResourceBindingD3D12Impl::GetVariable(SHADER_TYPE ShaderType, const char *Name) { auto ShaderInd = GetShaderTypeIndex(ShaderType); auto ResLayoutInd = m_ResourceLayoutIndex[ShaderInd]; @@ -121,7 +121,7 @@ Uint32 ShaderResourceBindingD3D12Impl::GetVariableCount(SHADER_TYPE ShaderType) return m_pShaderVarMgrs[ResLayoutInd].GetVariableCount(); } -IShaderVariable* ShaderResourceBindingD3D12Impl::GetVariable(SHADER_TYPE ShaderType, Uint32 Index) +IShaderResourceVariable* ShaderResourceBindingD3D12Impl::GetVariable(SHADER_TYPE ShaderType, Uint32 Index) { auto ShaderInd = GetShaderTypeIndex(ShaderType); auto ResLayoutInd = m_ResourceLayoutIndex[ShaderInd]; diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp index eada5310..ca133acc 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp @@ -33,6 +33,7 @@ #include "ShaderD3D12Impl.h" #include "RootSignature.h" #include "PipelineStateD3D12Impl.h" +#include "ShaderResourceVariableBase.h" namespace Diligent { @@ -78,20 +79,21 @@ D3D12_DESCRIPTOR_RANGE_TYPE GetDescriptorRangeType(CachedResourceType ResType) return ResTypeToDescrRangeTypeMap[ResType]; } -void ShaderResourceLayoutD3D12::AllocateMemory(IMemoryAllocator& Allocator, - const std::array& CbvSrvUavCount, - const std::array& SamplerCount) + +void ShaderResourceLayoutD3D12::AllocateMemory(IMemoryAllocator& Allocator, + const std::array& CbvSrvUavCount, + const std::array& SamplerCount) { m_CbvSrvUavOffsets[0] = 0; - for(SHADER_VARIABLE_TYPE VarType = SHADER_VARIABLE_TYPE_STATIC; VarType < SHADER_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_EXPR(GetCbvSrvUavCount(VarType) == CbvSrvUavCount[VarType]); } - m_SamplersOffsets[0] = m_CbvSrvUavOffsets[SHADER_VARIABLE_TYPE_NUM_TYPES]; - for(SHADER_VARIABLE_TYPE VarType = SHADER_VARIABLE_TYPE_STATIC; VarType < SHADER_VARIABLE_TYPE_NUM_TYPES; VarType = static_cast(VarType+1)) + 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)) { 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]); @@ -102,7 +104,7 @@ void ShaderResourceLayoutD3D12::AllocateMemory(IMemoryAllocator& if(MemSize == 0) return; - auto *pRawMem = ALLOCATE(Allocator, "Raw memory buffer for shader resource layout resources", MemSize); + auto* pRawMem = ALLOCATE(Allocator, "Raw memory buffer for shader resource layout resources", MemSize); m_ResourceBuffer = std::unique_ptr >(pRawMem, Allocator); } @@ -110,9 +112,10 @@ void ShaderResourceLayoutD3D12::AllocateMemory(IMemoryAllocator& // http://diligentgraphics.com/diligent-engine/architecture/d3d12/shader-resource-layout#Initializing-Shader-Resource-Layouts-and-Root-Signature-in-a-Pipeline-State-Object // http://diligentgraphics.com/diligent-engine/architecture/d3d12/shader-resource-cache#Initializing-Shader-Resource-Layouts-in-a-Pipeline-State void ShaderResourceLayoutD3D12::Initialize(ID3D12Device* pd3d12Device, + const PipelineResourceLayoutDesc& ResourceLayout, std::shared_ptr pSrcResources, IMemoryAllocator& LayoutDataAllocator, - const SHADER_VARIABLE_TYPE* AllowedVarTypes, + const SHADER_RESOURCE_VARIABLE_TYPE* const AllowedVarTypes, Uint32 NumAllowedTypes, ShaderResourceCacheD3D12* pResourceCache, RootSignature* pRootSig) @@ -122,67 +125,78 @@ void ShaderResourceLayoutD3D12::Initialize(ID3D12Device* VERIFY_EXPR( (pResourceCache != nullptr) ^ (pRootSig != nullptr) ); - Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); + const Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); - std::array CbvSrvUavCount = {}; - std::array SamplerCount = {}; + std::array CbvSrvUavCount = {}; + std::array SamplerCount = {}; // Count number of resources to allocate all needed memory m_pResources->ProcessResources( - AllowedVarTypes, NumAllowedTypes, - [&](const D3DShaderResourceAttribs& CB, Uint32) { - VERIFY_EXPR(CB.IsAllowedType(AllowedTypeBits)); - ++CbvSrvUavCount[CB.GetVariableType()]; + auto VarType = m_pResources->FindVariableType(CB, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) + ++CbvSrvUavCount[VarType]; }, [&](const D3DShaderResourceAttribs& Sam, Uint32) { - VERIFY_EXPR(Sam.IsAllowedType(AllowedTypeBits)); - if (!Sam.IsStaticSampler()) + auto VarType = m_pResources->FindVariableType(Sam, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) { - ++SamplerCount[Sam.GetVariableType()]; + auto StaticSamplerInd = m_pResources->FindStaticSampler(Sam, ResourceLayout); + // Skip static samplers + if (StaticSamplerInd < 0) + ++SamplerCount[VarType]; } }, [&](const D3DShaderResourceAttribs& TexSRV, Uint32) { - VERIFY_EXPR(TexSRV.IsAllowedType(AllowedTypeBits)); - auto VarType = TexSRV.GetVariableType(); - ++CbvSrvUavCount[VarType]; - if(TexSRV.ValidSamplerAssigned()) + auto VarType = m_pResources->FindVariableType(TexSRV, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) { - auto SamplerId = TexSRV.GetSamplerId(); - const auto& SamplerAttribs = m_pResources->GetSampler(SamplerId); - DEV_CHECK_ERR(SamplerAttribs.GetVariableType() == TexSRV.GetVariableType(), - "The type (", GetShaderVariableTypeLiteralName(TexSRV.GetVariableType()),") of texture SRV variable '", TexSRV.Name, - "' is not consistent with the type (", GetShaderVariableTypeLiteralName(SamplerAttribs.GetVariableType()), - ") of the sampler '", SamplerAttribs.Name, "' that is assigned to it"); + ++CbvSrvUavCount[VarType]; + if (TexSRV.ValidSamplerAssigned()) + { + auto SamplerId = TexSRV.GetSamplerId(); + const auto& SamplerAttribs = m_pResources->GetSampler(SamplerId); + auto SamplerVarType = m_pResources->FindVariableType(SamplerAttribs, ResourceLayout); + DEV_CHECK_ERR(SamplerVarType == VarType, + "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; + } } }, [&](const D3DShaderResourceAttribs& TexUAV, Uint32) { - VERIFY_EXPR(TexUAV.IsAllowedType(AllowedTypeBits)); - ++CbvSrvUavCount[TexUAV.GetVariableType()]; + auto VarType = m_pResources->FindVariableType(TexUAV, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) + ++CbvSrvUavCount[VarType]; }, [&](const D3DShaderResourceAttribs& BufSRV, Uint32) { - VERIFY_EXPR(BufSRV.IsAllowedType(AllowedTypeBits)); - ++CbvSrvUavCount[BufSRV.GetVariableType()]; + auto VarType = m_pResources->FindVariableType(BufSRV, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) + ++CbvSrvUavCount[VarType]; }, [&](const D3DShaderResourceAttribs& BufUAV, Uint32) { - VERIFY_EXPR(BufUAV.IsAllowedType(AllowedTypeBits)); - ++CbvSrvUavCount[BufUAV.GetVariableType()]; + auto VarType = m_pResources->FindVariableType(BufUAV, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) + ++CbvSrvUavCount[VarType]; } ); AllocateMemory(LayoutDataAllocator, CbvSrvUavCount, SamplerCount); - std::array CurrCbvSrvUav = {}; - std::array CurrSampler = {}; + std::array CurrCbvSrvUav = {}; + std::array CurrSampler = {}; Uint32 StaticResCacheTblSizes[4] = {0, 0, 0, 0}; - auto AddResource = [&](const D3DShaderResourceAttribs& Attribs, CachedResourceType ResType, Uint32 SamplerId = D3D12Resource::InvalidSamplerId) + auto AddResource = [&](const D3DShaderResourceAttribs& Attribs, + CachedResourceType ResType, + SHADER_RESOURCE_VARIABLE_TYPE VarType, + Uint32 SamplerId = D3D12Resource::InvalidSamplerId) { Uint32 RootIndex = D3D12Resource::InvalidRootIndex; Uint32 Offset = D3D12Resource::InvalidOffset; @@ -214,92 +228,112 @@ void ShaderResourceLayoutD3D12::Initialize(ID3D12Device* VERIFY(Offset != D3D12Resource::InvalidOffset, "Offset must be valid"); // Static samplers are never copied, and SamplerId == InvalidSamplerId - auto VarType = Attribs.GetVariableType(); auto& NewResource = (ResType == CachedResourceType::Sampler) ? GetSampler (VarType, CurrSampler [VarType]++) : GetSrvCbvUav(VarType, CurrCbvSrvUav[VarType]++); - ::new (&NewResource) D3D12Resource(*this, Attribs, ResType, RootIndex, Offset, SamplerId); + ::new (&NewResource) D3D12Resource(*this, Attribs, VarType, ResType, RootIndex, Offset, SamplerId); }; m_pResources->ProcessResources( - AllowedVarTypes, NumAllowedTypes, - [&](const D3DShaderResourceAttribs& CB, Uint32) { - VERIFY_EXPR( CB.IsAllowedType(AllowedTypeBits) ); - AddResource(CB, CachedResourceType::CBV); + auto VarType = m_pResources->FindVariableType(CB, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) + AddResource(CB, CachedResourceType::CBV, VarType); }, [&](const D3DShaderResourceAttribs& Sam, Uint32) { - VERIFY_EXPR( Sam.IsAllowedType(AllowedTypeBits) ); - if (Sam.IsStaticSampler()) + auto VarType = m_pResources->FindVariableType(Sam, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) { - if (pRootSig != nullptr) - pRootSig->InitStaticSampler(m_pResources->GetShaderType(), Sam.Name, m_pResources->GetCombinedSamplerSuffix(), Sam); - } - else - { - AddResource(Sam, CachedResourceType::Sampler); + auto StaticSamplerInd = m_pResources->FindStaticSampler(Sam, ResourceLayout); + if (StaticSamplerInd >= 0) + { + if (pRootSig != nullptr) + pRootSig->InitStaticSampler(m_pResources->GetShaderType(), Sam.Name, m_pResources->GetCombinedSamplerSuffix(), Sam); + } + else + { + AddResource(Sam, CachedResourceType::Sampler, VarType); + } } }, [&](const D3DShaderResourceAttribs& TexSRV, Uint32) { - VERIFY_EXPR(TexSRV.IsAllowedType(AllowedTypeBits) ); - static_assert(SHADER_VARIABLE_TYPE_NUM_TYPES == 3, "Unexpected number of shader variable types"); - VERIFY(CurrSampler[SHADER_VARIABLE_TYPE_STATIC] + CurrSampler[SHADER_VARIABLE_TYPE_MUTABLE] + CurrSampler[SHADER_VARIABLE_TYPE_DYNAMIC] == GetTotalSamplerCount(), "All samplers must be initialized before texture SRVs"); - - Uint32 SamplerId = D3D12Resource::InvalidSamplerId; - if (TexSRV.ValidSamplerAssigned()) + auto VarType = m_pResources->FindVariableType(TexSRV, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) { - const auto& SamplerAttribs = m_pResources->GetSampler(TexSRV.GetSamplerId()); - DEV_CHECK_ERR(SamplerAttribs.GetVariableType() == TexSRV.GetVariableType(), - "The type (", GetShaderVariableTypeLiteralName(TexSRV.GetVariableType()),") of texture SRV variable '", TexSRV.Name, - "' is not consistent with the type (", GetShaderVariableTypeLiteralName(SamplerAttribs.GetVariableType()), - ") of the sampler '", SamplerAttribs.Name, "' that is assigned to it"); - - if (SamplerAttribs.IsStaticSampler()) - { - // Static samplers are never copied, and SamplerId == InvalidSamplerId - } - else + 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.ValidSamplerAssigned()) { - auto SamplerCount = GetTotalSamplerCount(); - for (SamplerId = 0; SamplerId < SamplerCount; ++SamplerId) + const auto& SamplerAttribs = m_pResources->GetSampler(TexSRV.GetSamplerId()); + auto SamplerVarType = m_pResources->FindVariableType(SamplerAttribs, ResourceLayout); + DEV_CHECK_ERR(SamplerVarType == VarType, + "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"); + + auto StaticSamplerInd = m_pResources->FindStaticSampler(SamplerAttribs, ResourceLayout); + if (StaticSamplerInd >= 0) { - const auto& Sampler = GetSampler(SamplerId); - if (strcmp(Sampler.Attribs.Name, SamplerAttribs.Name) == 0) - break; + // Static samplers are never copied, and SamplerId == InvalidSamplerId +#ifdef _DEBUG + auto SamplerCount = GetTotalSamplerCount(); + for (SamplerId = 0; SamplerId < SamplerCount; ++SamplerId) + { + const auto& Sampler = GetSampler(SamplerId); + if (strcmp(Sampler.Attribs.Name, SamplerAttribs.Name) == 0) + LOG_ERROR("Static sampler '", Sampler.Attribs.Name, "' was found among resources. This seems to be a bug"); + } +#endif } - if (SamplerId == SamplerCount) + else { - LOG_ERROR("Unable to find sampler '", SamplerAttribs.Name, "' assigned to texture SRV '", TexSRV.Name, "' in the list of already created resources. This seems to be a bug."); - SamplerId = D3D12Resource::InvalidSamplerId; + auto SamplerCount = GetTotalSamplerCount(); + for (SamplerId = 0; SamplerId < SamplerCount; ++SamplerId) + { + const auto& Sampler = GetSampler(SamplerId); + if (strcmp(Sampler.Attribs.Name, SamplerAttribs.Name) == 0) + break; + } + + if (SamplerId == SamplerCount) + { + LOG_ERROR("Unable to find sampler '", SamplerAttribs.Name, "' assigned to texture SRV '", TexSRV.Name, "' in the list of already created resources. This seems to be a bug."); + SamplerId = D3D12Resource::InvalidSamplerId; + } + VERIFY(SamplerId <= D3D12Resource::MaxSamplerId, "Sampler index excceeds allowed limit"); } - VERIFY(SamplerId <= D3D12Resource::MaxSamplerId, "Sampler index excceeds allowed limit"); } + AddResource(TexSRV, CachedResourceType::TexSRV, VarType, SamplerId); } - AddResource(TexSRV, CachedResourceType::TexSRV, SamplerId); }, [&](const D3DShaderResourceAttribs& TexUAV, Uint32) { - VERIFY_EXPR( TexUAV.IsAllowedType(AllowedTypeBits) ); - AddResource(TexUAV, CachedResourceType::TexUAV); + auto VarType = m_pResources->FindVariableType(TexUAV, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) + AddResource(TexUAV, CachedResourceType::TexUAV, VarType); }, [&](const D3DShaderResourceAttribs& BufSRV, Uint32) { - VERIFY_EXPR( BufSRV.IsAllowedType(AllowedTypeBits) ); - AddResource(BufSRV, CachedResourceType::BufSRV); + auto VarType = m_pResources->FindVariableType(BufSRV, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) + AddResource(BufSRV, CachedResourceType::BufSRV, VarType); }, [&](const D3DShaderResourceAttribs& BufUAV, Uint32) { - VERIFY_EXPR( BufUAV.IsAllowedType(AllowedTypeBits) ); - AddResource(BufUAV, CachedResourceType::BufUAV); + auto VarType = m_pResources->FindVariableType(BufUAV, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) + AddResource(BufUAV, CachedResourceType::BufUAV, VarType); } ); #ifdef _DEBUG - for(SHADER_VARIABLE_TYPE VarType = SHADER_VARIABLE_TYPE_STATIC; VarType < SHADER_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" ); @@ -326,7 +360,7 @@ void ShaderResourceLayoutD3D12::Initialize(ID3D12Device* #define LOG_RESOURCE_BINDING_ERROR(ResType, pResource, VarName, ShaderName, ...)\ { \ - const auto &ResName = pResource->GetDesc().Name; \ + const auto& ResName = pResource->GetDesc().Name; \ LOG_ERROR_MESSAGE( "Failed to bind ", ResType, " '", ResName, "' to variable '", VarName, \ "' in shader '", ShaderName, "'. ", __VA_ARGS__ ); \ } @@ -347,11 +381,11 @@ void ShaderResourceLayoutD3D12::D3D12Resource::CacheCB(IDeviceObject* { if (pBuffD3D12->GetDesc().BindFlags & BIND_UNIFORM_BUFFER) { - if (Attribs.GetVariableType() != SHADER_VARIABLE_TYPE_DYNAMIC && DstRes.pObject != nullptr) + if (GetVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC && DstRes.pObject != nullptr) { if (DstRes.pObject != pBuffD3D12) { - auto VarTypeStr = GetShaderVariableTypeLiteralName(Attribs.GetVariableType()); + auto VarTypeStr = GetShaderVariableTypeLiteralName(GetVariableType()); LOG_ERROR_MESSAGE( "Non-null constant buffer is already bound to ", VarTypeStr, " shader variable '", Attribs.GetPrintName(ArrayInd), "' in shader '", ParentResLayout.GetShaderName(), "'. Attempting to bind another constant buffer is an error and will be ignored. Use another shader resource binding instance or label the variable as dynamic." ); } @@ -429,19 +463,21 @@ void ShaderResourceLayoutD3D12::D3D12Resource::CacheResourceView(IDeviceObject* auto ViewType = ViewDesc.ViewType; if (ViewType != dbgExpectedViewType) { - const auto *ExpectedViewTypeName = GetViewTypeLiteralName( dbgExpectedViewType ); - const auto *ActualViewTypeName = GetViewTypeLiteralName( ViewType ); + const auto* ExpectedViewTypeName = GetViewTypeLiteralName( dbgExpectedViewType ); + const auto* ActualViewTypeName = GetViewTypeLiteralName( ViewType ); LOG_RESOURCE_BINDING_ERROR(ResourceViewTraits::Name, pViewD3D12, Attribs.GetPrintName(ArrayIndex), ParentResLayout.GetShaderName(), "Incorrect view type: ", ExpectedViewTypeName, " is expected, ", ActualViewTypeName, " provided." ); return; } #endif - if (Attribs.GetVariableType() != SHADER_VARIABLE_TYPE_DYNAMIC && DstRes.pObject != nullptr) + if (GetVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC && DstRes.pObject != nullptr) { if (DstRes.pObject != pViewD3D12) { - auto VarTypeStr = GetShaderVariableTypeLiteralName(Attribs.GetVariableType()); - LOG_ERROR_MESSAGE( "Non-null resource is already bound to ", VarTypeStr, " shader variable '", Attribs.GetPrintName(ArrayIndex), "' in shader '", ParentResLayout.GetShaderName(), "'. Attempting to bind another resource or null is an error and will be ignored. Use another shader resource binding instance or label the variable as dynamic." ); + auto VarTypeStr = GetShaderVariableTypeLiteralName(GetVariableType()); + LOG_ERROR_MESSAGE( "Non-null resource is already bound to ", VarTypeStr, " shader variable '", Attribs.GetPrintName(ArrayIndex), "' in shader '", + ParentResLayout.GetShaderName(), "'. Attempting to bind another resource or null is an error and will 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 @@ -484,11 +520,11 @@ void ShaderResourceLayoutD3D12::D3D12Resource::CacheSampler(IDeviceObject* RefCntAutoPtr pSamplerD3D12(pSampler, IID_SamplerD3D12); if (pSamplerD3D12) { - if (Attribs.GetVariableType() != SHADER_VARIABLE_TYPE_DYNAMIC && DstSam.pObject != nullptr) + if (GetVariableType() != SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC && DstSam.pObject != nullptr) { if (DstSam.pObject != pSampler) { - auto VarTypeStr = GetShaderVariableTypeLiteralName(Attribs.GetVariableType()); + 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." ); } @@ -525,7 +561,7 @@ const ShaderResourceLayoutD3D12::D3D12Resource& ShaderResourceLayoutD3D12::GetAs VERIFY(TexSrv.GetResType() == CachedResourceType::TexSRV, "Unexpected resource type: texture SRV is expected"); VERIFY(TexSrv.ValidSamplerAssigned(), "Texture SRV has no associated sampler"); const auto& SamInfo = GetSampler(TexSrv.SamplerId); - VERIFY(SamInfo.Attribs.GetVariableType() == TexSrv.Attribs.GetVariableType(), "Inconsistent texture and sampler variable types"); + VERIFY(SamInfo.GetVariableType() == TexSrv.GetVariableType(), "Inconsistent texture and sampler variable types"); VERIFY(StreqSuff(SamInfo.Attribs.Name, TexSrv.Attribs.Name, m_pResources->GetCombinedSamplerSuffix()), "Sampler name '", SamInfo.Attribs.Name, "' does not match texture name '", TexSrv.Attribs.Name, '\''); return SamInfo; } @@ -563,7 +599,7 @@ void ShaderResourceLayoutD3D12::D3D12Resource::BindResource(IDeviceObject* } else { - if(Attribs.GetVariableType() == SHADER_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"); @@ -587,10 +623,10 @@ void ShaderResourceLayoutD3D12::D3D12Resource::BindResource(IDeviceObject* case CachedResourceType::TexSRV: CacheResourceView(pObj, DstRes, ArrayIndex, ShdrVisibleHeapCPUDescriptorHandle, TEXTURE_VIEW_SHADER_RESOURCE, [&](ITextureViewD3D12* pTexView) { - if(ValidSamplerAssigned()) + if (ValidSamplerAssigned()) { auto& Sam = ParentResLayout.GetAssignedSampler(*this); - VERIFY( !Sam.Attribs.IsStaticSampler(), "Static samplers should never be assigned space in the cache" ); + //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); @@ -603,7 +639,7 @@ void ShaderResourceLayoutD3D12::D3D12Resource::BindResource(IDeviceObject* } else if (ResourceCache.DbgGetContentType() == ShaderResourceCacheD3D12::DbgCacheContentType::SRBResources) { - if(Attribs.GetVariableType() == SHADER_VARIABLE_TYPE_DYNAMIC) + 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"); @@ -649,7 +685,7 @@ void ShaderResourceLayoutD3D12::D3D12Resource::BindResource(IDeviceObject* } else { - if (DstRes.pObject != nullptr && Attribs.GetVariableType() != SHADER_VARIABLE_TYPE_DYNAMIC) + 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." ); DstRes = ShaderResourceCacheD3D12::Resource{}; @@ -659,7 +695,7 @@ void ShaderResourceLayoutD3D12::D3D12Resource::BindResource(IDeviceObject* 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.Attribs.GetVariableType() != SHADER_VARIABLE_TYPE_DYNAMIC) + 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." ); DstSam = ShaderResourceCacheD3D12::Resource{}; } @@ -699,13 +735,13 @@ void ShaderResourceLayoutD3D12::CopyStaticResourceDesriptorHandles(const ShaderR // Samplers at root index D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER // Every resource is stored at offset that equals resource bind point - auto CbvSrvUavCount = DstLayout.GetCbvSrvUavCount(SHADER_VARIABLE_TYPE_STATIC); - VERIFY(GetCbvSrvUavCount(SHADER_VARIABLE_TYPE_STATIC) == CbvSrvUavCount, "Number of static resources in the source cache (", GetCbvSrvUavCount(SHADER_VARIABLE_TYPE_STATIC), ") is not consistent with the number of static resources in destination cache (", CbvSrvUavCount, ")" ); + 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, ")" ); for(Uint32 r=0; r < CbvSrvUavCount; ++r) { // Get resource attributes - const auto& res = DstLayout.GetSrvCbvUav(SHADER_VARIABLE_TYPE_STATIC, r); + 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) { @@ -748,18 +784,18 @@ void ShaderResourceLayoutD3D12::CopyStaticResourceDesriptorHandles(const ShaderR { const auto& SamInfo = DstLayout.GetAssignedSampler(res); - VERIFY(!SamInfo.Attribs.IsStaticSampler(), "Static samplers should never be assigned space in the cache"); + //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_VARIABLE_TYPE_STATIC); - VERIFY(GetSamplerCount(SHADER_VARIABLE_TYPE_STATIC) == SamplerCount, "Number of static-type samplers in the source cache (", GetSamplerCount(SHADER_VARIABLE_TYPE_STATIC), ") is not consistent with the number of static-type samplers in destination cache (", SamplerCount, ")" ); + 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) { - const auto& SamInfo = DstLayout.GetSampler(SHADER_VARIABLE_TYPE_STATIC, s); + const auto& SamInfo = DstLayout.GetSampler(SHADER_RESOURCE_VARIABLE_TYPE_STATIC, s); for(Uint32 ArrInd = 0; ArrInd < SamInfo.Attribs.BindCount; ++ArrInd) { auto BindPoint = SamInfo.Attribs.BindPoint + ArrInd; @@ -768,7 +804,7 @@ void ShaderResourceLayoutD3D12::CopyStaticResourceDesriptorHandles(const ShaderR 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(), "'." ); - auto &DstSampler = DstCache.GetRootTable(SamInfo.RootIndex).GetResource(SamInfo.OffsetFromTableStart + ArrInd, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, m_pResources->GetShaderType()); + auto& DstSampler = DstCache.GetRootTable(SamInfo.RootIndex).GetResource(SamInfo.OffsetFromTableStart + ArrInd, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, m_pResources->GetShaderType()); if(DstSampler.pObject != SrcSampler.pObject) { @@ -800,12 +836,12 @@ void ShaderResourceLayoutD3D12::CopyStaticResourceDesriptorHandles(const ShaderR bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12& ResourceCache)const { bool BindingsOK = true; - for (SHADER_VARIABLE_TYPE VarType = SHADER_VARIABLE_TYPE_STATIC; VarType < SHADER_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) { const auto& res = GetSrvCbvUav(VarType, r); - VERIFY(res.Attribs.GetVariableType() == VarType, "Unexpected variable type"); + VERIFY(res.GetVariableType() == VarType, "Unexpected variable type"); for (Uint32 ArrInd = 0; ArrInd < res.Attribs.BindCount; ++ArrInd) { @@ -819,7 +855,7 @@ bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12 // 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.Attribs.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; } @@ -857,7 +893,7 @@ bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12 } else { - if (res.Attribs.GetVariableType() == SHADER_VARIABLE_TYPE_DYNAMIC) + if (res.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"); @@ -875,7 +911,7 @@ bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12 { 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.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) @@ -900,7 +936,7 @@ bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12 } else if (ResourceCache.DbgGetContentType() == ShaderResourceCacheD3D12::DbgCacheContentType::SRBResources) { - if (SamInfo.Attribs.GetVariableType() == SHADER_VARIABLE_TYPE_DYNAMIC) + if (SamInfo.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"); @@ -918,7 +954,7 @@ bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12 for (Uint32 s=0; s < GetSamplerCount(VarType); ++s) { const auto& sam = GetSampler(VarType, s); - VERIFY(sam.Attribs.GetVariableType() == VarType, "Unexpected sampler variable type"); + VERIFY(sam.GetVariableType() == VarType, "Unexpected sampler variable type"); for (Uint32 ArrInd = 0; ArrInd < sam.Attribs.BindCount; ++ArrInd) { @@ -940,35 +976,4 @@ bool ShaderResourceLayoutD3D12::dvpVerifyBindings(const ShaderResourceCacheD3D12 } #endif -const Char* ShaderResourceLayoutD3D12::GetShaderName()const -{ - RefCntAutoPtr pShader(&m_Owner, IID_Shader); - if (pShader) - { - return pShader->GetDesc().Name; - } - else - { - RefCntAutoPtr pPSO(&m_Owner, IID_PipelineState); - if(pPSO) - { - auto* pPSOD3D12 = pPSO.RawPtr(); - auto* ppShaders = pPSOD3D12->GetShaders(); - auto NumShaders = pPSOD3D12->GetNumShaders(); - for (Uint32 s = 0; s < NumShaders; ++s) - { - const auto& ShaderDesc = ppShaders[s]->GetDesc(); - if(ShaderDesc.ShaderType == m_pResources->GetShaderType()) - return ShaderDesc.Name; - } - UNEXPECTED("Shader not found"); - } - else - { - UNEXPECTED("Shader resource layout owner is expected to be a shader or a pipeline state"); - } - } - return ""; -} - } diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderResourcesD3D12.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderResourcesD3D12.cpp index efb6602a..2504d198 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderResourcesD3D12.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderResourcesD3D12.cpp @@ -48,7 +48,7 @@ ShaderResourcesD3D12::ShaderResourcesD3D12(ID3DBlob* pShaderBytecode, const Shad Initialize( pShaderBytecode, NewResourceHandler{}, - ShdrDesc, + ShdrDesc.Name, CombinedSamplerSuffix ); } diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp index 35bd4d81..877a270d 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp @@ -24,18 +24,19 @@ #include "pch.h" #include "ShaderVariableD3D12.h" +#include "ShaderResourceVariableBase.h" namespace Diligent { -size_t ShaderVariableManagerD3D12::GetRequiredMemorySize(const ShaderResourceLayoutD3D12& Layout, - const SHADER_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; Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); - for (SHADER_VARIABLE_TYPE VarType = SHADER_VARIABLE_TYPE_STATIC; VarType < SHADER_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)) { @@ -49,11 +50,11 @@ size_t ShaderVariableManagerD3D12::GetRequiredMemorySize(const ShaderResourceLay } // Creates shader variable for every resource from SrcLayout whose type is one AllowedVarTypes -void ShaderVariableManagerD3D12::Initialize(const ShaderResourceLayoutD3D12& SrcLayout, - IMemoryAllocator& Allocator, - const SHADER_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - ShaderResourceCacheD3D12& ResourceCache) +void ShaderVariableManagerD3D12::Initialize(const ShaderResourceLayoutD3D12& SrcLayout, + IMemoryAllocator& Allocator, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes, + ShaderResourceCacheD3D12& ResourceCache) { m_pResourceLayout = &SrcLayout; m_pResourceCache = &ResourceCache; @@ -72,7 +73,7 @@ void ShaderVariableManagerD3D12::Initialize(const ShaderResourceLayoutD3D12& Src m_pVariables = reinterpret_cast(pRawMem); Uint32 VarInd = 0; - for (SHADER_VARIABLE_TYPE VarType = SHADER_VARIABLE_TYPE_STATIC; VarType < SHADER_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; @@ -177,7 +178,7 @@ void ShaderVariableManagerD3D12::BindResources( IResourceMapping* pResourceMappi auto &Var = m_pVariables[v]; const auto& Res = Var.m_Resource; - if ( (Flags & (1 << Res.Attribs.GetVariableType())) == 0 ) + if ( (Flags & (1 << Res.GetVariableType())) == 0 ) continue; for (Uint32 ArrInd = 0; ArrInd < Res.Attribs.BindCount; ++ArrInd) -- cgit v1.2.3 From bb8b65b012f0c07afa6dd1f257d79fa98119157c Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Mon, 4 Mar 2019 08:41:33 -0800 Subject: Minor interface improvement --- Graphics/GraphicsEngine/interface/BufferView.h | 2 +- Graphics/GraphicsEngine/interface/DeviceContext.h | 2 +- Graphics/GraphicsEngine/interface/DeviceObject.h | 2 +- Graphics/GraphicsEngine/interface/Fence.h | 2 +- Graphics/GraphicsEngine/interface/PipelineState.h | 2 +- Graphics/GraphicsEngine/interface/RenderDevice.h | 2 +- Graphics/GraphicsEngine/interface/ResourceMapping.h | 2 +- Graphics/GraphicsEngine/interface/Sampler.h | 2 +- Graphics/GraphicsEngine/interface/Shader.h | 2 +- Graphics/GraphicsEngine/interface/ShaderResourceBinding.h | 2 +- Graphics/GraphicsEngine/interface/Texture.h | 2 +- Graphics/GraphicsEngine/interface/TextureView.h | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngine/interface/BufferView.h b/Graphics/GraphicsEngine/interface/BufferView.h index 37162724..d1a43ea2 100644 --- a/Graphics/GraphicsEngine/interface/BufferView.h +++ b/Graphics/GraphicsEngine/interface/BufferView.h @@ -138,7 +138,7 @@ class IBufferView : public IDeviceObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Returns the buffer view description used to create the object virtual const BufferViewDesc& GetDesc()const = 0; diff --git a/Graphics/GraphicsEngine/interface/DeviceContext.h b/Graphics/GraphicsEngine/interface/DeviceContext.h index 32b4ac59..46b48337 100644 --- a/Graphics/GraphicsEngine/interface/DeviceContext.h +++ b/Graphics/GraphicsEngine/interface/DeviceContext.h @@ -450,7 +450,7 @@ class IDeviceContext : public IObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details. - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Sets the pipeline state. diff --git a/Graphics/GraphicsEngine/interface/DeviceObject.h b/Graphics/GraphicsEngine/interface/DeviceObject.h index e74ebdc7..939ad080 100644 --- a/Graphics/GraphicsEngine/interface/DeviceObject.h +++ b/Graphics/GraphicsEngine/interface/DeviceObject.h @@ -41,7 +41,7 @@ class IDeviceObject : public IObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface ) = 0; + virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface )override = 0; /// Returns the buffer object description virtual const DeviceObjectAttribs& GetDesc()const = 0; diff --git a/Graphics/GraphicsEngine/interface/Fence.h b/Graphics/GraphicsEngine/interface/Fence.h index 0d72985f..bdecd369 100644 --- a/Graphics/GraphicsEngine/interface/Fence.h +++ b/Graphics/GraphicsEngine/interface/Fence.h @@ -48,7 +48,7 @@ class IFence : public IDeviceObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Returns the fence description used to create the object virtual const FenceDesc& GetDesc()const = 0; diff --git a/Graphics/GraphicsEngine/interface/PipelineState.h b/Graphics/GraphicsEngine/interface/PipelineState.h index 7768daf8..0f6efcf6 100644 --- a/Graphics/GraphicsEngine/interface/PipelineState.h +++ b/Graphics/GraphicsEngine/interface/PipelineState.h @@ -242,7 +242,7 @@ class IPipelineState : public IDeviceObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface ) = 0; + virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface )override = 0; /// Returns the blend state description used to create the object diff --git a/Graphics/GraphicsEngine/interface/RenderDevice.h b/Graphics/GraphicsEngine/interface/RenderDevice.h index fd10f17c..ece8eda3 100644 --- a/Graphics/GraphicsEngine/interface/RenderDevice.h +++ b/Graphics/GraphicsEngine/interface/RenderDevice.h @@ -57,7 +57,7 @@ class IRenderDevice : public IObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface ) = 0; + virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface )override = 0; /// Creates a new buffer object diff --git a/Graphics/GraphicsEngine/interface/ResourceMapping.h b/Graphics/GraphicsEngine/interface/ResourceMapping.h index c3fb9e57..f8f8d49b 100644 --- a/Graphics/GraphicsEngine/interface/ResourceMapping.h +++ b/Graphics/GraphicsEngine/interface/ResourceMapping.h @@ -83,7 +83,7 @@ namespace Diligent { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface (const INTERFACE_ID& IID, IObject** ppInterface) = 0; + virtual void QueryInterface (const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Adds a resource to the mapping. diff --git a/Graphics/GraphicsEngine/interface/Sampler.h b/Graphics/GraphicsEngine/interface/Sampler.h index 65579f5e..2ad99605 100644 --- a/Graphics/GraphicsEngine/interface/Sampler.h +++ b/Graphics/GraphicsEngine/interface/Sampler.h @@ -170,7 +170,7 @@ class ISampler : public IDeviceObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Returns the sampler description used to create the object virtual const SamplerDesc& GetDesc()const = 0; diff --git a/Graphics/GraphicsEngine/interface/Shader.h b/Graphics/GraphicsEngine/interface/Shader.h index e877ce17..d6c07629 100644 --- a/Graphics/GraphicsEngine/interface/Shader.h +++ b/Graphics/GraphicsEngine/interface/Shader.h @@ -232,7 +232,7 @@ class IShader : public IDeviceObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Returns the shader description virtual const ShaderDesc& GetDesc()const = 0; diff --git a/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h b/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h index a216cfbe..d2523685 100644 --- a/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h +++ b/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h @@ -46,7 +46,7 @@ class IShaderResourceBinding : public IObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Returns pointer to the referenced buffer object. diff --git a/Graphics/GraphicsEngine/interface/Texture.h b/Graphics/GraphicsEngine/interface/Texture.h index a1b56ed9..0b3cedbc 100644 --- a/Graphics/GraphicsEngine/interface/Texture.h +++ b/Graphics/GraphicsEngine/interface/Texture.h @@ -273,7 +273,7 @@ class ITexture : public IDeviceObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Returns the texture description used to create the object virtual const TextureDesc& GetDesc()const = 0; diff --git a/Graphics/GraphicsEngine/interface/TextureView.h b/Graphics/GraphicsEngine/interface/TextureView.h index 84df8ce4..a1e2b439 100644 --- a/Graphics/GraphicsEngine/interface/TextureView.h +++ b/Graphics/GraphicsEngine/interface/TextureView.h @@ -163,7 +163,7 @@ class ITextureView : public IDeviceObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface ) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Returns the texture view description used to create the object virtual const TextureViewDesc& GetDesc()const = 0; -- cgit v1.2.3 From c72191a465edd01905181aa47cc57e47fcc29b9e Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Mon, 4 Mar 2019 19:17:32 -0800 Subject: Completed D3D12 back-end refactor to comply with the new API --- .../include/PipelineStateD3D11Impl.h | 25 +++-- .../src/ShaderResourceLayoutD3D11.cpp | 8 +- .../src/ShaderResourcesD3D11.cpp | 4 +- .../include/PipelineStateD3D12Impl.h | 31 ++++- .../GraphicsEngineD3D12/include/RootSignature.h | 5 +- .../GraphicsEngineD3D12/include/ShaderD3D12Impl.h | 10 ++ .../include/ShaderResourceBindingD3D12Impl.h | 4 +- .../include/ShaderResourceLayoutD3D12.h | 32 +++--- .../include/ShaderVariableD3D12.h | 33 +++--- .../src/PipelineStateD3D12Impl.cpp | 125 +++++++++++++++++++-- .../src/RenderDeviceD3D12Impl.cpp | 6 +- Graphics/GraphicsEngineD3D12/src/RootSignature.cpp | 30 ++--- .../src/ShaderResourceBindingD3D12Impl.cpp | 28 +++-- .../src/ShaderResourceLayoutD3D12.cpp | 49 ++++---- .../src/ShaderVariableD3D12.cpp | 29 ++--- .../include/ShaderResources.h | 66 ++++++----- 16 files changed, 326 insertions(+), 159 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h index 71830432..81e03ca2 100644 --- a/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h @@ -50,6 +50,20 @@ public: virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; + + virtual void BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags)override final; + + virtual Uint32 GetStaticVariableCount(SHADER_TYPE ShaderType) const override final; + + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) override final; + + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) override final; + + virtual void CreateShaderResourceBinding( IShaderResourceBinding **ppShaderResourceBinding, bool InitStaticResources )override final; + + virtual bool IsCompatibleWith(const IPipelineState *pPSO)const override final; + + /// Implementation of the IPipelineStateD3D11::GetD3D11BlendState() method. virtual ID3D11BlendState* GetD3D11BlendState()override final; @@ -68,17 +82,6 @@ public: virtual ID3D11HullShader* GetD3D11HullShader()override final; virtual ID3D11ComputeShader* GetD3D11ComputeShader()override final; - virtual void CreateShaderResourceBinding( IShaderResourceBinding **ppShaderResourceBinding, bool InitStaticResources )override final; - - virtual bool IsCompatibleWith(const IPipelineState *pPSO)const override final; - - virtual void BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags)override final; - - virtual Uint32 GetStaticVariableCount(SHADER_TYPE ShaderType) const override final; - - virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) override final; - - virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) override final; SRBMemoryAllocator& GetSRBMemoryAllocator() { diff --git a/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp b/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp index 12ca400a..262902b0 100755 --- a/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp +++ b/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp @@ -199,9 +199,9 @@ ShaderResourceLayoutD3D11::ShaderResourceLayoutD3D11(IObject& VERIFY(sam == NumSamplers, "All samplers must be initialized before texture SRVs"); Uint32 AssignedSamplerIndex = TexSRVBindInfo::InvalidSamplerIndex; - if (TexSRV.ValidSamplerAssigned()) + if (TexSRV.IsCombinedWithSampler()) { - const auto& AssignedSamplerAttribs = m_pResources->GetSampler(TexSRV.GetSamplerId()); + const auto& AssignedSamplerAttribs = m_pResources->GetCombinedSampler(TexSRV); auto AssignedSamplerType = m_pResources->FindVariableType(AssignedSamplerAttribs, ResourceLayout); DEV_CHECK_ERR(AssignedSamplerType == VarType, "The type (", GetShaderVariableTypeLiteralName(VarType),") of texture SRV variable '", TexSRV.Name, @@ -553,9 +553,9 @@ void ShaderResourceLayoutD3D11::SamplerBindInfo::BindResource(IDeviceObject* pSa if (pSampler && !pSamplerD3D11) LOG_RESOURCE_BINDING_ERROR("sampler", pSampler, m_Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Incorect resource type: sampler is expected."); - if (m_Attribs.ValidTexSRVAssigned()) + if (m_Attribs.IsCombinedWithTexSRV()) { - auto* TexSRVName = m_ParentResLayout.m_pResources->GetTexSRV(m_Attribs.GetTexSRVId()).Name; + auto* TexSRVName = m_ParentResLayout.m_pResources->GetCombinedTextureSRV(m_Attribs).Name; LOG_WARNING_MESSAGE("Texture sampler sampler '", m_Attribs.Name, "' is assigned to texture SRV '", TexSRVName, "' and should not be accessed directly. The sampler is initialized when texture SRV is set to '", TexSRVName, "' variable."); } diff --git a/Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp b/Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp index a12a8ff6..b80cbccd 100755 --- a/Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp +++ b/Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp @@ -252,9 +252,9 @@ void ShaderResourcesD3D11::dvpVerifyCommittedResources(ID3D11Buffer* } } - if (tex.ValidSamplerAssigned()) + if (tex.IsCombinedWithSampler()) { - const auto& SamAttribs = GetSampler( tex.GetSamplerId() ); + const auto& SamAttribs = GetCombinedSampler(tex); VERIFY_EXPR(SamAttribs.IsValidBindPoint()); VERIFY_EXPR(SamAttribs.BindCount == 1 || SamAttribs.BindCount == tex.BindCount); } diff --git a/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h index 35cd4e7e..64dfdc2b 100644 --- a/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h @@ -33,6 +33,7 @@ #include "ShaderResourceLayoutD3D12.h" #include "SRBMemoryAllocator.h" #include "RenderDeviceD3D12Impl.h" +#include "ShaderVariableD3D12.h" namespace Diligent { @@ -49,12 +50,20 @@ public: virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; - virtual ID3D12PipelineState *GetD3D12PipelineState()const override final{return m_pd3d12PSO;} - + virtual void BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags)override final; + + virtual Uint32 GetStaticVariableCount(SHADER_TYPE ShaderType) const override final; + + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) override final; + + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) override final; + virtual void CreateShaderResourceBinding( IShaderResourceBinding **ppShaderResourceBinding, bool InitStaticResources )override final; virtual bool IsCompatibleWith(const IPipelineState *pPSO)const override final; + virtual ID3D12PipelineState *GetD3D12PipelineState()const override final{return m_pd3d12PSO;} + virtual ID3D12RootSignature *GetD3D12RootSignature()const override final{return m_RootSig.GetD3D12RootSignature(); } ShaderResourceCacheD3D12* CommitAndTransitionShaderResources(IShaderResourceBinding* pShaderResourceBinding, @@ -70,7 +79,19 @@ public: VERIFY_EXPR(ShaderInd < m_NumShaders); return m_pShaderResourceLayouts[ShaderInd]; } + + const ShaderResourceLayoutD3D12& GetStaticShaderResLayout(Uint32 ShaderInd)const + { + VERIFY_EXPR(ShaderInd < m_NumShaders); + return m_pShaderResourceLayouts[m_NumShaders + ShaderInd]; + } + ShaderResourceCacheD3D12& GetStaticShaderResCache(Uint32 ShaderInd)const + { + VERIFY_EXPR(ShaderInd < m_NumShaders); + return m_pStaticResourceCaches[ShaderInd]; + } + bool dbgContainsShaderResources()const; SRBMemoryAllocator& GetSRBMemoryAllocator() @@ -87,7 +108,11 @@ private: // Must be defined before default SRB SRBMemoryAllocator m_SRBMemAllocator; - ShaderResourceLayoutD3D12* m_pShaderResourceLayouts; + 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}; }; } diff --git a/Graphics/GraphicsEngineD3D12/include/RootSignature.h b/Graphics/GraphicsEngineD3D12/include/RootSignature.h index ebe2083e..1d312399 100644 --- a/Graphics/GraphicsEngineD3D12/include/RootSignature.h +++ b/Graphics/GraphicsEngineD3D12/include/RootSignature.h @@ -288,9 +288,9 @@ class RootSignature public: RootSignature(); - void AllocateStaticSamplers(IShader* const *ppShaders, Uint32 NumShaders); + void AllocateStaticSamplers(const PipelineResourceLayoutDesc& ResourceLayout); - void Finalize(ID3D12Device *pd3d12Device); + void Finalize(ID3D12Device* pd3d12Device); ID3D12RootSignature* GetD3D12RootSignature()const{return m_pd3d12RootSignature;} @@ -305,6 +305,7 @@ public: void AllocateResourceSlot(SHADER_TYPE ShaderType, const D3DShaderResourceAttribs& ShaderResAttribs, + SHADER_RESOURCE_VARIABLE_TYPE VariableType, D3D12_DESCRIPTOR_RANGE_TYPE RangeType, Uint32& RootIndex, Uint32& OffsetFromTableStart); diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/ShaderD3D12Impl.h index 674beafb..9227287e 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderD3D12Impl.h @@ -52,6 +52,16 @@ public: virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; + virtual Uint32 GetResourceCount()const override final + { + return m_pShaderResources->GetTotalResources(); + } + + virtual ShaderResourceDesc GetResource(Uint32 Index)const override final + { + return m_pShaderResources->GetShaderResourceDesc(Index); + } + ID3DBlob* GetShaderByteCode(){return m_pShaderByteCode;} const std::shared_ptr& GetShaderResources()const { return m_pShaderResources; } diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h index b45514da..18f03df1 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderResourceBindingD3D12Impl.h @@ -74,9 +74,9 @@ private: 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}; + Int8 m_ResourceLayoutIndex[6] = {-1, -1, -1, -1, -1, -1}; bool m_bStaticResourcesInitialized = false; - const Uint8 m_NumShaders = 0; + const Uint8 m_NumShaders = 0; }; } diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h b/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h index 2ae5c927..26ed260e 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h @@ -108,7 +108,21 @@ namespace Diligent class ShaderResourceLayoutD3D12 final { public: - ShaderResourceLayoutD3D12(IObject& Owner); + + // 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; + // no shader resource cache is provided + ShaderResourceLayoutD3D12(IObject& Owner, + ID3D12Device* pd3d12Device, + const PipelineResourceLayoutDesc& ResourceLayout, + std::shared_ptr pSrcResources, + IMemoryAllocator& LayoutDataAllocator, + const SHADER_RESOURCE_VARIABLE_TYPE* const VarTypes, + Uint32 NumAllowedTypes, + ShaderResourceCacheD3D12* pResourceCache, + class RootSignature* pRootSig); ShaderResourceLayoutD3D12 (const ShaderResourceLayoutD3D12&) = delete; ShaderResourceLayoutD3D12 (ShaderResourceLayoutD3D12&&) = delete; @@ -117,20 +131,6 @@ public: ~ShaderResourceLayoutD3D12(); - // The method is called to - // - 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; - // no shader resource cache is provided - void Initialize(ID3D12Device* pd3d12Device, - const PipelineResourceLayoutDesc& ResourceLayout, - std::shared_ptr pSrcResources, - IMemoryAllocator& LayoutDataAllocator, - const SHADER_RESOURCE_VARIABLE_TYPE* const VarTypes, - Uint32 NumAllowedTypes, - ShaderResourceCacheD3D12* pResourceCache, - class RootSignature* pRootSig); - // sizeof(D3D12Resource) == 24 (x64) struct D3D12Resource final { @@ -327,8 +327,8 @@ private: std::array m_CbvSrvUavOffsets = {}; std::array m_SamplersOffsets = {}; - CComPtr m_pd3d12Device; IObject& m_Owner; + CComPtr m_pd3d12Device; // We must use shared_ptr to reference ShaderResources instance, because // there may be multiple objects referencing the same set of resources std::shared_ptr m_pResources; diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h b/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h index 0b6d2762..85dc30c7 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h @@ -70,16 +70,14 @@ class ShaderVariableD3D12Impl; class ShaderVariableManagerD3D12 { public: - ShaderVariableManagerD3D12(IObject &Owner) : - m_Owner(Owner) - {} + ShaderVariableManagerD3D12(IObject& Owner, + const ShaderResourceLayoutD3D12& Layout, + IMemoryAllocator& Allocator, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes, + ShaderResourceCacheD3D12& ResourceCache); ~ShaderVariableManagerD3D12(); - void Initialize(const ShaderResourceLayoutD3D12& Layout, - IMemoryAllocator& Allocator, - const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - ShaderResourceCacheD3D12& ResourceCache); void Destroy(IMemoryAllocator& Allocator); ShaderVariableD3D12Impl* GetVariable(const Char* Name); @@ -99,13 +97,14 @@ private: Uint32 GetVariableIndex(const ShaderVariableD3D12Impl& Variable); - IObject& m_Owner; - // Variable mgr is owned by either Shader object (in which case m_pResourceLayout points to - // static resource layout owned by the same shader object), or by SRB object (in which case + IObject& m_Owner; + + // Variable mgr is owned by either PSO object (in which case m_pResourceLayout points to + // static resource layout owned by the same PSO object), or by SRB object (in which case // m_pResourceLayout points to corresponding layout in pipeline state). Since SRB keeps strong // reference to PSO, the layout is guaranteed be alive while SRB is alive - const ShaderResourceLayoutD3D12* m_pResourceLayout= nullptr; - ShaderResourceCacheD3D12* m_pResourceCache = nullptr; + const ShaderResourceLayoutD3D12& m_ResourceLayout; + ShaderResourceCacheD3D12& m_ResourceCache; // Memory is allocated through the allocator provided by the pipeline state. If allocation granularity > 1, fixed block // memory allocator is used. This ensures that all resources from different shader resource bindings reside in @@ -114,7 +113,7 @@ private: Uint32 m_NumVariables = 0; #ifdef _DEBUG - IMemoryAllocator* m_pDbgAllocator = nullptr; + IMemoryAllocator& m_DbgAllocator; #endif }; @@ -168,15 +167,13 @@ public: virtual void Set(IDeviceObject *pObject)override final { - VERIFY_EXPR(m_ParentManager.m_pResourceCache != nullptr); - m_Resource.BindResource(pObject, 0, *m_ParentManager.m_pResourceCache); + m_Resource.BindResource(pObject, 0, m_ParentManager.m_ResourceCache); } virtual void SetArray(IDeviceObject* const* ppObjects, Uint32 FirstElement, Uint32 NumElements)override final { - VERIFY_EXPR(m_ParentManager.m_pResourceCache != nullptr); for (Uint32 Elem = 0; Elem < NumElements; ++Elem) - m_Resource.BindResource(ppObjects[Elem], FirstElement + Elem, *m_ParentManager.m_pResourceCache); + m_Resource.BindResource(ppObjects[Elem], FirstElement + Elem, m_ParentManager.m_ResourceCache); } virtual Uint32 GetArraySize()const override final diff --git a/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp index 82c3f587..91835158 100644 --- a/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp @@ -67,17 +67,87 @@ PipelineStateD3D12Impl :: PipelineStateD3D12Impl(IReferenceCounters* pRefCo m_SRBMemAllocator(GetRawAllocator()) { auto pd3d12Device = pDeviceD3D12->GetD3D12Device(); - - m_RootSig.AllocateStaticSamplers( GetShaders(), GetNumShaders() ); + const auto& ResourceLayout = m_Desc.ResourceLayout; + m_RootSig.AllocateStaticSamplers(ResourceLayout); + + { + auto& ShaderResLayoutAllocator = GetRawAllocator(); + auto* pShaderResLayoutRawMem = ALLOCATE(ShaderResLayoutAllocator, "Raw memory for ShaderResourceLayoutD3D12", sizeof(ShaderResourceLayoutD3D12) * m_NumShaders * 2); + m_pShaderResourceLayouts = reinterpret_cast(pShaderResLayoutRawMem); + } + + { + auto& ShaderResCacheAllocator = GetRawAllocator(); + auto* pShaderResCacheRawMem = ALLOCATE(ShaderResCacheAllocator, "Raw memory for ShaderResourceCacheD3D12", sizeof(ShaderResourceCacheD3D12) * m_NumShaders); + m_pStaticResourceCaches = reinterpret_cast(pShaderResCacheRawMem); + } + + { + auto& ShaderVarMgrAllocator = GetRawAllocator(); + auto* pStaticVarsMgrRawMem = ALLOCATE(ShaderVarMgrAllocator, "Raw memory for ShaderVariableManagerD3D12", sizeof(ShaderVariableManagerD3D12) * m_NumShaders); + m_pStaticVarManagers = reinterpret_cast(pStaticVarsMgrRawMem); + } + +#ifdef DEVELOPMENT + { + const ShaderResources* pResources[MaxShadersInPipeline] = {}; + for (Uint32 s = 0; s < m_NumShaders; ++s) + { + const auto* pShader = GetShader(s); + pResources[s] = &(*pShader->GetShaderResources()); + } + ShaderResources::DvpVerifyResourceLayout(ResourceLayout, pResources, m_NumShaders); + } +#endif - auto& ShaderResLayoutAllocator = GetRawAllocator(); - auto* pShaderResLayoutRawMem = ALLOCATE(ShaderResLayoutAllocator, "Raw memory for ShaderResourceLayoutD3D12", sizeof(ShaderResourceLayoutD3D12) * m_NumShaders); - m_pShaderResourceLayouts = reinterpret_cast(pShaderResLayoutRawMem); for (Uint32 s=0; s < m_NumShaders; ++s) { auto* pShaderD3D12 = GetShader(s); - new (m_pShaderResourceLayouts+s) ShaderResourceLayoutD3D12(*this); - m_pShaderResourceLayouts[s].Initialize(pDeviceD3D12->GetD3D12Device(), pShaderD3D12->GetShaderResources(), GetRawAllocator(), nullptr, 0, nullptr, &m_RootSig); + auto ShaderType = pShaderD3D12->GetDesc().ShaderType; + auto ShaderInd = GetShaderTypeIndex(ShaderType); + m_ResourceLayoutIndex[ShaderInd] = static_cast(s); + + new (m_pShaderResourceLayouts+s) + ShaderResourceLayoutD3D12 + { + *this, + pDeviceD3D12->GetD3D12Device(), + ResourceLayout, + pShaderD3D12->GetShaderResources(), + GetRawAllocator(), + nullptr, + 0, + nullptr, + &m_RootSig + }; + + 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 + { + *this, + pDeviceD3D12->GetD3D12Device(), + ResourceLayout, + pShaderD3D12->GetShaderResources(), + GetRawAllocator(), + StaticVarType, + _countof(StaticVarType), + m_pStaticResourceCaches+s, + nullptr + }; + + new (m_pStaticVarManagers+s) + ShaderVariableManagerD3D12 + { + *this, + GetStaticShaderResLayout(s), + GetRawAllocator(), + nullptr, + 0, + GetStaticShaderResCache(s) + }; } m_RootSig.Finalize(pd3d12Device); @@ -221,8 +291,14 @@ PipelineStateD3D12Impl::~PipelineStateD3D12Impl() auto& ShaderResLayoutAllocator = GetRawAllocator(); for(Uint32 s = 0; s < m_NumShaders; ++s) { + m_pStaticVarManagers[s].Destroy(GetRawAllocator()); + m_pStaticVarManagers[s].~ShaderVariableManagerD3D12(); + m_pStaticResourceCaches [s].~ShaderResourceCacheD3D12(); m_pShaderResourceLayouts[s].~ShaderResourceLayoutD3D12(); + m_pShaderResourceLayouts[m_NumShaders+s].~ShaderResourceLayoutD3D12(); } + ShaderResLayoutAllocator.Free(m_pStaticVarManagers); + ShaderResLayoutAllocator.Free(m_pStaticResourceCaches); ShaderResLayoutAllocator.Free(m_pShaderResourceLayouts); // D3D12 object can only be destroyed when it is no longer used by the GPU @@ -366,4 +442,39 @@ bool PipelineStateD3D12Impl::dbgContainsShaderResources()const return false; } +void PipelineStateD3D12Impl::BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags) +{ + for (Uint32 s=0; s < m_NumShaders; ++s) + { + m_pStaticVarManagers[s].BindResources(pResourceMapping, Flags); + } +} + +Uint32 PipelineStateD3D12Impl::GetStaticVariableCount(SHADER_TYPE ShaderType) const +{ + const auto LayoutInd = m_ResourceLayoutIndex[GetShaderTypeIndex(ShaderType)]; + if (LayoutInd < 0) + return 0; + + return m_pStaticVarManagers[LayoutInd].GetVariableCount(); +} + +IShaderResourceVariable* PipelineStateD3D12Impl::GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) +{ + const auto LayoutInd = m_ResourceLayoutIndex[GetShaderTypeIndex(ShaderType)]; + if (LayoutInd < 0) + return nullptr; + + return m_pStaticVarManagers[LayoutInd].GetVariable(Name); +} + +IShaderResourceVariable* PipelineStateD3D12Impl::GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) +{ + const auto LayoutInd = m_ResourceLayoutIndex[GetShaderTypeIndex(ShaderType)]; + if (LayoutInd < 0) + return nullptr; + + return m_pStaticVarManagers[LayoutInd].GetVariable(Index); +} + } diff --git a/Graphics/GraphicsEngineD3D12/src/RenderDeviceD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/RenderDeviceD3D12Impl.cpp index 202b729a..4640daad 100644 --- a/Graphics/GraphicsEngineD3D12/src/RenderDeviceD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/RenderDeviceD3D12Impl.cpp @@ -318,12 +318,12 @@ void RenderDeviceD3D12Impl :: CreateBuffer(const BufferDesc& BuffDesc, const Buf } -void RenderDeviceD3D12Impl :: CreateShader(const ShaderCreationAttribs& ShaderCreationAttribs, IShader** ppShader) +void RenderDeviceD3D12Impl :: CreateShader(const ShaderCreateInfo& ShaderCI, IShader** ppShader) { - CreateDeviceObject( "shader", ShaderCreationAttribs.Desc, ppShader, + CreateDeviceObject( "shader", ShaderCI.Desc, ppShader, [&]() { - ShaderD3D12Impl *pShaderD3D12( NEW_RC_OBJ(m_ShaderObjAllocator, "ShaderD3D12Impl instance", ShaderD3D12Impl)(this, ShaderCreationAttribs ) ); + ShaderD3D12Impl *pShaderD3D12( NEW_RC_OBJ(m_ShaderObjAllocator, "ShaderD3D12Impl instance", ShaderD3D12Impl)(this, ShaderCI ) ); pShaderD3D12->QueryInterface( IID_Shader, reinterpret_cast(ppShader) ); OnCreateDeviceObject( pShaderD3D12 ); diff --git a/Graphics/GraphicsEngineD3D12/src/RootSignature.cpp b/Graphics/GraphicsEngineD3D12/src/RootSignature.cpp index 64da64c9..b5809eb5 100644 --- a/Graphics/GraphicsEngineD3D12/src/RootSignature.cpp +++ b/Graphics/GraphicsEngineD3D12/src/RootSignature.cpp @@ -267,8 +267,8 @@ void RootSignature::InitStaticSampler(SHADER_TYPE ShaderType StreqSuff(SamplerName, StSmplr.SamplerDesc.SamplerOrTextureName, SamplerSuffix)) { StSmplr.ShaderRegister = SamplerAttribs.BindPoint; - StSmplr.ArraySize = SamplerAttribs.BindCount; - StSmplr.RegisterSpace = 0; + StSmplr.ArraySize = SamplerAttribs.BindCount; + StSmplr.RegisterSpace = 0; SamplerFound = true; break; } @@ -283,6 +283,7 @@ 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, + SHADER_RESOURCE_VARIABLE_TYPE VariableType, D3D12_DESCRIPTOR_RANGE_TYPE RangeType, Uint32& RootIndex, // Output parameter Uint32& OffsetFromTableStart // Output parameter @@ -299,12 +300,12 @@ void RootSignature::AllocateResourceSlot(SHADER_TYPE ShaderT OffsetFromTableStart = 0; // Add new root view to existing root parameters - m_RootParams.AddRootView(D3D12_ROOT_PARAMETER_TYPE_CBV, RootIndex, ShaderResAttribs.BindPoint, ShaderVisibility, ShaderResAttribs.GetVariableType()); + m_RootParams.AddRootView(D3D12_ROOT_PARAMETER_TYPE_CBV, RootIndex, ShaderResAttribs.BindPoint, ShaderVisibility, VariableType); } else { // Use the same table for static and mutable resources. Treat both as static - auto RootTableType = (ShaderResAttribs.GetVariableType() == SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) ? SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC : SHADER_RESOURCE_VARIABLE_TYPE_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; // Get the table array index (this is not the root index!) auto& RootTableArrayInd = (( RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER ) ? m_SamplerRootTablesMap : m_SrvCbvUavRootTablesMap)[ TableIndKey ]; @@ -411,23 +412,22 @@ void RootSignature::dbgVerifyRootParameters()const } #endif -void RootSignature::AllocateStaticSamplers(IShader* const* ppShaders, Uint32 NumShaders) +void RootSignature::AllocateStaticSamplers(const PipelineResourceLayoutDesc& ResourceLayout) { - Uint32 TotalSamplers = 0; - for(Uint32 s=0;s < NumShaders; ++s) - TotalSamplers += ppShaders[s]->GetDesc().NumStaticSamplers; - if (TotalSamplers > 0) + if (ResourceLayout.NumStaticSamplers > 0) { - m_StaticSamplers.reserve(TotalSamplers); - for(Uint32 sh=0;sh < NumShaders; ++sh) + m_StaticSamplers.reserve(ResourceLayout.NumStaticSamplers); + for(Uint32 sam=0; sam < ResourceLayout.NumStaticSamplers; ++sam) { - const auto& Desc = ppShaders[sh]->GetDesc(); - for(Uint32 sam=0; sam < Desc.NumStaticSamplers; ++sam) + const auto& StSamDesc = ResourceLayout.StaticSamplers[sam]; + Uint32 ShaderStages = StSamDesc.ShaderStages; + while (ShaderStages != 0) { - m_StaticSamplers.emplace_back(Desc.StaticSamplers[sam], GetShaderVisibility(Desc.ShaderType)); + auto Stage = ShaderStages & ~(ShaderStages-1); + m_StaticSamplers.emplace_back(StSamDesc, GetShaderVisibility(static_cast(Stage))); + ShaderStages &= ~Stage; } } - VERIFY_EXPR(m_StaticSamplers.size() == TotalSamplers); } } diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderResourceBindingD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderResourceBindingD3D12Impl.cpp index b8d46dbb..644eb1ff 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderResourceBindingD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderResourceBindingD3D12Impl.cpp @@ -52,15 +52,22 @@ ShaderResourceBindingD3D12Impl::ShaderResourceBindingD3D12Impl(IReferenceCounter auto ShaderType = pShader->GetDesc().ShaderType; auto ShaderInd = GetShaderTypeIndex(ShaderType); - // Create shader variable manager in place - new (m_pShaderVarMgrs + s) ShaderVariableManagerD3D12(*this); - 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 - std::array AllowedVarTypes = { SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC }; + const SHADER_RESOURCE_VARIABLE_TYPE AllowedVarTypes[] = { SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC }; const auto& SrcLayout = pPSO->GetShaderResLayout(s); - m_pShaderVarMgrs[s].Initialize(SrcLayout, VarDataAllocator, AllowedVarTypes.data(), static_cast(AllowedVarTypes.size()), m_ShaderResourceCache); + // Create shader variable manager in place + new (m_pShaderVarMgrs + s) + ShaderVariableManagerD3D12 + { + *this, + SrcLayout, + VarDataAllocator, + AllowedVarTypes, + _countof(AllowedVarTypes), + m_ShaderResourceCache + }; m_ResourceLayoutIndex[ShaderInd] = static_cast(s); } @@ -173,23 +180,22 @@ void ShaderResourceBindingD3D12Impl::InitializeStaticResources(const IPipelineSt auto* pPSO12 = ValidatedCast(pPSO); auto NumShaders = pPSO12->GetNumShaders(); - auto ppShaders = pPSO12->GetShaders(); // Copy static resources for (Uint32 s = 0; s < NumShaders; ++s) { - auto* pShader = ValidatedCast( ppShaders[s] ); + const auto& ShaderResLayout = pPSO12->GetShaderResLayout(s); + auto& StaticResLayout = pPSO12->GetStaticShaderResLayout(s); + auto& StaticResCache = pPSO12->GetStaticShaderResCache(s); #ifdef DEVELOPMENT - if (!pShader->DvpVerifyStaticResourceBindings()) + 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 the shader before calling InitializeStaticResources() " "directly or indirectly by passing InitStaticResources=true to CreateShaderResourceBinding() method."); } #endif - const auto& ShaderResLayout = pPSO12->GetShaderResLayout(s); - auto& StaticResLayout = pShader->GetStaticResLayout(); - auto& StaticResCache = pShader->GetStaticResCache(); StaticResLayout.CopyStaticResourceDesriptorHandles(StaticResCache, ShaderResLayout, m_ShaderResourceCache); } diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp index ca133acc..de7458b6 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp @@ -38,11 +38,6 @@ namespace Diligent { -ShaderResourceLayoutD3D12::ShaderResourceLayoutD3D12(IObject& Owner) : - m_Owner(Owner) -{ -} - ShaderResourceLayoutD3D12::~ShaderResourceLayoutD3D12() { for(Uint32 r=0; r < GetTotalResourceCount(); ++r) @@ -111,18 +106,19 @@ void ShaderResourceLayoutD3D12::AllocateMemory(IMemoryAllocator& // http://diligentgraphics.com/diligent-engine/architecture/d3d12/shader-resource-layout#Initializing-Shader-Resource-Layouts-and-Root-Signature-in-a-Pipeline-State-Object // http://diligentgraphics.com/diligent-engine/architecture/d3d12/shader-resource-cache#Initializing-Shader-Resource-Layouts-in-a-Pipeline-State -void ShaderResourceLayoutD3D12::Initialize(ID3D12Device* pd3d12Device, - const PipelineResourceLayoutDesc& ResourceLayout, - std::shared_ptr pSrcResources, - IMemoryAllocator& LayoutDataAllocator, - const SHADER_RESOURCE_VARIABLE_TYPE* const AllowedVarTypes, - Uint32 NumAllowedTypes, - ShaderResourceCacheD3D12* pResourceCache, - RootSignature* pRootSig) +ShaderResourceLayoutD3D12::ShaderResourceLayoutD3D12(IObject& Owner, + ID3D12Device* pd3d12Device, + const PipelineResourceLayoutDesc& ResourceLayout, + std::shared_ptr pSrcResources, + IMemoryAllocator& LayoutDataAllocator, + const SHADER_RESOURCE_VARIABLE_TYPE* const AllowedVarTypes, + Uint32 NumAllowedTypes, + ShaderResourceCacheD3D12* pResourceCache, + RootSignature* pRootSig) : + m_Owner (Owner), + m_pd3d12Device (pd3d12Device), + m_pResources (std::move(pSrcResources)) { - m_pResources = std::move(pSrcResources); - m_pd3d12Device = pd3d12Device; - VERIFY_EXPR( (pResourceCache != nullptr) ^ (pRootSig != nullptr) ); const Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); @@ -155,10 +151,9 @@ void ShaderResourceLayoutD3D12::Initialize(ID3D12Device* if (IsAllowedType(VarType, AllowedTypeBits)) { ++CbvSrvUavCount[VarType]; - if (TexSRV.ValidSamplerAssigned()) + if (TexSRV.IsCombinedWithSampler()) { - auto SamplerId = TexSRV.GetSamplerId(); - const auto& SamplerAttribs = m_pResources->GetSampler(SamplerId); + const auto& SamplerAttribs = m_pResources->GetCombinedSampler(TexSRV); auto SamplerVarType = m_pResources->FindVariableType(SamplerAttribs, ResourceLayout); DEV_CHECK_ERR(SamplerVarType == VarType, "The type (", GetShaderVariableTypeLiteralName(VarType),") of texture SRV variable '", TexSRV.Name, @@ -203,7 +198,7 @@ void ShaderResourceLayoutD3D12::Initialize(ID3D12Device* D3D12_DESCRIPTOR_RANGE_TYPE DescriptorRangeType = GetDescriptorRangeType(ResType); if (pRootSig) { - pRootSig->AllocateResourceSlot(m_pResources->GetShaderType(), Attribs, DescriptorRangeType, RootIndex, Offset ); + pRootSig->AllocateResourceSlot(m_pResources->GetShaderType(), Attribs, VarType, DescriptorRangeType, RootIndex, Offset ); VERIFY(RootIndex <= D3D12Resource::MaxRootIndex, "Root index excceeds allowed limit"); } else @@ -268,9 +263,9 @@ void ShaderResourceLayoutD3D12::Initialize(ID3D12Device* 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.ValidSamplerAssigned()) + if (TexSRV.IsCombinedWithSampler()) { - const auto& SamplerAttribs = m_pResources->GetSampler(TexSRV.GetSamplerId()); + const auto& SamplerAttribs = m_pResources->GetCombinedSampler(TexSRV); auto SamplerVarType = m_pResources->FindVariableType(SamplerAttribs, ResourceLayout); DEV_CHECK_ERR(SamplerVarType == VarType, "The type (", GetShaderVariableTypeLiteralName(VarType),") of texture SRV variable '", TexSRV.Name, @@ -283,9 +278,9 @@ void ShaderResourceLayoutD3D12::Initialize(ID3D12Device* // Static samplers are never copied, and SamplerId == InvalidSamplerId #ifdef _DEBUG auto SamplerCount = GetTotalSamplerCount(); - for (SamplerId = 0; SamplerId < SamplerCount; ++SamplerId) + for (Uint32 s = 0; s < SamplerCount; ++s) { - const auto& Sampler = GetSampler(SamplerId); + const auto& Sampler = GetSampler(s); if (strcmp(Sampler.Attribs.Name, SamplerAttribs.Name) == 0) LOG_ERROR("Static sampler '", Sampler.Attribs.Name, "' was found among resources. This seems to be a bug"); } @@ -294,14 +289,16 @@ void ShaderResourceLayoutD3D12::Initialize(ID3D12Device* else { auto SamplerCount = GetTotalSamplerCount(); + bool SamplerFound = false; for (SamplerId = 0; SamplerId < SamplerCount; ++SamplerId) { const auto& Sampler = GetSampler(SamplerId); - if (strcmp(Sampler.Attribs.Name, SamplerAttribs.Name) == 0) + SamplerFound = strcmp(Sampler.Attribs.Name, SamplerAttribs.Name) == 0; + if (SamplerFound) break; } - if (SamplerId == SamplerCount) + if (!SamplerFound) { LOG_ERROR("Unable to find sampler '", SamplerAttribs.Name, "' assigned to texture SRV '", TexSRV.Name, "' in the list of already created resources. This seems to be a bug."); SamplerId = D3D12Resource::InvalidSamplerId; diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp index 877a270d..3c14c461 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp @@ -50,18 +50,20 @@ size_t ShaderVariableManagerD3D12::GetRequiredMemorySize(const ShaderResourceLay } // Creates shader variable for every resource from SrcLayout whose type is one AllowedVarTypes -void ShaderVariableManagerD3D12::Initialize(const ShaderResourceLayoutD3D12& SrcLayout, - IMemoryAllocator& Allocator, - const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes, - ShaderResourceCacheD3D12& ResourceCache) -{ - m_pResourceLayout = &SrcLayout; - m_pResourceCache = &ResourceCache; +ShaderVariableManagerD3D12::ShaderVariableManagerD3D12(IObject& Owner, + const ShaderResourceLayoutD3D12& SrcLayout, + IMemoryAllocator& Allocator, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes, + ShaderResourceCacheD3D12& ResourceCache) : + m_Owner (Owner), + m_ResourceLayout (SrcLayout), + m_ResourceCache (ResourceCache) #ifdef _DEBUG - m_pDbgAllocator = &Allocator; + , m_DbgAllocator(Allocator) #endif +{ const Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); VERIFY_EXPR(m_NumVariables == 0); auto MemSize = GetRequiredMemorySize(SrcLayout, AllowedVarTypes, NumAllowedTypes, m_NumVariables); @@ -107,7 +109,7 @@ ShaderVariableManagerD3D12::~ShaderVariableManagerD3D12() void ShaderVariableManagerD3D12::Destroy(IMemoryAllocator &Allocator) { - VERIFY(m_pDbgAllocator == &Allocator, "Incosistent alloctor"); + VERIFY(&m_DbgAllocator == &Allocator, "Incosistent alloctor"); if(m_pVariables != nullptr) { @@ -167,7 +169,6 @@ Uint32 ShaderVariableManagerD3D12::GetVariableIndex(const ShaderVariableD3D12Imp void ShaderVariableManagerD3D12::BindResources( IResourceMapping* pResourceMapping, Uint32 Flags) { - VERIFY_EXPR(m_pResourceCache != nullptr); DEV_CHECK_ERR(pResourceMapping != nullptr, "Failed to bind resources: resource mapping is null"); if ( (Flags & BIND_SHADER_RESOURCES_UPDATE_ALL) == 0 ) @@ -183,7 +184,7 @@ void ShaderVariableManagerD3D12::BindResources( IResourceMapping* pResourceMappi for (Uint32 ArrInd = 0; ArrInd < Res.Attribs.BindCount; ++ArrInd) { - if( (Flags & BIND_SHADER_RESOURCES_KEEP_EXISTING) && Res.IsBound(ArrInd, *m_pResourceCache) ) + if( (Flags & BIND_SHADER_RESOURCES_KEEP_EXISTING) && Res.IsBound(ArrInd, m_ResourceCache) ) continue; RefCntAutoPtr pObj; @@ -192,11 +193,11 @@ void ShaderVariableManagerD3D12::BindResources( IResourceMapping* pResourceMappi if ( pObj ) { // Call non-virtual function - Res.BindResource(pObj, ArrInd, *m_pResourceCache); + Res.BindResource(pObj, ArrInd, m_ResourceCache); } else { - if( (Flags & BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED) && !Res.IsBound(ArrInd, *m_pResourceCache) ) + 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" ); } } diff --git a/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h b/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h index 7bfd2cfd..f8f6917b 100644 --- a/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h +++ b/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h @@ -126,7 +126,7 @@ public: VERIFY(_SamplerId < (1 << SamplerOrTexSRVIdBits), "SamplerOrTexSRVId is out of representable range"); if (_InputType == D3D_SIT_TEXTURE && _SRVDimension != D3D_SRV_DIMENSION_BUFFER) - VERIFY_EXPR(GetSamplerId() == _SamplerId); + VERIFY_EXPR(GetCombinedSamplerId() == _SamplerId); else VERIFY(_SamplerId == InvalidSamplerId, "Only texture SRV can be assigned a valid texture sampler"); #endif @@ -174,33 +174,14 @@ public: return static_cast(SRVDimension); } - Uint32 GetSamplerId()const + bool IsCombinedWithSampler()const { - VERIFY(GetInputType() == D3D_SIT_TEXTURE && GetSRVDimension() != D3D_SRV_DIMENSION_BUFFER, "Invalid input type: D3D_SIT_TEXTURE is expected" ); - return SamplerOrTexSRVId; - } - - void SetTexSRVId(Uint32 TexSRVId) - { - VERIFY(GetInputType() == D3D_SIT_SAMPLER, "Invalid input type: D3D_SIT_SAMPLER is expected" ); - VERIFY(TexSRVId < (1 << SamplerOrTexSRVIdBits), "TexSRVId (", TexSRVId, ") is out of representable range"); - SamplerOrTexSRVId = TexSRVId; - } - - Uint32 GetTexSRVId()const - { - VERIFY(GetInputType() == D3D_SIT_SAMPLER, "Invalid input type: D3D_SIT_SAMPLER is expected" ); - return SamplerOrTexSRVId; - } - - bool ValidSamplerAssigned()const - { - return GetSamplerId() != InvalidSamplerId; + return GetCombinedSamplerId() != InvalidSamplerId; } - bool ValidTexSRVAssigned()const + bool IsCombinedWithTexSRV()const { - return GetTexSRVId() != InvalidTexSRVId; + return GetCombinedTexSRVId() != InvalidTexSRVId; } bool IsValidBindPoint()const @@ -230,6 +211,29 @@ public: { return ComputeHash(BindPoint, BindCount, InputType, SRVDimension, SamplerOrTexSRVId); } + + +private: + friend class ShaderResources; + + Uint32 GetCombinedSamplerId()const + { + VERIFY(GetInputType() == D3D_SIT_TEXTURE && GetSRVDimension() != D3D_SRV_DIMENSION_BUFFER, "Invalid input type: D3D_SIT_TEXTURE is expected" ); + return SamplerOrTexSRVId; + } + + void SetTexSRVId(Uint32 TexSRVId) + { + VERIFY(GetInputType() == D3D_SIT_SAMPLER, "Invalid input type: D3D_SIT_SAMPLER is expected" ); + VERIFY(TexSRVId < (1 << SamplerOrTexSRVIdBits), "TexSRVId (", TexSRVId, ") is out of representable range"); + SamplerOrTexSRVId = TexSRVId; + } + + Uint32 GetCombinedTexSRVId()const + { + VERIFY(GetInputType() == D3D_SIT_SAMPLER, "Invalid input type: D3D_SIT_SAMPLER is expected" ); + return SamplerOrTexSRVId; + } }; static_assert(sizeof(D3DShaderResourceAttribs) == sizeof(void*) + sizeof(Uint32)*2, "Unexpected sizeof(D3DShaderResourceAttribs)"); @@ -265,6 +269,18 @@ public: const D3DShaderResourceAttribs& GetBufUAV (Uint32 n)const noexcept { return GetResAttribs(n, GetNumBufUAV(), m_BufUAVOffset); } const D3DShaderResourceAttribs& GetSampler(Uint32 n)const noexcept { return GetResAttribs(n, GetNumSamplers(), m_SamplersOffset); } + const D3DShaderResourceAttribs& GetCombinedSampler(const D3DShaderResourceAttribs& TexSRV)const noexcept + { + VERIFY(TexSRV.IsCombinedWithSampler(), "This texture SRV is not combined with any sampler"); + return GetSampler(TexSRV.GetCombinedSamplerId()); + } + + const D3DShaderResourceAttribs& GetCombinedTextureSRV(const D3DShaderResourceAttribs& Sampler)const noexcept + { + VERIFY(Sampler.IsCombinedWithTexSRV(), "This sampler is not combined with any texture SRV"); + return GetTexSRV(Sampler.GetCombinedTexSRVId()); + } + SHADER_TYPE GetShaderType()const noexcept{return m_ShaderType;} ShaderResourceDesc GetShaderResourceDesc(Uint32 Index)const; @@ -486,7 +502,7 @@ void ShaderResources::Initialize(ID3DBlob* pShaderByteCode, for (Uint32 n=0; n < GetNumSamplers(); ++n) { const auto& Sampler = GetSampler(n); - if (!Sampler.ValidTexSRVAssigned()) + if (!Sampler.IsCombinedWithTexSRV()) LOG_ERROR_MESSAGE("Shader '", ShaderName, "' uses combined texture samplers, but sampler '", Sampler.Name, "' is not assigned to any texture"); } #endif -- cgit v1.2.3 From f551f6353eaf4efe9b7f26d48822b96ebb0706a0 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Mon, 4 Mar 2019 22:38:04 -0800 Subject: Updated D3D11, D3D12, and Vk EngineFactory headers & structures --- Graphics/GraphicsEngine/interface/GraphicsTypes.h | 45 ++- Graphics/GraphicsEngineD3D11/CMakeLists.txt | 5 +- .../include/DeviceContextD3D11Impl.h | 12 +- .../include/RenderDeviceD3D11Impl.h | 13 +- .../interface/EngineD3D11Attribs.h | 70 ---- .../interface/EngineFactoryD3D11.h | 129 ++++++ .../interface/RenderDeviceFactoryD3D11.h | 131 ------ Graphics/GraphicsEngineD3D11/readme.md | 2 +- .../src/DeviceContextD3D11Impl.cpp | 13 +- .../GraphicsEngineD3D11/src/EngineFactoryD3D11.cpp | 382 ++++++++++++++++++ .../src/RenderDeviceD3D11Impl.cpp | 10 +- .../src/RenderDeviceFactoryD3D11.cpp | 382 ------------------ Graphics/GraphicsEngineD3D12/CMakeLists.txt | 4 +- .../include/DeviceContextD3D12Impl.h | 12 +- .../include/RenderDeviceD3D12Impl.h | 16 +- .../interface/EngineFactoryD3D12.h | 133 +++++++ .../interface/RenderDeviceFactoryD3D12.h | 133 ------- Graphics/GraphicsEngineD3D12/readme.md | 2 +- .../src/DeviceContextD3D12Impl.cpp | 20 +- .../GraphicsEngineD3D12/src/EngineFactoryD3D12.cpp | 438 +++++++++++++++++++++ .../src/RenderDeviceD3D12Impl.cpp | 30 +- .../src/RenderDeviceFactoryD3D12.cpp | 438 --------------------- .../src/ShaderResourceLayoutD3D12.cpp | 2 +- Graphics/GraphicsEngineVulkan/CMakeLists.txt | 4 +- .../include/DeviceContextVkImpl.h | 2 +- .../include/RenderDeviceVkImpl.h | 12 +- .../interface/EngineFactoryVk.h | 128 ++++++ .../interface/RenderDeviceFactoryVk.h | 128 ------ .../src/DeviceContextVkImpl.cpp | 20 +- .../GraphicsEngineVulkan/src/EngineFactoryVk.cpp | 372 +++++++++++++++++ .../src/RenderDeviceFactoryVk.cpp | 372 ----------------- .../src/RenderDeviceVkImpl.cpp | 52 +-- .../src/ShaderResourceLayoutVk.cpp | 2 +- .../GraphicsEngineVulkan/src/VulkanDynamicHeap.cpp | 8 +- 34 files changed, 1743 insertions(+), 1779 deletions(-) delete mode 100644 Graphics/GraphicsEngineD3D11/interface/EngineD3D11Attribs.h create mode 100644 Graphics/GraphicsEngineD3D11/interface/EngineFactoryD3D11.h delete mode 100644 Graphics/GraphicsEngineD3D11/interface/RenderDeviceFactoryD3D11.h create mode 100644 Graphics/GraphicsEngineD3D11/src/EngineFactoryD3D11.cpp delete mode 100644 Graphics/GraphicsEngineD3D11/src/RenderDeviceFactoryD3D11.cpp create mode 100644 Graphics/GraphicsEngineD3D12/interface/EngineFactoryD3D12.h delete mode 100644 Graphics/GraphicsEngineD3D12/interface/RenderDeviceFactoryD3D12.h create mode 100644 Graphics/GraphicsEngineD3D12/src/EngineFactoryD3D12.cpp delete mode 100644 Graphics/GraphicsEngineD3D12/src/RenderDeviceFactoryD3D12.cpp create mode 100644 Graphics/GraphicsEngineVulkan/interface/EngineFactoryVk.h delete mode 100644 Graphics/GraphicsEngineVulkan/interface/RenderDeviceFactoryVk.h create mode 100644 Graphics/GraphicsEngineVulkan/src/EngineFactoryVk.cpp delete mode 100644 Graphics/GraphicsEngineVulkan/src/RenderDeviceFactoryVk.cpp (limited to 'Graphics') diff --git a/Graphics/GraphicsEngine/interface/GraphicsTypes.h b/Graphics/GraphicsEngine/interface/GraphicsTypes.h index d402fb18..2cc9024b 100644 --- a/Graphics/GraphicsEngine/interface/GraphicsTypes.h +++ b/Graphics/GraphicsEngine/interface/GraphicsTypes.h @@ -1242,7 +1242,7 @@ namespace Diligent }; /// Engine creation attibutes - struct EngineCreationAttribs + struct EngineCreateInfo { /// Pointer to the raw memory allocator that will be used for all memory allocation/deallocation /// operations in the engine @@ -1252,8 +1252,47 @@ namespace Diligent DebugMessageCallbackType DebugMessageCallback = nullptr; }; + + /// Debug flags that can be specified when creating Direct3D11-based engine implementation. + /// + /// \sa CreateDeviceAndContextsD3D11Type, CreateSwapChainD3D11Type, LoadGraphicsEngineD3D11 + enum class EngineD3D11DebugFlags : Uint32 + { + /// Before executing draw/dispatch command, verify that + /// all required shader resources are bound to the device context + VerifyCommittedShaderResources = 0x01, + + /// Verify that all committed cotext resources are relevant, + /// i.e. they are consistent with the committed resource cache. + /// This is very expensive operation and should generally not be + /// necessary. + VerifyCommittedResourceRelevance = 0x02 + }; + + /// Attributes specific to D3D11 engine + struct EngineD3D11CreateInfo : public EngineCreateInfo + { + static constexpr Uint32 DefaultAdapterId = 0xFFFFFFFF; + + /// Id of the hardware adapter the engine should be initialized on + Uint32 AdapterId = DefaultAdapterId; + + /// Debug flags. See Diligent::EngineD3D11DebugFlags for a list of allowed values. + /// + /// \sa CreateDeviceAndContextsD3D11Type, CreateSwapChainD3D11Type, LoadGraphicsEngineD3D11 + Uint32 DebugFlags; + + EngineD3D11CreateInfo() : + DebugFlags(0) + { +#ifdef _DEBUG + DebugFlags = static_cast(EngineD3D11DebugFlags::VerifyCommittedShaderResources); +#endif + } + }; + /// Attributes specific to D3D12 engine - struct EngineD3D12Attribs : public EngineCreationAttribs + struct EngineD3D12CreateInfo : public EngineCreateInfo { static constexpr Uint32 DefaultAdapterId = 0xFFFFFFFF; @@ -1310,7 +1349,7 @@ namespace Diligent }; /// Attributes specific to Vulkan engine - struct EngineVkAttribs : public EngineCreationAttribs + struct EngineVkCreateInfo : public EngineCreateInfo { /// Enable validation layers. Validation is always enabled in Debug mode bool EnableValidation = false; diff --git a/Graphics/GraphicsEngineD3D11/CMakeLists.txt b/Graphics/GraphicsEngineD3D11/CMakeLists.txt index b263d602..f54fa680 100644 --- a/Graphics/GraphicsEngineD3D11/CMakeLists.txt +++ b/Graphics/GraphicsEngineD3D11/CMakeLists.txt @@ -34,11 +34,10 @@ set(INTERFACE interface/BufferD3D11.h interface/BufferViewD3D11.h interface/DeviceContextD3D11.h - interface/EngineD3D11Attribs.h + interface/EngineFactoryD3D11.h interface/FenceD3D11.h interface/PipelineStateD3D11.h interface/RenderDeviceD3D11.h - interface/RenderDeviceFactoryD3D11.h interface/SamplerD3D11.h interface/ShaderD3D11.h interface/ShaderResourceBindingD3D11.h @@ -54,11 +53,11 @@ set(SRC src/CommandListD3D11Impl.cpp src/D3D11TypeConversions.cpp src/DeviceContextD3D11Impl.cpp + src/EngineFactoryD3D11.cpp src/FenceD3D11Impl.cpp src/GUIDDef.cpp src/PipelineStateD3D11Impl.cpp src/RenderDeviceD3D11Impl.cpp - src/RenderDeviceFactoryD3D11.cpp src/SamplerD3D11Impl.cpp src/ShaderD3D11Impl.cpp src/ShaderResourceBindingD3D11Impl.cpp diff --git a/Graphics/GraphicsEngineD3D11/include/DeviceContextD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/DeviceContextD3D11Impl.h index d9a0e44d..01a54eeb 100755 --- a/Graphics/GraphicsEngineD3D11/include/DeviceContextD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/DeviceContextD3D11Impl.h @@ -53,12 +53,12 @@ class DeviceContextD3D11Impl final : public DeviceContextBase; - DeviceContextD3D11Impl(IReferenceCounters* pRefCounters, - IMemoryAllocator& Allocator, - IRenderDevice* pDevice, - ID3D11DeviceContext* pd3d11DeviceContext, - const struct EngineD3D11Attribs& EngineAttribs, - bool bIsDeferred); + DeviceContextD3D11Impl(IReferenceCounters* pRefCounters, + IMemoryAllocator& Allocator, + IRenderDevice* pDevice, + ID3D11DeviceContext* pd3d11DeviceContext, + const struct EngineD3D11CreateInfo& EngineAttribs, + bool bIsDeferred); virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual void SetPipelineState(IPipelineState* pPipelineState)override final; diff --git a/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h index 87189352..b325554f 100644 --- a/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h @@ -29,7 +29,6 @@ #include "RenderDeviceD3D11.h" #include "RenderDeviceD3DBase.h" #include "DeviceContextD3D11.h" -#include "EngineD3D11Attribs.h" namespace Diligent { @@ -40,11 +39,11 @@ class RenderDeviceD3D11Impl final : public RenderDeviceD3DBase; - RenderDeviceD3D11Impl( IReferenceCounters* pRefCounters, - IMemoryAllocator& RawMemAllocator, - const EngineD3D11Attribs& EngineAttribs, - ID3D11Device* pd3d11Device, - Uint32 NumDeferredContexts ); + RenderDeviceD3D11Impl( IReferenceCounters* pRefCounters, + IMemoryAllocator& RawMemAllocator, + const EngineD3D11CreateInfo& EngineAttribs, + ID3D11Device* pd3d11Device, + Uint32 NumDeferredContexts ); virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; virtual void CreateBuffer(const BufferDesc& BuffDesc, const BufferData* pBuffData, IBuffer** ppBuffer)override final; @@ -74,7 +73,7 @@ public: private: virtual void TestTextureFormat( TEXTURE_FORMAT TexFormat )override final; - EngineD3D11Attribs m_EngineAttribs; + EngineD3D11CreateInfo m_EngineAttribs; /// D3D11 device CComPtr m_pd3d11Device; diff --git a/Graphics/GraphicsEngineD3D11/interface/EngineD3D11Attribs.h b/Graphics/GraphicsEngineD3D11/interface/EngineD3D11Attribs.h deleted file mode 100644 index a5208ef5..00000000 --- a/Graphics/GraphicsEngineD3D11/interface/EngineD3D11Attribs.h +++ /dev/null @@ -1,70 +0,0 @@ -/* Copyright 2015-2019 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -/// \file -/// Definition of the Engine D3D11 attribs - -#include "../../GraphicsEngine/interface/GraphicsTypes.h" - -namespace Diligent -{ - /// Debug flags that can be specified when creating Direct3D11-based engine implementation. - /// - /// \sa CreateDeviceAndContextsD3D11Type, CreateSwapChainD3D11Type, LoadGraphicsEngineD3D11 - enum class EngineD3D11DebugFlags : Uint32 - { - /// Before executing draw/dispatch command, verify that - /// all required shader resources are bound to the device context - VerifyCommittedShaderResources = 0x01, - - /// Verify that all committed cotext resources are relevant, - /// i.e. they are consistent with the committed resource cache. - /// This is very expensive operation and should generally not be - /// necessary. - VerifyCommittedResourceRelevance = 0x02 - }; - - /// Attributes of the Direct3D11-based engine implementation - struct EngineD3D11Attribs : public EngineCreationAttribs - { - static constexpr Uint32 DefaultAdapterId = 0xFFFFFFFF; - - /// Id of the hardware adapter the engine should be initialized on - Uint32 AdapterId = DefaultAdapterId; - - /// Debug flags. See Diligent::EngineD3D11DebugFlags for a list of allowed values. - /// - /// \sa CreateDeviceAndContextsD3D11Type, CreateSwapChainD3D11Type, LoadGraphicsEngineD3D11 - Uint32 DebugFlags; - - EngineD3D11Attribs() : - DebugFlags(0) - { - #ifdef _DEBUG - DebugFlags = static_cast(EngineD3D11DebugFlags::VerifyCommittedShaderResources); - #endif - } - }; -} diff --git a/Graphics/GraphicsEngineD3D11/interface/EngineFactoryD3D11.h b/Graphics/GraphicsEngineD3D11/interface/EngineFactoryD3D11.h new file mode 100644 index 00000000..dceab777 --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/interface/EngineFactoryD3D11.h @@ -0,0 +1,129 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +/// \file +/// Declaration of functions that initialize Direct3D11-based engine implementation + +#include + +#include "../../GraphicsEngine/interface/RenderDevice.h" +#include "../../GraphicsEngine/interface/DeviceContext.h" +#include "../../GraphicsEngine/interface/SwapChain.h" + +#if PLATFORM_UNIVERSAL_WINDOWS && defined(ENGINE_DLL) +# include "../../../Common/interface/StringTools.h" +#endif + +namespace Diligent +{ + +class IEngineFactoryD3D11 +{ +public: + virtual void CreateDeviceAndContextsD3D11(const EngineD3D11CreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts ) = 0; + + virtual void CreateSwapChainD3D11( IRenderDevice* pDevice, + IDeviceContext* pImmediateContext, + const SwapChainDesc& SCDesc, + const FullScreenModeDesc& FSDesc, + void* pNativeWndHandle, + ISwapChain** ppSwapChain ) = 0; + + virtual void AttachToD3D11Device(void* pd3d11NativeDevice, + void* pd3d11ImmediateContext, + const EngineD3D11CreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts) = 0; + + virtual void EnumerateHardwareAdapters(Uint32& NumAdapters, + HardwareAdapterAttribs* Adapters) = 0; + + virtual void EnumerateDisplayModes(Uint32 AdapterId, + Uint32 OutputId, + TEXTURE_FORMAT Format, + Uint32& NumDisplayModes, + DisplayModeAttribs* DisplayModes) = 0; +}; + +#if ENGINE_DLL + + typedef IEngineFactoryD3D11* (*GetEngineFactoryD3D11Type)(); + + static bool LoadGraphicsEngineD3D11(GetEngineFactoryD3D11Type &GetFactoryFunc) + { + GetFactoryFunc = nullptr; + std::string LibName = "GraphicsEngineD3D11_"; + +#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 ) + { + std::stringstream ss; + ss << "Failed to load " << LibName << " library.\n"; + OutputDebugStringA(ss.str().c_str()); + return false; + } + + GetFactoryFunc = reinterpret_cast( GetProcAddress(hModule, "GetEngineFactoryD3D11") ); + if( GetFactoryFunc == NULL ) + { + std::stringstream ss; + ss << "Failed to load GetEngineFactoryD3D11() from " << LibName << " library.\n"; + OutputDebugStringA(ss.str().c_str()); + FreeLibrary( hModule ); + return false; + } + + return true; + } +#else + + IEngineFactoryD3D11* GetEngineFactoryD3D11(); + +#endif + +} diff --git a/Graphics/GraphicsEngineD3D11/interface/RenderDeviceFactoryD3D11.h b/Graphics/GraphicsEngineD3D11/interface/RenderDeviceFactoryD3D11.h deleted file mode 100644 index a4dd8476..00000000 --- a/Graphics/GraphicsEngineD3D11/interface/RenderDeviceFactoryD3D11.h +++ /dev/null @@ -1,131 +0,0 @@ -/* Copyright 2015-2019 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -/// \file -/// Declaration of functions that initialize Direct3D11-based engine implementation - -#include - -#include "../../GraphicsEngine/interface/RenderDevice.h" -#include "../../GraphicsEngine/interface/DeviceContext.h" -#include "../../GraphicsEngine/interface/SwapChain.h" - -#if PLATFORM_UNIVERSAL_WINDOWS && defined(ENGINE_DLL) -# include "../../../Common/interface/StringTools.h" -#endif - -#include "EngineD3D11Attribs.h" - -namespace Diligent -{ - -class IEngineFactoryD3D11 -{ -public: - virtual void CreateDeviceAndContextsD3D11( const EngineD3D11Attribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts ) = 0; - - virtual void CreateSwapChainD3D11( IRenderDevice* pDevice, - IDeviceContext* pImmediateContext, - const SwapChainDesc& SCDesc, - const FullScreenModeDesc& FSDesc, - void* pNativeWndHandle, - ISwapChain** ppSwapChain ) = 0; - - virtual void AttachToD3D11Device(void* pd3d11NativeDevice, - void* pd3d11ImmediateContext, - const EngineD3D11Attribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts) = 0; - - virtual void EnumerateHardwareAdapters(Uint32& NumAdapters, - HardwareAdapterAttribs* Adapters) = 0; - - virtual void EnumerateDisplayModes(Uint32 AdapterId, - Uint32 OutputId, - TEXTURE_FORMAT Format, - Uint32& NumDisplayModes, - DisplayModeAttribs* DisplayModes) = 0; -}; - -#if ENGINE_DLL - - typedef IEngineFactoryD3D11* (*GetEngineFactoryD3D11Type)(); - - static bool LoadGraphicsEngineD3D11(GetEngineFactoryD3D11Type &GetFactoryFunc) - { - GetFactoryFunc = nullptr; - std::string LibName = "GraphicsEngineD3D11_"; - -#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 ) - { - std::stringstream ss; - ss << "Failed to load " << LibName << " library.\n"; - OutputDebugStringA(ss.str().c_str()); - return false; - } - - GetFactoryFunc = reinterpret_cast( GetProcAddress(hModule, "GetEngineFactoryD3D11") ); - if( GetFactoryFunc == NULL ) - { - std::stringstream ss; - ss << "Failed to load GetEngineFactoryD3D11() from " << LibName << " library.\n"; - OutputDebugStringA(ss.str().c_str()); - FreeLibrary( hModule ); - return false; - } - - return true; - } -#else - - IEngineFactoryD3D11* GetEngineFactoryD3D11(); - -#endif - -} diff --git a/Graphics/GraphicsEngineD3D11/readme.md b/Graphics/GraphicsEngineD3D11/readme.md index 3a9dab60..121d4a49 100644 --- a/Graphics/GraphicsEngineD3D11/readme.md +++ b/Graphics/GraphicsEngineD3D11/readme.md @@ -8,7 +8,7 @@ Implementation of Direct3D11 back-end The following code snippet shows how to initialize Diligent Engine in D3D11 mode. ```cpp -#include "RenderDeviceFactoryD3D11.h" +#include "EngineFactoryD3D11.h" using namespace Diligent; // ... diff --git a/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp index f531ab9a..f177586d 100755 --- a/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp @@ -34,7 +34,6 @@ #include "PipelineStateD3D11Impl.h" #include "SwapChainD3D11.h" #include "ShaderResourceBindingD3D11Impl.h" -#include "EngineD3D11Attribs.h" #include "EngineD3D11Defines.h" #include "CommandListD3D11Impl.h" #include "RenderDeviceD3D11Impl.h" @@ -42,12 +41,12 @@ namespace Diligent { - DeviceContextD3D11Impl::DeviceContextD3D11Impl( IReferenceCounters* pRefCounters, - IMemoryAllocator& Allocator, - IRenderDevice* pDevice, - ID3D11DeviceContext* pd3d11DeviceContext, - const struct EngineD3D11Attribs& EngineAttribs, - bool bIsDeferred ) : + DeviceContextD3D11Impl::DeviceContextD3D11Impl( IReferenceCounters* pRefCounters, + IMemoryAllocator& Allocator, + IRenderDevice* pDevice, + ID3D11DeviceContext* pd3d11DeviceContext, + const struct EngineD3D11CreateInfo& EngineAttribs, + bool bIsDeferred ) : TDeviceContextBase(pRefCounters, pDevice, bIsDeferred), m_pd3d11DeviceContext( pd3d11DeviceContext ), m_DebugFlags(EngineAttribs.DebugFlags), diff --git a/Graphics/GraphicsEngineD3D11/src/EngineFactoryD3D11.cpp b/Graphics/GraphicsEngineD3D11/src/EngineFactoryD3D11.cpp new file mode 100644 index 00000000..d69a94ee --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/src/EngineFactoryD3D11.cpp @@ -0,0 +1,382 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +/// \file +/// Routines that initialize D3D11-based engine implementation + +#include "pch.h" +#include "EngineFactoryD3D11.h" +#include "RenderDeviceD3D11Impl.h" +#include "DeviceContextD3D11Impl.h" +#include "SwapChainD3D11Impl.h" +#include "D3D11TypeConversions.h" +#include "EngineMemory.h" +#include "EngineFactoryD3DBase.h" +#include +#include + +namespace Diligent +{ + +/// Engine factory for D3D11 implementation +class EngineFactoryD3D11Impl : public EngineFactoryD3DBase +{ +public: + static EngineFactoryD3D11Impl* GetInstance() + { + static EngineFactoryD3D11Impl TheFactory; + return &TheFactory; + } + + void CreateDeviceAndContextsD3D11(const EngineD3D11CreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts)override final; + + void CreateSwapChainD3D11(IRenderDevice* pDevice, + IDeviceContext* pImmediateContext, + const SwapChainDesc& SCDesc, + const FullScreenModeDesc& FSDesc, + void* pNativeWndHandle, + ISwapChain** ppSwapChain)override final; + + void AttachToD3D11Device(void* pd3d11NativeDevice, + void* pd3d11ImmediateContext, + const EngineD3D11CreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts)override final; +}; + + +#if defined(_DEBUG) +// Check for SDK Layer support. +inline bool SdkLayersAvailable() +{ + HRESULT hr = D3D11CreateDevice( + nullptr, + D3D_DRIVER_TYPE_NULL, // There is no need to create a real hardware device. + 0, + D3D11_CREATE_DEVICE_DEBUG, // Check for the SDK layers. + nullptr, // Any feature level will do. + 0, + D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION for Windows Store apps. + nullptr, // No need to keep the D3D device reference. + nullptr, // No need to know the feature level. + nullptr // No need to keep the D3D device context reference. + ); + + return SUCCEEDED(hr); +} +#endif + +/// Creates render device and device contexts for Direct3D11-based engine implementation + +/// \param [in] EngineCI - Engine creation attributes. +/// \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 +/// the contexts will be written. Pointer to the immediate +/// context goes at position 0. If NumDeferredContexts > 0, +/// pointers to the deferred contexts go afterwards. +/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number +/// of deferred contexts is requested, pointers to the +/// contexts are written to ppContexts array starting +/// at position 1 +void EngineFactoryD3D11Impl::CreateDeviceAndContextsD3D11(const EngineD3D11CreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts ) +{ + if (EngineCI.DebugMessageCallback != nullptr) + SetDebugMessageCallback(EngineCI.DebugMessageCallback); + + VERIFY( ppDevice && ppContexts, "Null pointer provided" ); + if( !ppDevice || !ppContexts ) + return; + + *ppDevice = nullptr; + memset(ppContexts, 0, sizeof(*ppContexts) * (1+NumDeferredContexts)); + + // This flag adds support for surfaces with a different color channel ordering + // than the API default. It is required for compatibility with Direct2D. + // D3D11_CREATE_DEVICE_BGRA_SUPPORT; + UINT creationFlags = 0; + +#if defined(_DEBUG) + if (SdkLayersAvailable()) + { + // If the project is in a debug build, enable debugging via SDK Layers with this flag. + creationFlags |= D3D11_CREATE_DEVICE_DEBUG; + } +#endif + + // This array defines the set of DirectX hardware feature levels this app will support. + // Note the ordering should be preserved. + // Don't forget to declare your application's minimum required feature level in its + // description. All applications are assumed to support 9.1 unless otherwise stated. + D3D_FEATURE_LEVEL featureLevels[] = + { +#if PLATFORM_UNIVERSAL_WINDOWS + D3D_FEATURE_LEVEL_11_1, +#endif + D3D_FEATURE_LEVEL_11_0, + D3D_FEATURE_LEVEL_10_1, + D3D_FEATURE_LEVEL_10_0, + D3D_FEATURE_LEVEL_9_3, + D3D_FEATURE_LEVEL_9_2, + D3D_FEATURE_LEVEL_9_1 + }; + + // Create the Direct3D 11 API device object and a corresponding context. + CComPtr pd3d11Device; + CComPtr pd3d11Context; + + CComPtr hardwareAdapter; + if (EngineCI.AdapterId != EngineD3D11CreateInfo::DefaultAdapterId) + { + auto Adapters = FindCompatibleAdapters(); + if (EngineCI.AdapterId < Adapters.size()) + hardwareAdapter = Adapters[EngineCI.AdapterId]; + else + { + LOG_ERROR_AND_THROW(EngineCI.AdapterId, " is not a valid hardware adapter id. Total number of compatible adapters available on this system: ", Adapters.size()); + } + } + + D3D_FEATURE_LEVEL d3dFeatureLevel = D3D_FEATURE_LEVEL_11_0; + HRESULT hr = D3D11CreateDevice( + hardwareAdapter, // Specify nullptr to use the default adapter. + hardwareAdapter ? D3D_DRIVER_TYPE_UNKNOWN : D3D_DRIVER_TYPE_HARDWARE, // If no adapter specified, request hardware graphics driver. + 0, // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE. + creationFlags, // Set debug and Direct2D compatibility flags. + featureLevels, // List of feature levels this app can support. + ARRAYSIZE(featureLevels), // Size of the list above. + D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION for Windows Store apps. + &pd3d11Device, // Returns the Direct3D device created. + &d3dFeatureLevel, // Returns feature level of device created. + &pd3d11Context // Returns the device immediate context. + ); + + if (FAILED(hr)) + { + // If the initialization fails, fall back to the WARP device. + // For more information on WARP, see: + // http://go.microsoft.com/fwlink/?LinkId=286690 + hr = D3D11CreateDevice( + nullptr, + D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device. + 0, + creationFlags, + featureLevels, + ARRAYSIZE(featureLevels), + D3D11_SDK_VERSION, + &pd3d11Device, + &d3dFeatureLevel, + &pd3d11Context + ); + LOG_ERROR("Failed to create D3D11 native device and immediate context"); + return; + } + + AttachToD3D11Device(pd3d11Device, pd3d11Context, EngineCI, ppDevice, ppContexts, NumDeferredContexts); +} + + +/// Attaches to existing D3D11 render device and immediate context + +/// \param [in] pd3d11NativeDevice - pointer to native D3D11 device +/// \param [in] pd3d11ImmediateContext - pointer to native D3D11 immediate context +/// \param [in] EngineCI - Engine creation attributes. +/// \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 +/// the contexts will be written. Pointer to the immediate +/// context goes at position 0. If NumDeferredContexts > 0, +/// pointers to deferred contexts go afterwards. +/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number +/// of deferred contexts is requested, pointers to the +/// contexts are written to ppContexts array starting +/// at position 1 +void EngineFactoryD3D11Impl::AttachToD3D11Device(void* pd3d11NativeDevice, + void* pd3d11ImmediateContext, + const EngineD3D11CreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts) +{ + if (EngineCI.DebugMessageCallback != nullptr) + SetDebugMessageCallback(EngineCI.DebugMessageCallback); + + VERIFY( ppDevice && ppContexts, "Null pointer provided" ); + if( !ppDevice || !ppContexts ) + return; + + try + { + ID3D11Device *pd3d11Device = reinterpret_cast(pd3d11NativeDevice); + ID3D11DeviceContext *pd3d11ImmediateCtx = reinterpret_cast(pd3d11ImmediateContext); + + SetRawAllocator(EngineCI.pRawMemAllocator); + auto &RawAlloctor = GetRawAllocator(); + RenderDeviceD3D11Impl *pRenderDeviceD3D11(NEW_RC_OBJ(RawAlloctor, "RenderDeviceD3D11Impl instance", RenderDeviceD3D11Impl) + (RawAlloctor, EngineCI, pd3d11Device, NumDeferredContexts)); + pRenderDeviceD3D11->QueryInterface(IID_RenderDevice, reinterpret_cast(ppDevice)); + + RefCntAutoPtr pDeviceContextD3D11(NEW_RC_OBJ(RawAlloctor, "DeviceContextD3D11Impl instance", DeviceContextD3D11Impl) + (RawAlloctor, pRenderDeviceD3D11, pd3d11ImmediateCtx, EngineCI, false)); + // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceD3D11 will + // keep a weak reference to the context + pDeviceContextD3D11->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts)); + pRenderDeviceD3D11->SetImmediateContext(pDeviceContextD3D11); + + for (Uint32 DeferredCtx = 0; DeferredCtx < NumDeferredContexts; ++DeferredCtx) + { + CComPtr pd3d11DeferredCtx; + HRESULT hr = pd3d11Device->CreateDeferredContext(0, &pd3d11DeferredCtx); + CHECK_D3D_RESULT_THROW(hr, "Failed to create D3D11 deferred context"); + RefCntAutoPtr pDeferredCtxD3D11( + NEW_RC_OBJ(RawAlloctor, "DeviceContextD3D11Impl instance", DeviceContextD3D11Impl) + (RawAlloctor, pRenderDeviceD3D11, pd3d11DeferredCtx, EngineCI, true)); + // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceD3D12 will + // keep a weak reference to the context + pDeferredCtxD3D11->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts + 1 + DeferredCtx)); + pRenderDeviceD3D11->SetDeferredContext(DeferredCtx, pDeferredCtxD3D11); + } + } + catch( const std::runtime_error & ) + { + if( *ppDevice ) + { + (*ppDevice)->Release(); + *ppDevice = nullptr; + } + for(Uint32 ctx=0; ctx < 1 + NumDeferredContexts; ++ctx) + { + if( ppContexts[ctx] != nullptr ) + { + ppContexts[ctx]->Release(); + ppContexts[ctx] = nullptr; + } + } + + LOG_ERROR( "Failed to initialize D3D11 device and contexts" ); + } +} + + +/// Creates a swap chain for Direct3D11-based engine implementation + +/// \param [in] pDevice - Pointer to the render device +/// \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 +/// the swap chain will be associated with: +/// * On Win32 platform, this should be window handle (HWND) +/// * On Universal Windows Platform, this should be reference to the +/// core window (Windows::UI::Core::CoreWindow) +/// +/// \param [out] ppSwapChain - Address of the memory location where pointer to the new +/// swap chain will be written +void EngineFactoryD3D11Impl::CreateSwapChainD3D11(IRenderDevice* pDevice, + IDeviceContext* pImmediateContext, + const SwapChainDesc& SCDesc, + const FullScreenModeDesc& FSDesc, + void* pNativeWndHandle, + ISwapChain** ppSwapChain) +{ + VERIFY( ppSwapChain, "Null pointer provided" ); + if( !ppSwapChain ) + return; + + *ppSwapChain = nullptr; + + try + { + auto *pDeviceD3D11 = ValidatedCast( pDevice ); + auto *pDeviceContextD3D11 = ValidatedCast(pImmediateContext); + auto &RawMemAllocator = GetRawAllocator(); + + auto *pSwapChainD3D11 = NEW_RC_OBJ(RawMemAllocator, "SwapChainD3D11Impl instance", SwapChainD3D11Impl) + (SCDesc, FSDesc, pDeviceD3D11, pDeviceContextD3D11, pNativeWndHandle); + pSwapChainD3D11->QueryInterface( IID_SwapChain, reinterpret_cast(ppSwapChain) ); + + pDeviceContextD3D11->SetSwapChain(pSwapChainD3D11); + // Bind default render target + pDeviceContextD3D11->SetRenderTargets( 0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); + // Set default viewport + pDeviceContextD3D11->SetViewports( 1, nullptr, 0, 0 ); + + auto NumDeferredCtx = pDeviceD3D11->GetNumDeferredContexts(); + for (size_t ctx = 0; ctx < NumDeferredCtx; ++ctx) + { + if (auto pDeferredCtx = pDeviceD3D11->GetDeferredContext(ctx)) + { + auto *pDeferredCtxD3D11 = pDeferredCtx.RawPtr(); + pDeferredCtxD3D11->SetSwapChain(pSwapChainD3D11); + // Do not bind default render target and viewport to be + // consistent with D3D12 + //// Bind default render target + //pDeferredCtxD3D11->SetRenderTargets( 0, nullptr, nullptr ); + //// Set default viewport + //pDeferredCtxD3D11->SetViewports( 1, nullptr, 0, 0 ); + } + } + } + catch( const std::runtime_error & ) + { + if( *ppSwapChain ) + { + (*ppSwapChain)->Release(); + *ppSwapChain = nullptr; + } + + LOG_ERROR( "Failed to create the swap chain" ); + } +} + +#ifdef DOXYGEN +/// Loads Direct3D11-based engine implementation and exports factory functions +/// \param [out] GetFactoryFunc - Pointer to the function that returns factory for D3D11 engine implementation +/// See EngineFactoryD3D11Impl. +/// \remarks Depending on the configuration and platform, the function loads different dll: +/// Platform\\Configuration | Debug | Release +/// --------------------------|-------------------------------|---------------------------- +/// x86 | GraphicsEngineD3D11_32d.dll | GraphicsEngineD3D11_32r.dll +/// x64 | GraphicsEngineD3D11_64d.dll | GraphicsEngineD3D11_64r.dll +/// +void LoadGraphicsEngineD3D11(GetEngineFactoryD3D11Type &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; +} +#endif + + +IEngineFactoryD3D11* GetEngineFactoryD3D11() +{ + return EngineFactoryD3D11Impl::GetInstance(); +} + +} diff --git a/Graphics/GraphicsEngineD3D11/src/RenderDeviceD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/RenderDeviceD3D11Impl.cpp index 86eae24a..04f54ad5 100644 --- a/Graphics/GraphicsEngineD3D11/src/RenderDeviceD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/RenderDeviceD3D11Impl.cpp @@ -40,11 +40,11 @@ namespace Diligent { -RenderDeviceD3D11Impl :: RenderDeviceD3D11Impl(IReferenceCounters* pRefCounters, - IMemoryAllocator& RawMemAllocator, - const EngineD3D11Attribs& EngineAttribs, - ID3D11Device* pd3d11Device, - Uint32 NumDeferredContexts) : +RenderDeviceD3D11Impl :: RenderDeviceD3D11Impl(IReferenceCounters* pRefCounters, + IMemoryAllocator& RawMemAllocator, + const EngineD3D11CreateInfo& EngineAttribs, + ID3D11Device* pd3d11Device, + Uint32 NumDeferredContexts) : TRenderDeviceBase { pRefCounters, diff --git a/Graphics/GraphicsEngineD3D11/src/RenderDeviceFactoryD3D11.cpp b/Graphics/GraphicsEngineD3D11/src/RenderDeviceFactoryD3D11.cpp deleted file mode 100644 index 7e5ff13f..00000000 --- a/Graphics/GraphicsEngineD3D11/src/RenderDeviceFactoryD3D11.cpp +++ /dev/null @@ -1,382 +0,0 @@ -/* Copyright 2015-2019 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -/// \file -/// Routines that initialize D3D11-based engine implementation - -#include "pch.h" -#include "RenderDeviceFactoryD3D11.h" -#include "RenderDeviceD3D11Impl.h" -#include "DeviceContextD3D11Impl.h" -#include "SwapChainD3D11Impl.h" -#include "D3D11TypeConversions.h" -#include "EngineMemory.h" -#include "EngineFactoryD3DBase.h" -#include -#include - -namespace Diligent -{ - -/// Engine factory for D3D11 implementation -class EngineFactoryD3D11Impl : public EngineFactoryD3DBase -{ -public: - static EngineFactoryD3D11Impl* GetInstance() - { - static EngineFactoryD3D11Impl TheFactory; - return &TheFactory; - } - - void CreateDeviceAndContextsD3D11( const EngineD3D11Attribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts )override final; - - void CreateSwapChainD3D11( IRenderDevice* pDevice, - IDeviceContext* pImmediateContext, - const SwapChainDesc& SCDesc, - const FullScreenModeDesc& FSDesc, - void* pNativeWndHandle, - ISwapChain** ppSwapChain )override final; - - void AttachToD3D11Device(void* pd3d11NativeDevice, - void* pd3d11ImmediateContext, - const EngineD3D11Attribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts)override final; -}; - - -#if defined(_DEBUG) -// Check for SDK Layer support. -inline bool SdkLayersAvailable() -{ - HRESULT hr = D3D11CreateDevice( - nullptr, - D3D_DRIVER_TYPE_NULL, // There is no need to create a real hardware device. - 0, - D3D11_CREATE_DEVICE_DEBUG, // Check for the SDK layers. - nullptr, // Any feature level will do. - 0, - D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION for Windows Store apps. - nullptr, // No need to keep the D3D device reference. - nullptr, // No need to know the feature level. - nullptr // No need to keep the D3D device context reference. - ); - - return SUCCEEDED(hr); -} -#endif - -/// Creates render device and device contexts for Direct3D11-based engine implementation - -/// \param [in] EngineAttribs - Engine creation attributes. -/// \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 -/// the contexts will be written. Pointer to the immediate -/// context goes at position 0. If NumDeferredContexts > 0, -/// pointers to the deferred contexts go afterwards. -/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number -/// of deferred contexts is requested, pointers to the -/// contexts are written to ppContexts array starting -/// at position 1 -void EngineFactoryD3D11Impl::CreateDeviceAndContextsD3D11( const EngineD3D11Attribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts ) -{ - if (EngineAttribs.DebugMessageCallback != nullptr) - SetDebugMessageCallback(EngineAttribs.DebugMessageCallback); - - VERIFY( ppDevice && ppContexts, "Null pointer provided" ); - if( !ppDevice || !ppContexts ) - return; - - *ppDevice = nullptr; - memset(ppContexts, 0, sizeof(*ppContexts) * (1+NumDeferredContexts)); - - // This flag adds support for surfaces with a different color channel ordering - // than the API default. It is required for compatibility with Direct2D. - // D3D11_CREATE_DEVICE_BGRA_SUPPORT; - UINT creationFlags = 0; - -#if defined(_DEBUG) - if (SdkLayersAvailable()) - { - // If the project is in a debug build, enable debugging via SDK Layers with this flag. - creationFlags |= D3D11_CREATE_DEVICE_DEBUG; - } -#endif - - // This array defines the set of DirectX hardware feature levels this app will support. - // Note the ordering should be preserved. - // Don't forget to declare your application's minimum required feature level in its - // description. All applications are assumed to support 9.1 unless otherwise stated. - D3D_FEATURE_LEVEL featureLevels[] = - { -#if PLATFORM_UNIVERSAL_WINDOWS - D3D_FEATURE_LEVEL_11_1, -#endif - D3D_FEATURE_LEVEL_11_0, - D3D_FEATURE_LEVEL_10_1, - D3D_FEATURE_LEVEL_10_0, - D3D_FEATURE_LEVEL_9_3, - D3D_FEATURE_LEVEL_9_2, - D3D_FEATURE_LEVEL_9_1 - }; - - // Create the Direct3D 11 API device object and a corresponding context. - CComPtr pd3d11Device; - CComPtr pd3d11Context; - - CComPtr hardwareAdapter; - if(EngineAttribs.AdapterId != EngineD3D11Attribs::DefaultAdapterId) - { - auto Adapters = FindCompatibleAdapters(); - if (EngineAttribs.AdapterId < Adapters.size()) - hardwareAdapter = Adapters[EngineAttribs.AdapterId]; - else - { - LOG_ERROR_AND_THROW(EngineAttribs.AdapterId, " is not a valid hardware adapter id. Total number of compatible adapters available on this system: ", Adapters.size()); - } - } - - D3D_FEATURE_LEVEL d3dFeatureLevel = D3D_FEATURE_LEVEL_11_0; - HRESULT hr = D3D11CreateDevice( - hardwareAdapter, // Specify nullptr to use the default adapter. - hardwareAdapter ? D3D_DRIVER_TYPE_UNKNOWN : D3D_DRIVER_TYPE_HARDWARE, // If no adapter specified, request hardware graphics driver. - 0, // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE. - creationFlags, // Set debug and Direct2D compatibility flags. - featureLevels, // List of feature levels this app can support. - ARRAYSIZE(featureLevels), // Size of the list above. - D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION for Windows Store apps. - &pd3d11Device, // Returns the Direct3D device created. - &d3dFeatureLevel, // Returns feature level of device created. - &pd3d11Context // Returns the device immediate context. - ); - - if (FAILED(hr)) - { - // If the initialization fails, fall back to the WARP device. - // For more information on WARP, see: - // http://go.microsoft.com/fwlink/?LinkId=286690 - hr = D3D11CreateDevice( - nullptr, - D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device. - 0, - creationFlags, - featureLevels, - ARRAYSIZE(featureLevels), - D3D11_SDK_VERSION, - &pd3d11Device, - &d3dFeatureLevel, - &pd3d11Context - ); - LOG_ERROR("Failed to create D3D11 native device and immediate context"); - return; - } - - AttachToD3D11Device(pd3d11Device, pd3d11Context, EngineAttribs, ppDevice, ppContexts, NumDeferredContexts); -} - - -/// Attaches to existing D3D11 render device and immediate context - -/// \param [in] pd3d11NativeDevice - pointer to native D3D11 device -/// \param [in] pd3d11ImmediateContext - pointer to native D3D11 immediate context -/// \param [in] EngineAttribs - Engine creation attributes. -/// \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 -/// the contexts will be written. Pointer to the immediate -/// context goes at position 0. If NumDeferredContexts > 0, -/// pointers to deferred contexts go afterwards. -/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number -/// of deferred contexts is requested, pointers to the -/// contexts are written to ppContexts array starting -/// at position 1 -void EngineFactoryD3D11Impl::AttachToD3D11Device(void* pd3d11NativeDevice, - void* pd3d11ImmediateContext, - const EngineD3D11Attribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts) -{ - if (EngineAttribs.DebugMessageCallback != nullptr) - SetDebugMessageCallback(EngineAttribs.DebugMessageCallback); - - VERIFY( ppDevice && ppContexts, "Null pointer provided" ); - if( !ppDevice || !ppContexts ) - return; - - try - { - ID3D11Device *pd3d11Device = reinterpret_cast(pd3d11NativeDevice); - ID3D11DeviceContext *pd3d11ImmediateCtx = reinterpret_cast(pd3d11ImmediateContext); - - SetRawAllocator(EngineAttribs.pRawMemAllocator); - auto &RawAlloctor = GetRawAllocator(); - RenderDeviceD3D11Impl *pRenderDeviceD3D11(NEW_RC_OBJ(RawAlloctor, "RenderDeviceD3D11Impl instance", RenderDeviceD3D11Impl) - (RawAlloctor, EngineAttribs, pd3d11Device, NumDeferredContexts)); - pRenderDeviceD3D11->QueryInterface(IID_RenderDevice, reinterpret_cast(ppDevice)); - - RefCntAutoPtr pDeviceContextD3D11(NEW_RC_OBJ(RawAlloctor, "DeviceContextD3D11Impl instance", DeviceContextD3D11Impl) - (RawAlloctor, pRenderDeviceD3D11, pd3d11ImmediateCtx, EngineAttribs, false)); - // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceD3D11 will - // keep a weak reference to the context - pDeviceContextD3D11->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts)); - pRenderDeviceD3D11->SetImmediateContext(pDeviceContextD3D11); - - for (Uint32 DeferredCtx = 0; DeferredCtx < NumDeferredContexts; ++DeferredCtx) - { - CComPtr pd3d11DeferredCtx; - HRESULT hr = pd3d11Device->CreateDeferredContext(0, &pd3d11DeferredCtx); - CHECK_D3D_RESULT_THROW(hr, "Failed to create D3D11 deferred context"); - RefCntAutoPtr pDeferredCtxD3D11( - NEW_RC_OBJ(RawAlloctor, "DeviceContextD3D11Impl instance", DeviceContextD3D11Impl) - (RawAlloctor, pRenderDeviceD3D11, pd3d11DeferredCtx, EngineAttribs, true)); - // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceD3D12 will - // keep a weak reference to the context - pDeferredCtxD3D11->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts + 1 + DeferredCtx)); - pRenderDeviceD3D11->SetDeferredContext(DeferredCtx, pDeferredCtxD3D11); - } - } - catch( const std::runtime_error & ) - { - if( *ppDevice ) - { - (*ppDevice)->Release(); - *ppDevice = nullptr; - } - for(Uint32 ctx=0; ctx < 1 + NumDeferredContexts; ++ctx) - { - if( ppContexts[ctx] != nullptr ) - { - ppContexts[ctx]->Release(); - ppContexts[ctx] = nullptr; - } - } - - LOG_ERROR( "Failed to initialize D3D11 device and contexts" ); - } -} - - -/// Creates a swap chain for Direct3D11-based engine implementation - -/// \param [in] pDevice - Pointer to the render device -/// \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 -/// the swap chain will be associated with: -/// * On Win32 platform, this should be window handle (HWND) -/// * On Universal Windows Platform, this should be reference to the -/// core window (Windows::UI::Core::CoreWindow) -/// -/// \param [out] ppSwapChain - Address of the memory location where pointer to the new -/// swap chain will be written -void EngineFactoryD3D11Impl::CreateSwapChainD3D11( IRenderDevice* pDevice, - IDeviceContext* pImmediateContext, - const SwapChainDesc& SCDesc, - const FullScreenModeDesc& FSDesc, - void* pNativeWndHandle, - ISwapChain** ppSwapChain ) -{ - VERIFY( ppSwapChain, "Null pointer provided" ); - if( !ppSwapChain ) - return; - - *ppSwapChain = nullptr; - - try - { - auto *pDeviceD3D11 = ValidatedCast( pDevice ); - auto *pDeviceContextD3D11 = ValidatedCast(pImmediateContext); - auto &RawMemAllocator = GetRawAllocator(); - - auto *pSwapChainD3D11 = NEW_RC_OBJ(RawMemAllocator, "SwapChainD3D11Impl instance", SwapChainD3D11Impl) - (SCDesc, FSDesc, pDeviceD3D11, pDeviceContextD3D11, pNativeWndHandle); - pSwapChainD3D11->QueryInterface( IID_SwapChain, reinterpret_cast(ppSwapChain) ); - - pDeviceContextD3D11->SetSwapChain(pSwapChainD3D11); - // Bind default render target - pDeviceContextD3D11->SetRenderTargets( 0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); - // Set default viewport - pDeviceContextD3D11->SetViewports( 1, nullptr, 0, 0 ); - - auto NumDeferredCtx = pDeviceD3D11->GetNumDeferredContexts(); - for (size_t ctx = 0; ctx < NumDeferredCtx; ++ctx) - { - if (auto pDeferredCtx = pDeviceD3D11->GetDeferredContext(ctx)) - { - auto *pDeferredCtxD3D11 = pDeferredCtx.RawPtr(); - pDeferredCtxD3D11->SetSwapChain(pSwapChainD3D11); - // Do not bind default render target and viewport to be - // consistent with D3D12 - //// Bind default render target - //pDeferredCtxD3D11->SetRenderTargets( 0, nullptr, nullptr ); - //// Set default viewport - //pDeferredCtxD3D11->SetViewports( 1, nullptr, 0, 0 ); - } - } - } - catch( const std::runtime_error & ) - { - if( *ppSwapChain ) - { - (*ppSwapChain)->Release(); - *ppSwapChain = nullptr; - } - - LOG_ERROR( "Failed to create the swap chain" ); - } -} - -#ifdef DOXYGEN -/// Loads Direct3D11-based engine implementation and exports factory functions -/// \param [out] GetFactoryFunc - Pointer to the function that returns factory for D3D11 engine implementation -/// See EngineFactoryD3D11Impl. -/// \remarks Depending on the configuration and platform, the function loads different dll: -/// Platform\\Configuration | Debug | Release -/// --------------------------|-------------------------------|---------------------------- -/// x86 | GraphicsEngineD3D11_32d.dll | GraphicsEngineD3D11_32r.dll -/// x64 | GraphicsEngineD3D11_64d.dll | GraphicsEngineD3D11_64r.dll -/// -void LoadGraphicsEngineD3D11(GetEngineFactoryD3D11Type &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; -} -#endif - - -IEngineFactoryD3D11* GetEngineFactoryD3D11() -{ - return EngineFactoryD3D11Impl::GetInstance(); -} - -} diff --git a/Graphics/GraphicsEngineD3D12/CMakeLists.txt b/Graphics/GraphicsEngineD3D12/CMakeLists.txt index d9505bd0..a5fac952 100644 --- a/Graphics/GraphicsEngineD3D12/CMakeLists.txt +++ b/Graphics/GraphicsEngineD3D12/CMakeLists.txt @@ -40,10 +40,10 @@ set(INTERFACE interface/BufferViewD3D12.h interface/CommandQueueD3D12.h interface/DeviceContextD3D12.h + interface/EngineFactoryD3D12.h interface/FenceD3D12.h interface/PipelineStateD3D12.h interface/RenderDeviceD3D12.h - interface/RenderDeviceFactoryD3D12.h interface/SamplerD3D12.h interface/ShaderD3D12.h interface/ShaderResourceBindingD3D12.h @@ -64,11 +64,11 @@ set(SRC src/DescriptorHeap.cpp src/DeviceContextD3D12Impl.cpp src/D3D12DynamicHeap.cpp + src/EngineFactoryD3D12.cpp src/FenceD3D12Impl.cpp src/GenerateMips.cpp src/PipelineStateD3D12Impl.cpp src/RenderDeviceD3D12Impl.cpp - src/RenderDeviceFactoryD3D12.cpp src/RootSignature.cpp src/SamplerD3D12Impl.cpp src/ShaderD3D12Impl.cpp diff --git a/Graphics/GraphicsEngineD3D12/include/DeviceContextD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/DeviceContextD3D12Impl.h index 438014e3..d22784dd 100644 --- a/Graphics/GraphicsEngineD3D12/include/DeviceContextD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/DeviceContextD3D12Impl.h @@ -52,12 +52,12 @@ class DeviceContextD3D12Impl final : public DeviceContextNextGenBase< DeviceCont public: using TDeviceContextBase = DeviceContextNextGenBase< DeviceContextBase >; - DeviceContextD3D12Impl(IReferenceCounters* pRefCounters, - class RenderDeviceD3D12Impl* pDevice, - bool bIsDeferred, - const EngineD3D12Attribs& Attribs, - Uint32 ContextId, - Uint32 CommandQueueId); + DeviceContextD3D12Impl(IReferenceCounters* pRefCounters, + class RenderDeviceD3D12Impl* pDevice, + bool bIsDeferred, + const EngineD3D12CreateInfo& EngineCI, + Uint32 ContextId, + Uint32 CommandQueueId); ~DeviceContextD3D12Impl(); virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; diff --git a/Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.h index f9e4d3aa..376e32d1 100644 --- a/Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/RenderDeviceD3D12Impl.h @@ -45,13 +45,13 @@ class RenderDeviceD3D12Impl final : public RenderDeviceNextGenBase< RenderDevice public: using TRenderDeviceBase = RenderDeviceNextGenBase< RenderDeviceD3DBase, ICommandQueueD3D12 >; - RenderDeviceD3D12Impl( IReferenceCounters* pRefCounters, - IMemoryAllocator& RawMemAllocator, - const EngineD3D12Attribs& CreationAttribs, - ID3D12Device* pD3D12Device, - size_t CommandQueueCount, - ICommandQueueD3D12** ppCmdQueues, - Uint32 NumDeferredContexts ); + RenderDeviceD3D12Impl( IReferenceCounters* pRefCounters, + IMemoryAllocator& RawMemAllocator, + const EngineD3D12CreateInfo& EngineCI, + ID3D12Device* pD3D12Device, + size_t CommandQueueCount, + ICommandQueueD3D12** ppCmdQueues, + Uint32 NumDeferredContexts ); ~RenderDeviceD3D12Impl(); virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; @@ -108,7 +108,7 @@ private: CComPtr m_pd3d12Device; - EngineD3D12Attribs m_EngineAttribs; + EngineD3D12CreateInfo m_EngineAttribs; CPUDescriptorHeap m_CPUDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES]; GPUDescriptorHeap m_GPUDescriptorHeaps[2]; // D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV == 0 diff --git a/Graphics/GraphicsEngineD3D12/interface/EngineFactoryD3D12.h b/Graphics/GraphicsEngineD3D12/interface/EngineFactoryD3D12.h new file mode 100644 index 00000000..7ac6e9e0 --- /dev/null +++ b/Graphics/GraphicsEngineD3D12/interface/EngineFactoryD3D12.h @@ -0,0 +1,133 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +/// \file +/// Declaration of functions that initialize Direct3D12-based engine implementation + +#include + +#include "../../GraphicsEngine/interface/RenderDevice.h" +#include "../../GraphicsEngine/interface/DeviceContext.h" +#include "../../GraphicsEngine/interface/SwapChain.h" + +#if PLATFORM_UNIVERSAL_WINDOWS && defined(ENGINE_DLL) +# include "../../../Common/interface/StringTools.h" +#endif + +namespace Diligent +{ + +class IEngineFactoryD3D12 +{ +public: + virtual void CreateDeviceAndContextsD3D12(const EngineD3D12CreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts) = 0; + + virtual void AttachToD3D12Device(void* pd3d12NativeDevice, + size_t CommandQueueCount, + class ICommandQueueD3D12** ppCommandQueues, + const EngineD3D12CreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts) = 0; + + virtual void CreateSwapChainD3D12( IRenderDevice* pDevice, + IDeviceContext* pImmediateContext, + const SwapChainDesc& SwapChainDesc, + const FullScreenModeDesc& FSDesc, + void* pNativeWndHandle, + ISwapChain** ppSwapChain ) = 0; + + virtual void EnumerateHardwareAdapters(Uint32& NumAdapters, + HardwareAdapterAttribs* Adapters) = 0; + + virtual void EnumerateDisplayModes(Uint32 AdapterId, + Uint32 OutputId, + TEXTURE_FORMAT Format, + Uint32& NumDisplayModes, + DisplayModeAttribs* DisplayModes) = 0; + +}; + + +#if ENGINE_DLL + + typedef IEngineFactoryD3D12* (*GetEngineFactoryD3D12Type)(); + + 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 ) + { + 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; + } +#else + + IEngineFactoryD3D12* GetEngineFactoryD3D12(); + +#endif + +} diff --git a/Graphics/GraphicsEngineD3D12/interface/RenderDeviceFactoryD3D12.h b/Graphics/GraphicsEngineD3D12/interface/RenderDeviceFactoryD3D12.h deleted file mode 100644 index 80e6f580..00000000 --- a/Graphics/GraphicsEngineD3D12/interface/RenderDeviceFactoryD3D12.h +++ /dev/null @@ -1,133 +0,0 @@ -/* Copyright 2015-2019 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -/// \file -/// Declaration of functions that initialize Direct3D12-based engine implementation - -#include - -#include "../../GraphicsEngine/interface/RenderDevice.h" -#include "../../GraphicsEngine/interface/DeviceContext.h" -#include "../../GraphicsEngine/interface/SwapChain.h" - -#if PLATFORM_UNIVERSAL_WINDOWS && defined(ENGINE_DLL) -# include "../../../Common/interface/StringTools.h" -#endif - -namespace Diligent -{ - -class IEngineFactoryD3D12 -{ -public: - virtual void CreateDeviceAndContextsD3D12( const EngineD3D12Attribs& CreationAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts) = 0; - - virtual void AttachToD3D12Device(void* pd3d12NativeDevice, - size_t CommandQueueCount, - class ICommandQueueD3D12** ppCommandQueues, - const EngineD3D12Attribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts) = 0; - - virtual void CreateSwapChainD3D12( IRenderDevice* pDevice, - IDeviceContext* pImmediateContext, - const SwapChainDesc& SwapChainDesc, - const FullScreenModeDesc& FSDesc, - void* pNativeWndHandle, - ISwapChain** ppSwapChain ) = 0; - - virtual void EnumerateHardwareAdapters(Uint32& NumAdapters, - HardwareAdapterAttribs* Adapters) = 0; - - virtual void EnumerateDisplayModes(Uint32 AdapterId, - Uint32 OutputId, - TEXTURE_FORMAT Format, - Uint32& NumDisplayModes, - DisplayModeAttribs* DisplayModes) = 0; - -}; - - -#if ENGINE_DLL - - typedef IEngineFactoryD3D12* (*GetEngineFactoryD3D12Type)(); - - 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 ) - { - 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; - } -#else - - IEngineFactoryD3D12* GetEngineFactoryD3D12(); - -#endif - -} diff --git a/Graphics/GraphicsEngineD3D12/readme.md b/Graphics/GraphicsEngineD3D12/readme.md index 3827a4f0..85ad141b 100644 --- a/Graphics/GraphicsEngineD3D12/readme.md +++ b/Graphics/GraphicsEngineD3D12/readme.md @@ -8,7 +8,7 @@ Implementation of Direct3D12 back-end The following code snippet shows how to initialize Diligent Engine in D3D12 mode. ```cpp -#include "RenderDeviceFactoryD3D12.h" +#include "EngineFactoryD3D12.h" using namespace Diligent; // ... diff --git a/Graphics/GraphicsEngineD3D12/src/DeviceContextD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/DeviceContextD3D12Impl.cpp index 7e8eeeed..a1d9db3f 100644 --- a/Graphics/GraphicsEngineD3D12/src/DeviceContextD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/DeviceContextD3D12Impl.cpp @@ -51,39 +51,39 @@ namespace Diligent return ss.str(); } - DeviceContextD3D12Impl::DeviceContextD3D12Impl( IReferenceCounters* pRefCounters, - RenderDeviceD3D12Impl* pDeviceD3D12Impl, - bool bIsDeferred, - const EngineD3D12Attribs& Attribs, - Uint32 ContextId, - Uint32 CommandQueueId) : + 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() : Attribs.NumCommandsToFlushCmdList, + bIsDeferred ? std::numeric_limits::max() : EngineCI.NumCommandsToFlushCmdList, bIsDeferred }, m_DynamicHeap { pDeviceD3D12Impl->GetDynamicMemoryManager(), GetContextObjectName("Dynamic heap", bIsDeferred, ContextId), - Attribs.DynamicHeapPageSize + EngineCI.DynamicHeapPageSize }, m_DynamicGPUDescriptorAllocator { { GetRawAllocator(), pDeviceD3D12Impl->GetGPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), - Attribs.DynamicDescriptorAllocationChunkSize[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), - Attribs.DynamicDescriptorAllocationChunkSize[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER], + EngineCI.DynamicDescriptorAllocationChunkSize[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER], GetContextObjectName("SAMPLER dynamic descriptor allocator", bIsDeferred, ContextId) } }, diff --git a/Graphics/GraphicsEngineD3D12/src/EngineFactoryD3D12.cpp b/Graphics/GraphicsEngineD3D12/src/EngineFactoryD3D12.cpp new file mode 100644 index 00000000..18a69020 --- /dev/null +++ b/Graphics/GraphicsEngineD3D12/src/EngineFactoryD3D12.cpp @@ -0,0 +1,438 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +/// \file +/// Routines that initialize D3D12-based engine implementation + +#include "pch.h" +#include +#include "EngineFactoryD3D12.h" +#include "RenderDeviceD3D12Impl.h" +#include "DeviceContextD3D12Impl.h" +#include "SwapChainD3D12Impl.h" +#include "D3D12TypeConversions.h" +#include "EngineFactoryD3DBase.h" +#include "StringTools.h" +#include "EngineMemory.h" +#include "CommandQueueD3D12Impl.h" +#include +#include + +namespace Diligent +{ + +/// Engine factory for D3D12 implementation +class EngineFactoryD3D12Impl : public EngineFactoryD3DBase +{ +public: + static EngineFactoryD3D12Impl* GetInstance() + { + static EngineFactoryD3D12Impl TheFactory; + return &TheFactory; + } + + void CreateDeviceAndContextsD3D12(const EngineD3D12CreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts)override final; + + void AttachToD3D12Device(void* pd3d12NativeDevice, + size_t CommandQueueCount, + ICommandQueueD3D12** ppCommandQueues, + const EngineD3D12CreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts)override final; + + void CreateSwapChainD3D12( IRenderDevice* pDevice, + IDeviceContext* pImmediateContext, + const SwapChainDesc& SwapChainDesc, + const FullScreenModeDesc& FSDesc, + void* pNativeWndHandle, + ISwapChain** ppSwapChain )override final; +}; + +void GetHardwareAdapter(IDXGIFactory2* pFactory, IDXGIAdapter1** ppAdapter) +{ + CComPtr adapter; + *ppAdapter = nullptr; + + for (UINT adapterIndex = 0; DXGI_ERROR_NOT_FOUND != pFactory->EnumAdapters1(adapterIndex, &adapter); ++adapterIndex) + { + 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, D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), nullptr))) + { + break; + } + } + + *ppAdapter = adapter.Detach(); +} + +/// Creates render device and device contexts for Direct3D12-based engine implementation + +/// \param [in] EngineCI - Engine creation attributes. +/// \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 +/// the contexts will be written. The new immediate +/// context goes at position 0. If NumDeferredContexts > 0, +/// pointers to the deferred contexts are written afterwards. +/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number +/// of deferred contexts is requested, pointers to the +/// contexts are written to ppContexts array starting +/// at position 1 +void EngineFactoryD3D12Impl::CreateDeviceAndContextsD3D12(const EngineD3D12CreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts) +{ + if (EngineCI.DebugMessageCallback != nullptr) + SetDebugMessageCallback(EngineCI.DebugMessageCallback); + + 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) + { + 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 ); + return; + } + + if( (CPUHeapAllocSize % 16) != 0 ) + { + LOG_ERROR( "CPU Heap allocation size (", CPUHeapAllocSize, ") is expected to be multiple of 16" ); + return; + } + } + + *ppDevice = nullptr; + memset(ppContexts, 0, sizeof(*ppContexts) * (1+NumDeferredContexts)); + + RefCntAutoPtr pCmdQueueD3D12; + CComPtr d3d12Device; + try + { +#if defined(_DEBUG) + // Enable the D3D12 debug layer. + { + CComPtr debugController; + if (SUCCEEDED(D3D12GetDebugInterface(__uuidof(debugController), reinterpret_cast(static_cast(&debugController)) ))) + { + debugController->EnableDebugLayer(); + } + } +#endif + + CComPtr factory; + HRESULT hr = CreateDXGIFactory1(__uuidof(factory), reinterpret_cast(static_cast(&factory)) ); + CHECK_D3D_RESULT_THROW(hr, "Failed to create DXGI factory"); + + CComPtr hardwareAdapter; + if(EngineCI.AdapterId == EngineD3D12CreateInfo::DefaultAdapterId) + { + GetHardwareAdapter(factory, &hardwareAdapter); + if(hardwareAdapter == nullptr) + LOG_ERROR_AND_THROW("No suitable hardware adapter found"); + } + else + { + auto Adapters = FindCompatibleAdapters(); + if(EngineCI.AdapterId < Adapters.size()) + hardwareAdapter = Adapters[EngineCI.AdapterId]; + else + { + LOG_ERROR_AND_THROW(EngineCI.AdapterId, " is not a valid hardware adapter id. Total number of compatible adapters available on this system: ", Adapters.size()); + } + } + + { + DXGI_ADAPTER_DESC1 desc; + hardwareAdapter->GetDesc1(&desc); + LOG_INFO_MESSAGE("D3D12-capabale hardware found: ", NarrowString(desc.Description), " (", desc.DedicatedVideoMemory >> 20, " MB)"); + } + + hr = D3D12CreateDevice(hardwareAdapter, D3D_FEATURE_LEVEL_11_0, __uuidof(d3d12Device), reinterpret_cast(static_cast(&d3d12Device)) ); + 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)) ); + CHECK_D3D_RESULT_THROW(hr, "Failed to enum warp adapter"); + + hr = D3D12CreateDevice( warpAdapter, D3D_FEATURE_LEVEL_11_0, __uuidof(d3d12Device), reinterpret_cast(static_cast(&d3d12Device)) ); + CHECK_D3D_RESULT_THROW(hr, "Failed to crate warp device"); + } + +#if _DEBUG + { + 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); + VERIFY(SUCCEEDED(hr), "Failed to push storage filter"); + } + } +#endif + +#ifndef RELEASE + // 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; + + CComPtr pd3d12CmdQueue; + hr = d3d12Device->CreateCommandQueue(&queueDesc, __uuidof(pd3d12CmdQueue), reinterpret_cast(static_cast(&pd3d12CmdQueue))); + CHECK_D3D_RESULT_THROW(hr, "Failed to create command queue"); + hr = pd3d12CmdQueue->SetName(L"Main Command Queue"); + VERIFY_EXPR(SUCCEEDED(hr)); + + 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"); + + auto &RawMemAllocator = GetRawAllocator(); + pCmdQueueD3D12 = NEW_RC_OBJ(RawMemAllocator, "CommandQueueD3D12 instance", CommandQueueD3D12Impl)(pd3d12CmdQueue, pd3d12Fence); + } + catch( const std::runtime_error & ) + { + LOG_ERROR( "Failed to initialize D3D12 resources" ); + return; + } + + std::array CmdQueues = {pCmdQueueD3D12}; + AttachToD3D12Device(d3d12Device, CmdQueues.size(), CmdQueues.data(), EngineCI, ppDevice, ppContexts, NumDeferredContexts); +} + + +/// Attaches to existing D3D12 device + +/// \param [in] pd3d12NativeDevice - pointer to native D3D12 device +/// \param [in] CommandQueueCount - Number of command queues +/// \param [in] ppCommandQueues - pointer to the array of command queues +/// \param [in] EngineCI - Engine creation attributes. +/// \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 +/// the contexts will be written. Pointer to the immediate +/// context goes at position 0. If NumDeferredContexts > 0, +/// pointers to the deferred contexts go afterwards. +/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number +/// of deferred contexts is requested, pointers to the +/// contexts are written to ppContexts array starting +/// at position 1 +void EngineFactoryD3D12Impl::AttachToD3D12Device(void* pd3d12NativeDevice, + size_t CommandQueueCount, + ICommandQueueD3D12** ppCommandQueues, + const EngineD3D12CreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts) +{ + if (EngineCI.DebugMessageCallback != nullptr) + SetDebugMessageCallback(EngineCI.DebugMessageCallback); + + VERIFY( pd3d12NativeDevice && ppCommandQueues && ppDevice && ppContexts, "Null pointer provided" ); + if( !pd3d12NativeDevice || !ppCommandQueues || !ppDevice || !ppContexts ) + return; + + *ppDevice = nullptr; + memset(ppContexts, 0, sizeof(*ppContexts) * (1+NumDeferredContexts)); + + try + { + SetRawAllocator(EngineCI.pRawMemAllocator); + auto &RawMemAllocator = GetRawAllocator(); + auto d3d12Device = reinterpret_cast(pd3d12NativeDevice); + RenderDeviceD3D12Impl *pRenderDeviceD3D12( NEW_RC_OBJ(RawMemAllocator, "RenderDeviceD3D12Impl instance", RenderDeviceD3D12Impl)(RawMemAllocator, EngineCI, d3d12Device, CommandQueueCount, ppCommandQueues, NumDeferredContexts ) ); + 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) ); + pRenderDeviceD3D12->SetImmediateContext(pImmediateCtxD3D12); + + for (Uint32 DeferredCtx = 0; DeferredCtx < NumDeferredContexts; ++DeferredCtx) + { + 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) ); + pRenderDeviceD3D12->SetDeferredContext(DeferredCtx, pDeferredCtxD3D12); + } + } + catch( const std::runtime_error & ) + { + if( *ppDevice ) + { + (*ppDevice)->Release(); + *ppDevice = nullptr; + } + for(Uint32 ctx=0; ctx < 1 + NumDeferredContexts; ++ctx) + { + if( ppContexts[ctx] != nullptr ) + { + ppContexts[ctx]->Release(); + ppContexts[ctx] = nullptr; + } + } + + LOG_ERROR( "Failed to create device and contexts" ); + } +} + +/// Creates a swap chain for Direct3D12-based engine implementation + +/// \param [in] pDevice - Pointer to the render device +/// \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 +/// the swap chain will be associated with: +/// * On Win32 platform, this should be window handle (HWND) +/// * On Universal Windows Platform, this should be reference to the +/// core window (Windows::UI::Core::CoreWindow) +/// +/// \param [out] ppSwapChain - Address of the memory location where pointer to the new +/// swap chain will be written +void EngineFactoryD3D12Impl::CreateSwapChainD3D12(IRenderDevice* pDevice, + IDeviceContext* pImmediateContext, + const SwapChainDesc& SCDesc, + const FullScreenModeDesc& FSDesc, + void* pNativeWndHandle, + ISwapChain** ppSwapChain ) +{ + VERIFY( ppSwapChain, "Null pointer provided" ); + if( !ppSwapChain ) + return; + + *ppSwapChain = nullptr; + + try + { + auto *pDeviceD3D12 = ValidatedCast( pDevice ); + auto *pDeviceContextD3D12 = ValidatedCast(pImmediateContext); + auto &RawMemAllocator = GetRawAllocator(); + auto *pSwapChainD3D12 = NEW_RC_OBJ(RawMemAllocator, "SwapChainD3D12Impl instance", SwapChainD3D12Impl)(SCDesc, FSDesc, pDeviceD3D12, pDeviceContextD3D12, pNativeWndHandle); + pSwapChainD3D12->QueryInterface( IID_SwapChain, reinterpret_cast(ppSwapChain) ); + + pDeviceContextD3D12->SetSwapChain(pSwapChainD3D12); + // Bind default render target + pDeviceContextD3D12->SetRenderTargets( 0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); + // Set default viewport + pDeviceContextD3D12->SetViewports( 1, nullptr, 0, 0 ); + + auto NumDeferredCtx = pDeviceD3D12->GetNumDeferredContexts(); + for (size_t ctx = 0; ctx < NumDeferredCtx; ++ctx) + { + if (auto pDeferredCtx = pDeviceD3D12->GetDeferredContext(ctx)) + { + auto* pDeferredCtxD3D12 = pDeferredCtx.RawPtr(); + 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 + // RTV of an inactive buffer in the swap chain + } + } + } + catch( const std::runtime_error& ) + { + if( *ppSwapChain ) + { + (*ppSwapChain)->Release(); + *ppSwapChain = nullptr; + } + + LOG_ERROR( "Failed to create the swap chain" ); + } +} + + +#ifdef DOXYGEN +/// Loads Direct3D12-based engine implementation and exports factory functions +/// \param [out] GetFactoryFunc - Pointer to the function that returns factory for D3D12 engine implementation. +/// See EngineFactoryD3D12Impl. +/// \remarks Depending on the configuration and platform, the function loads different dll: +/// Platform\\Configuration | Debug | Release +/// --------------------------|-------------------------------|---------------------------- +/// x86 | GraphicsEngineD3D12_32d.dll | GraphicsEngineD3D12_32r.dll +/// x64 | GraphicsEngineD3D12_64d.dll | GraphicsEngineD3D12_64r.dll +/// +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; +} +#endif + + +IEngineFactoryD3D12* GetEngineFactoryD3D12() +{ + return EngineFactoryD3D12Impl::GetInstance(); +} + +} diff --git a/Graphics/GraphicsEngineD3D12/src/RenderDeviceD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/RenderDeviceD3D12Impl.cpp index 4640daad..54396583 100644 --- a/Graphics/GraphicsEngineD3D12/src/RenderDeviceD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/RenderDeviceD3D12Impl.cpp @@ -37,13 +37,13 @@ namespace Diligent { -RenderDeviceD3D12Impl :: RenderDeviceD3D12Impl(IReferenceCounters* pRefCounters, - IMemoryAllocator& RawMemAllocator, - const EngineD3D12Attribs& CreationAttribs, - ID3D12Device* pd3d12Device, - size_t CommandQueueCount, - ICommandQueueD3D12** ppCmdQueues, - Uint32 NumDeferredContexts) : +RenderDeviceD3D12Impl :: RenderDeviceD3D12Impl(IReferenceCounters* pRefCounters, + IMemoryAllocator& RawMemAllocator, + const EngineD3D12CreateInfo& EngineCI, + ID3D12Device* pd3d12Device, + size_t CommandQueueCount, + ICommandQueueD3D12** ppCmdQueues, + Uint32 NumDeferredContexts) : TRenderDeviceBase { pRefCounters, @@ -62,22 +62,22 @@ RenderDeviceD3D12Impl :: RenderDeviceD3D12Impl(IReferenceCounters* pRef sizeof(FenceD3D12Impl) }, m_pd3d12Device (pd3d12Device), - m_EngineAttribs (CreationAttribs), + m_EngineAttribs (EngineCI), m_CmdListManager(*this), m_CPUDescriptorHeaps { - {RawMemAllocator, *this, CreationAttribs.CPUDescriptorHeapAllocationSize[0], D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}, - {RawMemAllocator, *this, CreationAttribs.CPUDescriptorHeapAllocationSize[1], D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}, - {RawMemAllocator, *this, CreationAttribs.CPUDescriptorHeapAllocationSize[2], D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}, - {RawMemAllocator, *this, CreationAttribs.CPUDescriptorHeapAllocationSize[3], D3D12_DESCRIPTOR_HEAP_TYPE_DSV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE} + {RawMemAllocator, *this, EngineCI.CPUDescriptorHeapAllocationSize[0], D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}, + {RawMemAllocator, *this, EngineCI.CPUDescriptorHeapAllocationSize[1], D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}, + {RawMemAllocator, *this, EngineCI.CPUDescriptorHeapAllocationSize[2], D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}, + {RawMemAllocator, *this, EngineCI.CPUDescriptorHeapAllocationSize[3], D3D12_DESCRIPTOR_HEAP_TYPE_DSV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE} }, m_GPUDescriptorHeaps { - {RawMemAllocator, *this, CreationAttribs.GPUDescriptorHeapSize[0], CreationAttribs.GPUDescriptorHeapDynamicSize[0], D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, - {RawMemAllocator, *this, CreationAttribs.GPUDescriptorHeapSize[1], CreationAttribs.GPUDescriptorHeapDynamicSize[1], D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE} + {RawMemAllocator, *this, EngineCI.GPUDescriptorHeapSize[0], EngineCI.GPUDescriptorHeapDynamicSize[0], D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, + {RawMemAllocator, *this, EngineCI.GPUDescriptorHeapSize[1], EngineCI.GPUDescriptorHeapDynamicSize[1], D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE} }, m_ContextPool(STD_ALLOCATOR_RAW_MEM(PooledCommandContext, GetRawAllocator(), "Allocator for vector")), - m_DynamicMemoryManager(GetRawAllocator(), *this, CreationAttribs.NumDynamicHeapPagesToReserve, CreationAttribs.DynamicHeapPageSize), + m_DynamicMemoryManager(GetRawAllocator(), *this, EngineCI.NumDynamicHeapPagesToReserve, EngineCI.DynamicHeapPageSize), m_MipsGenerator(pd3d12Device) { m_DeviceCaps.DevType = DeviceType::D3D12; diff --git a/Graphics/GraphicsEngineD3D12/src/RenderDeviceFactoryD3D12.cpp b/Graphics/GraphicsEngineD3D12/src/RenderDeviceFactoryD3D12.cpp deleted file mode 100644 index 3096ea9e..00000000 --- a/Graphics/GraphicsEngineD3D12/src/RenderDeviceFactoryD3D12.cpp +++ /dev/null @@ -1,438 +0,0 @@ -/* Copyright 2015-2019 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -/// \file -/// Routines that initialize D3D12-based engine implementation - -#include "pch.h" -#include -#include "RenderDeviceFactoryD3D12.h" -#include "RenderDeviceD3D12Impl.h" -#include "DeviceContextD3D12Impl.h" -#include "SwapChainD3D12Impl.h" -#include "D3D12TypeConversions.h" -#include "EngineFactoryD3DBase.h" -#include "StringTools.h" -#include "EngineMemory.h" -#include "CommandQueueD3D12Impl.h" -#include -#include - -namespace Diligent -{ - -/// Engine factory for D3D12 implementation -class EngineFactoryD3D12Impl : public EngineFactoryD3DBase -{ -public: - static EngineFactoryD3D12Impl* GetInstance() - { - static EngineFactoryD3D12Impl TheFactory; - return &TheFactory; - } - - void CreateDeviceAndContextsD3D12( const EngineD3D12Attribs& CreationAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts)override final; - - void AttachToD3D12Device(void* pd3d12NativeDevice, - size_t CommandQueueCount, - ICommandQueueD3D12** ppCommandQueues, - const EngineD3D12Attribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts)override final; - - void CreateSwapChainD3D12( IRenderDevice* pDevice, - IDeviceContext* pImmediateContext, - const SwapChainDesc& SwapChainDesc, - const FullScreenModeDesc& FSDesc, - void* pNativeWndHandle, - ISwapChain** ppSwapChain )override final; -}; - -void GetHardwareAdapter(IDXGIFactory2* pFactory, IDXGIAdapter1** ppAdapter) -{ - CComPtr adapter; - *ppAdapter = nullptr; - - for (UINT adapterIndex = 0; DXGI_ERROR_NOT_FOUND != pFactory->EnumAdapters1(adapterIndex, &adapter); ++adapterIndex) - { - 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, D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), nullptr))) - { - break; - } - } - - *ppAdapter = adapter.Detach(); -} - -/// Creates render device and device contexts for Direct3D12-based engine implementation - -/// \param [in] CreationAttribs - Engine creation attributes. -/// \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 -/// the contexts will be written. The new immediate -/// context goes at position 0. If NumDeferredContexts > 0, -/// pointers to the deferred contexts are written afterwards. -/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number -/// of deferred contexts is requested, pointers to the -/// contexts are written to ppContexts array starting -/// at position 1 -void EngineFactoryD3D12Impl::CreateDeviceAndContextsD3D12( const EngineD3D12Attribs& CreationAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts) -{ - if (CreationAttribs.DebugMessageCallback != nullptr) - SetDebugMessageCallback(CreationAttribs.DebugMessageCallback); - - 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) - { - auto CPUHeapAllocSize = CreationAttribs.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 ); - return; - } - - if( (CPUHeapAllocSize % 16) != 0 ) - { - LOG_ERROR( "CPU Heap allocation size (", CPUHeapAllocSize, ") is expected to be multiple of 16" ); - return; - } - } - - *ppDevice = nullptr; - memset(ppContexts, 0, sizeof(*ppContexts) * (1+NumDeferredContexts)); - - RefCntAutoPtr pCmdQueueD3D12; - CComPtr d3d12Device; - try - { -#if defined(_DEBUG) - // Enable the D3D12 debug layer. - { - CComPtr debugController; - if (SUCCEEDED(D3D12GetDebugInterface(__uuidof(debugController), reinterpret_cast(static_cast(&debugController)) ))) - { - debugController->EnableDebugLayer(); - } - } -#endif - - CComPtr factory; - HRESULT hr = CreateDXGIFactory1(__uuidof(factory), reinterpret_cast(static_cast(&factory)) ); - CHECK_D3D_RESULT_THROW(hr, "Failed to create DXGI factory"); - - CComPtr hardwareAdapter; - if(CreationAttribs.AdapterId == EngineD3D12Attribs::DefaultAdapterId) - { - GetHardwareAdapter(factory, &hardwareAdapter); - if(hardwareAdapter == nullptr) - LOG_ERROR_AND_THROW("No suitable hardware adapter found"); - } - else - { - auto Adapters = FindCompatibleAdapters(); - if(CreationAttribs.AdapterId < Adapters.size()) - hardwareAdapter = Adapters[CreationAttribs.AdapterId]; - else - { - LOG_ERROR_AND_THROW(CreationAttribs.AdapterId, " is not a valid hardware adapter id. Total number of compatible adapters available on this system: ", Adapters.size()); - } - } - - { - DXGI_ADAPTER_DESC1 desc; - hardwareAdapter->GetDesc1(&desc); - LOG_INFO_MESSAGE("D3D12-capabale hardware found: ", NarrowString(desc.Description), " (", desc.DedicatedVideoMemory >> 20, " MB)"); - } - - hr = D3D12CreateDevice(hardwareAdapter, D3D_FEATURE_LEVEL_11_0, __uuidof(d3d12Device), reinterpret_cast(static_cast(&d3d12Device)) ); - 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)) ); - CHECK_D3D_RESULT_THROW(hr, "Failed to enum warp adapter"); - - hr = D3D12CreateDevice( warpAdapter, D3D_FEATURE_LEVEL_11_0, __uuidof(d3d12Device), reinterpret_cast(static_cast(&d3d12Device)) ); - CHECK_D3D_RESULT_THROW(hr, "Failed to crate warp device"); - } - -#if _DEBUG - { - 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); - VERIFY(SUCCEEDED(hr), "Failed to push storage filter"); - } - } -#endif - -#ifndef RELEASE - // 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; - - CComPtr pd3d12CmdQueue; - hr = d3d12Device->CreateCommandQueue(&queueDesc, __uuidof(pd3d12CmdQueue), reinterpret_cast(static_cast(&pd3d12CmdQueue))); - CHECK_D3D_RESULT_THROW(hr, "Failed to create command queue"); - hr = pd3d12CmdQueue->SetName(L"Main Command Queue"); - VERIFY_EXPR(SUCCEEDED(hr)); - - 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"); - - auto &RawMemAllocator = GetRawAllocator(); - pCmdQueueD3D12 = NEW_RC_OBJ(RawMemAllocator, "CommandQueueD3D12 instance", CommandQueueD3D12Impl)(pd3d12CmdQueue, pd3d12Fence); - } - catch( const std::runtime_error & ) - { - LOG_ERROR( "Failed to initialize D3D12 resources" ); - return; - } - - std::array CmdQueues = {pCmdQueueD3D12}; - AttachToD3D12Device(d3d12Device, CmdQueues.size(), CmdQueues.data(), CreationAttribs, ppDevice, ppContexts, NumDeferredContexts); -} - - -/// Attaches to existing D3D12 device - -/// \param [in] pd3d12NativeDevice - pointer to native D3D12 device -/// \param [in] CommandQueueCount - Number of command queues -/// \param [in] ppCommandQueues - pointer to the array of command queues -/// \param [in] EngineAttribs - Engine creation attributes. -/// \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 -/// the contexts will be written. Pointer to the immediate -/// context goes at position 0. If NumDeferredContexts > 0, -/// pointers to the deferred contexts go afterwards. -/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number -/// of deferred contexts is requested, pointers to the -/// contexts are written to ppContexts array starting -/// at position 1 -void EngineFactoryD3D12Impl::AttachToD3D12Device(void* pd3d12NativeDevice, - size_t CommandQueueCount, - ICommandQueueD3D12** ppCommandQueues, - const EngineD3D12Attribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts) -{ - if (EngineAttribs.DebugMessageCallback != nullptr) - SetDebugMessageCallback(EngineAttribs.DebugMessageCallback); - - VERIFY( pd3d12NativeDevice && ppCommandQueues && ppDevice && ppContexts, "Null pointer provided" ); - if( !pd3d12NativeDevice || !ppCommandQueues || !ppDevice || !ppContexts ) - return; - - *ppDevice = nullptr; - memset(ppContexts, 0, sizeof(*ppContexts) * (1+NumDeferredContexts)); - - try - { - SetRawAllocator(EngineAttribs.pRawMemAllocator); - auto &RawMemAllocator = GetRawAllocator(); - auto d3d12Device = reinterpret_cast(pd3d12NativeDevice); - RenderDeviceD3D12Impl *pRenderDeviceD3D12( NEW_RC_OBJ(RawMemAllocator, "RenderDeviceD3D12Impl instance", RenderDeviceD3D12Impl)(RawMemAllocator, EngineAttribs, d3d12Device, CommandQueueCount, ppCommandQueues, NumDeferredContexts ) ); - pRenderDeviceD3D12->QueryInterface(IID_RenderDevice, reinterpret_cast(ppDevice) ); - - RefCntAutoPtr pImmediateCtxD3D12( NEW_RC_OBJ(RawMemAllocator, "DeviceContextD3D12Impl instance", DeviceContextD3D12Impl)(pRenderDeviceD3D12, false, EngineAttribs, 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) ); - pRenderDeviceD3D12->SetImmediateContext(pImmediateCtxD3D12); - - for (Uint32 DeferredCtx = 0; DeferredCtx < NumDeferredContexts; ++DeferredCtx) - { - RefCntAutoPtr pDeferredCtxD3D12( NEW_RC_OBJ(RawMemAllocator, "DeviceContextD3D12Impl instance", DeviceContextD3D12Impl)(pRenderDeviceD3D12, true, EngineAttribs, 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) ); - pRenderDeviceD3D12->SetDeferredContext(DeferredCtx, pDeferredCtxD3D12); - } - } - catch( const std::runtime_error & ) - { - if( *ppDevice ) - { - (*ppDevice)->Release(); - *ppDevice = nullptr; - } - for(Uint32 ctx=0; ctx < 1 + NumDeferredContexts; ++ctx) - { - if( ppContexts[ctx] != nullptr ) - { - ppContexts[ctx]->Release(); - ppContexts[ctx] = nullptr; - } - } - - LOG_ERROR( "Failed to create device and contexts" ); - } -} - -/// Creates a swap chain for Direct3D12-based engine implementation - -/// \param [in] pDevice - Pointer to the render device -/// \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 -/// the swap chain will be associated with: -/// * On Win32 platform, this should be window handle (HWND) -/// * On Universal Windows Platform, this should be reference to the -/// core window (Windows::UI::Core::CoreWindow) -/// -/// \param [out] ppSwapChain - Address of the memory location where pointer to the new -/// swap chain will be written -void EngineFactoryD3D12Impl::CreateSwapChainD3D12( IRenderDevice* pDevice, - IDeviceContext* pImmediateContext, - const SwapChainDesc& SCDesc, - const FullScreenModeDesc& FSDesc, - void* pNativeWndHandle, - ISwapChain** ppSwapChain ) -{ - VERIFY( ppSwapChain, "Null pointer provided" ); - if( !ppSwapChain ) - return; - - *ppSwapChain = nullptr; - - try - { - auto *pDeviceD3D12 = ValidatedCast( pDevice ); - auto *pDeviceContextD3D12 = ValidatedCast(pImmediateContext); - auto &RawMemAllocator = GetRawAllocator(); - auto *pSwapChainD3D12 = NEW_RC_OBJ(RawMemAllocator, "SwapChainD3D12Impl instance", SwapChainD3D12Impl)(SCDesc, FSDesc, pDeviceD3D12, pDeviceContextD3D12, pNativeWndHandle); - pSwapChainD3D12->QueryInterface( IID_SwapChain, reinterpret_cast(ppSwapChain) ); - - pDeviceContextD3D12->SetSwapChain(pSwapChainD3D12); - // Bind default render target - pDeviceContextD3D12->SetRenderTargets( 0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); - // Set default viewport - pDeviceContextD3D12->SetViewports( 1, nullptr, 0, 0 ); - - auto NumDeferredCtx = pDeviceD3D12->GetNumDeferredContexts(); - for (size_t ctx = 0; ctx < NumDeferredCtx; ++ctx) - { - if (auto pDeferredCtx = pDeviceD3D12->GetDeferredContext(ctx)) - { - auto *pDeferredCtxD3D12 = pDeferredCtx.RawPtr(); - 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 - // RTV of an inactive buffer in the swap chain - } - } - } - catch( const std::runtime_error & ) - { - if( *ppSwapChain ) - { - (*ppSwapChain)->Release(); - *ppSwapChain = nullptr; - } - - LOG_ERROR( "Failed to create the swap chain" ); - } -} - - -#ifdef DOXYGEN -/// Loads Direct3D12-based engine implementation and exports factory functions -/// \param [out] GetFactoryFunc - Pointer to the function that returns factory for D3D12 engine implementation. -/// See EngineFactoryD3D12Impl. -/// \remarks Depending on the configuration and platform, the function loads different dll: -/// Platform\\Configuration | Debug | Release -/// --------------------------|-------------------------------|---------------------------- -/// x86 | GraphicsEngineD3D12_32d.dll | GraphicsEngineD3D12_32r.dll -/// x64 | GraphicsEngineD3D12_64d.dll | GraphicsEngineD3D12_64r.dll -/// -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; -} -#endif - - -IEngineFactoryD3D12* GetEngineFactoryD3D12() -{ - return EngineFactoryD3D12Impl::GetInstance(); -} - -} diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp index de7458b6..393c1c3b 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderResourceLayoutD3D12.cpp @@ -749,7 +749,7 @@ void ShaderResourceLayoutD3D12::CopyStaticResourceDesriptorHandles(const ShaderR // 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 assigned to static shader variable '", res.Attribs.GetPrintName(ArrInd), "' in shader '", GetShaderName(), "'." ); + 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()); diff --git a/Graphics/GraphicsEngineVulkan/CMakeLists.txt b/Graphics/GraphicsEngineVulkan/CMakeLists.txt index 18887fea..be94ed10 100644 --- a/Graphics/GraphicsEngineVulkan/CMakeLists.txt +++ b/Graphics/GraphicsEngineVulkan/CMakeLists.txt @@ -51,10 +51,10 @@ set(INTERFACE interface/BufferViewVk.h interface/CommandQueueVk.h interface/DeviceContextVk.h + interface/EngineFactoryVk.h interface/FenceVk.h interface/PipelineStateVk.h interface/RenderDeviceVk.h - interface/RenderDeviceFactoryVk.h interface/SamplerVk.h interface/ShaderVk.h interface/ShaderResourceBindingVk.h @@ -71,6 +71,7 @@ set(SRC src/CommandQueueVkImpl.cpp src/DescriptorPoolManager.cpp src/DeviceContextVkImpl.cpp + src/EngineFactoryVk.cpp src/FenceVkImpl.cpp src/VulkanDynamicHeap.cpp src/FramebufferCache.cpp @@ -79,7 +80,6 @@ set(SRC src/PipelineStateVkImpl.cpp src/RenderDeviceVkImpl.cpp src/RenderPassCache.cpp - src/RenderDeviceFactoryVk.cpp src/SamplerVkImpl.cpp src/ShaderVkImpl.cpp src/ShaderResourceBindingVkImpl.cpp diff --git a/Graphics/GraphicsEngineVulkan/include/DeviceContextVkImpl.h b/Graphics/GraphicsEngineVulkan/include/DeviceContextVkImpl.h index 84e8bfdd..09eaa1a5 100644 --- a/Graphics/GraphicsEngineVulkan/include/DeviceContextVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/DeviceContextVkImpl.h @@ -62,7 +62,7 @@ public: DeviceContextVkImpl(IReferenceCounters* pRefCounters, class RenderDeviceVkImpl* pDevice, bool bIsDeferred, - const EngineVkAttribs& Attribs, + const EngineVkCreateInfo& EngineCI, Uint32 ContextId, Uint32 CommandQueueId, std::shared_ptr GenerateMipsHelper); diff --git a/Graphics/GraphicsEngineVulkan/include/RenderDeviceVkImpl.h b/Graphics/GraphicsEngineVulkan/include/RenderDeviceVkImpl.h index c0e2847b..167949df 100644 --- a/Graphics/GraphicsEngineVulkan/include/RenderDeviceVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/RenderDeviceVkImpl.h @@ -55,11 +55,11 @@ class RenderDeviceVkImpl final : public RenderDeviceNextGenBase, ICommandQueueVk>; - RenderDeviceVkImpl( IReferenceCounters* pRefCounters, - IMemoryAllocator& RawMemAllocator, - const EngineVkAttribs& CreationAttribs, - size_t CommandQueueCount, - ICommandQueueVk** pCmdQueues, + RenderDeviceVkImpl( IReferenceCounters* pRefCounters, + IMemoryAllocator& RawMemAllocator, + const EngineVkCreateInfo& EngineCI, + size_t CommandQueueCount, + ICommandQueueVk** pCmdQueues, std::shared_ptr Instance, std::unique_ptr PhysicalDevice, std::shared_ptr LogicalDevice, @@ -134,7 +134,7 @@ private: std::unique_ptr m_PhysicalDevice; std::shared_ptr m_LogicalVkDevice; - EngineVkAttribs m_EngineAttribs; + EngineVkCreateInfo m_EngineAttribs; FramebufferCache m_FramebufferCache; RenderPassCache m_RenderPassCache; diff --git a/Graphics/GraphicsEngineVulkan/interface/EngineFactoryVk.h b/Graphics/GraphicsEngineVulkan/interface/EngineFactoryVk.h new file mode 100644 index 00000000..861f5514 --- /dev/null +++ b/Graphics/GraphicsEngineVulkan/interface/EngineFactoryVk.h @@ -0,0 +1,128 @@ +/* Copyright 2015-2019 Egor Yusov +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. +* +* In no event and under no legal theory, whether in tort (including negligence), +* contract, or otherwise, unless required by applicable law (such as deliberate +* and grossly negligent acts) or agreed to in writing, shall any Contributor be +* liable for any damages, including any direct, indirect, special, incidental, +* or consequential damages of any character arising as a result of this License or +* out of the use or inability to use the software (including but not limited to damages +* for loss of goodwill, work stoppage, computer failure or malfunction, or any and +* all other commercial damages or losses), even if such Contributor has been advised +* of the possibility of such damages. +*/ + +#pragma once + +/// \file +/// Declaration of functions that initialize Direct3D12-based engine implementation + +#include + +#include "../../GraphicsEngine/interface/RenderDevice.h" +#include "../../GraphicsEngine/interface/DeviceContext.h" +#include "../../GraphicsEngine/interface/SwapChain.h" + +#if PLATFORM_ANDROID || PLATFORM_LINUX || PLATFORM_MACOS || PLATFORM_IOS || (PLATFORM_WIN32 && !defined(_MSC_VER)) + + // https://gcc.gnu.org/wiki/Visibility +# define API_QUALIFIER __attribute__((visibility("default"))) + +#elif PLATFORM_WIN32 + +# define API_QUALIFIER + +#else +# error Unsupported platform +#endif + +namespace Diligent +{ + +class IEngineFactoryVk +{ +public: + virtual void CreateDeviceAndContextsVk(const EngineVkCreateInfo& EngineCI, + IRenderDevice **ppDevice, + IDeviceContext **ppContexts, + Uint32 NumDeferredContexts) = 0; + + //virtual void AttachToVulkanDevice(void *pVkNativeDevice, + // class ICommandQueueVk *pCommandQueue, + // const EngineVkCreateInfo& EngineCI, + // IRenderDevice **ppDevice, + // IDeviceContext **ppContexts, + // Uint32 NumDeferredContexts) = 0; + + virtual void CreateSwapChainVk(IRenderDevice* pDevice, + IDeviceContext* pImmediateContext, + const SwapChainDesc& SwapChainDesc, + void* pNativeWndHandle, + ISwapChain** ppSwapChain) = 0; + +}; + + +#if ENGINE_DLL && PLATFORM_WIN32 && defined(_MSC_VER) + +# define EXPLICITLY_LOAD_ENGINE_VK_DLL 1 + + typedef IEngineFactoryVk* (*GetEngineFactoryVkType)(); + + static bool LoadGraphicsEngineVk(GetEngineFactoryVkType& GetFactoryFunc) + { + GetFactoryFunc = nullptr; + std::string LibName = "GraphicsEngineVk_"; + +# if _WIN64 + LibName += "64"; +# else + LibName += "32"; +# endif + +# ifdef _DEBUG + LibName += "d"; +# else + LibName += "r"; +# endif + + LibName += ".dll"; + auto hModule = LoadLibraryA(LibName.c_str()); + 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, "GetEngineFactoryVk")); + if (GetFactoryFunc == NULL) + { + std::stringstream ss; + ss << "Failed to load GetEngineFactoryVk() from " << LibName << " library.\n"; + OutputDebugStringA(ss.str().c_str()); + FreeLibrary(hModule); + return false; + } + + return true; + } + +#else + + API_QUALIFIER + IEngineFactoryVk* GetEngineFactoryVk(); + +#endif + +} diff --git a/Graphics/GraphicsEngineVulkan/interface/RenderDeviceFactoryVk.h b/Graphics/GraphicsEngineVulkan/interface/RenderDeviceFactoryVk.h deleted file mode 100644 index b5de2664..00000000 --- a/Graphics/GraphicsEngineVulkan/interface/RenderDeviceFactoryVk.h +++ /dev/null @@ -1,128 +0,0 @@ -/* Copyright 2015-2019 Egor Yusov -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. -* -* In no event and under no legal theory, whether in tort (including negligence), -* contract, or otherwise, unless required by applicable law (such as deliberate -* and grossly negligent acts) or agreed to in writing, shall any Contributor be -* liable for any damages, including any direct, indirect, special, incidental, -* or consequential damages of any character arising as a result of this License or -* out of the use or inability to use the software (including but not limited to damages -* for loss of goodwill, work stoppage, computer failure or malfunction, or any and -* all other commercial damages or losses), even if such Contributor has been advised -* of the possibility of such damages. -*/ - -#pragma once - -/// \file -/// Declaration of functions that initialize Direct3D12-based engine implementation - -#include - -#include "../../GraphicsEngine/interface/RenderDevice.h" -#include "../../GraphicsEngine/interface/DeviceContext.h" -#include "../../GraphicsEngine/interface/SwapChain.h" - -#if PLATFORM_ANDROID || PLATFORM_LINUX || PLATFORM_MACOS || PLATFORM_IOS || (PLATFORM_WIN32 && !defined(_MSC_VER)) - - // https://gcc.gnu.org/wiki/Visibility -# define API_QUALIFIER __attribute__((visibility("default"))) - -#elif PLATFORM_WIN32 - -# define API_QUALIFIER - -#else -# error Unsupported platform -#endif - -namespace Diligent -{ - -class IEngineFactoryVk -{ -public: - virtual void CreateDeviceAndContextsVk(const EngineVkAttribs& CreationAttribs, - IRenderDevice **ppDevice, - IDeviceContext **ppContexts, - Uint32 NumDeferredContexts) = 0; - - //virtual void AttachToVulkanDevice(void *pVkNativeDevice, - // class ICommandQueueVk *pCommandQueue, - // const EngineVkAttribs& EngineAttribs, - // IRenderDevice **ppDevice, - // IDeviceContext **ppContexts, - // Uint32 NumDeferredContexts) = 0; - - virtual void CreateSwapChainVk(IRenderDevice *pDevice, - IDeviceContext *pImmediateContext, - const SwapChainDesc& SwapChainDesc, - void* pNativeWndHandle, - ISwapChain **ppSwapChain) = 0; - -}; - - -#if ENGINE_DLL && PLATFORM_WIN32 && defined(_MSC_VER) - -# define EXPLICITLY_LOAD_ENGINE_VK_DLL 1 - - typedef IEngineFactoryVk* (*GetEngineFactoryVkType)(); - - static bool LoadGraphicsEngineVk(GetEngineFactoryVkType &GetFactoryFunc) - { - GetFactoryFunc = nullptr; - std::string LibName = "GraphicsEngineVk_"; - -# if _WIN64 - LibName += "64"; -# else - LibName += "32"; -# endif - -# ifdef _DEBUG - LibName += "d"; -# else - LibName += "r"; -# endif - - LibName += ".dll"; - auto hModule = LoadLibraryA(LibName.c_str()); - 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, "GetEngineFactoryVk")); - if (GetFactoryFunc == NULL) - { - std::stringstream ss; - ss << "Failed to load GetEngineFactoryVk() from " << LibName << " library.\n"; - OutputDebugStringA(ss.str().c_str()); - FreeLibrary(hModule); - return false; - } - - return true; - } - -#else - - API_QUALIFIER - IEngineFactoryVk* GetEngineFactoryVk(); - -#endif - -} diff --git a/Graphics/GraphicsEngineVulkan/src/DeviceContextVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/DeviceContextVkImpl.cpp index 0200476d..daabca38 100644 --- a/Graphics/GraphicsEngineVulkan/src/DeviceContextVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/DeviceContextVkImpl.cpp @@ -45,20 +45,20 @@ namespace Diligent return ss.str(); } - DeviceContextVkImpl::DeviceContextVkImpl( IReferenceCounters* pRefCounters, - RenderDeviceVkImpl* pDeviceVkImpl, - bool bIsDeferred, - const EngineVkAttribs& Attribs, - Uint32 ContextId, - Uint32 CommandQueueId, - std::shared_ptr GenerateMipsHelper) : + DeviceContextVkImpl::DeviceContextVkImpl(IReferenceCounters* pRefCounters, + RenderDeviceVkImpl* pDeviceVkImpl, + bool bIsDeferred, + const EngineVkCreateInfo& EngineCI, + Uint32 ContextId, + Uint32 CommandQueueId, + std::shared_ptr GenerateMipsHelper) : TDeviceContextBase { pRefCounters, pDeviceVkImpl, ContextId, CommandQueueId, - bIsDeferred ? std::numeric_limits::max() : Attribs.NumCommandsToFlushCmdBuffer, + bIsDeferred ? std::numeric_limits::max() : EngineCI.NumCommandsToFlushCmdBuffer, bIsDeferred }, m_CommandBuffer { pDeviceVkImpl->GetLogicalDevice().GetEnabledGraphicsShaderStages() }, @@ -76,13 +76,13 @@ namespace Diligent { *pDeviceVkImpl, GetContextObjectName("Upload heap", bIsDeferred, ContextId), - Attribs.UploadHeapPageSize + EngineCI.UploadHeapPageSize }, m_DynamicHeap { pDeviceVkImpl->GetDynamicMemoryManager(), GetContextObjectName("Dynamic heap", bIsDeferred, ContextId), - Attribs.DynamicHeapPageSize + EngineCI.DynamicHeapPageSize }, m_DynamicDescrSetAllocator { diff --git a/Graphics/GraphicsEngineVulkan/src/EngineFactoryVk.cpp b/Graphics/GraphicsEngineVulkan/src/EngineFactoryVk.cpp new file mode 100644 index 00000000..acb6265a --- /dev/null +++ b/Graphics/GraphicsEngineVulkan/src/EngineFactoryVk.cpp @@ -0,0 +1,372 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +/// \file +/// Routines that initialize Vulkan-based engine implementation + +#include "pch.h" +#include +#include "EngineFactoryVk.h" +#include "RenderDeviceVkImpl.h" +#include "DeviceContextVkImpl.h" +#include "SwapChainVkImpl.h" +#include "EngineMemory.h" +#include "CommandQueueVkImpl.h" +#include "VulkanUtilities/VulkanInstance.h" +#include "VulkanUtilities/VulkanPhysicalDevice.h" + +namespace Diligent +{ + +/// Engine factory for Vk implementation +class EngineFactoryVkImpl : public IEngineFactoryVk +{ +public: + static EngineFactoryVkImpl* GetInstance() + { + static EngineFactoryVkImpl TheFactory; + return &TheFactory; + } + + void CreateDeviceAndContextsVk(const EngineVkCreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts)override final; + + void AttachToVulkanDevice(std::shared_ptr Instance, + std::unique_ptr PhysicalDevice, + std::shared_ptr LogicalDevice, + size_t CommandQueueCount, + ICommandQueueVk** ppCommandQueues, + const EngineVkCreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts);//override final; + + void CreateSwapChainVk(IRenderDevice* pDevice, + IDeviceContext* pImmediateContext, + const SwapChainDesc& SwapChainDesc, + void* pNativeWndHandle, + ISwapChain** ppSwapChain)override final; +}; + +/// Creates render device and device contexts for Vulkan backend + +/// \param [in] EngineCI - Engine creation attributes. +/// \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 +/// the contexts will be written. The new immediate +/// context goes at position 0. If NumDeferredContexts > 0, +/// pointers to the deferred contexts are written afterwards. +/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number +/// of deferred contexts is requested, pointers to the +/// contexts are written to ppContexts array starting +/// at position 1 +void EngineFactoryVkImpl::CreateDeviceAndContextsVk(const EngineVkCreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts) +{ + VERIFY( ppDevice && ppContexts, "Null pointer provided" ); + if( !ppDevice || !ppContexts ) + return; + +#if 0 + for (Uint32 Type = Vk_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; Type < Vk_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; ++Type) + { + 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); + return; + } + + if ((CPUHeapAllocSize % 16) != 0) + { + LOG_ERROR("CPU Heap allocation size (", CPUHeapAllocSize, ") is expected to be multiple of 16"); + return; + } + } +#endif + + SetRawAllocator(EngineCI.pRawMemAllocator); + + *ppDevice = nullptr; + memset(ppContexts, 0, sizeof(*ppContexts) * (1 + NumDeferredContexts)); + + try + { + auto Instance = VulkanUtilities::VulkanInstance::Create( + EngineCI.EnableValidation, + EngineCI.GlobalExtensionCount, + EngineCI.ppGlobalExtensionNames, + reinterpret_cast(EngineCI.pVkAllocator)); + + auto vkDevice = Instance->SelectPhysicalDevice(); + auto PhysicalDevice = VulkanUtilities::VulkanPhysicalDevice::Create(vkDevice); + + // If an implementation exposes any queue family that supports graphics operations, + // at least one queue family of at least one physical device exposed by the implementation + // must support both graphics and compute operations. + + VkDeviceQueueCreateInfo QueueInfo{}; + QueueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + QueueInfo.flags = 0; // reserved for future use + // All commands that are allowed on a queue that supports transfer operations are also allowed on a + // queue that supports either graphics or compute operations.Thus, if the capabilities of a queue family + // include VK_QUEUE_GRAPHICS_BIT or VK_QUEUE_COMPUTE_BIT, then reporting the VK_QUEUE_TRANSFER_BIT + // capability separately for that queue family is optional (4.1). + QueueInfo.queueFamilyIndex = PhysicalDevice->FindQueueFamily(VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT); + QueueInfo.queueCount = 1; + const float defaultQueuePriority = 1.0f; // Ask for highest priority for our queue. (range [0,1]) + QueueInfo.pQueuePriorities = &defaultQueuePriority; + + VkDeviceCreateInfo DeviceCreateInfo = {}; + DeviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; + DeviceCreateInfo.flags = 0; // Reserved for future use + // https://www.khronos.org/registry/vulkan/specs/1.0/html/vkspec.html#extended-functionality-device-layer-deprecation + DeviceCreateInfo.enabledLayerCount = 0; // Deprecated and ignored. + DeviceCreateInfo.ppEnabledLayerNames = nullptr; // Deprecated and ignored + DeviceCreateInfo.queueCreateInfoCount = 1; + DeviceCreateInfo.pQueueCreateInfos = &QueueInfo; + VkPhysicalDeviceFeatures DeviceFeatures = {}; + DeviceFeatures.depthBiasClamp = EngineCI.EnabledFeatures.depthBiasClamp ? VK_TRUE : VK_FALSE; + DeviceFeatures.fillModeNonSolid = EngineCI.EnabledFeatures.fillModeNonSolid ? VK_TRUE : VK_FALSE; + DeviceFeatures.depthClamp = EngineCI.EnabledFeatures.depthClamp ? VK_TRUE : VK_FALSE; + DeviceFeatures.independentBlend = EngineCI.EnabledFeatures.independentBlend ? VK_TRUE : VK_FALSE; + DeviceFeatures.samplerAnisotropy = EngineCI.EnabledFeatures.samplerAnisotropy ? VK_TRUE : VK_FALSE; + DeviceFeatures.geometryShader = EngineCI.EnabledFeatures.geometryShader ? VK_TRUE : VK_FALSE; + DeviceFeatures.tessellationShader = EngineCI.EnabledFeatures.tessellationShader ? VK_TRUE : VK_FALSE; + DeviceFeatures.dualSrcBlend = EngineCI.EnabledFeatures.dualSrcBlend ? VK_TRUE : VK_FALSE; + DeviceFeatures.multiViewport = EngineCI.EnabledFeatures.multiViewport ? VK_TRUE : VK_FALSE; + DeviceFeatures.imageCubeArray = EngineCI.EnabledFeatures.imageCubeArray ? VK_TRUE : VK_FALSE; + DeviceFeatures.textureCompressionBC = EngineCI.EnabledFeatures.textureCompressionBC ? VK_TRUE : VK_FALSE; + DeviceFeatures.vertexPipelineStoresAndAtomics = EngineCI.EnabledFeatures.vertexPipelineStoresAndAtomics ? VK_TRUE : VK_FALSE; + DeviceFeatures.fragmentStoresAndAtomics = EngineCI.EnabledFeatures.fragmentStoresAndAtomics ? VK_TRUE : VK_FALSE; + DeviceFeatures.shaderStorageImageExtendedFormats = EngineCI.EnabledFeatures.shaderStorageImageExtendedFormats ? VK_TRUE : VK_FALSE; + DeviceCreateInfo.pEnabledFeatures = &DeviceFeatures; // NULL or a pointer to a VkPhysicalDeviceFeatures structure that contains + // boolean indicators of all the features to be enabled. + + std::vector DeviceExtensions = + { + VK_KHR_SWAPCHAIN_EXTENSION_NAME, + VK_KHR_MAINTENANCE1_EXTENSION_NAME // To allow negative viewport height + }; + DeviceCreateInfo.ppEnabledExtensionNames = DeviceExtensions.empty() ? nullptr : DeviceExtensions.data(); + DeviceCreateInfo.enabledExtensionCount = static_cast(DeviceExtensions.size()); + + auto vkAllocator = Instance->GetVkAllocator(); + auto vkPhysicalDevice = PhysicalDevice->GetVkDeviceHandle(); + auto LogicalDevice = VulkanUtilities::VulkanLogicalDevice::Create(vkPhysicalDevice, DeviceCreateInfo, vkAllocator); + + RefCntAutoPtr pCmdQueueVk; + auto &RawMemAllocator = GetRawAllocator(); + pCmdQueueVk = NEW_RC_OBJ(RawMemAllocator, "CommandQueueVk instance", CommandQueueVkImpl)(LogicalDevice, QueueInfo.queueFamilyIndex); + + std::array CommandQueues = {{pCmdQueueVk}}; + AttachToVulkanDevice(Instance, std::move(PhysicalDevice), LogicalDevice, CommandQueues.size(), CommandQueues.data(), EngineCI, ppDevice, ppContexts, NumDeferredContexts); + + FenceDesc Desc; + Desc.Name = "Command queue fence"; + // Render device owns command queue that in turn owns the fence, so it is an internal device object + bool IsDeviceInternal = true; + auto* pRenderDeviceVk = ValidatedCast(*ppDevice); + RefCntAutoPtr pFenceVk( NEW_RC_OBJ(RawMemAllocator, "FenceVkImpl instance", FenceVkImpl)(pRenderDeviceVk, Desc, IsDeviceInternal) ); + pCmdQueueVk->SetFence(std::move(pFenceVk)); + } + catch(std::runtime_error& ) + { + return; + } +} + +/// Attaches to existing Vulkan device + +/// \param [in] Instance - shared pointer to a VulkanUtilities::VulkanInstance object +/// \param [in] PhysicalDevice - pointer to the object representing physical device +/// \param [in] LogicalDevice - shared pointer to a VulkanUtilities::VulkanLogicalDevice object +/// \param [in] pCommandQueue - pointer to the implementation of command queue +/// \param [in] EngineCI - Engine creation attributes. +/// \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 +/// the contexts will be written. Pointer to the immediate +/// context goes at position 0. If NumDeferredContexts > 0, +/// pointers to the deferred contexts go afterwards. +/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number +/// of deferred contexts is requested, pointers to the +/// contexts are written to ppContexts array starting +/// at position 1 +void EngineFactoryVkImpl::AttachToVulkanDevice(std::shared_ptr Instance, + std::unique_ptr PhysicalDevice, + std::shared_ptr LogicalDevice, + size_t CommandQueueCount, + ICommandQueueVk** ppCommandQueues, + const EngineVkCreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts) +{ + VERIFY( ppCommandQueues && ppDevice && ppContexts, "Null pointer provided" ); + if(!LogicalDevice || !ppCommandQueues || !ppDevice || !ppContexts ) + return; + + *ppDevice = nullptr; + memset(ppContexts, 0, sizeof(*ppContexts) * (1+NumDeferredContexts)); + + try + { + auto &RawMemAllocator = GetRawAllocator(); + RenderDeviceVkImpl *pRenderDeviceVk( NEW_RC_OBJ(RawMemAllocator, "RenderDeviceVkImpl instance", RenderDeviceVkImpl)(RawMemAllocator, EngineCI, CommandQueueCount, ppCommandQueues, Instance, std::move(PhysicalDevice), LogicalDevice, NumDeferredContexts ) ); + pRenderDeviceVk->QueryInterface(IID_RenderDevice, reinterpret_cast(ppDevice) ); + + std::shared_ptr GenerateMipsHelper(new GenerateMipsVkHelper(*pRenderDeviceVk)); + + RefCntAutoPtr pImmediateCtxVk( NEW_RC_OBJ(RawMemAllocator, "DeviceContextVkImpl instance", DeviceContextVkImpl)(pRenderDeviceVk, false, EngineCI, 0, 0, GenerateMipsHelper) ); + // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceVk will + // keep a weak reference to the context + pImmediateCtxVk->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts) ); + pRenderDeviceVk->SetImmediateContext(pImmediateCtxVk); + + for (Uint32 DeferredCtx = 0; DeferredCtx < NumDeferredContexts; ++DeferredCtx) + { + RefCntAutoPtr pDeferredCtxVk( NEW_RC_OBJ(RawMemAllocator, "DeviceContextVkImpl instance", DeviceContextVkImpl)(pRenderDeviceVk, true, EngineCI, 1+DeferredCtx, 0, GenerateMipsHelper) ); + // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceVk will + // keep a weak reference to the context + pDeferredCtxVk->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts + 1 + DeferredCtx) ); + pRenderDeviceVk->SetDeferredContext(DeferredCtx, pDeferredCtxVk); + } + } + catch( const std::runtime_error & ) + { + if( *ppDevice ) + { + (*ppDevice)->Release(); + *ppDevice = nullptr; + } + for(Uint32 ctx=0; ctx < 1 + NumDeferredContexts; ++ctx) + { + if( ppContexts[ctx] != nullptr ) + { + ppContexts[ctx]->Release(); + ppContexts[ctx] = nullptr; + } + } + + LOG_ERROR( "Failed to create device and contexts" ); + } +} + + +/// Creates a swap chain for Direct3D12-based engine implementation + +/// \param [in] pDevice - Pointer to the render device +/// \param [in] pImmediateContext - Pointer to the immediate device context +/// \param [in] SCDesc - Swap chain description +/// \param [in] pNativeWndHandle - Platform-specific native handle of the window +/// the swap chain will be associated with: +/// * On Win32 platform, this should be window handle (HWND) +/// * On Universal Windows Platform, this should be reference to the +/// core window (Windows::UI::Core::CoreWindow) +/// +/// \param [out] ppSwapChain - Address of the memory location where pointer to the new +/// swap chain will be written +void EngineFactoryVkImpl::CreateSwapChainVk(IRenderDevice* pDevice, + IDeviceContext* pImmediateContext, + const SwapChainDesc& SCDesc, + void* pNativeWndHandle, + ISwapChain** ppSwapChain) +{ + VERIFY( ppSwapChain, "Null pointer provided" ); + if( !ppSwapChain ) + return; + + *ppSwapChain = nullptr; + + try + { + auto *pDeviceVk = ValidatedCast( pDevice ); + auto *pDeviceContextVk = ValidatedCast(pImmediateContext); + auto &RawMemAllocator = GetRawAllocator(); + auto *pSwapChainVk = NEW_RC_OBJ(RawMemAllocator, "SwapChainVkImpl instance", SwapChainVkImpl)(SCDesc, pDeviceVk, pDeviceContextVk, pNativeWndHandle); + pSwapChainVk->QueryInterface( IID_SwapChain, reinterpret_cast(ppSwapChain) ); + + pDeviceContextVk->SetSwapChain(pSwapChainVk); + // Bind default render target + pDeviceContextVk->SetRenderTargets( 0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); + // Set default viewport + pDeviceContextVk->SetViewports( 1, nullptr, 0, 0 ); + + auto NumDeferredCtx = pDeviceVk->GetNumDeferredContexts(); + for (size_t ctx = 0; ctx < NumDeferredCtx; ++ctx) + { + if (auto pDeferredCtx = pDeviceVk->GetDeferredContext(ctx)) + { + auto *pDeferredCtxVk = pDeferredCtx.RawPtr(); + pDeferredCtxVk->SetSwapChain(pSwapChainVk); + // 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 + // RTV of an inactive buffer in the swap chain + } + } + } + catch( const std::runtime_error & ) + { + if( *ppSwapChain ) + { + (*ppSwapChain)->Release(); + *ppSwapChain = nullptr; + } + + LOG_ERROR( "Failed to create the swap chain" ); + } +} + + +#ifdef DOXYGEN +/// Loads Direct3D12-based engine implementation and exports factory functions +/// \param [out] GetFactoryFunc - Pointer to the function that returns factory for Vk engine implementation. +/// See EngineFactoryVkImpl. +/// \remarks Depending on the configuration and platform, the function loads different dll: +/// Platform\\Configuration | Debug | Release +/// --------------------------|-------------------------------|---------------------------- +/// x86 | GraphicsEngineVk_32d.dll | GraphicsEngineVk_32r.dll +/// x64 | GraphicsEngineVk_64d.dll | GraphicsEngineVk_64r.dll +/// +void LoadGraphicsEngineVk(GetEngineFactoryVkType &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; +} +#endif + +API_QUALIFIER +IEngineFactoryVk* GetEngineFactoryVk() +{ + return EngineFactoryVkImpl::GetInstance(); +} + +} diff --git a/Graphics/GraphicsEngineVulkan/src/RenderDeviceFactoryVk.cpp b/Graphics/GraphicsEngineVulkan/src/RenderDeviceFactoryVk.cpp deleted file mode 100644 index a4ab8ae3..00000000 --- a/Graphics/GraphicsEngineVulkan/src/RenderDeviceFactoryVk.cpp +++ /dev/null @@ -1,372 +0,0 @@ -/* Copyright 2015-2019 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -/// \file -/// Routines that initialize Vulkan-based engine implementation - -#include "pch.h" -#include -#include "RenderDeviceFactoryVk.h" -#include "RenderDeviceVkImpl.h" -#include "DeviceContextVkImpl.h" -#include "SwapChainVkImpl.h" -#include "EngineMemory.h" -#include "CommandQueueVkImpl.h" -#include "VulkanUtilities/VulkanInstance.h" -#include "VulkanUtilities/VulkanPhysicalDevice.h" - -namespace Diligent -{ - -/// Engine factory for Vk implementation -class EngineFactoryVkImpl : public IEngineFactoryVk -{ -public: - static EngineFactoryVkImpl* GetInstance() - { - static EngineFactoryVkImpl TheFactory; - return &TheFactory; - } - - void CreateDeviceAndContextsVk( const EngineVkAttribs& CreationAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts)override final; - - void AttachToVulkanDevice(std::shared_ptr Instance, - std::unique_ptr PhysicalDevice, - std::shared_ptr LogicalDevice, - size_t CommandQueueCount, - ICommandQueueVk** ppCommandQueues, - const EngineVkAttribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts);//override final; - - void CreateSwapChainVk( IRenderDevice* pDevice, - IDeviceContext* pImmediateContext, - const SwapChainDesc& SwapChainDesc, - void* pNativeWndHandle, - ISwapChain** ppSwapChain )override final; -}; - -/// Creates render device and device contexts for Vulkan backend - -/// \param [in] CreationAttribs - Engine creation attributes. -/// \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 -/// the contexts will be written. The new immediate -/// context goes at position 0. If NumDeferredContexts > 0, -/// pointers to the deferred contexts are written afterwards. -/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number -/// of deferred contexts is requested, pointers to the -/// contexts are written to ppContexts array starting -/// at position 1 -void EngineFactoryVkImpl::CreateDeviceAndContextsVk( const EngineVkAttribs& CreationAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts) -{ - VERIFY( ppDevice && ppContexts, "Null pointer provided" ); - if( !ppDevice || !ppContexts ) - return; - -#if 0 - for (Uint32 Type = Vk_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; Type < Vk_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; ++Type) - { - auto CPUHeapAllocSize = CreationAttribs.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); - return; - } - - if ((CPUHeapAllocSize % 16) != 0) - { - LOG_ERROR("CPU Heap allocation size (", CPUHeapAllocSize, ") is expected to be multiple of 16"); - return; - } - } -#endif - - SetRawAllocator(CreationAttribs.pRawMemAllocator); - - *ppDevice = nullptr; - memset(ppContexts, 0, sizeof(*ppContexts) * (1 + NumDeferredContexts)); - - try - { - auto Instance = VulkanUtilities::VulkanInstance::Create( - CreationAttribs.EnableValidation, - CreationAttribs.GlobalExtensionCount, - CreationAttribs.ppGlobalExtensionNames, - reinterpret_cast(CreationAttribs.pVkAllocator)); - - auto vkDevice = Instance->SelectPhysicalDevice(); - auto PhysicalDevice = VulkanUtilities::VulkanPhysicalDevice::Create(vkDevice); - - // If an implementation exposes any queue family that supports graphics operations, - // at least one queue family of at least one physical device exposed by the implementation - // must support both graphics and compute operations. - - VkDeviceQueueCreateInfo QueueInfo{}; - QueueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; - QueueInfo.flags = 0; // reserved for future use - // All commands that are allowed on a queue that supports transfer operations are also allowed on a - // queue that supports either graphics or compute operations.Thus, if the capabilities of a queue family - // include VK_QUEUE_GRAPHICS_BIT or VK_QUEUE_COMPUTE_BIT, then reporting the VK_QUEUE_TRANSFER_BIT - // capability separately for that queue family is optional (4.1). - QueueInfo.queueFamilyIndex = PhysicalDevice->FindQueueFamily(VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT); - QueueInfo.queueCount = 1; - const float defaultQueuePriority = 1.0f; // Ask for highest priority for our queue. (range [0,1]) - QueueInfo.pQueuePriorities = &defaultQueuePriority; - - VkDeviceCreateInfo DeviceCreateInfo = {}; - DeviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; - DeviceCreateInfo.flags = 0; // Reserved for future use - // https://www.khronos.org/registry/vulkan/specs/1.0/html/vkspec.html#extended-functionality-device-layer-deprecation - DeviceCreateInfo.enabledLayerCount = 0; // Deprecated and ignored. - DeviceCreateInfo.ppEnabledLayerNames = nullptr; // Deprecated and ignored - DeviceCreateInfo.queueCreateInfoCount = 1; - DeviceCreateInfo.pQueueCreateInfos = &QueueInfo; - VkPhysicalDeviceFeatures DeviceFeatures = {}; - DeviceFeatures.depthBiasClamp = CreationAttribs.EnabledFeatures.depthBiasClamp ? VK_TRUE : VK_FALSE; - DeviceFeatures.fillModeNonSolid = CreationAttribs.EnabledFeatures.fillModeNonSolid ? VK_TRUE : VK_FALSE; - DeviceFeatures.depthClamp = CreationAttribs.EnabledFeatures.depthClamp ? VK_TRUE : VK_FALSE; - DeviceFeatures.independentBlend = CreationAttribs.EnabledFeatures.independentBlend ? VK_TRUE : VK_FALSE; - DeviceFeatures.samplerAnisotropy = CreationAttribs.EnabledFeatures.samplerAnisotropy ? VK_TRUE : VK_FALSE; - DeviceFeatures.geometryShader = CreationAttribs.EnabledFeatures.geometryShader ? VK_TRUE : VK_FALSE; - DeviceFeatures.tessellationShader = CreationAttribs.EnabledFeatures.tessellationShader ? VK_TRUE : VK_FALSE; - DeviceFeatures.dualSrcBlend = CreationAttribs.EnabledFeatures.dualSrcBlend ? VK_TRUE : VK_FALSE; - DeviceFeatures.multiViewport = CreationAttribs.EnabledFeatures.multiViewport ? VK_TRUE : VK_FALSE; - DeviceFeatures.imageCubeArray = CreationAttribs.EnabledFeatures.imageCubeArray ? VK_TRUE : VK_FALSE; - DeviceFeatures.textureCompressionBC = CreationAttribs.EnabledFeatures.textureCompressionBC ? VK_TRUE : VK_FALSE; - DeviceFeatures.vertexPipelineStoresAndAtomics = CreationAttribs.EnabledFeatures.vertexPipelineStoresAndAtomics ? VK_TRUE : VK_FALSE; - DeviceFeatures.fragmentStoresAndAtomics = CreationAttribs.EnabledFeatures.fragmentStoresAndAtomics ? VK_TRUE : VK_FALSE; - DeviceFeatures.shaderStorageImageExtendedFormats = CreationAttribs.EnabledFeatures.shaderStorageImageExtendedFormats ? VK_TRUE : VK_FALSE; - DeviceCreateInfo.pEnabledFeatures = &DeviceFeatures; // NULL or a pointer to a VkPhysicalDeviceFeatures structure that contains - // boolean indicators of all the features to be enabled. - - std::vector DeviceExtensions = - { - VK_KHR_SWAPCHAIN_EXTENSION_NAME, - VK_KHR_MAINTENANCE1_EXTENSION_NAME // To allow negative viewport height - }; - DeviceCreateInfo.ppEnabledExtensionNames = DeviceExtensions.empty() ? nullptr : DeviceExtensions.data(); - DeviceCreateInfo.enabledExtensionCount = static_cast(DeviceExtensions.size()); - - auto vkAllocator = Instance->GetVkAllocator(); - auto vkPhysicalDevice = PhysicalDevice->GetVkDeviceHandle(); - auto LogicalDevice = VulkanUtilities::VulkanLogicalDevice::Create(vkPhysicalDevice, DeviceCreateInfo, vkAllocator); - - RefCntAutoPtr pCmdQueueVk; - auto &RawMemAllocator = GetRawAllocator(); - pCmdQueueVk = NEW_RC_OBJ(RawMemAllocator, "CommandQueueVk instance", CommandQueueVkImpl)(LogicalDevice, QueueInfo.queueFamilyIndex); - - std::array CommandQueues = {{pCmdQueueVk}}; - AttachToVulkanDevice(Instance, std::move(PhysicalDevice), LogicalDevice, CommandQueues.size(), CommandQueues.data(), CreationAttribs, ppDevice, ppContexts, NumDeferredContexts); - - FenceDesc Desc; - Desc.Name = "Command queue fence"; - // Render device owns command queue that in turn owns the fence, so it is an internal device object - bool IsDeviceInternal = true; - auto* pRenderDeviceVk = ValidatedCast(*ppDevice); - RefCntAutoPtr pFenceVk( NEW_RC_OBJ(RawMemAllocator, "FenceVkImpl instance", FenceVkImpl)(pRenderDeviceVk, Desc, IsDeviceInternal) ); - pCmdQueueVk->SetFence(std::move(pFenceVk)); - } - catch(std::runtime_error& ) - { - return; - } -} - -/// Attaches to existing Vulkan device - -/// \param [in] Instance - shared pointer to a VulkanUtilities::VulkanInstance object -/// \param [in] PhysicalDevice - pointer to the object representing physical device -/// \param [in] LogicalDevice - shared pointer to a VulkanUtilities::VulkanLogicalDevice object -/// \param [in] pCommandQueue - pointer to the implementation of command queue -/// \param [in] EngineAttribs - Engine creation attributes. -/// \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 -/// the contexts will be written. Pointer to the immediate -/// context goes at position 0. If NumDeferredContexts > 0, -/// pointers to the deferred contexts go afterwards. -/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number -/// of deferred contexts is requested, pointers to the -/// contexts are written to ppContexts array starting -/// at position 1 -void EngineFactoryVkImpl::AttachToVulkanDevice(std::shared_ptr Instance, - std::unique_ptr PhysicalDevice, - std::shared_ptr LogicalDevice, - size_t CommandQueueCount, - ICommandQueueVk** ppCommandQueues, - const EngineVkAttribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts) -{ - VERIFY( ppCommandQueues && ppDevice && ppContexts, "Null pointer provided" ); - if(!LogicalDevice || !ppCommandQueues || !ppDevice || !ppContexts ) - return; - - *ppDevice = nullptr; - memset(ppContexts, 0, sizeof(*ppContexts) * (1+NumDeferredContexts)); - - try - { - auto &RawMemAllocator = GetRawAllocator(); - RenderDeviceVkImpl *pRenderDeviceVk( NEW_RC_OBJ(RawMemAllocator, "RenderDeviceVkImpl instance", RenderDeviceVkImpl)(RawMemAllocator, EngineAttribs, CommandQueueCount, ppCommandQueues, Instance, std::move(PhysicalDevice), LogicalDevice, NumDeferredContexts ) ); - pRenderDeviceVk->QueryInterface(IID_RenderDevice, reinterpret_cast(ppDevice) ); - - std::shared_ptr GenerateMipsHelper(new GenerateMipsVkHelper(*pRenderDeviceVk)); - - RefCntAutoPtr pImmediateCtxVk( NEW_RC_OBJ(RawMemAllocator, "DeviceContextVkImpl instance", DeviceContextVkImpl)(pRenderDeviceVk, false, EngineAttribs, 0, 0, GenerateMipsHelper) ); - // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceVk will - // keep a weak reference to the context - pImmediateCtxVk->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts) ); - pRenderDeviceVk->SetImmediateContext(pImmediateCtxVk); - - for (Uint32 DeferredCtx = 0; DeferredCtx < NumDeferredContexts; ++DeferredCtx) - { - RefCntAutoPtr pDeferredCtxVk( NEW_RC_OBJ(RawMemAllocator, "DeviceContextVkImpl instance", DeviceContextVkImpl)(pRenderDeviceVk, true, EngineAttribs, 1+DeferredCtx, 0, GenerateMipsHelper) ); - // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceVk will - // keep a weak reference to the context - pDeferredCtxVk->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts + 1 + DeferredCtx) ); - pRenderDeviceVk->SetDeferredContext(DeferredCtx, pDeferredCtxVk); - } - } - catch( const std::runtime_error & ) - { - if( *ppDevice ) - { - (*ppDevice)->Release(); - *ppDevice = nullptr; - } - for(Uint32 ctx=0; ctx < 1 + NumDeferredContexts; ++ctx) - { - if( ppContexts[ctx] != nullptr ) - { - ppContexts[ctx]->Release(); - ppContexts[ctx] = nullptr; - } - } - - LOG_ERROR( "Failed to create device and contexts" ); - } -} - - -/// Creates a swap chain for Direct3D12-based engine implementation - -/// \param [in] pDevice - Pointer to the render device -/// \param [in] pImmediateContext - Pointer to the immediate device context -/// \param [in] SCDesc - Swap chain description -/// \param [in] pNativeWndHandle - Platform-specific native handle of the window -/// the swap chain will be associated with: -/// * On Win32 platform, this should be window handle (HWND) -/// * On Universal Windows Platform, this should be reference to the -/// core window (Windows::UI::Core::CoreWindow) -/// -/// \param [out] ppSwapChain - Address of the memory location where pointer to the new -/// swap chain will be written -void EngineFactoryVkImpl::CreateSwapChainVk( IRenderDevice* pDevice, - IDeviceContext* pImmediateContext, - const SwapChainDesc& SCDesc, - void* pNativeWndHandle, - ISwapChain** ppSwapChain ) -{ - VERIFY( ppSwapChain, "Null pointer provided" ); - if( !ppSwapChain ) - return; - - *ppSwapChain = nullptr; - - try - { - auto *pDeviceVk = ValidatedCast( pDevice ); - auto *pDeviceContextVk = ValidatedCast(pImmediateContext); - auto &RawMemAllocator = GetRawAllocator(); - auto *pSwapChainVk = NEW_RC_OBJ(RawMemAllocator, "SwapChainVkImpl instance", SwapChainVkImpl)(SCDesc, pDeviceVk, pDeviceContextVk, pNativeWndHandle); - pSwapChainVk->QueryInterface( IID_SwapChain, reinterpret_cast(ppSwapChain) ); - - pDeviceContextVk->SetSwapChain(pSwapChainVk); - // Bind default render target - pDeviceContextVk->SetRenderTargets( 0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); - // Set default viewport - pDeviceContextVk->SetViewports( 1, nullptr, 0, 0 ); - - auto NumDeferredCtx = pDeviceVk->GetNumDeferredContexts(); - for (size_t ctx = 0; ctx < NumDeferredCtx; ++ctx) - { - if (auto pDeferredCtx = pDeviceVk->GetDeferredContext(ctx)) - { - auto *pDeferredCtxVk = pDeferredCtx.RawPtr(); - pDeferredCtxVk->SetSwapChain(pSwapChainVk); - // 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 - // RTV of an inactive buffer in the swap chain - } - } - } - catch( const std::runtime_error & ) - { - if( *ppSwapChain ) - { - (*ppSwapChain)->Release(); - *ppSwapChain = nullptr; - } - - LOG_ERROR( "Failed to create the swap chain" ); - } -} - - -#ifdef DOXYGEN -/// Loads Direct3D12-based engine implementation and exports factory functions -/// \param [out] GetFactoryFunc - Pointer to the function that returns factory for Vk engine implementation. -/// See EngineFactoryVkImpl. -/// \remarks Depending on the configuration and platform, the function loads different dll: -/// Platform\\Configuration | Debug | Release -/// --------------------------|-------------------------------|---------------------------- -/// x86 | GraphicsEngineVk_32d.dll | GraphicsEngineVk_32r.dll -/// x64 | GraphicsEngineVk_64d.dll | GraphicsEngineVk_64r.dll -/// -void LoadGraphicsEngineVk(GetEngineFactoryVkType &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; -} -#endif - -API_QUALIFIER -IEngineFactoryVk* GetEngineFactoryVk() -{ - return EngineFactoryVkImpl::GetInstance(); -} - -} diff --git a/Graphics/GraphicsEngineVulkan/src/RenderDeviceVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/RenderDeviceVkImpl.cpp index 89ed5d01..a126a937 100644 --- a/Graphics/GraphicsEngineVulkan/src/RenderDeviceVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/RenderDeviceVkImpl.cpp @@ -39,7 +39,7 @@ namespace Diligent RenderDeviceVkImpl :: RenderDeviceVkImpl(IReferenceCounters* pRefCounters, IMemoryAllocator& RawMemAllocator, - const EngineVkAttribs& CreationAttribs, + const EngineVkCreateInfo& EngineCI, size_t CommandQueueCount, ICommandQueueVk** CmdQueues, std::shared_ptr Instance, @@ -66,7 +66,7 @@ RenderDeviceVkImpl :: RenderDeviceVkImpl(IReferenceCounters* m_VulkanInstance(Instance), m_PhysicalDevice(std::move(PhysicalDevice)), m_LogicalVkDevice(std::move(LogicalDevice)), - m_EngineAttribs(CreationAttribs), + m_EngineAttribs(EngineCI), m_FramebufferCache(*this), m_RenderPassCache(*this), m_DescriptorSetAllocator @@ -75,18 +75,18 @@ RenderDeviceVkImpl :: RenderDeviceVkImpl(IReferenceCounters* "Main descriptor pool", std::vector { - {VK_DESCRIPTOR_TYPE_SAMPLER, CreationAttribs.MainDescriptorPoolSize.NumSeparateSamplerDescriptors}, - {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, CreationAttribs.MainDescriptorPoolSize.NumCombinedSamplerDescriptors}, - {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, CreationAttribs.MainDescriptorPoolSize.NumSampledImageDescriptors}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, CreationAttribs.MainDescriptorPoolSize.NumStorageImageDescriptors}, - {VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, CreationAttribs.MainDescriptorPoolSize.NumUniformTexelBufferDescriptors}, - {VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, CreationAttribs.MainDescriptorPoolSize.NumStorageTexelBufferDescriptors}, - //{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, CreationAttribs.MainDescriptorPoolSize.NumUniformBufferDescriptors}, - //{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, CreationAttribs.MainDescriptorPoolSize.NumStorageBufferDescriptors}, - {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, CreationAttribs.MainDescriptorPoolSize.NumUniformBufferDescriptors}, - {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, CreationAttribs.MainDescriptorPoolSize.NumStorageBufferDescriptors}, + {VK_DESCRIPTOR_TYPE_SAMPLER, EngineCI.MainDescriptorPoolSize.NumSeparateSamplerDescriptors}, + {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, EngineCI.MainDescriptorPoolSize.NumCombinedSamplerDescriptors}, + {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, EngineCI.MainDescriptorPoolSize.NumSampledImageDescriptors}, + {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, EngineCI.MainDescriptorPoolSize.NumStorageImageDescriptors}, + {VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, EngineCI.MainDescriptorPoolSize.NumUniformTexelBufferDescriptors}, + {VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, EngineCI.MainDescriptorPoolSize.NumStorageTexelBufferDescriptors}, + //{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, EngineCI.MainDescriptorPoolSize.NumUniformBufferDescriptors}, + //{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, EngineCI.MainDescriptorPoolSize.NumStorageBufferDescriptors}, + {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, EngineCI.MainDescriptorPoolSize.NumUniformBufferDescriptors}, + {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, EngineCI.MainDescriptorPoolSize.NumStorageBufferDescriptors}, }, - CreationAttribs.MainDescriptorPoolSize.MaxDescriptorSets, + EngineCI.MainDescriptorPoolSize.MaxDescriptorSets, true }, m_DynamicDescriptorPool @@ -95,27 +95,27 @@ RenderDeviceVkImpl :: RenderDeviceVkImpl(IReferenceCounters* "Dynamic descriptor pool", std::vector { - {VK_DESCRIPTOR_TYPE_SAMPLER, CreationAttribs.DynamicDescriptorPoolSize.NumSeparateSamplerDescriptors}, - {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, CreationAttribs.DynamicDescriptorPoolSize.NumCombinedSamplerDescriptors}, - {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, CreationAttribs.DynamicDescriptorPoolSize.NumSampledImageDescriptors}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, CreationAttribs.DynamicDescriptorPoolSize.NumStorageImageDescriptors}, - {VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, CreationAttribs.DynamicDescriptorPoolSize.NumUniformTexelBufferDescriptors}, - {VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, CreationAttribs.DynamicDescriptorPoolSize.NumStorageTexelBufferDescriptors}, - //{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, CreationAttribs.DynamicDescriptorPoolSize.NumUniformBufferDescriptors}, - //{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, CreationAttribs.DynamicDescriptorPoolSize.NumStorageBufferDescriptors}, - {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, CreationAttribs.DynamicDescriptorPoolSize.NumUniformBufferDescriptors}, - {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, CreationAttribs.DynamicDescriptorPoolSize.NumStorageBufferDescriptors}, + {VK_DESCRIPTOR_TYPE_SAMPLER, EngineCI.DynamicDescriptorPoolSize.NumSeparateSamplerDescriptors}, + {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, EngineCI.DynamicDescriptorPoolSize.NumCombinedSamplerDescriptors}, + {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, EngineCI.DynamicDescriptorPoolSize.NumSampledImageDescriptors}, + {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, EngineCI.DynamicDescriptorPoolSize.NumStorageImageDescriptors}, + {VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, EngineCI.DynamicDescriptorPoolSize.NumUniformTexelBufferDescriptors}, + {VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, EngineCI.DynamicDescriptorPoolSize.NumStorageTexelBufferDescriptors}, + //{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, EngineCI.DynamicDescriptorPoolSize.NumUniformBufferDescriptors}, + //{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, EngineCI.DynamicDescriptorPoolSize.NumStorageBufferDescriptors}, + {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, EngineCI.DynamicDescriptorPoolSize.NumUniformBufferDescriptors}, + {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, EngineCI.DynamicDescriptorPoolSize.NumStorageBufferDescriptors}, }, - CreationAttribs.DynamicDescriptorPoolSize.MaxDescriptorSets, + EngineCI.DynamicDescriptorPoolSize.MaxDescriptorSets, false // Pools can only be reset }, m_TransientCmdPoolMgr(*this, "Transient command buffer pool manager", CmdQueues[0]->GetQueueFamilyIndex(), VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), - m_MemoryMgr("Global resource memory manager", *m_LogicalVkDevice, *m_PhysicalDevice, GetRawAllocator(), CreationAttribs.DeviceLocalMemoryPageSize, CreationAttribs.HostVisibleMemoryPageSize, CreationAttribs.DeviceLocalMemoryReserveSize, CreationAttribs.HostVisibleMemoryReserveSize), + m_MemoryMgr("Global resource memory manager", *m_LogicalVkDevice, *m_PhysicalDevice, GetRawAllocator(), EngineCI.DeviceLocalMemoryPageSize, EngineCI.HostVisibleMemoryPageSize, EngineCI.DeviceLocalMemoryReserveSize, EngineCI.HostVisibleMemoryReserveSize), m_DynamicMemoryManager { GetRawAllocator(), *this, - CreationAttribs.DynamicHeapSize, + EngineCI.DynamicHeapSize, ~Uint64{0} } { diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp index 9f212fd4..e65aaa91 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderResourceLayoutVk.cpp @@ -920,7 +920,7 @@ void ShaderResourceLayoutVk::InitializeStaticResources(const ShaderResourceLayou const auto& SrcCachedRes = SrcCachedSet.GetResource(SrcOffset); IDeviceObject* pObject = SrcCachedRes.pObject.RawPtr(); if (!pObject) - LOG_ERROR_MESSAGE("No resource assigned to static shader variable '", SrcRes.SpirvAttribs.GetPrintName(ArrInd), "' in shader '", GetShaderName(), "'."); + LOG_ERROR_MESSAGE("No resource is assigned to static shader variable '", SrcRes.SpirvAttribs.GetPrintName(ArrInd), "' in shader '", GetShaderName(), "'."); auto DstOffset = DstRes.CacheOffset + ArrInd; IDeviceObject* pCachedResource = DstResourceCache.GetDescriptorSet(DstRes.DescriptorSet).GetResource(DstOffset).pObject; diff --git a/Graphics/GraphicsEngineVulkan/src/VulkanDynamicHeap.cpp b/Graphics/GraphicsEngineVulkan/src/VulkanDynamicHeap.cpp index 5fccdad8..57b55f15 100644 --- a/Graphics/GraphicsEngineVulkan/src/VulkanDynamicHeap.cpp +++ b/Graphics/GraphicsEngineVulkan/src/VulkanDynamicHeap.cpp @@ -165,22 +165,22 @@ VulkanDynamicMemoryManager::MasterBlock VulkanDynamicMemoryManager::AllocateMast Block = TBase::AllocateMasterBlock(SizeInBytes, Alignment); if (!Block.IsValid()) { - LOG_ERROR_MESSAGE("Space in dynamic heap is exausted! After idling for ", std::fixed, std::setprecision(1), IdleDuration.count()*1000.0, " ms still no space is available. Increase the size of the heap by setting EngineVkAttribs::DynamicHeapSize to a greater value or optimize dynamic resource usage"); + LOG_ERROR_MESSAGE("Space in dynamic heap is exausted! After idling for ", std::fixed, std::setprecision(1), IdleDuration.count()*1000.0, " ms still no space is available. Increase the size of the heap by setting EngineVkCreateInfo::DynamicHeapSize to a greater value or optimize dynamic resource usage"); } else { - LOG_WARNING_MESSAGE("Space in dynamic heap is almost exausted. Allocation forced idling the GPU. Increase the size of the heap by setting EngineVkAttribs::DynamicHeapSize to a greater value or optimize dynamic resource usage"); + LOG_WARNING_MESSAGE("Space in dynamic heap is almost exausted. Allocation forced idling the GPU. Increase the size of the heap by setting EngineVkCreateInfo::DynamicHeapSize to a greater value or optimize dynamic resource usage"); } } else { if(SleepIterations == 0) { - LOG_WARNING_MESSAGE("Space in dynamic heap is almost exausted forcing mid-frame shrinkage. Increase the size of the heap buffer by setting EngineVkAttribs::DynamicHeapSize to a greater value or optimize dynamic resource usage"); + LOG_WARNING_MESSAGE("Space in dynamic heap is almost exausted forcing mid-frame shrinkage. Increase the size of the heap buffer by setting EngineVkCreateInfo::DynamicHeapSize to a greater value or optimize dynamic resource usage"); } else { - LOG_WARNING_MESSAGE("Space in dynamic heap is almost exausted. Allocation forced wait time of ", std::fixed, std::setprecision(1), IdleDuration.count()*1000.0, " ms. Increase the size of the heap by setting EngineVkAttribs::DynamicHeapSize to a greater value or optimize dynamic resource usage"); + LOG_WARNING_MESSAGE("Space in dynamic heap is almost exausted. Allocation forced wait time of ", std::fixed, std::setprecision(1), IdleDuration.count()*1000.0, " ms. Increase the size of the heap by setting EngineVkCreateInfo::DynamicHeapSize to a greater value or optimize dynamic resource usage"); } } } -- cgit v1.2.3 From 68bb0c88ba7d427550dd9ac5a796ff2d6d05262d Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Mon, 4 Mar 2019 22:54:00 -0800 Subject: Updated GL engine factory headers and structures --- Graphics/GraphicsEngine/interface/GraphicsTypes.h | 17 ++ Graphics/GraphicsEngineOpenGL/CMakeLists.txt | 5 +- .../interface/EngineFactoryOpenGL.h | 123 +++++++++++ .../interface/EngineGLAttribs.h | 48 ---- .../interface/RenderDeviceFactoryOpenGL.h | 124 ----------- .../src/EngineFactoryOpenGL.cpp | 243 +++++++++++++++++++++ .../src/RenderDeviceFactoryOpenGL.cpp | 243 --------------------- 7 files changed, 385 insertions(+), 418 deletions(-) create mode 100644 Graphics/GraphicsEngineOpenGL/interface/EngineFactoryOpenGL.h delete mode 100644 Graphics/GraphicsEngineOpenGL/interface/EngineGLAttribs.h delete mode 100644 Graphics/GraphicsEngineOpenGL/interface/RenderDeviceFactoryOpenGL.h create mode 100644 Graphics/GraphicsEngineOpenGL/src/EngineFactoryOpenGL.cpp delete mode 100644 Graphics/GraphicsEngineOpenGL/src/RenderDeviceFactoryOpenGL.cpp (limited to 'Graphics') diff --git a/Graphics/GraphicsEngine/interface/GraphicsTypes.h b/Graphics/GraphicsEngine/interface/GraphicsTypes.h index 2cc9024b..751279da 100644 --- a/Graphics/GraphicsEngine/interface/GraphicsTypes.h +++ b/Graphics/GraphicsEngine/interface/GraphicsTypes.h @@ -1253,6 +1253,23 @@ namespace Diligent }; + /// Attributes of the OpenGL-based engine implementation + struct EngineGLCreateInfo : public EngineCreateInfo + { + /// Native window handle + + /// * On Win32 platform, this is a window handle (HWND) + /// * On Android platform, this is a pointer to the native window (ANativeWindow*) + /// * On Linux, this is the native window (Window) + void* pNativeWndHandle = nullptr; + +#if PLATFORM_LINUX + /// For linux platform only, this is the pointer to the display + void* pDisplay = nullptr; +#endif + }; + + /// Debug flags that can be specified when creating Direct3D11-based engine implementation. /// /// \sa CreateDeviceAndContextsD3D11Type, CreateSwapChainD3D11Type, LoadGraphicsEngineD3D11 diff --git a/Graphics/GraphicsEngineOpenGL/CMakeLists.txt b/Graphics/GraphicsEngineOpenGL/CMakeLists.txt index bfde3d05..6f69366b 100644 --- a/Graphics/GraphicsEngineOpenGL/CMakeLists.txt +++ b/Graphics/GraphicsEngineOpenGL/CMakeLists.txt @@ -39,10 +39,9 @@ set(INTERFACE interface/BufferGL.h interface/BufferViewGL.h interface/DeviceContextGL.h - interface/EngineGLAttribs.h + interface/EngineFactoryOpenGL.h interface/FenceGL.h interface/PipelineStateGL.h - interface/RenderDeviceFactoryOpenGL.h interface/RenderDeviceGL.h interface/SamplerGL.h interface/ShaderGL.h @@ -56,6 +55,7 @@ set(SOURCE src/BufferGLImpl.cpp src/BufferViewGLImpl.cpp src/DeviceContextGLImpl.cpp + src/EngineFactoryOpenGL.cpp src/FBOCache.cpp src/FenceGLImpl.cpp src/GLContextState.cpp @@ -64,7 +64,6 @@ set(SOURCE src/GLProgramResources.cpp src/GLTypeConversions.cpp src/PipelineStateGLImpl.cpp - src/RenderDeviceFactoryOpenGL.cpp src/RenderDeviceGLImpl.cpp src/SamplerGLImpl.cpp src/ShaderGLImpl.cpp diff --git a/Graphics/GraphicsEngineOpenGL/interface/EngineFactoryOpenGL.h b/Graphics/GraphicsEngineOpenGL/interface/EngineFactoryOpenGL.h new file mode 100644 index 00000000..63627856 --- /dev/null +++ b/Graphics/GraphicsEngineOpenGL/interface/EngineFactoryOpenGL.h @@ -0,0 +1,123 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +/// \file +/// Declaration of functions that create OpenGL-based engine implementation + +#include + +#include "../../GraphicsEngine/interface/RenderDevice.h" +#include "../../GraphicsEngine/interface/DeviceContext.h" +#include "../../GraphicsEngine/interface/SwapChain.h" + +#include "../../HLSL2GLSLConverterLib/interface/HLSL2GLSLConverter.h" + + +#if PLATFORM_ANDROID || PLATFORM_LINUX || PLATFORM_MACOS || PLATFORM_IOS || (PLATFORM_WIN32 && !defined(_MSC_VER)) + + // https://gcc.gnu.org/wiki/Visibility +# define API_QUALIFIER __attribute__((visibility("default"))) + +#elif PLATFORM_WIN32 + +# define API_QUALIFIER + +#else +# error Unsupported platform +#endif + +namespace Diligent +{ + +class IEngineFactoryOpenGL +{ +public: + virtual void CreateDeviceAndSwapChainGL(const EngineGLCreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppImmediateContext, + const SwapChainDesc& SCDesc, + ISwapChain** ppSwapChain ) = 0; + virtual void CreateHLSL2GLSLConverter(IHLSL2GLSLConverter** ppConverter) = 0; + + virtual void AttachToActiveGLContext(const EngineGLCreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppImmediateContext) = 0; +}; + + +#if ENGINE_DLL && PLATFORM_WIN32 && defined(_MSC_VER) + +# define EXPLICITLY_LOAD_ENGINE_GL_DLL 1 + + typedef IEngineFactoryOpenGL* (*GetEngineFactoryOpenGLType)(); + + static bool LoadGraphicsEngineOpenGL(GetEngineFactoryOpenGLType& GetFactoryFunc) + { + GetFactoryFunc = nullptr; + std::string LibName = "GraphicsEngineOpenGL_"; + +# if _WIN64 + LibName += "64"; +# else + LibName += "32"; +# endif + +# ifdef _DEBUG + LibName += "d"; +# else + LibName += "r"; +# endif + + LibName += ".dll"; + auto hModule = LoadLibraryA( LibName.c_str() ); + 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, "GetEngineFactoryOpenGL") ); + if( GetFactoryFunc == NULL ) + { + std::stringstream ss; + ss << "Failed to load GetEngineFactoryOpenGL() from " << LibName << " library.\n"; + OutputDebugStringA(ss.str().c_str()); + FreeLibrary( hModule ); + return false; + } + return true; + } + +#else + + // Do not forget to call System.loadLibrary("GraphicsEngineOpenGL") in Java on Android! + API_QUALIFIER + IEngineFactoryOpenGL* GetEngineFactoryOpenGL(); + +#endif + +} diff --git a/Graphics/GraphicsEngineOpenGL/interface/EngineGLAttribs.h b/Graphics/GraphicsEngineOpenGL/interface/EngineGLAttribs.h deleted file mode 100644 index 89fd0590..00000000 --- a/Graphics/GraphicsEngineOpenGL/interface/EngineGLAttribs.h +++ /dev/null @@ -1,48 +0,0 @@ -/* Copyright 2015-2019 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -/// \file -/// Definition of the Engine OpenGL/GLES attribs - -#include "../../GraphicsEngine/interface/GraphicsTypes.h" - -namespace Diligent -{ - /// Attributes of the OpenGL-based engine implementation - struct EngineGLAttribs : public EngineCreationAttribs - { - /// Native window handle - - /// * On Win32 platform, this is a window handle (HWND) - /// * On Android platform, this is a pointer to the native window (ANativeWindow*) - /// * On Linux, this is the native window (Window) - void *pNativeWndHandle = nullptr; - -#if PLATFORM_LINUX - /// For linux platform only, this is the pointer to the display - void *pDisplay = nullptr; -#endif - }; -} diff --git a/Graphics/GraphicsEngineOpenGL/interface/RenderDeviceFactoryOpenGL.h b/Graphics/GraphicsEngineOpenGL/interface/RenderDeviceFactoryOpenGL.h deleted file mode 100644 index 93b8d8f4..00000000 --- a/Graphics/GraphicsEngineOpenGL/interface/RenderDeviceFactoryOpenGL.h +++ /dev/null @@ -1,124 +0,0 @@ -/* Copyright 2015-2019 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -/// \file -/// Declaration of functions that create OpenGL-based engine implementation - -#include - -#include "../../GraphicsEngine/interface/RenderDevice.h" -#include "../../GraphicsEngine/interface/DeviceContext.h" -#include "../../GraphicsEngine/interface/SwapChain.h" - -#include "../../HLSL2GLSLConverterLib/interface/HLSL2GLSLConverter.h" - -#include "EngineGLAttribs.h" - -#if PLATFORM_ANDROID || PLATFORM_LINUX || PLATFORM_MACOS || PLATFORM_IOS || (PLATFORM_WIN32 && !defined(_MSC_VER)) - - // https://gcc.gnu.org/wiki/Visibility -# define API_QUALIFIER __attribute__((visibility("default"))) - -#elif PLATFORM_WIN32 - -# define API_QUALIFIER - -#else -# error Unsupported platform -#endif - -namespace Diligent -{ - -class IEngineFactoryOpenGL -{ -public: - virtual void CreateDeviceAndSwapChainGL(const EngineGLAttribs& CreationAttribs, - IRenderDevice **ppDevice, - IDeviceContext **ppImmediateContext, - const SwapChainDesc& SCDesc, - ISwapChain **ppSwapChain ) = 0; - virtual void CreateHLSL2GLSLConverter(IHLSL2GLSLConverter **ppConverter) = 0; - - virtual void AttachToActiveGLContext( const EngineGLAttribs& CreationAttribs, - IRenderDevice **ppDevice, - IDeviceContext **ppImmediateContext ) = 0; -}; - - -#if ENGINE_DLL && PLATFORM_WIN32 && defined(_MSC_VER) - -# define EXPLICITLY_LOAD_ENGINE_GL_DLL 1 - - typedef IEngineFactoryOpenGL* (*GetEngineFactoryOpenGLType)(); - - static bool LoadGraphicsEngineOpenGL(GetEngineFactoryOpenGLType &GetFactoryFunc) - { - GetFactoryFunc = nullptr; - std::string LibName = "GraphicsEngineOpenGL_"; - -# if _WIN64 - LibName += "64"; -# else - LibName += "32"; -# endif - -# ifdef _DEBUG - LibName += "d"; -# else - LibName += "r"; -# endif - - LibName += ".dll"; - auto hModule = LoadLibraryA( LibName.c_str() ); - 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, "GetEngineFactoryOpenGL") ); - if( GetFactoryFunc == NULL ) - { - std::stringstream ss; - ss << "Failed to load GetEngineFactoryOpenGL() from " << LibName << " library.\n"; - OutputDebugStringA(ss.str().c_str()); - FreeLibrary( hModule ); - return false; - } - return true; - } - -#else - - // Do not forget to call System.loadLibrary("GraphicsEngineOpenGL") in Java on Android! - API_QUALIFIER - IEngineFactoryOpenGL* GetEngineFactoryOpenGL(); - -#endif - -} diff --git a/Graphics/GraphicsEngineOpenGL/src/EngineFactoryOpenGL.cpp b/Graphics/GraphicsEngineOpenGL/src/EngineFactoryOpenGL.cpp new file mode 100644 index 00000000..04d1ce83 --- /dev/null +++ b/Graphics/GraphicsEngineOpenGL/src/EngineFactoryOpenGL.cpp @@ -0,0 +1,243 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +/// \file +/// Routines that initialize OpenGL/GLES-based engine implementation + +#include "pch.h" +#include "RenderDeviceFactoryOpenGL.h" +#include "RenderDeviceGLImpl.h" +#include "DeviceContextGLImpl.h" +#include "EngineMemory.h" +#include "HLSL2GLSLConverterObject.h" + +#if PLATFORM_IOS +# include "SwapChainGLIOS.h" +#else +# include "SwapChainGLImpl.h" +#endif + +#if PLATFORM_ANDROID +# include "RenderDeviceGLESImpl.h" +#endif + +namespace Diligent +{ + +#if PLATFORM_WIN32 || PLATFORM_UNIVERSAL_WINDOWS || PLATFORM_LINUX || PLATFORM_MACOS + typedef RenderDeviceGLImpl TRenderDeviceGLImpl; + typedef SwapChainGLImpl TSwapChain; +#elif PLATFORM_ANDROID + typedef RenderDeviceGLESImpl TRenderDeviceGLImpl; + typedef SwapChainGLImpl TSwapChain; +#elif PLATFORM_IOS + typedef RenderDeviceGLImpl TRenderDeviceGLImpl; + typedef SwapChainGLIOS TSwapChain; +#else +# error Unsupported platform +#endif + +/// Engine factory for OpenGL implementation +class EngineFactoryOpenGLImpl : public IEngineFactoryOpenGL +{ +public: + static EngineFactoryOpenGLImpl* GetInstance() + { + static EngineFactoryOpenGLImpl TheFactory; + return &TheFactory; + } + + virtual void CreateDeviceAndSwapChainGL(const EngineGLCreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppImmediateContext, + const SwapChainDesc& SCDesc, + ISwapChain** ppSwapChain )override final; + + virtual void CreateHLSL2GLSLConverter(IHLSL2GLSLConverter** ppConverter)override final; + + virtual void AttachToActiveGLContext(const EngineGLCreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppImmediateContext )override final; +}; + + + +/// Creates render device, device context and swap chain for OpenGL/GLES-based engine implementation + +/// \param [in] EngineCI - Engine creation attributes. +/// \param [out] ppDevice - Address of the memory location where pointer to +/// the created device will be written. +/// \param [out] ppImmediateContext - Address of the memory location where pointers to +/// the immediate context will be written. +/// \param [in] SCDesc - Swap chain description. +/// \param [out] ppSwapChain - Address of the memory location where pointer to the new +/// swap chain will be written. +void EngineFactoryOpenGLImpl::CreateDeviceAndSwapChainGL(const EngineGLCreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppImmediateContext, + const SwapChainDesc& SCDesc, + ISwapChain** ppSwapChain) +{ + if (EngineCI.DebugMessageCallback != nullptr) + SetDebugMessageCallback(EngineCI.DebugMessageCallback); + + VERIFY( ppDevice && ppImmediateContext && ppSwapChain, "Null pointer provided" ); + if( !ppDevice || !ppImmediateContext || !ppSwapChain ) + return; + + *ppDevice = nullptr; + *ppImmediateContext = nullptr; + *ppSwapChain = nullptr; + + try + { + SetRawAllocator(EngineCI.pRawMemAllocator); + auto &RawMemAllocator = GetRawAllocator(); + + RenderDeviceGLImpl *pRenderDeviceOpenGL( NEW_RC_OBJ(RawMemAllocator, "TRenderDeviceGLImpl instance", TRenderDeviceGLImpl)(RawMemAllocator, EngineCI) ); + pRenderDeviceOpenGL->QueryInterface(IID_RenderDevice, reinterpret_cast(ppDevice) ); + + DeviceContextGLImpl *pDeviceContextOpenGL( NEW_RC_OBJ(RawMemAllocator, "DeviceContextGLImpl instance", DeviceContextGLImpl)(pRenderDeviceOpenGL, false ) ); + // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceOpenGL will + // keep a weak reference to the context + pDeviceContextOpenGL->QueryInterface(IID_DeviceContext, reinterpret_cast(ppImmediateContext) ); + pRenderDeviceOpenGL->SetImmediateContext(pDeviceContextOpenGL); + + TSwapChain *pSwapChainGL = NEW_RC_OBJ(RawMemAllocator, "SwapChainGLImpl instance", TSwapChain)(EngineCI, SCDesc, pRenderDeviceOpenGL, pDeviceContextOpenGL ); + pSwapChainGL->QueryInterface(IID_SwapChain, reinterpret_cast(ppSwapChain) ); + + pDeviceContextOpenGL->SetSwapChain(pSwapChainGL); + // Bind default framebuffer and viewport + pDeviceContextOpenGL->SetRenderTargets( 0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); + pDeviceContextOpenGL->SetViewports( 1, nullptr, 0, 0 ); + } + catch( const std::runtime_error & ) + { + if( *ppDevice ) + { + (*ppDevice)->Release(); + *ppDevice = nullptr; + } + + if( *ppImmediateContext ) + { + (*ppImmediateContext)->Release(); + *ppImmediateContext = nullptr; + } + + if( *ppSwapChain ) + { + (*ppSwapChain)->Release(); + *ppSwapChain = nullptr; + } + + LOG_ERROR( "Failed to initialize OpenGL-based render device" ); + } +} + + +/// Creates render device, device context and attaches to existing GL context + +/// \param [in] EngineCI - Engine creation attributes. +/// \param [out] ppDevice - Address of the memory location where pointer to +/// the created device will be written. +/// \param [out] ppImmediateContext - Address of the memory location where pointers to +/// the immediate context will be written. +void EngineFactoryOpenGLImpl::AttachToActiveGLContext(const EngineGLCreateInfo& EngineCI, + IRenderDevice** ppDevice, + IDeviceContext** ppImmediateContext ) +{ + if (EngineCI.DebugMessageCallback != nullptr) + SetDebugMessageCallback(EngineCI.DebugMessageCallback); + + VERIFY( ppDevice && ppImmediateContext, "Null pointer provided" ); + if( !ppDevice || !ppImmediateContext ) + return; + + *ppDevice = nullptr; + *ppImmediateContext = nullptr; + + try + { + SetRawAllocator(EngineCI.pRawMemAllocator); + auto &RawMemAllocator = GetRawAllocator(); + + RenderDeviceGLImpl *pRenderDeviceOpenGL( NEW_RC_OBJ(RawMemAllocator, "TRenderDeviceGLImpl instance", TRenderDeviceGLImpl)(RawMemAllocator, EngineCI) ); + pRenderDeviceOpenGL->QueryInterface(IID_RenderDevice, reinterpret_cast(ppDevice) ); + + DeviceContextGLImpl *pDeviceContextOpenGL( NEW_RC_OBJ(RawMemAllocator, "DeviceContextGLImpl instance", DeviceContextGLImpl)(pRenderDeviceOpenGL, false ) ); + // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceOpenGL will + // keep a weak reference to the context + pDeviceContextOpenGL->QueryInterface(IID_DeviceContext, reinterpret_cast(ppImmediateContext) ); + pRenderDeviceOpenGL->SetImmediateContext(pDeviceContextOpenGL); + } + catch( const std::runtime_error & ) + { + if( *ppDevice ) + { + (*ppDevice)->Release(); + *ppDevice = nullptr; + } + + if( *ppImmediateContext ) + { + (*ppImmediateContext)->Release(); + *ppImmediateContext = nullptr; + } + + LOG_ERROR( "Failed to initialize OpenGL-based render device" ); + } +} + +#ifdef DOXYGEN +/// Loads OpenGL-based engine implementation and exports factory functions +/// \param [out] GetFactoryFunc - Pointer to the function that returns pointer to the factory for +/// the OpenGL engine implementation +/// See EngineFactoryOpenGLImpl::CreateDeviceAndSwapChainGL(). +/// \remarks Depending on the configuration and platform, the function loads different dll: +/// Platform\\Configuration | Debug | Release +/// --------------------------|------------------------------|---------------------------- +/// Win32/x86 | GraphicsEngineOpenGL_32d.dll | GraphicsEngineOpenGL_32r.dll +/// Win32/x64 | GraphicsEngineOpenGL_64d.dll | GraphicsEngineOpenGL_64r.dll +/// +/// To load the library on Android, it is necessary to call System.loadLibrary("GraphicsEngineOpenGL") from Java. +void LoadGraphicsEngineOpenGL(GetEngineFactoryOpenGLType &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; +} +#endif + +void EngineFactoryOpenGLImpl::CreateHLSL2GLSLConverter(IHLSL2GLSLConverter** ppConverter) +{ + HLSL2GLSLConverterObject *pConverter( NEW_RC_OBJ(GetRawAllocator(), "HLSL2GLSLConverterObject instance", HLSL2GLSLConverterObject)() ); + pConverter->QueryInterface( IID_HLSL2GLSLConverter, reinterpret_cast(ppConverter) ); +} + +API_QUALIFIER +Diligent::IEngineFactoryOpenGL* GetEngineFactoryOpenGL() +{ + return Diligent::EngineFactoryOpenGLImpl::GetInstance(); +} + +} diff --git a/Graphics/GraphicsEngineOpenGL/src/RenderDeviceFactoryOpenGL.cpp b/Graphics/GraphicsEngineOpenGL/src/RenderDeviceFactoryOpenGL.cpp deleted file mode 100644 index 474f914e..00000000 --- a/Graphics/GraphicsEngineOpenGL/src/RenderDeviceFactoryOpenGL.cpp +++ /dev/null @@ -1,243 +0,0 @@ -/* Copyright 2015-2019 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -/// \file -/// Routines that initialize OpenGL/GLES-based engine implementation - -#include "pch.h" -#include "RenderDeviceFactoryOpenGL.h" -#include "RenderDeviceGLImpl.h" -#include "DeviceContextGLImpl.h" -#include "EngineMemory.h" -#include "HLSL2GLSLConverterObject.h" - -#if PLATFORM_IOS -# include "SwapChainGLIOS.h" -#else -# include "SwapChainGLImpl.h" -#endif - -#if PLATFORM_ANDROID -# include "RenderDeviceGLESImpl.h" -#endif - -namespace Diligent -{ - -#if PLATFORM_WIN32 || PLATFORM_UNIVERSAL_WINDOWS || PLATFORM_LINUX || PLATFORM_MACOS - typedef RenderDeviceGLImpl TRenderDeviceGLImpl; - typedef SwapChainGLImpl TSwapChain; -#elif PLATFORM_ANDROID - typedef RenderDeviceGLESImpl TRenderDeviceGLImpl; - typedef SwapChainGLImpl TSwapChain; -#elif PLATFORM_IOS - typedef RenderDeviceGLImpl TRenderDeviceGLImpl; - typedef SwapChainGLIOS TSwapChain; -#else -# error Unsupported platform -#endif - -/// Engine factory for OpenGL implementation -class EngineFactoryOpenGLImpl : public IEngineFactoryOpenGL -{ -public: - static EngineFactoryOpenGLImpl* GetInstance() - { - static EngineFactoryOpenGLImpl TheFactory; - return &TheFactory; - } - - virtual void CreateDeviceAndSwapChainGL(const EngineGLAttribs& CreationAttribs, - IRenderDevice **ppDevice, - IDeviceContext **ppImmediateContext, - const SwapChainDesc& SCDesc, - ISwapChain **ppSwapChain )override final; - - virtual void CreateHLSL2GLSLConverter(IHLSL2GLSLConverter **ppConverter)override final; - - virtual void AttachToActiveGLContext( const EngineGLAttribs& CreationAttribs, - IRenderDevice **ppDevice, - IDeviceContext **ppImmediateContext )override final; -}; - - - -/// Creates render device, device context and swap chain for OpenGL/GLES-based engine implementation - -/// \param [in] CreationAttribs - Engine creation attributes. -/// \param [out] ppDevice - Address of the memory location where pointer to -/// the created device will be written. -/// \param [out] ppImmediateContext - Address of the memory location where pointers to -/// the immediate context will be written. -/// \param [in] SCDesc - Swap chain description. -/// \param [out] ppSwapChain - Address of the memory location where pointer to the new -/// swap chain will be written. -void EngineFactoryOpenGLImpl::CreateDeviceAndSwapChainGL(const EngineGLAttribs& CreationAttribs, - IRenderDevice **ppDevice, - IDeviceContext **ppImmediateContext, - const SwapChainDesc& SCDesc, - ISwapChain **ppSwapChain ) -{ - if (CreationAttribs.DebugMessageCallback != nullptr) - SetDebugMessageCallback(CreationAttribs.DebugMessageCallback); - - VERIFY( ppDevice && ppImmediateContext && ppSwapChain, "Null pointer provided" ); - if( !ppDevice || !ppImmediateContext || !ppSwapChain ) - return; - - *ppDevice = nullptr; - *ppImmediateContext = nullptr; - *ppSwapChain = nullptr; - - try - { - SetRawAllocator(CreationAttribs.pRawMemAllocator); - auto &RawMemAllocator = GetRawAllocator(); - - RenderDeviceGLImpl *pRenderDeviceOpenGL( NEW_RC_OBJ(RawMemAllocator, "TRenderDeviceGLImpl instance", TRenderDeviceGLImpl)(RawMemAllocator, CreationAttribs) ); - pRenderDeviceOpenGL->QueryInterface(IID_RenderDevice, reinterpret_cast(ppDevice) ); - - DeviceContextGLImpl *pDeviceContextOpenGL( NEW_RC_OBJ(RawMemAllocator, "DeviceContextGLImpl instance", DeviceContextGLImpl)(pRenderDeviceOpenGL, false ) ); - // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceOpenGL will - // keep a weak reference to the context - pDeviceContextOpenGL->QueryInterface(IID_DeviceContext, reinterpret_cast(ppImmediateContext) ); - pRenderDeviceOpenGL->SetImmediateContext(pDeviceContextOpenGL); - - TSwapChain *pSwapChainGL = NEW_RC_OBJ(RawMemAllocator, "SwapChainGLImpl instance", TSwapChain)(CreationAttribs, SCDesc, pRenderDeviceOpenGL, pDeviceContextOpenGL ); - pSwapChainGL->QueryInterface(IID_SwapChain, reinterpret_cast(ppSwapChain) ); - - pDeviceContextOpenGL->SetSwapChain(pSwapChainGL); - // Bind default framebuffer and viewport - pDeviceContextOpenGL->SetRenderTargets( 0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); - pDeviceContextOpenGL->SetViewports( 1, nullptr, 0, 0 ); - } - catch( const std::runtime_error & ) - { - if( *ppDevice ) - { - (*ppDevice)->Release(); - *ppDevice = nullptr; - } - - if( *ppImmediateContext ) - { - (*ppImmediateContext)->Release(); - *ppImmediateContext = nullptr; - } - - if( *ppSwapChain ) - { - (*ppSwapChain)->Release(); - *ppSwapChain = nullptr; - } - - LOG_ERROR( "Failed to initialize OpenGL-based render device" ); - } -} - - -/// Creates render device, device context and attaches to existing GL context - -/// \param [in] CreationAttribs - Engine creation attributes. -/// \param [out] ppDevice - Address of the memory location where pointer to -/// the created device will be written. -/// \param [out] ppImmediateContext - Address of the memory location where pointers to -/// the immediate context will be written. -void EngineFactoryOpenGLImpl::AttachToActiveGLContext( const EngineGLAttribs& CreationAttribs, - IRenderDevice **ppDevice, - IDeviceContext **ppImmediateContext ) -{ - if (CreationAttribs.DebugMessageCallback != nullptr) - SetDebugMessageCallback(CreationAttribs.DebugMessageCallback); - - VERIFY( ppDevice && ppImmediateContext, "Null pointer provided" ); - if( !ppDevice || !ppImmediateContext ) - return; - - *ppDevice = nullptr; - *ppImmediateContext = nullptr; - - try - { - SetRawAllocator(CreationAttribs.pRawMemAllocator); - auto &RawMemAllocator = GetRawAllocator(); - - RenderDeviceGLImpl *pRenderDeviceOpenGL( NEW_RC_OBJ(RawMemAllocator, "TRenderDeviceGLImpl instance", TRenderDeviceGLImpl)(RawMemAllocator, CreationAttribs) ); - pRenderDeviceOpenGL->QueryInterface(IID_RenderDevice, reinterpret_cast(ppDevice) ); - - DeviceContextGLImpl *pDeviceContextOpenGL( NEW_RC_OBJ(RawMemAllocator, "DeviceContextGLImpl instance", DeviceContextGLImpl)(pRenderDeviceOpenGL, false ) ); - // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceOpenGL will - // keep a weak reference to the context - pDeviceContextOpenGL->QueryInterface(IID_DeviceContext, reinterpret_cast(ppImmediateContext) ); - pRenderDeviceOpenGL->SetImmediateContext(pDeviceContextOpenGL); - } - catch( const std::runtime_error & ) - { - if( *ppDevice ) - { - (*ppDevice)->Release(); - *ppDevice = nullptr; - } - - if( *ppImmediateContext ) - { - (*ppImmediateContext)->Release(); - *ppImmediateContext = nullptr; - } - - LOG_ERROR( "Failed to initialize OpenGL-based render device" ); - } -} - -#ifdef DOXYGEN -/// Loads OpenGL-based engine implementation and exports factory functions -/// \param [out] GetFactoryFunc - Pointer to the function that returns pointer to the factory for -/// the OpenGL engine implementation -/// See EngineFactoryOpenGLImpl::CreateDeviceAndSwapChainGL(). -/// \remarks Depending on the configuration and platform, the function loads different dll: -/// Platform\\Configuration | Debug | Release -/// --------------------------|------------------------------|---------------------------- -/// Win32/x86 | GraphicsEngineOpenGL_32d.dll | GraphicsEngineOpenGL_32r.dll -/// Win32/x64 | GraphicsEngineOpenGL_64d.dll | GraphicsEngineOpenGL_64r.dll -/// -/// To load the library on Android, it is necessary to call System.loadLibrary("GraphicsEngineOpenGL") from Java. -void LoadGraphicsEngineOpenGL(GetEngineFactoryOpenGLType &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; -} -#endif - -void EngineFactoryOpenGLImpl::CreateHLSL2GLSLConverter(IHLSL2GLSLConverter **ppConverter) -{ - HLSL2GLSLConverterObject *pConverter( NEW_RC_OBJ(GetRawAllocator(), "HLSL2GLSLConverterObject instance", HLSL2GLSLConverterObject)() ); - pConverter->QueryInterface( IID_HLSL2GLSLConverter, reinterpret_cast(ppConverter) ); -} - -API_QUALIFIER -Diligent::IEngineFactoryOpenGL* GetEngineFactoryOpenGL() -{ - return Diligent::EngineFactoryOpenGLImpl::GetInstance(); -} - -} -- cgit v1.2.3 From bdbca67b0e03baec3b9dd803e803d267210e892b Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Mon, 4 Mar 2019 23:19:07 -0800 Subject: Added ShaderFlags parameter to IPipelineState::BindStaticResources --- Graphics/GraphicsEngine/interface/PipelineState.h | 4 +++- Graphics/GraphicsEngine/interface/ShaderResourceBinding.h | 4 ++-- Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h | 2 +- Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp | 6 ++++-- Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h | 2 +- .../GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h | 2 ++ Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp | 6 ++++-- Graphics/GraphicsEngineVulkan/include/PipelineStateVkImpl.h | 2 +- Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h | 5 +++++ Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp | 10 +++++++--- 10 files changed, 30 insertions(+), 13 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngine/interface/PipelineState.h b/Graphics/GraphicsEngine/interface/PipelineState.h index 0f6efcf6..f562a2cd 100644 --- a/Graphics/GraphicsEngine/interface/PipelineState.h +++ b/Graphics/GraphicsEngine/interface/PipelineState.h @@ -251,9 +251,11 @@ public: /// Binds resources for all shaders in the pipeline state + /// \param [in] ShaderFlags - Flags that specify shader stages, for which resources will be bound. + /// Any combination of Diligent::SHADER_TYPE may be used. /// \param [in] pResourceMapping - Pointer to the resource mapping interface. /// \param [in] Flags - Additional flags. See Diligent::BIND_SHADER_RESOURCES_FLAGS. - virtual void BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags) = 0; + virtual void BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags) = 0; /// Returns the number of static shader resource variables. diff --git a/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h b/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h index d2523685..0afaa1f1 100644 --- a/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h +++ b/Graphics/GraphicsEngine/interface/ShaderResourceBinding.h @@ -56,8 +56,8 @@ public: /// Binds mutable and dynamice resources using the resource mapping - /// \param [in] ShaderFlags - Flags for the shader stages, for which resources will be bound. - /// Any combination of Diligent::SHADER_TYPE may be specified. + /// \param [in] ShaderFlags - Flags that specify shader stages, for which resources will be bound. + /// Any combination of Diligent::SHADER_TYPE may be used. /// \param [in] pResMapping - Shader resource mapping, where required resources will be looked up /// \param [in] Flags - Additional flags. See Diligent::BIND_SHADER_RESOURCES_FLAGS. virtual void BindResources(Uint32 ShaderFlags, IResourceMapping* pResMapping, Uint32 Flags) = 0; diff --git a/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h index 81e03ca2..c56d8479 100644 --- a/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h @@ -51,7 +51,7 @@ public: virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; - virtual void BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags)override final; + virtual void BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags)override final; virtual Uint32 GetStaticVariableCount(SHADER_TYPE ShaderType) const override final; diff --git a/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp index 84bc1ef5..d9cc1c21 100644 --- a/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp @@ -322,11 +322,13 @@ ID3D11ComputeShader* PipelineStateD3D11Impl::GetD3D11ComputeShader() } -void PipelineStateD3D11Impl::BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags) +void PipelineStateD3D11Impl::BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags) { for (Uint32 s=0; s < m_NumShaders; ++s) { - m_pStaticResourceLayouts[s].BindResources(pResourceMapping, Flags, m_pStaticResourceCaches[s]); + auto& StaticResLayout = m_pStaticResourceLayouts[s]; + if ( (ShaderFlags & StaticResLayout.GetShaderType()) != 0 ) + StaticResLayout.BindResources(pResourceMapping, Flags, m_pStaticResourceCaches[s]); } } diff --git a/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h b/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h index 64dfdc2b..fa51b6d0 100644 --- a/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h +++ b/Graphics/GraphicsEngineD3D12/include/PipelineStateD3D12Impl.h @@ -50,7 +50,7 @@ public: virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; - virtual void BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags)override final; + virtual void BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags)override final; virtual Uint32 GetStaticVariableCount(SHADER_TYPE ShaderType) const override final; diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h b/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h index 26ed260e..35ddfbc7 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderResourceLayoutD3D12.h @@ -252,6 +252,8 @@ public: } const bool IsUsingSeparateSamplers() const {return !m_pResources->IsUsingCombinedTextureSamplers();} + + SHADER_TYPE GetShaderType() const {return m_pResources->GetShaderType();} private: const D3D12Resource& GetAssignedSampler(const D3D12Resource& TexSrv)const; diff --git a/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp b/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp index 91835158..46530860 100644 --- a/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp +++ b/Graphics/GraphicsEngineD3D12/src/PipelineStateD3D12Impl.cpp @@ -442,11 +442,13 @@ bool PipelineStateD3D12Impl::dbgContainsShaderResources()const return false; } -void PipelineStateD3D12Impl::BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags) +void PipelineStateD3D12Impl::BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags) { for (Uint32 s=0; s < m_NumShaders; ++s) { - m_pStaticVarManagers[s].BindResources(pResourceMapping, Flags); + auto ShaderType = GetStaticShaderResLayout(s).GetShaderType(); + if ((ShaderFlags & ShaderType) != 0) + m_pStaticVarManagers[s].BindResources(pResourceMapping, Flags); } } diff --git a/Graphics/GraphicsEngineVulkan/include/PipelineStateVkImpl.h b/Graphics/GraphicsEngineVulkan/include/PipelineStateVkImpl.h index d03066fe..e9be63a3 100644 --- a/Graphics/GraphicsEngineVulkan/include/PipelineStateVkImpl.h +++ b/Graphics/GraphicsEngineVulkan/include/PipelineStateVkImpl.h @@ -66,7 +66,7 @@ public: virtual VkPipeline GetVkPipeline() const override final { return m_Pipeline; } - virtual void BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags)override final; + virtual void BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags)override final; virtual Uint32 GetStaticVariableCount(SHADER_TYPE ShaderType) const override final; diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h index 729997f9..8f7d2940 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderResourceLayoutVk.h @@ -285,6 +285,11 @@ public: return m_pResources->GetShaderName(); } + SHADER_TYPE GetShaderType()const + { + return m_pResources->GetShaderType(); + } + const VkResource& GetResource(SHADER_RESOURCE_VARIABLE_TYPE VarType, Uint32 r)const { VERIFY_EXPR( r < m_NumResources[VarType] ); diff --git a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp index f28b2068..776db721 100644 --- a/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp +++ b/Graphics/GraphicsEngineVulkan/src/PipelineStateVkImpl.cpp @@ -618,12 +618,16 @@ void PipelineStateVkImpl::CommitAndTransitionShaderResources(IShaderResourceBind } } -void PipelineStateVkImpl::BindStaticResources(IResourceMapping* pResourceMapping, Uint32 Flags) +void PipelineStateVkImpl::BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags) { for (Uint32 s=0; s < m_NumShaders; ++s) { - auto& StaticVarMgr = GetStaticVarMgr(s); - StaticVarMgr.BindResources(pResourceMapping, Flags); + auto ShaderType = GetStaticShaderResLayout(s).GetShaderType(); + if ((ShaderType & ShaderFlags) != 0) + { + auto& StaticVarMgr = GetStaticVarMgr(s); + StaticVarMgr.BindResources(pResourceMapping, Flags); + } } } -- cgit v1.2.3 From 4af7e990f7895de63ba886a6e6cd42259ce539aa Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Mon, 4 Mar 2019 23:49:24 -0800 Subject: Started updating GL backend to comply with the updated API --- .../include/GLContextAndroid.h | 2 +- .../GraphicsEngineOpenGL/include/GLContextIOS.h | 2 +- .../GraphicsEngineOpenGL/include/GLContextLinux.h | 2 +- .../GraphicsEngineOpenGL/include/GLContextMacOS.h | 2 +- .../include/GLContextWindows.h | 2 +- Graphics/GraphicsEngineOpenGL/include/GLProgram.h | 4 ++-- .../include/GLProgramResources.h | 25 +++++++++++----------- .../include/PipelineStateGLImpl.h | 2 +- .../include/RenderDeviceGLImpl.h | 7 +++--- .../GraphicsEngineOpenGL/include/ShaderGLImpl.h | 16 +++++++------- .../include/ShaderResourceBindingGLImpl.h | 4 ++-- .../GraphicsEngineOpenGL/include/SwapChainGLImpl.h | 11 +++++----- .../GraphicsEngineOpenGL/include/TexRegionRender.h | 2 +- Graphics/GraphicsEngineOpenGL/readme.md | 2 +- .../src/EngineFactoryOpenGL.cpp | 2 +- .../GraphicsEngineOpenGL/src/GLContextAndroid.cpp | 3 +-- Graphics/GraphicsEngineOpenGL/src/GLContextIOS.mm | 3 +-- .../GraphicsEngineOpenGL/src/GLContextLinux.cpp | 3 +-- .../GraphicsEngineOpenGL/src/GLContextMacOS.mm | 3 +-- .../GraphicsEngineOpenGL/src/GLContextWindows.cpp | 3 +-- Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp | 6 +++--- .../src/GLProgramResources.cpp | 12 +++++------ .../src/PipelineStateGLImpl.cpp | 4 ++-- .../src/RenderDeviceGLImpl.cpp | 12 +++++------ Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp | 8 +++---- .../src/ShaderResourceBindingGLImpl.cpp | 8 +++---- .../GraphicsEngineOpenGL/src/SwapChainGLImpl.cpp | 2 +- .../GraphicsEngineOpenGL/src/TexRegionRender.cpp | 8 +++---- 28 files changed, 77 insertions(+), 83 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineOpenGL/include/GLContextAndroid.h b/Graphics/GraphicsEngineOpenGL/include/GLContextAndroid.h index db25be8e..72a3c031 100644 --- a/Graphics/GraphicsEngineOpenGL/include/GLContextAndroid.h +++ b/Graphics/GraphicsEngineOpenGL/include/GLContextAndroid.h @@ -33,7 +33,7 @@ namespace Diligent public: typedef EGLContext NativeGLContextType; - GLContext( const struct EngineGLAttribs &InitAttribs, DeviceCaps &DeviceCaps ); + GLContext( const struct EngineGLCreateInfo &InitAttribs, DeviceCaps &DeviceCaps ); ~GLContext(); bool Init( ANativeWindow* window ); diff --git a/Graphics/GraphicsEngineOpenGL/include/GLContextIOS.h b/Graphics/GraphicsEngineOpenGL/include/GLContextIOS.h index 4a343545..76f564fb 100644 --- a/Graphics/GraphicsEngineOpenGL/include/GLContextIOS.h +++ b/Graphics/GraphicsEngineOpenGL/include/GLContextIOS.h @@ -30,7 +30,7 @@ namespace Diligent public: typedef void* NativeGLContextType; // EAGLContext* - GLContext(const struct EngineGLAttribs &InitAttribs, struct DeviceCaps &DeviceCaps); + GLContext(const struct EngineGLCreateInfo &InitAttribs, struct DeviceCaps &DeviceCaps); NativeGLContextType GetCurrentNativeGLContext(); }; diff --git a/Graphics/GraphicsEngineOpenGL/include/GLContextLinux.h b/Graphics/GraphicsEngineOpenGL/include/GLContextLinux.h index 49c5d99a..8c70f11f 100644 --- a/Graphics/GraphicsEngineOpenGL/include/GLContextLinux.h +++ b/Graphics/GraphicsEngineOpenGL/include/GLContextLinux.h @@ -30,7 +30,7 @@ namespace Diligent public: typedef GLXContext NativeGLContextType; - GLContext(const struct EngineGLAttribs &InitAttribs, struct DeviceCaps &DeviceCaps); + GLContext(const struct EngineGLCreateInfo &InitAttribs, struct DeviceCaps &DeviceCaps); ~GLContext(); void SwapBuffers(); diff --git a/Graphics/GraphicsEngineOpenGL/include/GLContextMacOS.h b/Graphics/GraphicsEngineOpenGL/include/GLContextMacOS.h index c8aeb055..1ed87ab4 100644 --- a/Graphics/GraphicsEngineOpenGL/include/GLContextMacOS.h +++ b/Graphics/GraphicsEngineOpenGL/include/GLContextMacOS.h @@ -30,7 +30,7 @@ namespace Diligent public: typedef void* NativeGLContextType; // NSOpenGLContext* - GLContext(const struct EngineGLAttribs &InitAttribs, struct DeviceCaps &DeviceCaps); + GLContext(const struct EngineGLCreateInfo &InitAttribs, struct DeviceCaps &DeviceCaps); NativeGLContextType GetCurrentNativeGLContext(); }; diff --git a/Graphics/GraphicsEngineOpenGL/include/GLContextWindows.h b/Graphics/GraphicsEngineOpenGL/include/GLContextWindows.h index 7c21a25b..cd01d88c 100644 --- a/Graphics/GraphicsEngineOpenGL/include/GLContextWindows.h +++ b/Graphics/GraphicsEngineOpenGL/include/GLContextWindows.h @@ -30,7 +30,7 @@ namespace Diligent public: typedef HGLRC NativeGLContextType; - GLContext( const struct EngineGLAttribs &InitAttribs, struct DeviceCaps &DeviceCaps ); + GLContext( const struct EngineGLCreateInfo &InitAttribs, struct DeviceCaps &DeviceCaps ); ~GLContext(); void SwapBuffers(); diff --git a/Graphics/GraphicsEngineOpenGL/include/GLProgram.h b/Graphics/GraphicsEngineOpenGL/include/GLProgram.h index 296ff4fd..96729fed 100644 --- a/Graphics/GraphicsEngineOpenGL/include/GLProgram.h +++ b/Graphics/GraphicsEngineOpenGL/include/GLProgram.h @@ -38,8 +38,8 @@ namespace Diligent GLProgram& operator = ( GLProgram&&) = delete; void InitResources(RenderDeviceGLImpl* pDeviceGLImpl, - SHADER_VARIABLE_TYPE DefaultVariableType, - const ShaderVariableDesc* VariableDesc, + SHADER_RESOURCE_VARIABLE_TYPE DefaultVariableType, + const ShaderResourceVariableDesc* VariableDesc, Uint32 NumVars, const StaticSamplerDesc* StaticSamplers, Uint32 NumStaticSamplers, diff --git a/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h b/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h index 5cf2efe0..85651833 100644 --- a/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h +++ b/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h @@ -27,6 +27,7 @@ #include "ShaderBase.h" #include "SamplerGLImpl.h" #include "HashUtils.h" +#include "ShaderResourceVariableBase.h" #ifdef _DEBUG # define VERIFY_RESOURCE_BINDINGS @@ -46,14 +47,14 @@ namespace Diligent void LoadUniforms(class RenderDeviceGLImpl* pDeviceGLImpl, GLuint GLProgram, - const SHADER_VARIABLE_TYPE DefaultVariableType, - const ShaderVariableDesc* VariableDesc, + const SHADER_RESOURCE_VARIABLE_TYPE DefaultVariableType, + const ShaderResourceVariableDesc* VariableDesc, Uint32 NumVars, const StaticSamplerDesc* StaticSamplers, Uint32 NumStaticSamplers); void Clone(const GLProgramResources& SrcLayout, - SHADER_VARIABLE_TYPE* VarTypes, + SHADER_RESOURCE_VARIABLE_TYPE* VarTypes, Uint32 NumVarTypes, IObject& Owner); @@ -61,7 +62,7 @@ namespace Diligent { GLProgramVariableBase(String _Name, size_t _ArraySize, - SHADER_VARIABLE_TYPE _VarType) : + SHADER_RESOURCE_VARIABLE_TYPE _VarType) : Name ( std::move(_Name) ), pResources(_ArraySize), VarType (_VarType) @@ -82,14 +83,14 @@ namespace Diligent String Name; std::vector< RefCntAutoPtr > pResources; - const SHADER_VARIABLE_TYPE VarType; + const SHADER_RESOURCE_VARIABLE_TYPE VarType; }; struct UniformBufferInfo : GLProgramVariableBase { UniformBufferInfo(String _Name, size_t _ArraySize, - SHADER_VARIABLE_TYPE _VarType, + SHADER_RESOURCE_VARIABLE_TYPE _VarType, GLint _Index) : GLProgramVariableBase(std::move(_Name), _ArraySize, _VarType), Index(_Index) @@ -114,7 +115,7 @@ namespace Diligent { SamplerInfo(String _Name, size_t _ArraySize, - SHADER_VARIABLE_TYPE _VarType, + SHADER_RESOURCE_VARIABLE_TYPE _VarType, GLint _Location, GLenum _Type, class SamplerGLImpl* _pStaticSampler) : @@ -146,7 +147,7 @@ namespace Diligent { ImageInfo(String _Name, size_t _ArraySize, - SHADER_VARIABLE_TYPE _VarType, + SHADER_RESOURCE_VARIABLE_TYPE _VarType, GLint _BindingPoint, GLenum _Type) : GLProgramVariableBase(std::move(_Name), _ArraySize, _VarType), @@ -175,7 +176,7 @@ namespace Diligent { StorageBlockInfo(String _Name, size_t _ArraySize, - SHADER_VARIABLE_TYPE _VarType, + SHADER_RESOURCE_VARIABLE_TYPE _VarType, GLint _Binding) : GLProgramVariableBase(std::move(_Name), _ArraySize, _VarType), Binding(_Binding) @@ -216,7 +217,7 @@ namespace Diligent ProgramVar.pResources[FirstElement + i] = ppObjects[i]; } - virtual SHADER_VARIABLE_TYPE GetType()const override final + virtual SHADER_RESOURCE_VARIABLE_TYPE GetType()const override final { return ProgramVar.VarType; } @@ -247,8 +248,8 @@ namespace Diligent void dbgVerifyResourceBindings(); #endif - IShaderVariable* GetShaderVariable(const Char* Name); - IShaderVariable* GetShaderVariable(Uint32 Index) + IShaderResourceVariable* GetShaderVariable(const Char* Name); + IShaderResourceVariable* GetShaderVariable(Uint32 Index) { return Index < m_VariablesByIndex.size() ? m_VariablesByIndex[Index] : nullptr; } diff --git a/Graphics/GraphicsEngineOpenGL/include/PipelineStateGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/PipelineStateGLImpl.h index 3e1bbbb1..dbf2b07b 100644 --- a/Graphics/GraphicsEngineOpenGL/include/PipelineStateGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/PipelineStateGLImpl.h @@ -51,7 +51,7 @@ public: /// Queries the specific interface, see IObject::QueryInterface() for details virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface )override; - virtual void BindShaderResources( IResourceMapping* pResourceMapping, Uint32 Flags )override final; + virtual void BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags)override final; virtual void CreateShaderResourceBinding( IShaderResourceBinding** ppShaderResourceBinding, bool InitStaticResources )override final; diff --git a/Graphics/GraphicsEngineOpenGL/include/RenderDeviceGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/RenderDeviceGLImpl.h index b0b67c32..03c8f998 100644 --- a/Graphics/GraphicsEngineOpenGL/include/RenderDeviceGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/RenderDeviceGLImpl.h @@ -29,7 +29,6 @@ #include "BaseInterfacesGL.h" #include "FBOCache.h" #include "TexRegionRender.h" -#include "EngineGLAttribs.h" enum class GPU_VENDOR { @@ -55,15 +54,15 @@ class RenderDeviceGLImpl : public RenderDeviceBase public: using TRenderDeviceBase = RenderDeviceBase; - RenderDeviceGLImpl( IReferenceCounters *pRefCounters, IMemoryAllocator &RawMemAllocator, const EngineGLAttribs &InitAttribs ); + RenderDeviceGLImpl( IReferenceCounters *pRefCounters, IMemoryAllocator &RawMemAllocator, const EngineGLCreateInfo &InitAttribs ); ~RenderDeviceGLImpl(); virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override; void CreateBuffer(const BufferDesc& BuffDesc, const BufferData* pBuffData, IBuffer **ppBufferLayout, bool bIsDeviceInternal); virtual void CreateBuffer(const BufferDesc& BuffDesc, const BufferData* BuffData, IBuffer **ppBufferLayout)override final; - void CreateShader(const ShaderCreationAttribs &ShaderCreationAttribs, IShader **ppShader, bool bIsDeviceInternal ); - virtual void CreateShader(const ShaderCreationAttribs &ShaderCreationAttribs, IShader **ppShader)override final; + void CreateShader(const ShaderCreateInfo &ShaderCreateInfo, IShader **ppShader, bool bIsDeviceInternal ); + virtual void CreateShader(const ShaderCreateInfo &ShaderCreateInfo, IShader **ppShader)override final; void CreateTexture(const TextureDesc& TexDesc, const TextureData* pData, ITexture **ppTexture, bool bIsDeviceInternal); virtual void CreateTexture(const TextureDesc& TexDesc, const TextureData* Data, ITexture **ppTexture)override final; diff --git a/Graphics/GraphicsEngineOpenGL/include/ShaderGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/ShaderGLImpl.h index 77c5f554..b8d607ea 100644 --- a/Graphics/GraphicsEngineOpenGL/include/ShaderGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/ShaderGLImpl.h @@ -70,7 +70,7 @@ class ShaderGLImpl final : public ShaderBase public: using TShaderBase = ShaderBase; - ShaderGLImpl( IReferenceCounters *pRefCounters, RenderDeviceGLImpl *pDeviceGL, const ShaderCreationAttribs &ShaderCreationAttribs, bool bIsDeviceInternal = false ); + ShaderGLImpl( IReferenceCounters *pRefCounters, RenderDeviceGLImpl *pDeviceGL, const ShaderCreateInfo &ShaderCreateInfo, bool bIsDeviceInternal = false ); ~ShaderGLImpl(); virtual void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags )override final; @@ -79,21 +79,21 @@ public: // If separate shaders are not available, the method can optionally create // a placeholder for static resource variable - IShaderVariable* GetShaderVariable(const Char* Name, bool CreatePlaceholder); - virtual IShaderVariable* GetShaderVariable(const Char* Name)override final; + IShaderResourceVariable* GetShaderVariable(const Char* Name, bool CreatePlaceholder); + virtual IShaderResourceVariable* GetShaderVariable(const Char* Name)override final; virtual Uint32 GetVariableCount() const override final; - virtual IShaderVariable* GetShaderVariable(Uint32 Index) override final; + virtual IShaderResourceVariable* GetShaderVariable(Uint32 Index) override final; GLProgram& GetGlProgram(){return m_GlProgObj;} // This class is used to keep references to static resources when separate shaders are not available - class StaticVarPlaceholder final : public ObjectBase + class StaticVarPlaceholder final : public ObjectBase { public: StaticVarPlaceholder(IReferenceCounters* pRefCounters, String Name, Uint32 Index) : - ObjectBase(pRefCounters), + ObjectBase(pRefCounters), m_Name (std::move(Name)), m_Index (Index) {} @@ -109,9 +109,9 @@ public: for (Uint32 i=0; i < NumElements; ++i) m_Objects[FirstElement + i] = ppObjects[i]; } - virtual SHADER_VARIABLE_TYPE GetType()const override final + virtual SHADER_RESOURCE_VARIABLE_TYPE GetType()const override final { - return SHADER_VARIABLE_TYPE_STATIC; + return SHADER_RESOURCE_VARIABLE_TYPE_STATIC; } virtual Uint32 GetArraySize()const override final { diff --git a/Graphics/GraphicsEngineOpenGL/include/ShaderResourceBindingGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/ShaderResourceBindingGLImpl.h index ac76461b..243b7354 100644 --- a/Graphics/GraphicsEngineOpenGL/include/ShaderResourceBindingGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/ShaderResourceBindingGLImpl.h @@ -51,11 +51,11 @@ public: virtual void BindResources(Uint32 ShaderFlags, IResourceMapping* pResMapping, Uint32 Flags)override final; - virtual IShaderVariable* GetVariable(SHADER_TYPE ShaderType, const char *Name)override final; + virtual IShaderResourceVariable* GetVariable(SHADER_TYPE ShaderType, const char *Name)override final; virtual Uint32 GetVariableCount(SHADER_TYPE ShaderType) const override final; - virtual IShaderVariable* GetVariable(SHADER_TYPE ShaderType, Uint32 Index)override final; + virtual IShaderResourceVariable* GetVariable(SHADER_TYPE ShaderType, Uint32 Index)override final; virtual void InitializeStaticResources(const IPipelineState* pPipelineState)override final; diff --git a/Graphics/GraphicsEngineOpenGL/include/SwapChainGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/SwapChainGLImpl.h index e92bc0a5..d5d427f1 100644 --- a/Graphics/GraphicsEngineOpenGL/include/SwapChainGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/SwapChainGLImpl.h @@ -23,7 +23,6 @@ #pragma once -#include "EngineGLAttribs.h" #include "SwapChainGL.h" #include "SwapChainBase.h" #include "GLObjectWrapper.h" @@ -38,11 +37,11 @@ class SwapChainGLImpl final : public SwapChainBase public: using TSwapChainBase = SwapChainBase; - SwapChainGLImpl(IReferenceCounters *pRefCounters, - const EngineGLAttribs &InitAttribs, - const SwapChainDesc& SwapChainDesc, - class RenderDeviceGLImpl* pRenderDeviceGL, - class DeviceContextGLImpl* pImmediateContextGL); + SwapChainGLImpl(IReferenceCounters* pRefCounters, + const EngineGLCreateInfo& InitAttribs, + const SwapChainDesc& SwapChainDesc, + class RenderDeviceGLImpl* pRenderDeviceGL, + class DeviceContextGLImpl* pImmediateContextGL); ~SwapChainGLImpl(); virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; diff --git a/Graphics/GraphicsEngineOpenGL/include/TexRegionRender.h b/Graphics/GraphicsEngineOpenGL/include/TexRegionRender.h index 91c31b08..72c64d91 100644 --- a/Graphics/GraphicsEngineOpenGL/include/TexRegionRender.h +++ b/Graphics/GraphicsEngineOpenGL/include/TexRegionRender.h @@ -48,7 +48,7 @@ private: RefCntAutoPtr m_pConstantBuffer; RefCntAutoPtr m_pPSO[RESOURCE_DIM_NUM_DIMENSIONS * 3]; RefCntAutoPtr m_pSRB; - IShaderVariable* m_pSrcTexVar = nullptr; + IShaderResourceVariable* m_pSrcTexVar = nullptr; RefCntAutoPtr m_pOrigPSO; Uint32 m_OrigStencilRef = 0; diff --git a/Graphics/GraphicsEngineOpenGL/readme.md b/Graphics/GraphicsEngineOpenGL/readme.md index dfa2109d..ab987dad 100644 --- a/Graphics/GraphicsEngineOpenGL/readme.md +++ b/Graphics/GraphicsEngineOpenGL/readme.md @@ -23,7 +23,7 @@ RefCntAutoPtr pImmediateContext; SwapChainDesc SCDesc; RefCntAutoPtr pSwapChain; auto *pFactoryOpenGL = GetEngineFactoryOpenGL(); -EngineGLAttribs CreationAttribs; +EngineGLCreateInfo CreationAttribs; CreationAttribs.pNativeWndHandle = NativeWindowHandle; pFactoryOpenGL->CreateDeviceAndSwapChainGL( CreationAttribs, &pRenderDevice, &pImmediateContext, SCDesc, &pSwapChain); diff --git a/Graphics/GraphicsEngineOpenGL/src/EngineFactoryOpenGL.cpp b/Graphics/GraphicsEngineOpenGL/src/EngineFactoryOpenGL.cpp index 04d1ce83..21520138 100644 --- a/Graphics/GraphicsEngineOpenGL/src/EngineFactoryOpenGL.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/EngineFactoryOpenGL.cpp @@ -25,7 +25,7 @@ /// Routines that initialize OpenGL/GLES-based engine implementation #include "pch.h" -#include "RenderDeviceFactoryOpenGL.h" +#include "EngineFactoryOpenGL.h" #include "RenderDeviceGLImpl.h" #include "DeviceContextGLImpl.h" #include "EngineMemory.h" diff --git a/Graphics/GraphicsEngineOpenGL/src/GLContextAndroid.cpp b/Graphics/GraphicsEngineOpenGL/src/GLContextAndroid.cpp index 0e0f877e..f8f202c7 100644 --- a/Graphics/GraphicsEngineOpenGL/src/GLContextAndroid.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/GLContextAndroid.cpp @@ -25,7 +25,6 @@ #include #include "GLContextAndroid.h" -#include "EngineGLAttribs.h" #ifndef EGL_CONTEXT_MINOR_VERSION_KHR #define EGL_CONTEXT_MINOR_VERSION_KHR 0x30FB @@ -229,7 +228,7 @@ namespace Diligent return true; } - GLContext::GLContext( const EngineGLAttribs &InitAttribs, DeviceCaps &DeviceCaps ) : + GLContext::GLContext( const EngineGLCreateInfo &InitAttribs, DeviceCaps &DeviceCaps ) : display_( EGL_NO_DISPLAY ), surface_( EGL_NO_SURFACE ), context_( EGL_NO_CONTEXT ), diff --git a/Graphics/GraphicsEngineOpenGL/src/GLContextIOS.mm b/Graphics/GraphicsEngineOpenGL/src/GLContextIOS.mm index 5567eb0e..d5f2184b 100644 --- a/Graphics/GraphicsEngineOpenGL/src/GLContextIOS.mm +++ b/Graphics/GraphicsEngineOpenGL/src/GLContextIOS.mm @@ -28,11 +28,10 @@ #include "GLContextIOS.h" #include "DeviceCaps.h" #include "GLTypeConversions.h" -#include "EngineGLAttribs.h" namespace Diligent { - GLContext::GLContext( const EngineGLAttribs &Info, DeviceCaps &DeviceCaps ) + GLContext::GLContext( const EngineGLCreateInfo &Info, DeviceCaps &DeviceCaps ) { if (GetCurrentNativeGLContext() == nullptr) { diff --git a/Graphics/GraphicsEngineOpenGL/src/GLContextLinux.cpp b/Graphics/GraphicsEngineOpenGL/src/GLContextLinux.cpp index d4f38df3..e6fe5e89 100644 --- a/Graphics/GraphicsEngineOpenGL/src/GLContextLinux.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/GLContextLinux.cpp @@ -26,7 +26,6 @@ #include "GLContextLinux.h" #include "DeviceCaps.h" #include "GLTypeConversions.h" -#include "EngineGLAttribs.h" namespace Diligent { @@ -84,7 +83,7 @@ namespace Diligent LOG_INFO_MESSAGE( MessageSS.str().c_str() ); } - GLContext::GLContext( const EngineGLAttribs &InitAttribs, DeviceCaps &DeviceCaps ) : + GLContext::GLContext( const EngineGLCreateInfo &InitAttribs, DeviceCaps &DeviceCaps ) : m_Context(0), m_pNativeWindow(InitAttribs.pNativeWndHandle), m_pDisplay(InitAttribs.pDisplay) diff --git a/Graphics/GraphicsEngineOpenGL/src/GLContextMacOS.mm b/Graphics/GraphicsEngineOpenGL/src/GLContextMacOS.mm index 88e2c9c9..76cb9dcc 100644 --- a/Graphics/GraphicsEngineOpenGL/src/GLContextMacOS.mm +++ b/Graphics/GraphicsEngineOpenGL/src/GLContextMacOS.mm @@ -28,7 +28,6 @@ #include "GLContextMacOS.h" #include "DeviceCaps.h" #include "GLTypeConversions.h" -#include "EngineGLAttribs.h" static void glDrawArraysInstancedBaseInstance_stub(GLenum mode, GLint first, GLsizei count, GLsizei primcount, GLuint baseinstance) { @@ -48,7 +47,7 @@ static void glDrawElementsInstancedBaseVertexBaseInstance_stub(GLenum mode, GLs namespace Diligent { - GLContext::GLContext( const EngineGLAttribs &InitAttribs, DeviceCaps &DeviceCaps ) + GLContext::GLContext( const EngineGLCreateInfo &InitAttribs, DeviceCaps &DeviceCaps ) { if (GetCurrentNativeGLContext() == nullptr) { diff --git a/Graphics/GraphicsEngineOpenGL/src/GLContextWindows.cpp b/Graphics/GraphicsEngineOpenGL/src/GLContextWindows.cpp index 88b46b2b..9aa475ab 100644 --- a/Graphics/GraphicsEngineOpenGL/src/GLContextWindows.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/GLContextWindows.cpp @@ -26,7 +26,6 @@ #include "GLContextWindows.h" #include "DeviceCaps.h" #include "GLTypeConversions.h" -#include "EngineGLAttribs.h" namespace Diligent { @@ -89,7 +88,7 @@ namespace Diligent LOG_INFO_MESSAGE( MessageSS.str().c_str() ); } - GLContext::GLContext(const EngineGLAttribs &InitAttribs, DeviceCaps &DeviceCaps ) : + GLContext::GLContext(const EngineGLCreateInfo &InitAttribs, DeviceCaps &DeviceCaps ) : m_Context(0), m_WindowHandleToDeviceContext(0) { diff --git a/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp b/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp index c3108330..07c2117c 100644 --- a/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp @@ -39,8 +39,8 @@ namespace Diligent {} void GLProgram::InitResources(RenderDeviceGLImpl* pDeviceGLImpl, - const SHADER_VARIABLE_TYPE DefaultVariableType, - const ShaderVariableDesc *VariableDesc, + const SHADER_RESOURCE_VARIABLE_TYPE DefaultVariableType, + const ShaderResourceVariableDesc *VariableDesc, Uint32 NumVars, const StaticSamplerDesc *StaticSamplers, Uint32 NumStaticSamplers, @@ -49,7 +49,7 @@ namespace Diligent GLuint GLProgram = static_cast(*this); m_AllResources.LoadUniforms(pDeviceGLImpl, GLProgram, DefaultVariableType, VariableDesc, NumVars, StaticSamplers, NumStaticSamplers); - SHADER_VARIABLE_TYPE VarTypes[] = {SHADER_VARIABLE_TYPE_STATIC}; + SHADER_RESOURCE_VARIABLE_TYPE VarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_STATIC}; m_ConstantResources.Clone(m_AllResources, VarTypes, _countof(VarTypes), Owner); } diff --git a/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp b/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp index d662207f..34529cbf 100644 --- a/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp @@ -46,8 +46,8 @@ namespace Diligent void GLProgramResources::LoadUniforms(RenderDeviceGLImpl *pDeviceGLImpl, GLuint GLProgram, - const SHADER_VARIABLE_TYPE DefaultVariableType, - const ShaderVariableDesc *VariableDesc, + const SHADER_RESOURCE_VARIABLE_TYPE DefaultVariableType, + const ShaderResourceVariableDesc *VariableDesc, Uint32 NumVars, const StaticSamplerDesc *StaticSamplers, Uint32 NumStaticSamplers) @@ -348,7 +348,7 @@ namespace Diligent } - static bool CheckType(SHADER_VARIABLE_TYPE Type, SHADER_VARIABLE_TYPE* AllowedTypes, Uint32 NumAllowedTypes) + static bool CheckType(SHADER_RESOURCE_VARIABLE_TYPE Type, SHADER_RESOURCE_VARIABLE_TYPE* AllowedTypes, Uint32 NumAllowedTypes) { for(Uint32 i=0; i < NumAllowedTypes; ++i) if(Type == AllowedTypes[i]) @@ -358,7 +358,7 @@ namespace Diligent } void GLProgramResources::Clone(const GLProgramResources& SrcLayout, - SHADER_VARIABLE_TYPE* VarTypes, + SHADER_RESOURCE_VARIABLE_TYPE* VarTypes, Uint32 NumVarTypes, IObject& Owner) { @@ -414,7 +414,7 @@ namespace Diligent #undef STORE_SHADER_VARIABLES } - IShaderVariable* GLProgramResources::GetShaderVariable( const Char* Name ) + IShaderResourceVariable* GLProgramResources::GetShaderVariable( const Char* Name ) { // Name will be implicitly converted to HashMapStringKey without making a copy auto it = m_VariableHash.find( Name ); @@ -446,7 +446,7 @@ namespace Diligent if (pNewRes != nullptr) { - if(res.VarType == SHADER_VARIABLE_TYPE_STATIC && CurrResource != nullptr && CurrResource != pNewRes ) + if(res.VarType == SHADER_RESOURCE_VARIABLE_TYPE_STATIC && CurrResource != nullptr && CurrResource != pNewRes ) LOG_ERROR_MESSAGE( "Updating binding for static variable \"", Name, "\" is invalid and may result in an undefined behavior" ); CurrResource = pNewRes; } diff --git a/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp index 3f0fed9b..9071b815 100644 --- a/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp @@ -99,9 +99,9 @@ void PipelineStateGLImpl::LinkGLProgram(bool bIsProgramPipelineSupported) CHECK_GL_ERROR("glDetachShader() failed"); } - std::vector MergedVarTypesArray; + std::vector MergedVarTypesArray; std::vector MergedStSamArray; - SHADER_VARIABLE_TYPE DefaultVarType = SHADER_VARIABLE_TYPE_STATIC; + SHADER_RESOURCE_VARIABLE_TYPE DefaultVarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; for (Uint32 Shader = 0; Shader < m_NumShaders; ++Shader) { auto* pCurrShader = GetShader(Shader); diff --git a/Graphics/GraphicsEngineOpenGL/src/RenderDeviceGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/RenderDeviceGLImpl.cpp index d7f79554..0bd6538b 100644 --- a/Graphics/GraphicsEngineOpenGL/src/RenderDeviceGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/RenderDeviceGLImpl.cpp @@ -47,7 +47,7 @@ namespace Diligent { -RenderDeviceGLImpl :: RenderDeviceGLImpl(IReferenceCounters *pRefCounters, IMemoryAllocator& RawMemAllocator, const EngineGLAttribs& InitAttribs): +RenderDeviceGLImpl :: RenderDeviceGLImpl(IReferenceCounters *pRefCounters, IMemoryAllocator& RawMemAllocator, const EngineGLCreateInfo& InitAttribs): TRenderDeviceBase { pRefCounters, @@ -136,13 +136,13 @@ void RenderDeviceGLImpl :: CreateBufferFromGLHandle(Uint32 GLHandle, const Buffe ); } -void RenderDeviceGLImpl :: CreateShader(const ShaderCreationAttribs& ShaderCreationAttribs, IShader** ppShader, bool bIsDeviceInternal) +void RenderDeviceGLImpl :: CreateShader(const ShaderCreateInfo& ShaderCreateInfo, IShader** ppShader, bool bIsDeviceInternal) { - CreateDeviceObject( "shader", ShaderCreationAttribs.Desc, ppShader, + CreateDeviceObject( "shader", ShaderCreateInfo.Desc, ppShader, [&]() { ShaderGLImpl *pShaderOGL(NEW_RC_OBJ(m_ShaderObjAllocator, "ShaderGLImpl instance", ShaderGLImpl) - (this, ShaderCreationAttribs, bIsDeviceInternal)); + (this, ShaderCreateInfo, bIsDeviceInternal)); pShaderOGL->QueryInterface(IID_Shader, reinterpret_cast(ppShader) ); OnCreateDeviceObject( pShaderOGL ); @@ -150,9 +150,9 @@ void RenderDeviceGLImpl :: CreateShader(const ShaderCreationAttribs& ShaderCreat ); } -void RenderDeviceGLImpl :: CreateShader(const ShaderCreationAttribs& ShaderCreationAttribs, IShader **ppShader) +void RenderDeviceGLImpl :: CreateShader(const ShaderCreateInfo& ShaderCreateInfo, IShader **ppShader) { - CreateShader(ShaderCreationAttribs, ppShader, false); + CreateShader(ShaderCreateInfo, ppShader, false); } void RenderDeviceGLImpl :: CreateTexture(const TextureDesc& TexDesc, const TextureData* pData, ITexture **ppTexture, bool bIsDeviceInternal) diff --git a/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp index 65a797c0..7e6340dc 100644 --- a/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp @@ -35,7 +35,7 @@ namespace Diligent ShaderGLImpl::ShaderGLImpl(IReferenceCounters* pRefCounters, RenderDeviceGLImpl* pDeviceGL, - const ShaderCreationAttribs& CreationAttribs, + const ShaderCreateInfo& CreationAttribs, bool bIsDeviceInternal) : TShaderBase( pRefCounters, pDeviceGL, CreationAttribs.Desc, bIsDeviceInternal ), m_GlProgObj(false), @@ -186,12 +186,12 @@ void ShaderGLImpl::BindResources( IResourceMapping* pResourceMapping, Uint32 Fla } } -IShaderVariable* ShaderGLImpl::GetShaderVariable(const Char* Name) +IShaderResourceVariable* ShaderGLImpl::GetShaderVariable(const Char* Name) { return GetShaderVariable(Name, true); } -IShaderVariable* ShaderGLImpl::GetShaderVariable(const Char* Name, bool CreatePlaceholder) +IShaderResourceVariable* ShaderGLImpl::GetShaderVariable(const Char* Name, bool CreatePlaceholder) { if( m_GlProgObj ) return m_GlProgObj.GetConstantResources().GetShaderVariable(Name); @@ -228,7 +228,7 @@ Uint32 ShaderGLImpl::GetVariableCount() const } } -IShaderVariable* ShaderGLImpl::GetShaderVariable(Uint32 Index) +IShaderResourceVariable* ShaderGLImpl::GetShaderVariable(Uint32 Index) { if( m_GlProgObj ) return m_GlProgObj.GetConstantResources().GetShaderVariable(Index); diff --git a/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp index f58be350..5930f0a6 100644 --- a/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp @@ -35,7 +35,7 @@ ShaderResourceBindingGLImpl::ShaderResourceBindingGLImpl(IReferenceCounters* pRe { if (IsUsingSeparatePrograms()) { - SHADER_VARIABLE_TYPE VarTypes[] = {SHADER_VARIABLE_TYPE_MUTABLE, SHADER_VARIABLE_TYPE_DYNAMIC}; + SHADER_RESOURCE_VARIABLE_TYPE VarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; #define INIT_SHADER(SN)\ if(auto p##SN = ValidatedCast( pPSO->Get##SN() )) \ { \ @@ -54,7 +54,7 @@ ShaderResourceBindingGLImpl::ShaderResourceBindingGLImpl(IReferenceCounters* pRe else { // Clone all variable types - SHADER_VARIABLE_TYPE VarTypes[] = {SHADER_VARIABLE_TYPE_STATIC, SHADER_VARIABLE_TYPE_MUTABLE, SHADER_VARIABLE_TYPE_DYNAMIC}; + SHADER_RESOURCE_VARIABLE_TYPE VarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_STATIC, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; m_DynamicProgResources[0].Clone(pPSO->GetGLProgram().GetAllResources(), VarTypes, _countof(VarTypes), *this); } } @@ -94,7 +94,7 @@ void ShaderResourceBindingGLImpl::BindResources(Uint32 ShaderFlags, IResourceMap } } -IShaderVariable* ShaderResourceBindingGLImpl::GetVariable(SHADER_TYPE ShaderType, const char* Name) +IShaderResourceVariable* ShaderResourceBindingGLImpl::GetVariable(SHADER_TYPE ShaderType, const char* Name) { auto ShaderInd = IsUsingSeparatePrograms() ? GetShaderTypeIndex(ShaderType) : 0; return m_DynamicProgResources[ShaderInd].GetShaderVariable(Name); @@ -106,7 +106,7 @@ Uint32 ShaderResourceBindingGLImpl::GetVariableCount(SHADER_TYPE ShaderType) con return m_DynamicProgResources[ShaderInd].GetVariableCount(); } -IShaderVariable* ShaderResourceBindingGLImpl::GetVariable(SHADER_TYPE ShaderType, Uint32 Index) +IShaderResourceVariable* ShaderResourceBindingGLImpl::GetVariable(SHADER_TYPE ShaderType, Uint32 Index) { auto ShaderInd = IsUsingSeparatePrograms() ? GetShaderTypeIndex(ShaderType) : 0; return m_DynamicProgResources[ShaderInd].GetShaderVariable(Index); diff --git a/Graphics/GraphicsEngineOpenGL/src/SwapChainGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/SwapChainGLImpl.cpp index bf1e706c..9fb44c53 100644 --- a/Graphics/GraphicsEngineOpenGL/src/SwapChainGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/SwapChainGLImpl.cpp @@ -29,7 +29,7 @@ namespace Diligent { SwapChainGLImpl::SwapChainGLImpl(IReferenceCounters *pRefCounters, - const EngineGLAttribs &InitAttribs, + const EngineGLCreateInfo &InitAttribs, const SwapChainDesc& SCDesc, RenderDeviceGLImpl* pRenderDeviceGL, DeviceContextGLImpl* pImmediateContextGL) : diff --git a/Graphics/GraphicsEngineOpenGL/src/TexRegionRender.cpp b/Graphics/GraphicsEngineOpenGL/src/TexRegionRender.cpp index 312889e7..9bbb9c89 100644 --- a/Graphics/GraphicsEngineOpenGL/src/TexRegionRender.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/TexRegionRender.cpp @@ -58,10 +58,10 @@ namespace Diligent TexRegionRender::TexRegionRender( class RenderDeviceGLImpl *pDeviceGL ) { - ShaderCreationAttribs ShaderAttrs; + ShaderCreateInfo ShaderAttrs; ShaderAttrs.Desc.Name = "TexRegionRender : Vertex shader"; ShaderAttrs.Desc.ShaderType = SHADER_TYPE_VERTEX; - ShaderAttrs.Desc.DefaultVariableType = SHADER_VARIABLE_TYPE_DYNAMIC; + ShaderAttrs.Desc.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; ShaderAttrs.Source = VertexShaderSource; constexpr bool IsInternalDeviceObject = true; pDeviceGL->CreateShader(ShaderAttrs, &m_pVertexShader, IsInternalDeviceObject); @@ -117,9 +117,9 @@ namespace Diligent Name.append(SamplerDim); ShaderAttrs.Desc.Name = Name.c_str(); ShaderAttrs.Desc.ShaderType = SHADER_TYPE_PIXEL; - ShaderVariableDesc Vars[] = + ShaderResourceVariableDesc Vars[] = { - {"cbConstants", SHADER_VARIABLE_TYPE_MUTABLE} + {"cbConstants", SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE} }; ShaderAttrs.Desc.NumVariables = _countof(Vars); ShaderAttrs.Desc.VariableDesc = Vars; -- cgit v1.2.3 From 95174b2e8ceafdd5928fa2d0f81ce8c92b1c29f2 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Mon, 4 Mar 2019 23:51:06 -0800 Subject: Updated QueryInterface declaration in GL backend --- Graphics/GraphicsEngineOpenGL/include/BufferViewGLImpl.h | 2 +- Graphics/GraphicsEngineOpenGL/include/DeviceContextGLImpl.h | 2 +- Graphics/GraphicsEngineOpenGL/include/RenderDeviceGLImpl.h | 2 +- Graphics/GraphicsEngineOpenGL/include/SamplerGLImpl.h | 2 +- Graphics/GraphicsEngineOpenGL/include/SwapChainGLImpl.h | 2 +- Graphics/GraphicsEngineOpenGL/include/TextureViewGLImpl.h | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineOpenGL/include/BufferViewGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/BufferViewGLImpl.h index 0961179c..639b3456 100644 --- a/Graphics/GraphicsEngineOpenGL/include/BufferViewGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/BufferViewGLImpl.h @@ -53,7 +53,7 @@ public: bool bIsDefaultView); /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ); + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface )override final; const GLObjectWrappers::GLTextureObj& GetTexBufferHandle(){ return m_GLTexBuffer; } diff --git a/Graphics/GraphicsEngineOpenGL/include/DeviceContextGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/DeviceContextGLImpl.h index fe70d286..2be0a192 100644 --- a/Graphics/GraphicsEngineOpenGL/include/DeviceContextGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/DeviceContextGLImpl.h @@ -51,7 +51,7 @@ public: DeviceContextGLImpl( IReferenceCounters *pRefCounters, class RenderDeviceGLImpl *pDeviceGL, bool bIsDeferred ); /// Queries the specific interface, see IObject::QueryInterface() for details. - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface )override final; virtual void SetPipelineState(IPipelineState *pPipelineState)override final; diff --git a/Graphics/GraphicsEngineOpenGL/include/RenderDeviceGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/RenderDeviceGLImpl.h index 03c8f998..7502c69a 100644 --- a/Graphics/GraphicsEngineOpenGL/include/RenderDeviceGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/RenderDeviceGLImpl.h @@ -56,7 +56,7 @@ public: RenderDeviceGLImpl( IReferenceCounters *pRefCounters, IMemoryAllocator &RawMemAllocator, const EngineGLCreateInfo &InitAttribs ); ~RenderDeviceGLImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface )override final; void CreateBuffer(const BufferDesc& BuffDesc, const BufferData* pBuffData, IBuffer **ppBufferLayout, bool bIsDeviceInternal); virtual void CreateBuffer(const BufferDesc& BuffDesc, const BufferData* BuffData, IBuffer **ppBufferLayout)override final; diff --git a/Graphics/GraphicsEngineOpenGL/include/SamplerGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/SamplerGLImpl.h index 43d85b64..82ec8082 100644 --- a/Graphics/GraphicsEngineOpenGL/include/SamplerGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/SamplerGLImpl.h @@ -43,7 +43,7 @@ public: SamplerGLImpl( IReferenceCounters *pRefCounters, RenderDeviceGLImpl *pDeviceGL, const SamplerDesc& SamplerDesc, bool bIsDeviceInternal = false ); ~SamplerGLImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ); + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface )override final; const GLObjectWrappers::GLSamplerObj& GetHandle(){ return m_GlSampler; } diff --git a/Graphics/GraphicsEngineOpenGL/include/SwapChainGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/SwapChainGLImpl.h index d5d427f1..18e43a4b 100644 --- a/Graphics/GraphicsEngineOpenGL/include/SwapChainGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/SwapChainGLImpl.h @@ -44,7 +44,7 @@ public: class DeviceContextGLImpl* pImmediateContextGL); ~SwapChainGLImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface )override final; virtual void Present(Uint32 SyncInterval)override final; diff --git a/Graphics/GraphicsEngineOpenGL/include/TextureViewGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/TextureViewGLImpl.h index 06c71841..cae8a8d8 100644 --- a/Graphics/GraphicsEngineOpenGL/include/TextureViewGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/TextureViewGLImpl.h @@ -48,7 +48,7 @@ public: bool bIsDefaultView ); ~TextureViewGLImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface )override final; const GLObjectWrappers::GLTextureObj& GetHandle(); GLenum GetBindTarget(); -- cgit v1.2.3 From 0220c1820c60d08c71dcfa3db1a7e9ddc93eddc6 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Tue, 5 Mar 2019 08:04:52 -0800 Subject: Reworked GLProgramResources & GLProgram --- Graphics/GraphicsEngineOpenGL/include/GLProgram.h | 22 +---- .../include/GLProgramResources.h | 100 ++++++++++++--------- .../include/PipelineStateGLImpl.h | 8 +- .../GraphicsEngineOpenGL/include/ShaderGLImpl.h | 60 +------------ Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp | 63 ++----------- .../src/GLProgramResources.cpp | 87 +++++++----------- .../src/PipelineStateGLImpl.cpp | 21 +++++ Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp | 71 ++++----------- 8 files changed, 152 insertions(+), 280 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineOpenGL/include/GLProgram.h b/Graphics/GraphicsEngineOpenGL/include/GLProgram.h index 96729fed..617cf5f9 100644 --- a/Graphics/GraphicsEngineOpenGL/include/GLProgram.h +++ b/Graphics/GraphicsEngineOpenGL/include/GLProgram.h @@ -37,30 +37,16 @@ namespace Diligent GLProgram& operator = (const GLProgram&) = delete; GLProgram& operator = ( GLProgram&&) = delete; - void InitResources(RenderDeviceGLImpl* pDeviceGLImpl, - SHADER_RESOURCE_VARIABLE_TYPE DefaultVariableType, - const ShaderResourceVariableDesc* VariableDesc, - Uint32 NumVars, - const StaticSamplerDesc* StaticSamplers, - Uint32 NumStaticSamplers, - IObject& Owner); + void InitResources(RenderDeviceGLImpl* pDeviceGLImpl, + SHADER_TYPE ShaderStage, + IObject& Owner); void BindConstantResources(IResourceMapping* pResourceMapping, Uint32 Flags); - const GLProgramResources& GetAllResources() const{return m_AllResources;} - GLProgramResources& GetConstantResources() {return m_ConstantResources;} - const GLProgramResources& GetConstantResources()const{return m_ConstantResources;} - - -#ifdef VERIFY_RESOURCE_BINDINGS - template - void dbgVerifyBindingCompletenessHelper(TResArrayType& ResArr, GLProgramResources* pDynamicResources); - void dbgVerifyBindingCompleteness(GLProgramResources* pDynamicResources, class PipelineStateGLImpl* pPSO); -#endif + const GLProgramResources& GetResources() const { return m_AllResources; } private: GLProgramResources m_AllResources; - GLProgramResources m_ConstantResources; // When adding new member DO NOT FORGET TO UPDATE GLProgram( GLProgram&& Program )!!! }; } diff --git a/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h b/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h index 85651833..d3d25eb3 100644 --- a/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h +++ b/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h @@ -45,27 +45,23 @@ namespace Diligent GLProgramResources& operator = (const GLProgramResources&) = delete; GLProgramResources& operator = ( GLProgramResources&&) = delete; - void LoadUniforms(class RenderDeviceGLImpl* pDeviceGLImpl, - GLuint GLProgram, - const SHADER_RESOURCE_VARIABLE_TYPE DefaultVariableType, - const ShaderResourceVariableDesc* VariableDesc, - Uint32 NumVars, - const StaticSamplerDesc* StaticSamplers, - Uint32 NumStaticSamplers); - - void Clone(const GLProgramResources& SrcLayout, - SHADER_RESOURCE_VARIABLE_TYPE* VarTypes, - Uint32 NumVarTypes, - IObject& Owner); + void LoadUniforms(class RenderDeviceGLImpl* pDeviceGLImpl, + SHADER_TYPE ShaderStage, + GLuint GLProgram, + const PipelineResourceLayoutDesc* pResourceLayout, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes); struct GLProgramVariableBase { - GLProgramVariableBase(String _Name, - size_t _ArraySize, - SHADER_RESOURCE_VARIABLE_TYPE _VarType) : - Name ( std::move(_Name) ), - pResources(_ArraySize), - VarType (_VarType) + GLProgramVariableBase(String _Name, + size_t _ArraySize, + SHADER_RESOURCE_VARIABLE_TYPE _VarType, + SHADER_RESOURCE_TYPE _ResourceType) : + Name ( std::move(_Name) ), + pResources (_ArraySize), + VarType (_VarType), + ResourceType(_ResourceType) { VERIFY_EXPR(_ArraySize >= 1); } @@ -81,18 +77,29 @@ namespace Diligent return ComputeHash(static_cast(VarType), pResources.size()); } + ShaderResourceDesc GetResourceDesc()const + { + ShaderResourceDesc ResourceDesc; + ResourceDesc.Name = Name.c_str(); + ResourceDesc.ArraySize = static_cast(pResources.size()); + ResourceDesc.Type = ResourceType; + return ResourceDesc; + } + String Name; std::vector< RefCntAutoPtr > pResources; - const SHADER_RESOURCE_VARIABLE_TYPE VarType; + const SHADER_RESOURCE_VARIABLE_TYPE VarType; + const SHADER_RESOURCE_TYPE ResourceType; }; struct UniformBufferInfo : GLProgramVariableBase { - UniformBufferInfo(String _Name, - size_t _ArraySize, + UniformBufferInfo(String _Name, + size_t _ArraySize, SHADER_RESOURCE_VARIABLE_TYPE _VarType, - GLint _Index) : - GLProgramVariableBase(std::move(_Name), _ArraySize, _VarType), + SHADER_RESOURCE_TYPE _ResourceType, + GLint _Index) : + GLProgramVariableBase(std::move(_Name), _ArraySize, _VarType, _ResourceType), Index(_Index) {} @@ -113,13 +120,14 @@ namespace Diligent struct SamplerInfo : GLProgramVariableBase { - SamplerInfo(String _Name, - size_t _ArraySize, + SamplerInfo(String _Name, + size_t _ArraySize, SHADER_RESOURCE_VARIABLE_TYPE _VarType, - GLint _Location, - GLenum _Type, - class SamplerGLImpl* _pStaticSampler) : - GLProgramVariableBase(std::move(_Name), _ArraySize, _VarType), + SHADER_RESOURCE_TYPE _ResourceType, + GLint _Location, + GLenum _Type, + class SamplerGLImpl* _pStaticSampler) : + GLProgramVariableBase(std::move(_Name), _ArraySize, _VarType, _ResourceType), Location (_Location), Type (_Type), pStaticSampler(_pStaticSampler) @@ -145,12 +153,13 @@ namespace Diligent struct ImageInfo : GLProgramVariableBase { - ImageInfo(String _Name, - size_t _ArraySize, + ImageInfo(String _Name, + size_t _ArraySize, SHADER_RESOURCE_VARIABLE_TYPE _VarType, - GLint _BindingPoint, - GLenum _Type) : - GLProgramVariableBase(std::move(_Name), _ArraySize, _VarType), + SHADER_RESOURCE_TYPE _ResourceType, + GLint _BindingPoint, + GLenum _Type) : + GLProgramVariableBase(std::move(_Name), _ArraySize, _VarType, _ResourceType), BindingPoint(_BindingPoint), Type (_Type) {} @@ -174,11 +183,12 @@ namespace Diligent struct StorageBlockInfo : GLProgramVariableBase { - StorageBlockInfo(String _Name, - size_t _ArraySize, + StorageBlockInfo(String _Name, + size_t _ArraySize, SHADER_RESOURCE_VARIABLE_TYPE _VarType, - GLint _Binding) : - GLProgramVariableBase(std::move(_Name), _ArraySize, _VarType), + SHADER_RESOURCE_TYPE _ResourceType, + GLint _Binding) : + GLProgramVariableBase(std::move(_Name), _ArraySize, _VarType, _ResourceType), Binding(_Binding) {} @@ -237,6 +247,10 @@ namespace Diligent return VariableIndex; } + ShaderResourceDesc GetResourceDesc() const + { + return ProgramVar.GetResourceDesc(); + } private: GLProgramVariableBase& ProgramVar; const Uint32 VariableIndex; @@ -248,8 +262,12 @@ namespace Diligent void dbgVerifyResourceBindings(); #endif - IShaderResourceVariable* GetShaderVariable(const Char* Name); - IShaderResourceVariable* GetShaderVariable(Uint32 Index) + CGLShaderVariable* GetShaderVariable(const Char* Name); + CGLShaderVariable* GetShaderVariable(Uint32 Index) + { + return Index < m_VariablesByIndex.size() ? m_VariablesByIndex[Index] : nullptr; + } + const CGLShaderVariable* GetShaderVariable(Uint32 Index)const { return Index < m_VariablesByIndex.size() ? m_VariablesByIndex[Index] : nullptr; } @@ -264,9 +282,9 @@ namespace Diligent bool IsCompatibleWith(const GLProgramResources& Res)const; size_t GetHash()const; - private: void InitVariables(IObject &Owner); + private: std::vector m_UniformBlocks; std::vector m_Samplers; std::vector m_Images; diff --git a/Graphics/GraphicsEngineOpenGL/include/PipelineStateGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/PipelineStateGLImpl.h index dbf2b07b..fd42adf2 100644 --- a/Graphics/GraphicsEngineOpenGL/include/PipelineStateGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/PipelineStateGLImpl.h @@ -49,10 +49,16 @@ public: ~PipelineStateGLImpl(); /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override; virtual void BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags)override final; + virtual Uint32 GetStaticVariableCount(SHADER_TYPE ShaderType) const override final; + + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) override final; + + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) override final; + virtual void CreateShaderResourceBinding( IShaderResourceBinding** ppShaderResourceBinding, bool InitStaticResources )override final; virtual bool IsCompatibleWith(const IPipelineState* pPSO)const override final; diff --git a/Graphics/GraphicsEngineOpenGL/include/ShaderGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/ShaderGLImpl.h index b8d607ea..d579ef46 100644 --- a/Graphics/GraphicsEngineOpenGL/include/ShaderGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/ShaderGLImpl.h @@ -73,67 +73,14 @@ public: ShaderGLImpl( IReferenceCounters *pRefCounters, RenderDeviceGLImpl *pDeviceGL, const ShaderCreateInfo &ShaderCreateInfo, bool bIsDeviceInternal = false ); ~ShaderGLImpl(); - virtual void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags )override final; + virtual Uint32 GetResourceCount()const override final; + virtual ShaderResourceDesc GetResource(Uint32 Index)const override final; virtual void QueryInterface( const INTERFACE_ID &IID, IObject **ppInterface )override final; - // If separate shaders are not available, the method can optionally create - // a placeholder for static resource variable - IShaderResourceVariable* GetShaderVariable(const Char* Name, bool CreatePlaceholder); - virtual IShaderResourceVariable* GetShaderVariable(const Char* Name)override final; - - virtual Uint32 GetVariableCount() const override final; - - virtual IShaderResourceVariable* GetShaderVariable(Uint32 Index) override final; GLProgram& GetGlProgram(){return m_GlProgObj;} - // This class is used to keep references to static resources when separate shaders are not available - class StaticVarPlaceholder final : public ObjectBase - { - public: - StaticVarPlaceholder(IReferenceCounters* pRefCounters, String Name, Uint32 Index) : - ObjectBase(pRefCounters), - m_Name (std::move(Name)), - m_Index (Index) - {} - - virtual void Set(IDeviceObject* pObject)override final - { - SetArray(&pObject, 0, 1); - } - virtual void SetArray(IDeviceObject* const* ppObjects, Uint32 FirstElement, Uint32 NumElements)override final - { - if (m_Objects.size() < FirstElement + NumElements) - m_Objects.resize(FirstElement + NumElements); - for (Uint32 i=0; i < NumElements; ++i) - m_Objects[FirstElement + i] = ppObjects[i]; - } - virtual SHADER_RESOURCE_VARIABLE_TYPE GetType()const override final - { - return SHADER_RESOURCE_VARIABLE_TYPE_STATIC; - } - virtual Uint32 GetArraySize()const override final - { - return static_cast(m_Objects.size()); - } - virtual const Char* GetName()const override final - { - return m_Name.c_str(); - } - virtual Uint32 GetIndex()const override final - { - return m_Index; - } - IDeviceObject* Get(Uint32 ArrayIndex) - { - return ArrayIndex < m_Objects.size() ? m_Objects[ArrayIndex].RawPtr() : nullptr; - } - private: - const String m_Name; - const Uint32 m_Index; - std::vector> m_Objects; - }; private: friend class PipelineStateGLImpl; @@ -141,9 +88,6 @@ private: GLProgram m_GlProgObj; // Used if program pipeline supported GLObjectWrappers::GLShaderObj m_GLShaderObj; // Used if program pipelines are not supported - - std::vector> m_StaticResources; // Used only if program pipelines are not supported to - // hold static resources. }; } diff --git a/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp b/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp index 07c2117c..cd3e01fa 100644 --- a/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp @@ -33,67 +33,18 @@ namespace Diligent {} GLProgram::GLProgram( GLProgram&& Program ): - GLObjectWrappers::GLProgramObj(std::move(Program ) ), - m_AllResources (std::move(Program.m_AllResources) ), - m_ConstantResources (std::move(Program.m_ConstantResources)) + GLObjectWrappers::GLProgramObj(std::move(Program ) ), + m_AllResources (std::move(Program.m_AllResources)) {} - void GLProgram::InitResources(RenderDeviceGLImpl* pDeviceGLImpl, - const SHADER_RESOURCE_VARIABLE_TYPE DefaultVariableType, - const ShaderResourceVariableDesc *VariableDesc, - Uint32 NumVars, - const StaticSamplerDesc *StaticSamplers, - Uint32 NumStaticSamplers, - IObject &Owner) + void GLProgram::InitResources(RenderDeviceGLImpl* pDeviceGLImpl, + SHADER_TYPE ShaderStage, + IObject& Owner) { GLuint GLProgram = static_cast(*this); - m_AllResources.LoadUniforms(pDeviceGLImpl, GLProgram, DefaultVariableType, VariableDesc, NumVars, StaticSamplers, NumStaticSamplers); - - SHADER_RESOURCE_VARIABLE_TYPE VarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_STATIC}; - m_ConstantResources.Clone(m_AllResources, VarTypes, _countof(VarTypes), Owner); - } - - void GLProgram::BindConstantResources( IResourceMapping *pResourceMapping, Uint32 Flags ) - { - if( !pResourceMapping ) - return; - - m_ConstantResources.BindResources(pResourceMapping, Flags); + m_AllResources.LoadUniforms(pDeviceGLImpl, ShaderStage, GLProgram, nullptr, nullptr, 0); + m_AllResources.InitVariables(Owner); } -#ifdef VERIFY_RESOURCE_BINDINGS - template - void GLProgram::dbgVerifyBindingCompletenessHelper(TResArrayType &ResArr, GLProgramResources *pDynamicResources) - { - const auto &ConstVariables = m_ConstantResources.GetVariables(); - for( auto res = ResArr.begin(); res != ResArr.end(); ++res ) - { - auto ConstRes = ConstVariables.find(HashMapStringKey(res->Name.c_str())); - if (ConstRes == ConstVariables.end()) - { - bool bVarFound = false; - if( pDynamicResources) - { - const auto &DynamicVariables = pDynamicResources->GetVariables(); - auto DynRes = DynamicVariables.find(HashMapStringKey(res->Name.c_str())); - bVarFound = (DynRes != DynamicVariables.end()); - } - - if(!bVarFound) - { - LOG_ERROR_MESSAGE( "Incomplete binding: non-static shader variable \"", res->Name, "\" not found" ); - } - } - } - } - - void GLProgram::dbgVerifyBindingCompleteness(GLProgramResources *pDynamicResources, PipelineStateGLImpl *pPSO) - { - dbgVerifyBindingCompletenessHelper(m_AllResources.GetUniformBlocks(), pDynamicResources); - dbgVerifyBindingCompletenessHelper(m_AllResources.GetSamplers(), pDynamicResources); - dbgVerifyBindingCompletenessHelper(m_AllResources.GetImages(), pDynamicResources); - dbgVerifyBindingCompletenessHelper(m_AllResources.GetStorageBlocks(), pDynamicResources); - } -#endif } diff --git a/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp b/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp index 34529cbf..a9d8538f 100644 --- a/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp @@ -24,6 +24,7 @@ #include "pch.h" #include "GLProgramResources.h" #include "RenderDeviceGLImpl.h" +#include "ShaderResourceBindingBase.h" namespace Diligent { @@ -44,16 +45,17 @@ namespace Diligent *OpenBacketPtr = 0; } - void GLProgramResources::LoadUniforms(RenderDeviceGLImpl *pDeviceGLImpl, - GLuint GLProgram, - const SHADER_RESOURCE_VARIABLE_TYPE DefaultVariableType, - const ShaderResourceVariableDesc *VariableDesc, - Uint32 NumVars, - const StaticSamplerDesc *StaticSamplers, - Uint32 NumStaticSamplers) + void GLProgramResources::LoadUniforms(RenderDeviceGLImpl* pDeviceGLImpl, + SHADER_TYPE ShaderStage, + GLuint GLProgram, + const PipelineResourceLayoutDesc* pResourceLayout, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes) { VERIFY(GLProgram != 0, "Null GL program"); + const Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); + GLint numActiveUniforms = 0; glGetProgramiv( GLProgram, GL_ACTIVE_UNIFORMS, &numActiveUniforms ); CHECK_GL_ERROR_AND_THROW( "Unable to get number of active uniforms\n" ); @@ -176,18 +178,23 @@ namespace Diligent // The latter is only available in GL 4.4 and GLES 3.1 RemoveArrayBrackets(Name.data()); - auto VarType = GetShaderVariableType(Name.data(), DefaultVariableType, VariableDesc, NumVars); + SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; RefCntAutoPtr pStaticSampler; - for (Uint32 s = 0; s < NumStaticSamplers; ++s) + if (pResourceLayout != nullptr) { - if (strcmp(Name.data(), StaticSamplers[s].SamplerOrTextureName) == 0) + VarType = GetShaderVariableType(ShaderStage, Name.data(), *pResourceLayout); + for (Uint32 s = 0; s < pResourceLayout->NumStaticSamplers; ++s) { - pDeviceGLImpl->CreateSampler(StaticSamplers[s].Desc, reinterpret_cast(static_cast(&pStaticSampler)) ); - break; + const auto& StSam = pResourceLayout->StaticSamplers[s]; + if (strcmp(Name.data(), StSam.SamplerOrTextureName) == 0) + { + pDeviceGLImpl->CreateSampler(StSam.Desc, reinterpret_cast(static_cast(&pStaticSampler)) ); + break; + } } } - m_Samplers.emplace_back( Name.data(), size, VarType, UniformLocation, dataType, pStaticSampler ); + m_Samplers.emplace_back( Name.data(), size, VarType, SHADER_RESOURCE_TYPE_TEXTURE_SRV, UniformLocation, dataType, pStaticSampler ); break; } @@ -235,8 +242,10 @@ namespace Diligent VERIFY( BindingPoint >= 0, "Incorrect binding point" ); RemoveArrayBrackets(Name.data()); - auto VarType = GetShaderVariableType(Name.data(), DefaultVariableType, VariableDesc, NumVars); - m_Images.emplace_back( Name.data(), size, VarType, BindingPoint, dataType ); + SHADER_RESOURCE_VARIABLE_TYPE VarType = (pResourceLayout != nullptr) ? + GetShaderVariableType(ShaderStage, Name.data(), *pResourceLayout) : + SHADER_RESOURCE_VARIABLE_TYPE_STATIC; + m_Images.emplace_back( Name.data(), size, VarType, SHADER_RESOURCE_TYPE_TEXTURE_UAV, BindingPoint, dataType ); break; } #endif @@ -293,8 +302,10 @@ namespace Diligent } - auto VarType = GetShaderVariableType(Name.data(), DefaultVariableType, VariableDesc, NumVars); - m_UniformBlocks.emplace_back( Name.data(), ArraySize, VarType, UniformBlockIndex ); + SHADER_RESOURCE_VARIABLE_TYPE VarType = (pResourceLayout != nullptr) ? + GetShaderVariableType(ShaderStage, Name.data(), *pResourceLayout) : + SHADER_RESOURCE_VARIABLE_TYPE_STATIC; + m_UniformBlocks.emplace_back( Name.data(), ArraySize, VarType, SHADER_RESOURCE_TYPE_CONSTANT_BUFFER, UniformBlockIndex ); } #if GL_ARB_shader_storage_buffer_object @@ -341,8 +352,10 @@ namespace Diligent } } - auto VarType = GetShaderVariableType(Name.data(), DefaultVariableType, VariableDesc, NumVars); - m_StorageBlocks.emplace_back( Name.data(), ArraySize, VarType, Binding ); + SHADER_RESOURCE_VARIABLE_TYPE VarType = (pResourceLayout != nullptr) ? + GetShaderVariableType(ShaderStage, Name.data(), *pResourceLayout) : + SHADER_RESOURCE_VARIABLE_TYPE_STATIC; + m_StorageBlocks.emplace_back( Name.data(), ArraySize, VarType, SHADER_RESOURCE_TYPE_BUFFER_UAV, Binding ); } #endif @@ -357,39 +370,7 @@ namespace Diligent return false; } - void GLProgramResources::Clone(const GLProgramResources& SrcLayout, - SHADER_RESOURCE_VARIABLE_TYPE* VarTypes, - Uint32 NumVarTypes, - IObject& Owner) - { - for (auto& ub : SrcLayout.m_UniformBlocks) - { - if(CheckType(ub.VarType, VarTypes, NumVarTypes)) - m_UniformBlocks.emplace_back( ub.Name, ub.pResources.size(), ub.VarType, ub.Index ); - } - - for (auto& sam : SrcLayout.m_Samplers) - { - if(CheckType(sam.VarType, VarTypes, NumVarTypes)) - m_Samplers.emplace_back( sam.Name, sam.pResources.size(), sam.VarType, sam.Location, sam.Type, const_cast(sam.pStaticSampler.RawPtr()) ); - } - - for (auto& img : SrcLayout.m_Images) - { - if(CheckType(img.VarType, VarTypes, NumVarTypes)) - m_Images.emplace_back( img.Name, img.pResources.size(), img.VarType, img.BindingPoint, img.Type ); - } - - for (auto& sb : SrcLayout.m_StorageBlocks) - { - if(CheckType(sb.VarType, VarTypes, NumVarTypes)) - m_StorageBlocks.emplace_back( sb.Name, sb.pResources.size(), sb.VarType, sb.Binding ); - } - - InitVariables(Owner); - } - - void GLProgramResources::InitVariables(IObject &Owner) + void GLProgramResources::InitVariables(IObject& Owner) { // After all program resources are loaded, we can populate shader variable hash map. // The map contains raw pointers, but none of the arrays will ever change. @@ -414,7 +395,7 @@ namespace Diligent #undef STORE_SHADER_VARIABLES } - IShaderResourceVariable* GLProgramResources::GetShaderVariable( const Char* Name ) + GLProgramResources::CGLShaderVariable* GLProgramResources::GetShaderVariable( const Char* Name ) { // Name will be implicitly converted to HashMapStringKey without making a copy auto it = m_VariableHash.find( Name ); diff --git a/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp index 9071b815..d26fa887 100644 --- a/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp @@ -247,4 +247,25 @@ GLObjectWrappers::GLPipelineObj& PipelineStateGLImpl::GetGLProgramPipeline(GLCon } } + +void PipelineStateGLImpl::BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags) +{ + +} + +Uint32 PipelineStateGLImpl::GetStaticVariableCount(SHADER_TYPE ShaderType) const +{ + +} + +IShaderResourceVariable* PipelineStateGLImpl::GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) +{ + +} + +IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) +{ + +} + } diff --git a/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp index 7e6340dc..b155a373 100644 --- a/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp @@ -33,10 +33,10 @@ using namespace Diligent; namespace Diligent { -ShaderGLImpl::ShaderGLImpl(IReferenceCounters* pRefCounters, - RenderDeviceGLImpl* pDeviceGL, - const ShaderCreateInfo& CreationAttribs, - bool bIsDeviceInternal) : +ShaderGLImpl::ShaderGLImpl(IReferenceCounters* pRefCounters, + RenderDeviceGLImpl* pDeviceGL, + const ShaderCreateInfo& CreationAttribs, + bool bIsDeviceInternal) : TShaderBase( pRefCounters, pDeviceGL, CreationAttribs.Desc, bIsDeviceInternal ), m_GlProgObj(false), m_GLShaderObj( false, GLObjectWrappers::GLShaderObjCreateReleaseHelper( GetGLShaderType( m_Desc.ShaderType ) ) ) @@ -160,7 +160,7 @@ ShaderGLImpl::ShaderGLImpl(IReferenceCounters* pRefCounters, // boolean status bit DELETE_STATUS is set to true ShaderObj.Release(); - m_GlProgObj.InitResources(pDeviceGL, m_Desc.DefaultVariableType, m_Desc.VariableDesc, m_Desc.NumVariables, m_Desc.StaticSamplers, m_Desc.NumStaticSamplers, *this); + m_GlProgObj.InitResources(pDeviceGL, m_Desc.ShaderType, *this); } else { @@ -174,68 +174,33 @@ ShaderGLImpl::~ShaderGLImpl() IMPLEMENT_QUERY_INTERFACE( ShaderGLImpl, IID_ShaderGL, TShaderBase ) -void ShaderGLImpl::BindResources( IResourceMapping* pResourceMapping, Uint32 Flags ) +Uint32 ShaderGLImpl::GetResourceCount()const { - if( static_cast(m_GlProgObj) ) + Uint32 ResCount = 0; + if (m_GlProgObj) { - m_GlProgObj.BindConstantResources( pResourceMapping, Flags ); + return m_GlProgObj.GetResources().GetVariableCount(); } else { - LOG_WARNING_MESSAGE_ONCE( "IShader::BindResources() effectively does nothing when separable programs are not supported by the device." ); + LOG_WARNING_MESSAGE("Shader resource queries are not available when separate shader objects are unsupported"); } + return ResCount; } -IShaderResourceVariable* ShaderGLImpl::GetShaderVariable(const Char* Name) +ShaderResourceDesc ShaderGLImpl::GetResource(Uint32 Index)const { - return GetShaderVariable(Name, true); -} - -IShaderResourceVariable* ShaderGLImpl::GetShaderVariable(const Char* Name, bool CreatePlaceholder) -{ - if( m_GlProgObj ) - return m_GlProgObj.GetConstantResources().GetShaderVariable(Name); - else + ShaderResourceDesc ResourceDesc; + if (m_GlProgObj) { - for (auto& Res : m_StaticResources) - { - if( strcmp(Res->GetName(), Name) == 0) - return Res; - } - - if (CreatePlaceholder) - { - auto* pNewVar = MakeNewRCObj()(Name, static_cast(m_StaticResources.size())); - m_StaticResources.emplace_back(pNewVar); - return pNewVar; - } - else - { - return nullptr; - } - } -} - -Uint32 ShaderGLImpl::GetVariableCount() const -{ - if( m_GlProgObj ) - return m_GlProgObj.GetConstantResources().GetVariableCount(); - else - { - LOG_WARNING_MESSAGE("When separate shader objects are unavailable, GetVariableCount() returns the number of resources being set so far " - "rather than the total number of static shader resources."); - return static_cast(m_StaticResources.size()); + DEV_CHECK_ERR(Index < GetResourceCount(), "Index is out of range"); + ResourceDesc = m_GlProgObj.GetResources().GetShaderVariable(Index)->GetResourceDesc(); } -} - -IShaderResourceVariable* ShaderGLImpl::GetShaderVariable(Uint32 Index) -{ - if( m_GlProgObj ) - return m_GlProgObj.GetConstantResources().GetShaderVariable(Index); else { - return Index < m_StaticResources.size() ? m_StaticResources[Index].RawPtr() : nullptr; + LOG_WARNING_MESSAGE("Shader resource queries are not available when separate shader objects are unsupported"); } + return ResourceDesc; } } -- cgit v1.2.3 From 36c9ca813faf49dbb73f6774f298ebdd55d88459 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Tue, 5 Mar 2019 19:31:09 -0800 Subject: Final changes to make GL backend compile --- Graphics/GraphicsEngineOpenGL/include/GLProgram.h | 9 +- .../include/GLProgramResources.h | 15 +- .../include/PipelineStateGLImpl.h | 10 +- .../src/DeviceContextGLImpl.cpp | 4 +- Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp | 13 +- .../src/GLProgramResources.cpp | 77 +++++++-- .../src/PipelineStateGLImpl.cpp | 174 +++++++++------------ Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp | 2 +- .../src/ShaderResourceBindingGLImpl.cpp | 79 +--------- .../GraphicsEngineOpenGL/src/TexRegionRender.cpp | 16 +- 10 files changed, 190 insertions(+), 209 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineOpenGL/include/GLProgram.h b/Graphics/GraphicsEngineOpenGL/include/GLProgram.h index 617cf5f9..dbc0c6c8 100644 --- a/Graphics/GraphicsEngineOpenGL/include/GLProgram.h +++ b/Graphics/GraphicsEngineOpenGL/include/GLProgram.h @@ -37,9 +37,12 @@ namespace Diligent GLProgram& operator = (const GLProgram&) = delete; GLProgram& operator = ( GLProgram&&) = delete; - void InitResources(RenderDeviceGLImpl* pDeviceGLImpl, - SHADER_TYPE ShaderStage, - IObject& Owner); + void InitResources(RenderDeviceGLImpl* pDeviceGLImpl, + SHADER_TYPE ShaderStage, + IObject& Owner, + const PipelineResourceLayoutDesc* pResourceLayout, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes); void BindConstantResources(IResourceMapping* pResourceMapping, Uint32 Flags); diff --git a/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h b/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h index d3d25eb3..d75bb2a5 100644 --- a/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h +++ b/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h @@ -46,12 +46,20 @@ namespace Diligent GLProgramResources& operator = ( GLProgramResources&&) = delete; void LoadUniforms(class RenderDeviceGLImpl* pDeviceGLImpl, - SHADER_TYPE ShaderStage, + SHADER_TYPE ShaderStages, GLuint GLProgram, const PipelineResourceLayoutDesc* pResourceLayout, const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes); + + void Clone(class RenderDeviceGLImpl* pDeviceGLImpl, + IObject& Owner, + const GLProgramResources& SrcResources, + const PipelineResourceLayoutDesc& ResourceLayout, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes); + struct GLProgramVariableBase { GLProgramVariableBase(String _Name, @@ -284,7 +292,12 @@ namespace Diligent void InitVariables(IObject &Owner); + SHADER_TYPE GetShaderStages() const {return m_ShaderStages;} + private: + // There could be more than one stage is using non-separable programs + SHADER_TYPE m_ShaderStages = SHADER_TYPE_UNKNOWN; + std::vector m_UniformBlocks; std::vector m_Samplers; std::vector m_Images; diff --git a/Graphics/GraphicsEngineOpenGL/include/PipelineStateGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/PipelineStateGLImpl.h index fd42adf2..0c98d838 100644 --- a/Graphics/GraphicsEngineOpenGL/include/PipelineStateGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/PipelineStateGLImpl.h @@ -23,6 +23,7 @@ #pragma once +#include #include "PipelineStateGL.h" #include "PipelineStateBase.h" #include "RenderDevice.h" @@ -66,12 +67,19 @@ public: GLProgram& GetGLProgram(){return m_GLProgram;} GLObjectWrappers::GLPipelineObj& GetGLProgramPipeline(GLContext::NativeGLContextType Context); + GLProgramResources& GetStaticResources(Uint32 s) + { + return m_StaticResources[s]; + } + private: void LinkGLProgram(bool bIsProgramPipelineSupported); GLProgram m_GLProgram; ThreadingTools::LockFlag m_ProgPipelineLockFlag; - std::unordered_map m_GLProgPipelines; + std::vector< std::pair > m_GLProgPipelines; + std::vector m_StaticResources; + Int8 m_ResourceLayoutIndex[6] = {-1, -1, -1, -1, -1, -1}; }; } diff --git a/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp index d7ff2b32..cddce1ea 100644 --- a/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp @@ -385,13 +385,13 @@ namespace Diligent GLProgramResources* pDynamicResources = pShaderResBindingGL ? &pShaderResBindingGL->GetProgramResources(pShaderGL->GetDesc().ShaderType, m_pPipelineState) : nullptr; #ifdef VERIFY_RESOURCE_BINDINGS - GLProgramObj.dbgVerifyBindingCompleteness(pDynamicResources, m_pPipelineState); + //GLProgramObj.dbgVerifyBindingCompleteness(pDynamicResources, m_pPipelineState); #endif // When program pipelines are not supported, all resources are dynamic resources for (int BindDynamicResources = (ProgramPipelineSupported ? 0 : 1); BindDynamicResources < (pShaderResBindingGL ? 2 : 1); ++BindDynamicResources) { - GLProgramResources& ProgResources = BindDynamicResources ? *pDynamicResources : GLProgramObj.GetConstantResources(); + GLProgramResources& ProgResources = BindDynamicResources ? *pDynamicResources : m_pPipelineState->GetStaticResources(ProgNum); #ifdef VERIFY_RESOURCE_BINDINGS ProgResources.dbgVerifyResourceBindings(); diff --git a/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp b/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp index cd3e01fa..f4650151 100644 --- a/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp @@ -37,14 +37,15 @@ namespace Diligent m_AllResources (std::move(Program.m_AllResources)) {} - void GLProgram::InitResources(RenderDeviceGLImpl* pDeviceGLImpl, - SHADER_TYPE ShaderStage, - IObject& Owner) + void GLProgram::InitResources(RenderDeviceGLImpl* pDeviceGLImpl, + SHADER_TYPE ShaderStage, + IObject& Owner, + const PipelineResourceLayoutDesc* pResourceLayout, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes) { GLuint GLProgram = static_cast(*this); - m_AllResources.LoadUniforms(pDeviceGLImpl, ShaderStage, GLProgram, nullptr, nullptr, 0); + m_AllResources.LoadUniforms(pDeviceGLImpl, ShaderStage, GLProgram, pResourceLayout, AllowedVarTypes, NumAllowedTypes); m_AllResources.InitVariables(Owner); } - - } diff --git a/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp b/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp index a9d8538f..42dbf43f 100644 --- a/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp @@ -46,7 +46,7 @@ namespace Diligent } void GLProgramResources::LoadUniforms(RenderDeviceGLImpl* pDeviceGLImpl, - SHADER_TYPE ShaderStage, + SHADER_TYPE ShaderStages, GLuint GLProgram, const PipelineResourceLayoutDesc* pResourceLayout, const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, @@ -54,6 +54,7 @@ namespace Diligent { VERIFY(GLProgram != 0, "Null GL program"); + m_ShaderStages = ShaderStages; const Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); GLint numActiveUniforms = 0; @@ -183,7 +184,7 @@ namespace Diligent RefCntAutoPtr pStaticSampler; if (pResourceLayout != nullptr) { - VarType = GetShaderVariableType(ShaderStage, Name.data(), *pResourceLayout); + VarType = GetShaderVariableType(ShaderStages, Name.data(), *pResourceLayout); for (Uint32 s = 0; s < pResourceLayout->NumStaticSamplers; ++s) { const auto& StSam = pResourceLayout->StaticSamplers[s]; @@ -243,7 +244,7 @@ namespace Diligent RemoveArrayBrackets(Name.data()); SHADER_RESOURCE_VARIABLE_TYPE VarType = (pResourceLayout != nullptr) ? - GetShaderVariableType(ShaderStage, Name.data(), *pResourceLayout) : + GetShaderVariableType(ShaderStages, Name.data(), *pResourceLayout) : SHADER_RESOURCE_VARIABLE_TYPE_STATIC; m_Images.emplace_back( Name.data(), size, VarType, SHADER_RESOURCE_TYPE_TEXTURE_UAV, BindingPoint, dataType ); break; @@ -301,9 +302,9 @@ namespace Diligent } } - + SHADER_RESOURCE_VARIABLE_TYPE VarType = (pResourceLayout != nullptr) ? - GetShaderVariableType(ShaderStage, Name.data(), *pResourceLayout) : + GetShaderVariableType(ShaderStages, Name.data(), *pResourceLayout) : SHADER_RESOURCE_VARIABLE_TYPE_STATIC; m_UniformBlocks.emplace_back( Name.data(), ArraySize, VarType, SHADER_RESOURCE_TYPE_CONSTANT_BUFFER, UniformBlockIndex ); } @@ -353,21 +354,71 @@ namespace Diligent } SHADER_RESOURCE_VARIABLE_TYPE VarType = (pResourceLayout != nullptr) ? - GetShaderVariableType(ShaderStage, Name.data(), *pResourceLayout) : + GetShaderVariableType(ShaderStages, Name.data(), *pResourceLayout) : SHADER_RESOURCE_VARIABLE_TYPE_STATIC; m_StorageBlocks.emplace_back( Name.data(), ArraySize, VarType, SHADER_RESOURCE_TYPE_BUFFER_UAV, Binding ); } #endif - } - static bool CheckType(SHADER_RESOURCE_VARIABLE_TYPE Type, SHADER_RESOURCE_VARIABLE_TYPE* AllowedTypes, Uint32 NumAllowedTypes) + + void GLProgramResources::Clone(RenderDeviceGLImpl* pDeviceGLImpl, + IObject& Owner, + const GLProgramResources& SrcResources, + const PipelineResourceLayoutDesc& ResourceLayout, + const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, + Uint32 NumAllowedTypes) { - for(Uint32 i=0; i < NumAllowedTypes; ++i) - if(Type == AllowedTypes[i]) - return true; - - return false; + m_ShaderStages = SrcResources.m_ShaderStages; + const Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); + + for (auto& ub : SrcResources.m_UniformBlocks) + { + auto VarType = GetShaderVariableType(m_ShaderStages, ub.Name.data(), ResourceLayout); + if (IsAllowedType(VarType, VarType)) + { + m_UniformBlocks.emplace_back(ub.Name, ub.pResources.size(), ub.VarType, ub.ResourceType, ub.Index); + } + } + + for (auto& sam : SrcResources.m_Samplers) + { + auto VarType = GetShaderVariableType(m_ShaderStages, sam.Name.data(), ResourceLayout); + if (IsAllowedType(VarType, VarType)) + { + RefCntAutoPtr pStaticSampler; + for (Uint32 s = 0; s < ResourceLayout.NumStaticSamplers; ++s) + { + const auto& StSam = ResourceLayout.StaticSamplers[s]; + if (strcmp(sam.Name.data(), StSam.SamplerOrTextureName) == 0) + { + pDeviceGLImpl->CreateSampler(StSam.Desc, &pStaticSampler); + break; + } + } + m_Samplers.emplace_back(sam.Name, sam.pResources.size(), sam.VarType, sam.ResourceType, sam.Location, sam.Type, pStaticSampler.RawPtr()); + } + } + + for (auto& img : SrcResources.m_Images) + { + auto VarType = GetShaderVariableType(m_ShaderStages, img.Name.data(), ResourceLayout); + if (IsAllowedType(VarType, VarType)) + { + m_Images.emplace_back(img.Name, img.pResources.size(), img.VarType, img.ResourceType, img.BindingPoint, img.Type); + } + } + + for (auto& sb : SrcResources.m_StorageBlocks) + { + auto VarType = GetShaderVariableType(m_ShaderStages, sb.Name.data(), ResourceLayout); + if (IsAllowedType(VarType, VarType)) + { + m_StorageBlocks.emplace_back(sb.Name, sb.pResources.size(), sb.VarType, sb.ResourceType, sb.Binding); + } + } + + InitVariables(Owner); } void GLProgramResources::InitVariables(IObject& Owner) diff --git a/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp index d26fa887..25ee1d17 100644 --- a/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp @@ -53,10 +53,18 @@ void PipelineStateGLImpl::LinkGLProgram(bool bIsProgramPipelineSupported) // Program pipelines are not shared between GL contexts, so we cannot create // it now m_ShaderResourceLayoutHash = 0; + m_StaticResources.resize(m_NumShaders); for (Uint32 Shader = 0; Shader < m_NumShaders; ++Shader) { auto* pShaderGL = GetShader(Shader); - HashCombine(m_ShaderResourceLayoutHash, pShaderGL->m_GlProgObj.GetAllResources().GetHash()); + const SHADER_RESOURCE_VARIABLE_TYPE StaticVars[] = {SHADER_RESOURCE_VARIABLE_TYPE_STATIC}; + m_StaticResources[Shader].Clone(GetDevice(), *this, pShaderGL->GetGlProgram().GetResources(), m_Desc.ResourceLayout, StaticVars, _countof(StaticVars)); + + const auto ShaderType = pShaderGL->GetDesc().ShaderType; + const auto ShaderTypeInd = GetShaderTypeIndex(ShaderType); + m_ResourceLayoutIndex[ShaderTypeInd] = static_cast(Shader); + + HashCombine(m_ShaderResourceLayoutHash, pShaderGL->m_GlProgObj.GetResources().GetHash()); } } else @@ -99,81 +107,22 @@ void PipelineStateGLImpl::LinkGLProgram(bool bIsProgramPipelineSupported) CHECK_GL_ERROR("glDetachShader() failed"); } - std::vector MergedVarTypesArray; - std::vector MergedStSamArray; - SHADER_RESOURCE_VARIABLE_TYPE DefaultVarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; + SHADER_TYPE ShaderStages = SHADER_TYPE_UNKNOWN; for (Uint32 Shader = 0; Shader < m_NumShaders; ++Shader) { auto* pCurrShader = GetShader(Shader); const auto& Desc = pCurrShader->GetDesc(); - if (Shader == 0) - { - DefaultVarType = Desc.DefaultVariableType; - } - else - { - if (DefaultVarType != Desc.DefaultVariableType) - { - LOG_ERROR_MESSAGE("When separate shader programs are not available, all shaders linked into a program " - "must use the same default variable type."); - } - } - - for (Uint32 v = 0; v < Desc.NumVariables; ++v) - { - const auto& NewVar = Desc.VariableDesc[v]; - bool VarExists = false; - for (const auto& Var : MergedVarTypesArray) - { - if (strcmp(Var.Name, NewVar.Name) == 0) - { - VarExists = true; - if (Var.Type != NewVar.Type) - { - LOG_ERROR_MESSAGE("The type of variable '", Var.Name, "' is not consistent between shader stages. " - "When separate shader programs are not available, all shaders must use the same " - "type for identically named shader variables."); - } - break; - } - } - - if (!VarExists) - { - MergedVarTypesArray.push_back(NewVar); - } - } - - for (Uint32 s = 0; s < Desc.NumStaticSamplers; ++s) - { - const auto& NewSampler = Desc.StaticSamplers[s]; - bool SamplerExists = false; - for (const auto& Sampler : MergedStSamArray) - { - if (strcmp(Sampler.SamplerOrTextureName, NewSampler.SamplerOrTextureName) == 0) - { - SamplerExists = true; - if ( !(Sampler.Desc == NewSampler.Desc) ) - { - LOG_ERROR_MESSAGE("Static sampler defined for texture '", NewSampler.SamplerOrTextureName, "' is not consistent between shader stages. " - "When separate shader programs are not available, all shaders must use the same " - "static samplers for identically named shader variables."); - } - break; - } - } - - if (!SamplerExists) - { - MergedStSamArray.push_back(NewSampler); - } - } + ShaderStages |= Desc.ShaderType; } auto pDeviceGL = GetDevice(); - m_GLProgram.InitResources(pDeviceGL, DefaultVarType, MergedVarTypesArray.data(), static_cast(MergedVarTypesArray.size()), MergedStSamArray.data(), static_cast(MergedStSamArray.size()), *this); + m_GLProgram.InitResources(pDeviceGL, ShaderStages, *this, &m_Desc.ResourceLayout, nullptr, 0); + + m_StaticResources.resize(1); + const SHADER_RESOURCE_VARIABLE_TYPE StaticVars[] = {SHADER_RESOURCE_VARIABLE_TYPE_STATIC}; + m_StaticResources[0].Clone(GetDevice(), *this, m_GLProgram.GetResources(), m_Desc.ResourceLayout, StaticVars, _countof(StaticVars)); - m_ShaderResourceLayoutHash = m_GLProgram.GetAllResources().GetHash(); + m_ShaderResourceLayoutHash = m_GLProgram.GetResources().GetHash(); } } @@ -185,18 +134,6 @@ PipelineStateGLImpl::~PipelineStateGLImpl() IMPLEMENT_QUERY_INTERFACE( PipelineStateGLImpl, IID_PipelineStateGL, TPipelineStateBase ) -void PipelineStateGLImpl::BindShaderResources(IResourceMapping* pResourceMapping, Uint32 Flags) -{ - if (GetDevice()->GetDeviceCaps().bSeparableProgramSupported) - { - TPipelineStateBase::BindShaderResources(pResourceMapping, Flags); - } - else - { - if (m_GLProgram) - m_GLProgram.BindConstantResources(pResourceMapping, Flags); - } -} void PipelineStateGLImpl::CreateShaderResourceBinding(IShaderResourceBinding** ppShaderResourceBinding, bool InitStaticResources) { @@ -219,53 +156,82 @@ bool PipelineStateGLImpl::IsCompatibleWith(const IPipelineState* pPSO)const if (m_ShaderResourceLayoutHash != pPSOGL->m_ShaderResourceLayoutHash) return false; - return m_GLProgram.GetAllResources().IsCompatibleWith(pPSOGL->m_GLProgram.GetAllResources()); + return m_GLProgram.GetResources().IsCompatibleWith(pPSOGL->m_GLProgram.GetResources()); } GLObjectWrappers::GLPipelineObj& PipelineStateGLImpl::GetGLProgramPipeline(GLContext::NativeGLContextType Context) { ThreadingTools::LockHelper Lock(m_ProgPipelineLockFlag); - auto it = m_GLProgPipelines.find(Context); - if (it != m_GLProgPipelines.end()) - return it->second; - else + for(auto& ctx_pipeline : m_GLProgPipelines) { - // Create new progam pipeline - it = m_GLProgPipelines.emplace(Context, true).first; - GLuint Pipeline = it->second; - for (Uint32 Shader = 0; Shader < m_NumShaders; ++Shader) - { - auto* pCurrShader = GetShader(Shader); - auto GLShaderBit = ShaderTypeToGLShaderBit(pCurrShader->GetDesc().ShaderType); - // If the program has an active code for each stage mentioned in set flags, - // then that code will be used by the pipeline. If program is 0, then the given - // stages are cleared from the pipeline. - glUseProgramStages(Pipeline, GLShaderBit, pCurrShader->m_GlProgObj); - CHECK_GL_ERROR("glUseProgramStages() failed"); - } - return it->second; + if (ctx_pipeline.first == Context) + return ctx_pipeline.second; + } + + // Create new progam pipeline + m_GLProgPipelines.emplace_back(Context, true); + auto& ctx_pipeline = m_GLProgPipelines.back(); + GLuint Pipeline = ctx_pipeline.second; + for (Uint32 Shader = 0; Shader < m_NumShaders; ++Shader) + { + auto* pCurrShader = GetShader(Shader); + auto GLShaderBit = ShaderTypeToGLShaderBit(pCurrShader->GetDesc().ShaderType); + // If the program has an active code for each stage mentioned in set flags, + // then that code will be used by the pipeline. If program is 0, then the given + // stages are cleared from the pipeline. + glUseProgramStages(Pipeline, GLShaderBit, pCurrShader->m_GlProgObj); + CHECK_GL_ERROR("glUseProgramStages() failed"); } + return ctx_pipeline.second; } void PipelineStateGLImpl::BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags) { - + for(auto& StaticRes : m_StaticResources) + { + if ((StaticRes.GetShaderStages() & ShaderFlags)!=0) + StaticRes.BindResources(pResourceMapping, Flags); + } } Uint32 PipelineStateGLImpl::GetStaticVariableCount(SHADER_TYPE ShaderType) const { - + if (m_GLProgram) + { + return m_StaticResources[0].GetVariableCount(); + } + else + { + const auto LayoutInd = m_ResourceLayoutIndex[GetShaderTypeIndex(ShaderType)]; + return LayoutInd >= 0 ? m_StaticResources[LayoutInd].GetVariableCount() : 0; + } } IShaderResourceVariable* PipelineStateGLImpl::GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) { - + if (m_GLProgram) + { + return m_StaticResources[0].GetShaderVariable(Name); + } + else + { + const auto LayoutInd = m_ResourceLayoutIndex[GetShaderTypeIndex(ShaderType)]; + return LayoutInd >= 0 ? m_StaticResources[LayoutInd].GetShaderVariable(Name) : nullptr; + } } -IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) +IShaderResourceVariable* PipelineStateGLImpl::GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) { - + if (m_GLProgram) + { + return m_StaticResources[0].GetShaderVariable(Index); + } + else + { + const auto LayoutInd = m_ResourceLayoutIndex[GetShaderTypeIndex(ShaderType)]; + return LayoutInd >= 0 ? m_StaticResources[LayoutInd].GetShaderVariable(Index) : nullptr; + } } } diff --git a/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp index b155a373..278f79de 100644 --- a/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp @@ -160,7 +160,7 @@ ShaderGLImpl::ShaderGLImpl(IReferenceCounters* pRefCounters, // boolean status bit DELETE_STATUS is set to true ShaderObj.Release(); - m_GlProgObj.InitResources(pDeviceGL, m_Desc.ShaderType, *this); + m_GlProgObj.InitResources(pDeviceGL, m_Desc.ShaderType, *this, nullptr, nullptr, 0); } else { diff --git a/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp index 5930f0a6..15086b05 100644 --- a/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp @@ -40,7 +40,7 @@ ShaderResourceBindingGLImpl::ShaderResourceBindingGLImpl(IReferenceCounters* pRe if(auto p##SN = ValidatedCast( pPSO->Get##SN() )) \ { \ auto &GLProg = p##SN->GetGlProgram(); \ - m_DynamicProgResources[SN##Ind].Clone(GLProg.GetAllResources(), VarTypes, _countof(VarTypes), *this); \ + m_DynamicProgResources[SN##Ind].Clone(pPSO->GetDevice(), *this, GLProg.GetResources(), pPSO->GetDesc().ResourceLayout, VarTypes, _countof(VarTypes)); \ } INIT_SHADER(VS) @@ -55,7 +55,7 @@ ShaderResourceBindingGLImpl::ShaderResourceBindingGLImpl(IReferenceCounters* pRe { // Clone all variable types SHADER_RESOURCE_VARIABLE_TYPE VarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_STATIC, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; - m_DynamicProgResources[0].Clone(pPSO->GetGLProgram().GetAllResources(), VarTypes, _countof(VarTypes), *this); + m_DynamicProgResources[0].Clone(pPSO->GetDevice(), *this, pPSO->GetGLProgram().GetResources(), pPSO->GetDesc().ResourceLayout, VarTypes, _countof(VarTypes)); } } @@ -129,75 +129,12 @@ void ShaderResourceBindingGLImpl::InitializeStaticResources(const IPipelineState { if (!IsUsingSeparatePrograms()) { - class ResourceMappingProxy final : public IResourceMapping - { - public: - ResourceMappingProxy(const PipelineStateGLImpl& PSO) : - m_PSO(PSO) - { - } - virtual void QueryInterface (const INTERFACE_ID& IID, IObject** ppInterface)override final - { - UNEXPECTED("This method should never be called"); - } - virtual CounterValueType AddRef()override final - { - UNEXPECTED("This method should never be called"); - return 0; - } - virtual CounterValueType Release()override final - { - UNEXPECTED("This method should never be called"); - return 0; - } - virtual IReferenceCounters* GetReferenceCounters()const override final - { - UNEXPECTED("This method should never be called"); - return nullptr; - } - virtual void AddResource (const Char* Name, IDeviceObject* pObject, bool bIsUnique)override final - { - UNEXPECTED("This method should never be called"); - } - virtual void AddResourceArray (const Char* Name, Uint32 StartIndex, IDeviceObject* const* ppObjects, Uint32 NumElements, bool bIsUnique)override final - { - UNEXPECTED("This method should never be called"); - } - virtual void RemoveResourceByName (const Char* Name, Uint32 ArrayIndex = 0) - { - UNEXPECTED("This method should never be called"); - } - virtual void GetResource (const Char* Name, IDeviceObject** ppResource, Uint32 ArrayIndex = 0) - { - auto NumShaders = m_PSO.GetNumShaders(); - for (Uint32 s=0; s < NumShaders; ++s) - { - auto* pShader = m_PSO.GetShader(s); - auto* pVar = pShader->GetShaderVariable(Name, false); - if (pVar != nullptr) - { - auto* pStaticVarPlaceholder = ValidatedCast(pVar); - *ppResource = pStaticVarPlaceholder->Get(ArrayIndex); - if (*ppResource != nullptr) - (*ppResource)->AddRef(); - } - } - } - virtual size_t GetSize() - { - UNEXPECTED("This method should never be called"); - return 0; - } - private: - const PipelineStateGLImpl& m_PSO; - }; - - if (pPipelineState != nullptr) - { - const auto* PSOGL = ValidatedCast(pPipelineState); - ResourceMappingProxy StaticResMapping(*PSOGL); - m_DynamicProgResources[0].BindResources(&StaticResMapping, 0); - } + //if (pPipelineState != nullptr) + //{ + // const auto* PSOGL = ValidatedCast(pPipelineState); + // ResourceMappingProxy StaticResMapping(*PSOGL); + // m_DynamicProgResources[0].BindResources(&StaticResMapping, 0); + //} } } diff --git a/Graphics/GraphicsEngineOpenGL/src/TexRegionRender.cpp b/Graphics/GraphicsEngineOpenGL/src/TexRegionRender.cpp index 9bbb9c89..abd5c9f2 100644 --- a/Graphics/GraphicsEngineOpenGL/src/TexRegionRender.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/TexRegionRender.cpp @@ -61,7 +61,6 @@ namespace Diligent ShaderCreateInfo ShaderAttrs; ShaderAttrs.Desc.Name = "TexRegionRender : Vertex shader"; ShaderAttrs.Desc.ShaderType = SHADER_TYPE_VERTEX; - ShaderAttrs.Desc.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; ShaderAttrs.Source = VertexShaderSource; constexpr bool IsInternalDeviceObject = true; pDeviceGL->CreateShader(ShaderAttrs, &m_pVertexShader, IsInternalDeviceObject); @@ -117,12 +116,6 @@ namespace Diligent Name.append(SamplerDim); ShaderAttrs.Desc.Name = Name.c_str(); ShaderAttrs.Desc.ShaderType = SHADER_TYPE_PIXEL; - ShaderResourceVariableDesc Vars[] = - { - {"cbConstants", SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE} - }; - ShaderAttrs.Desc.NumVariables = _countof(Vars); - ShaderAttrs.Desc.VariableDesc = Vars; std::stringstream SourceSS; SourceSS << "uniform " << Prefix << SamplerDim << " gSourceTex;\n" @@ -141,6 +134,15 @@ namespace Diligent auto &FragmetShader = m_pFragmentShaders[Dim*3 + Fmt]; pDeviceGL->CreateShader(ShaderAttrs, &FragmetShader, IsInternalDeviceObject); GraphicsPipeline.pPS = FragmetShader; + + PSODesc.ResourceLayout.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; + ShaderResourceVariableDesc Vars[] = + { + {SHADER_TYPE_PIXEL, "cbConstants", SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE} + }; + PSODesc.ResourceLayout.NumVariables = _countof(Vars); + PSODesc.ResourceLayout.Variables = Vars; + pDeviceGL->CreatePipelineState(PSODesc, &m_pPSO[Dim*3 + Fmt], IsInternalDeviceObject); } m_pPSO[RESOURCE_DIM_TEX_2D*3]->CreateShaderResourceBinding(&m_pSRB); -- cgit v1.2.3 From 261869609fc566e74bc989919d5a204c76421f66 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Tue, 5 Mar 2019 20:01:30 -0800 Subject: Fixed Metal backend stub --- Graphics/GraphicsEngine/interface/GraphicsTypes.h | 8 + Graphics/GraphicsEngineMetal/CMakeLists.txt | 7 +- .../interface/EngineFactoryMtl.h | 66 ++++++ .../interface/EngineMtlAttribs.h | 38 ---- .../interface/RenderDeviceFactoryMtl.h | 66 ------ .../GraphicsEngineMetal/src/EngineFactoryMtl.mm | 249 +++++++++++++++++++++ .../src/RenderDeviceFactoryMtl.mm | 249 --------------------- 7 files changed, 326 insertions(+), 357 deletions(-) create mode 100644 Graphics/GraphicsEngineMetal/interface/EngineFactoryMtl.h delete mode 100644 Graphics/GraphicsEngineMetal/interface/EngineMtlAttribs.h delete mode 100644 Graphics/GraphicsEngineMetal/interface/RenderDeviceFactoryMtl.h create mode 100644 Graphics/GraphicsEngineMetal/src/EngineFactoryMtl.mm delete mode 100644 Graphics/GraphicsEngineMetal/src/RenderDeviceFactoryMtl.mm (limited to 'Graphics') diff --git a/Graphics/GraphicsEngine/interface/GraphicsTypes.h b/Graphics/GraphicsEngine/interface/GraphicsTypes.h index 751279da..8de7d784 100644 --- a/Graphics/GraphicsEngine/interface/GraphicsTypes.h +++ b/Graphics/GraphicsEngine/interface/GraphicsTypes.h @@ -1488,6 +1488,14 @@ namespace Diligent Uint32 DynamicHeapPageSize = 256 << 10; }; + + /// Attributes of the Metal-based engine implementation + struct EngineMtlCreateInfo : public EngineCreateInfo + { + + }; + + /// Box struct Box { diff --git a/Graphics/GraphicsEngineMetal/CMakeLists.txt b/Graphics/GraphicsEngineMetal/CMakeLists.txt index 6a2bb29d..294d7276 100644 --- a/Graphics/GraphicsEngineMetal/CMakeLists.txt +++ b/Graphics/GraphicsEngineMetal/CMakeLists.txt @@ -9,7 +9,7 @@ set(INCLUDE include/CommandListMtlImpl.h include/MtlTypeConversions.h include/DeviceContextMtlImpl.h - include/FenceMtlImpl.h + include/FenceMtlImpl.h include/PipelineStateMtlImpl.h include/RenderDeviceMtlImpl.h include/SamplerMtlImpl.h @@ -24,11 +24,10 @@ set(INTERFACE interface/BufferMtl.h interface/BufferViewMtl.h interface/DeviceContextMtl.h - interface/EngineMtlAttribs.h + interface/EngineFactoryMtl.h interface/FenceMtl.h interface/PipelineStateMtl.h interface/RenderDeviceMtl.h - interface/RenderDeviceFactoryMtl.h interface/SamplerMtl.h interface/ShaderMtl.h interface/ShaderResourceBindingMtl.h @@ -44,10 +43,10 @@ set(SRC src/CommandListMtlImpl.mm src/MtlTypeConversions.mm src/DeviceContextMtlImpl.mm + src/EngineFactoryMtl.mm src/FenceMtlImpl.mm src/PipelineStateMtlImpl.mm src/RenderDeviceMtlImpl.mm - src/RenderDeviceFactoryMtl.mm src/SamplerMtlImpl.mm src/ShaderMtlImpl.mm src/ShaderResourceBindingMtlImpl.mm diff --git a/Graphics/GraphicsEngineMetal/interface/EngineFactoryMtl.h b/Graphics/GraphicsEngineMetal/interface/EngineFactoryMtl.h new file mode 100644 index 00000000..01888518 --- /dev/null +++ b/Graphics/GraphicsEngineMetal/interface/EngineFactoryMtl.h @@ -0,0 +1,66 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +/// \file +/// Declaration of functions that initialize Vulkan-based engine implementation + +#include + +#include "../../GraphicsEngine/interface/RenderDevice.h" +#include "../../GraphicsEngine/interface/DeviceContext.h" +#include "../../GraphicsEngine/interface/SwapChain.h" +#include "EngineMtlAttribs.h" + +// https://gcc.gnu.org/wiki/Visibility +#define API_QUALIFIER __attribute__((visibility("default"))) + +namespace Diligent +{ + +class IEngineFactoryMtl +{ +public: + virtual void CreateDeviceAndContextsMtl(const EngineMtlCreateInfo& Attribs, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts ) = 0; + + virtual void CreateSwapChainMtl( IRenderDevice* pDevice, + IDeviceContext* pImmediateContext, + const SwapChainDesc& SCDesc, + void* pView, + ISwapChain** ppSwapChain ) = 0; + + virtual void AttachToMtlDevice(void* pMtlNativeDevice, + const EngineMtlCreateInfo& EngineAttribs, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts) = 0; +}; + + +API_QUALIFIER IEngineFactoryMtl* GetEngineFactoryMtl(); + +} diff --git a/Graphics/GraphicsEngineMetal/interface/EngineMtlAttribs.h b/Graphics/GraphicsEngineMetal/interface/EngineMtlAttribs.h deleted file mode 100644 index 935716df..00000000 --- a/Graphics/GraphicsEngineMetal/interface/EngineMtlAttribs.h +++ /dev/null @@ -1,38 +0,0 @@ -/* Copyright 2015-2019 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -/// \file -/// Definition of the Engine Mtl attribs - -#include "../../GraphicsEngine/interface/GraphicsTypes.h" - -namespace Diligent -{ - /// Attributes of the Metal-based engine implementation - struct EngineMtlAttribs : public EngineCreationAttribs - { - - }; -} diff --git a/Graphics/GraphicsEngineMetal/interface/RenderDeviceFactoryMtl.h b/Graphics/GraphicsEngineMetal/interface/RenderDeviceFactoryMtl.h deleted file mode 100644 index e0e9bffc..00000000 --- a/Graphics/GraphicsEngineMetal/interface/RenderDeviceFactoryMtl.h +++ /dev/null @@ -1,66 +0,0 @@ -/* Copyright 2015-2019 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -/// \file -/// Declaration of functions that initialize Vulkan-based engine implementation - -#include - -#include "../../GraphicsEngine/interface/RenderDevice.h" -#include "../../GraphicsEngine/interface/DeviceContext.h" -#include "../../GraphicsEngine/interface/SwapChain.h" -#include "EngineMtlAttribs.h" - -// https://gcc.gnu.org/wiki/Visibility -#define API_QUALIFIER __attribute__((visibility("default"))) - -namespace Diligent -{ - -class IEngineFactoryMtl -{ -public: - virtual void CreateDeviceAndContextsMtl( const EngineMtlAttribs& Attribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts ) = 0; - - virtual void CreateSwapChainMtl( IRenderDevice* pDevice, - IDeviceContext* pImmediateContext, - const SwapChainDesc& SCDesc, - void* pView, - ISwapChain** ppSwapChain ) = 0; - - virtual void AttachToMtlDevice(void* pMtlNativeDevice, - const EngineMtlAttribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts) = 0; -}; - - -API_QUALIFIER IEngineFactoryMtl* GetEngineFactoryMtl(); - -} diff --git a/Graphics/GraphicsEngineMetal/src/EngineFactoryMtl.mm b/Graphics/GraphicsEngineMetal/src/EngineFactoryMtl.mm new file mode 100644 index 00000000..7516d45e --- /dev/null +++ b/Graphics/GraphicsEngineMetal/src/EngineFactoryMtl.mm @@ -0,0 +1,249 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +/// \file +/// Routines that initialize Mtl-based engine implementation + +#include "EngineFactoryMtl.h" +#include "RenderDeviceMtlImpl.h" +#include "DeviceContextMtlImpl.h" +#include "SwapChainMtlImpl.h" +#include "MtlTypeConversions.h" +#include "EngineMemory.h" + +namespace Diligent +{ + +/// Engine factory for Mtl implementation +class EngineFactoryMtlImpl : public IEngineFactoryMtl +{ +public: + static EngineFactoryMtlImpl* GetInstance() + { + static EngineFactoryMtlImpl TheFactory; + return &TheFactory; + } + + void CreateDeviceAndContextsMtl(const EngineMtlCreateInfo& EngineAttribs, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts )override final; + + void CreateSwapChainMtl( IRenderDevice* pDevice, + IDeviceContext* pImmediateContext, + const SwapChainDesc& SCDesc, + void* pView, + ISwapChain** ppSwapChain )override final; + + void AttachToMtlDevice(void* pMtlNativeDevice, + const EngineMtlCreateInfo& EngineAttribs, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts)override final; +}; + + +/// Creates render device and device contexts for Metal-based engine implementation + +/// \param [in] EngineAttribs - Engine creation attributes. +/// \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 +/// the contexts will be written. Pointer to the immediate +/// context goes at position 0. If NumDeferredContexts > 0, +/// pointers to the deferred contexts go afterwards. +/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number +/// of deferred contexts is requested, pointers to the +/// contexts are written to ppContexts array starting +/// at position 1 +void EngineFactoryMtlImpl::CreateDeviceAndContextsMtl(const EngineMtlCreateInfo& EngineAttribs, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts ) +{ + if (EngineAttribs.DebugMessageCallback != nullptr) + SetDebugMessageCallback(EngineAttribs.DebugMessageCallback); + + VERIFY( ppDevice && ppContexts, "Null pointer provided" ); + if( !ppDevice || !ppContexts ) + return; + + *ppDevice = nullptr; + memset(ppContexts, 0, sizeof(*ppContexts) * (1+NumDeferredContexts)); + + void* pMtlDevice = nullptr; + AttachToMtlDevice(pMtlDevice, EngineAttribs, ppDevice, ppContexts, NumDeferredContexts); +} + + +/// Attaches to existing Mtl render device and immediate context + +/// \param [in] pMtlNativeDevice - pointer to native Mtl device +/// \param [in] pMtlImmediateContext - pointer to native Mtl immediate context +/// \param [in] EngineAttribs - Engine creation attributes. +/// \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 +/// the contexts will be written. Pointer to the immediate +/// context goes at position 0. If NumDeferredContexts > 0, +/// pointers to deferred contexts go afterwards. +/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number +/// of deferred contexts is requested, pointers to the +/// contexts are written to ppContexts array starting +/// at position 1 +void EngineFactoryMtlImpl::AttachToMtlDevice(void* pMtlNativeDevice, + const EngineMtlCreateInfo& EngineAttribs, + IRenderDevice** ppDevice, + IDeviceContext** ppContexts, + Uint32 NumDeferredContexts) +{ + if (EngineAttribs.DebugMessageCallback != nullptr) + SetDebugMessageCallback(EngineAttribs.DebugMessageCallback); + + VERIFY( ppDevice && ppContexts, "Null pointer provided" ); + if( !ppDevice || !ppContexts ) + return; + + try + { + SetRawAllocator(EngineAttribs.pRawMemAllocator); + auto &RawAlloctor = GetRawAllocator(); + RenderDeviceMtlImpl *pRenderDeviceMtl(NEW_RC_OBJ(RawAlloctor, "RenderDeviceMtlImpl instance", RenderDeviceMtlImpl) + (RawAlloctor, EngineAttribs, pMtlNativeDevice, NumDeferredContexts)); + pRenderDeviceMtl->QueryInterface(IID_RenderDevice, reinterpret_cast(ppDevice)); + + RefCntAutoPtr pDeviceContextMtl(NEW_RC_OBJ(RawAlloctor, "DeviceContextMtlImpl instance", DeviceContextMtlImpl) + (RawAlloctor, pRenderDeviceMtl, EngineAttribs, false)); + + // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceMtl will + // keep a weak reference to the context + pDeviceContextMtl->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts)); + pRenderDeviceMtl->SetImmediateContext(pDeviceContextMtl); + + for (Uint32 DeferredCtx = 0; DeferredCtx < NumDeferredContexts; ++DeferredCtx) + { + RefCntAutoPtr pDeferredCtxMtl( + NEW_RC_OBJ(RawAlloctor, "DeviceContextMtlImpl instance", DeviceContextMtlImpl) + (RawAlloctor, pRenderDeviceMtl, EngineAttribs, true)); + // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceD3D12 will + // keep a weak reference to the context + pDeferredCtxMtl->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts + 1 + DeferredCtx)); + pRenderDeviceMtl->SetDeferredContext(DeferredCtx, pDeferredCtxMtl); + } + } + catch( const std::runtime_error & ) + { + if( *ppDevice ) + { + (*ppDevice)->Release(); + *ppDevice = nullptr; + } + for(Uint32 ctx=0; ctx < 1 + NumDeferredContexts; ++ctx) + { + if( ppContexts[ctx] != nullptr ) + { + ppContexts[ctx]->Release(); + ppContexts[ctx] = nullptr; + } + } + + LOG_ERROR( "Failed to initialize Mtl device and contexts" ); + } +} + +/// Creates a swap chain for Direct3D11-based engine implementation + +/// \param [in] pDevice - Pointer to the render device +/// \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 +/// the swap chain will be associated with: +/// * On Win32 platform, this should be window handle (HWND) +/// * On Universal Windows Platform, this should be reference to the +/// core window (Windows::UI::Core::CoreWindow) +/// +/// \param [out] ppSwapChain - Address of the memory location where pointer to the new +/// swap chain will be written +void EngineFactoryMtlImpl::CreateSwapChainMtl(IRenderDevice* pDevice, + IDeviceContext* pImmediateContext, + const SwapChainDesc& SCDesc, + void* pView, + ISwapChain** ppSwapChain ) +{ + VERIFY( ppSwapChain, "Null pointer provided" ); + if( !ppSwapChain ) + return; + + *ppSwapChain = nullptr; + + try + { + auto *pDeviceMtl = ValidatedCast( pDevice ); + auto *pDeviceContextMtl = ValidatedCast(pImmediateContext); + auto &RawMemAllocator = GetRawAllocator(); + + auto *pSwapChainMtl = NEW_RC_OBJ(RawMemAllocator, "SwapChainMtlImpl instance", SwapChainMtlImpl) + (SCDesc, pDeviceMtl, pDeviceContextMtl, pView); + pSwapChainMtl->QueryInterface( IID_SwapChain, reinterpret_cast(ppSwapChain) ); + + pDeviceContextMtl->SetSwapChain(pSwapChainMtl); + // Bind default render target + pDeviceContextMtl->SetRenderTargets( 0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); + // Set default viewport + pDeviceContextMtl->SetViewports( 1, nullptr, 0, 0 ); + + auto NumDeferredCtx = pDeviceMtl->GetNumDeferredContexts(); + for (size_t ctx = 0; ctx < NumDeferredCtx; ++ctx) + { + if (auto pDeferredCtx = pDeviceMtl->GetDeferredContext(ctx)) + { + auto *pDeferredCtxMtl = pDeferredCtx.RawPtr(); + pDeferredCtxMtl->SetSwapChain(pSwapChainMtl); + // Do not bind default render target and viewport to be + // consistent with D3D12 + //// Bind default render target + //pDeferredCtxMtl->SetRenderTargets( 0, nullptr, nullptr ); + //// Set default viewport + //pDeferredCtxMtl->SetViewports( 1, nullptr, 0, 0 ); + } + } + } + catch( const std::runtime_error & ) + { + if( *ppSwapChain ) + { + (*ppSwapChain)->Release(); + *ppSwapChain = nullptr; + } + + LOG_ERROR( "Failed to create the swap chain" ); + } +} + +IEngineFactoryMtl* GetEngineFactoryMtl() +{ + return EngineFactoryMtlImpl::GetInstance(); +} + +} diff --git a/Graphics/GraphicsEngineMetal/src/RenderDeviceFactoryMtl.mm b/Graphics/GraphicsEngineMetal/src/RenderDeviceFactoryMtl.mm deleted file mode 100644 index 900a288b..00000000 --- a/Graphics/GraphicsEngineMetal/src/RenderDeviceFactoryMtl.mm +++ /dev/null @@ -1,249 +0,0 @@ -/* Copyright 2015-2019 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -/// \file -/// Routines that initialize Mtl-based engine implementation - -#include "RenderDeviceFactoryMtl.h" -#include "RenderDeviceMtlImpl.h" -#include "DeviceContextMtlImpl.h" -#include "SwapChainMtlImpl.h" -#include "MtlTypeConversions.h" -#include "EngineMemory.h" - -namespace Diligent -{ - -/// Engine factory for Mtl implementation -class EngineFactoryMtlImpl : public IEngineFactoryMtl -{ -public: - static EngineFactoryMtlImpl* GetInstance() - { - static EngineFactoryMtlImpl TheFactory; - return &TheFactory; - } - - void CreateDeviceAndContextsMtl( const EngineMtlAttribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts )override final; - - void CreateSwapChainMtl( IRenderDevice* pDevice, - IDeviceContext* pImmediateContext, - const SwapChainDesc& SCDesc, - void* pView, - ISwapChain** ppSwapChain )override final; - - void AttachToMtlDevice(void* pMtlNativeDevice, - const EngineMtlAttribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts)override final; -}; - - -/// Creates render device and device contexts for Metal-based engine implementation - -/// \param [in] EngineAttribs - Engine creation attributes. -/// \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 -/// the contexts will be written. Pointer to the immediate -/// context goes at position 0. If NumDeferredContexts > 0, -/// pointers to the deferred contexts go afterwards. -/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number -/// of deferred contexts is requested, pointers to the -/// contexts are written to ppContexts array starting -/// at position 1 -void EngineFactoryMtlImpl::CreateDeviceAndContextsMtl( const EngineMtlAttribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts ) -{ - if (EngineAttribs.DebugMessageCallback != nullptr) - SetDebugMessageCallback(EngineAttribs.DebugMessageCallback); - - VERIFY( ppDevice && ppContexts, "Null pointer provided" ); - if( !ppDevice || !ppContexts ) - return; - - *ppDevice = nullptr; - memset(ppContexts, 0, sizeof(*ppContexts) * (1+NumDeferredContexts)); - - void* pMtlDevice = nullptr; - AttachToMtlDevice(pMtlDevice, EngineAttribs, ppDevice, ppContexts, NumDeferredContexts); -} - - -/// Attaches to existing Mtl render device and immediate context - -/// \param [in] pMtlNativeDevice - pointer to native Mtl device -/// \param [in] pMtlImmediateContext - pointer to native Mtl immediate context -/// \param [in] EngineAttribs - Engine creation attributes. -/// \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 -/// the contexts will be written. Pointer to the immediate -/// context goes at position 0. If NumDeferredContexts > 0, -/// pointers to deferred contexts go afterwards. -/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number -/// of deferred contexts is requested, pointers to the -/// contexts are written to ppContexts array starting -/// at position 1 -void EngineFactoryMtlImpl::AttachToMtlDevice(void* pMtlNativeDevice, - const EngineMtlAttribs& EngineAttribs, - IRenderDevice** ppDevice, - IDeviceContext** ppContexts, - Uint32 NumDeferredContexts) -{ - if (EngineAttribs.DebugMessageCallback != nullptr) - SetDebugMessageCallback(EngineAttribs.DebugMessageCallback); - - VERIFY( ppDevice && ppContexts, "Null pointer provided" ); - if( !ppDevice || !ppContexts ) - return; - - try - { - SetRawAllocator(EngineAttribs.pRawMemAllocator); - auto &RawAlloctor = GetRawAllocator(); - RenderDeviceMtlImpl *pRenderDeviceMtl(NEW_RC_OBJ(RawAlloctor, "RenderDeviceMtlImpl instance", RenderDeviceMtlImpl) - (RawAlloctor, EngineAttribs, pMtlNativeDevice, NumDeferredContexts)); - pRenderDeviceMtl->QueryInterface(IID_RenderDevice, reinterpret_cast(ppDevice)); - - RefCntAutoPtr pDeviceContextMtl(NEW_RC_OBJ(RawAlloctor, "DeviceContextMtlImpl instance", DeviceContextMtlImpl) - (RawAlloctor, pRenderDeviceMtl, EngineAttribs, false)); - - // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceMtl will - // keep a weak reference to the context - pDeviceContextMtl->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts)); - pRenderDeviceMtl->SetImmediateContext(pDeviceContextMtl); - - for (Uint32 DeferredCtx = 0; DeferredCtx < NumDeferredContexts; ++DeferredCtx) - { - RefCntAutoPtr pDeferredCtxMtl( - NEW_RC_OBJ(RawAlloctor, "DeviceContextMtlImpl instance", DeviceContextMtlImpl) - (RawAlloctor, pRenderDeviceMtl, EngineAttribs, true)); - // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceD3D12 will - // keep a weak reference to the context - pDeferredCtxMtl->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts + 1 + DeferredCtx)); - pRenderDeviceMtl->SetDeferredContext(DeferredCtx, pDeferredCtxMtl); - } - } - catch( const std::runtime_error & ) - { - if( *ppDevice ) - { - (*ppDevice)->Release(); - *ppDevice = nullptr; - } - for(Uint32 ctx=0; ctx < 1 + NumDeferredContexts; ++ctx) - { - if( ppContexts[ctx] != nullptr ) - { - ppContexts[ctx]->Release(); - ppContexts[ctx] = nullptr; - } - } - - LOG_ERROR( "Failed to initialize Mtl device and contexts" ); - } -} - -/// Creates a swap chain for Direct3D11-based engine implementation - -/// \param [in] pDevice - Pointer to the render device -/// \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 -/// the swap chain will be associated with: -/// * On Win32 platform, this should be window handle (HWND) -/// * On Universal Windows Platform, this should be reference to the -/// core window (Windows::UI::Core::CoreWindow) -/// -/// \param [out] ppSwapChain - Address of the memory location where pointer to the new -/// swap chain will be written -void EngineFactoryMtlImpl::CreateSwapChainMtl( IRenderDevice* pDevice, - IDeviceContext* pImmediateContext, - const SwapChainDesc& SCDesc, - void* pView, - ISwapChain** ppSwapChain ) -{ - VERIFY( ppSwapChain, "Null pointer provided" ); - if( !ppSwapChain ) - return; - - *ppSwapChain = nullptr; - - try - { - auto *pDeviceMtl = ValidatedCast( pDevice ); - auto *pDeviceContextMtl = ValidatedCast(pImmediateContext); - auto &RawMemAllocator = GetRawAllocator(); - - auto *pSwapChainMtl = NEW_RC_OBJ(RawMemAllocator, "SwapChainMtlImpl instance", SwapChainMtlImpl) - (SCDesc, pDeviceMtl, pDeviceContextMtl, pView); - pSwapChainMtl->QueryInterface( IID_SwapChain, reinterpret_cast(ppSwapChain) ); - - pDeviceContextMtl->SetSwapChain(pSwapChainMtl); - // Bind default render target - pDeviceContextMtl->SetRenderTargets( 0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION ); - // Set default viewport - pDeviceContextMtl->SetViewports( 1, nullptr, 0, 0 ); - - auto NumDeferredCtx = pDeviceMtl->GetNumDeferredContexts(); - for (size_t ctx = 0; ctx < NumDeferredCtx; ++ctx) - { - if (auto pDeferredCtx = pDeviceMtl->GetDeferredContext(ctx)) - { - auto *pDeferredCtxMtl = pDeferredCtx.RawPtr(); - pDeferredCtxMtl->SetSwapChain(pSwapChainMtl); - // Do not bind default render target and viewport to be - // consistent with D3D12 - //// Bind default render target - //pDeferredCtxMtl->SetRenderTargets( 0, nullptr, nullptr ); - //// Set default viewport - //pDeferredCtxMtl->SetViewports( 1, nullptr, 0, 0 ); - } - } - } - catch( const std::runtime_error & ) - { - if( *ppSwapChain ) - { - (*ppSwapChain)->Release(); - *ppSwapChain = nullptr; - } - - LOG_ERROR( "Failed to create the swap chain" ); - } -} - -IEngineFactoryMtl* GetEngineFactoryMtl() -{ - return EngineFactoryMtlImpl::GetInstance(); -} - -} -- cgit v1.2.3 From 859717ac93f8f72f34765df32396ba56e0d6a885 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Tue, 5 Mar 2019 20:14:11 -0800 Subject: Fixed one more issue with Metal back-end --- Graphics/GraphicsEngineMetal/include/RenderDeviceMtlImpl.h | 1 - 1 file changed, 1 deletion(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineMetal/include/RenderDeviceMtlImpl.h b/Graphics/GraphicsEngineMetal/include/RenderDeviceMtlImpl.h index 05a3e8d4..109958d6 100644 --- a/Graphics/GraphicsEngineMetal/include/RenderDeviceMtlImpl.h +++ b/Graphics/GraphicsEngineMetal/include/RenderDeviceMtlImpl.h @@ -29,7 +29,6 @@ #include "RenderDeviceMtl.h" #include "RenderDeviceBase.h" #include "DeviceContextMtl.h" -#include "EngineMtlAttribs.h" namespace Diligent { -- cgit v1.2.3 From b9c210a8df72e620500509ed5243bef18a4390ec Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Tue, 5 Mar 2019 20:32:21 -0800 Subject: Fixed yet few another issues with Metal backend --- .../GraphicsEngineMetal/include/RenderDeviceMtlImpl.h | 12 ++++++------ Graphics/GraphicsEngineMetal/src/RenderDeviceMtlImpl.mm | 16 ++++++++-------- 2 files changed, 14 insertions(+), 14 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineMetal/include/RenderDeviceMtlImpl.h b/Graphics/GraphicsEngineMetal/include/RenderDeviceMtlImpl.h index 109958d6..fbc40a0c 100644 --- a/Graphics/GraphicsEngineMetal/include/RenderDeviceMtlImpl.h +++ b/Graphics/GraphicsEngineMetal/include/RenderDeviceMtlImpl.h @@ -39,16 +39,16 @@ class RenderDeviceMtlImpl final : public RenderDeviceBase public: using TRenderDeviceBase = RenderDeviceBase; - RenderDeviceMtlImpl( IReferenceCounters* pRefCounters, - IMemoryAllocator& RawMemAllocator, - const EngineMtlAttribs& EngineAttribs, - void* pMtlDevice, - Uint32 NumDeferredContexts ); + RenderDeviceMtlImpl( IReferenceCounters* pRefCounters, + IMemoryAllocator& RawMemAllocator, + const EngineMtlCreateInfo& EngineAttribs, + void* pMtlDevice, + Uint32 NumDeferredContexts ); virtual void QueryInterface( const INTERFACE_ID& IID, IObject **ppInterface )override final; virtual void CreateBuffer(const BufferDesc& BuffDesc, const BufferData* pBuffData, IBuffer** ppBuffer)override final; - virtual void CreateShader(const ShaderCreationAttribs& ShaderCreationAttribs, IShader** ppShader)override final; + virtual void CreateShader(const ShaderCreateInfo& ShaderCI, IShader** ppShader)override final; virtual void CreateTexture(const TextureDesc& TexDesc, const TextureData* pData, ITexture** ppTexture)override final; diff --git a/Graphics/GraphicsEngineMetal/src/RenderDeviceMtlImpl.mm b/Graphics/GraphicsEngineMetal/src/RenderDeviceMtlImpl.mm index df94eb0f..99ab0240 100644 --- a/Graphics/GraphicsEngineMetal/src/RenderDeviceMtlImpl.mm +++ b/Graphics/GraphicsEngineMetal/src/RenderDeviceMtlImpl.mm @@ -37,11 +37,11 @@ namespace Diligent { -RenderDeviceMtlImpl :: RenderDeviceMtlImpl(IReferenceCounters* pRefCounters, - IMemoryAllocator& RawMemAllocator, - const EngineMtlAttribs& EngineAttribs, - void* pMtlDevice, - Uint32 NumDeferredContexts) : +RenderDeviceMtlImpl :: RenderDeviceMtlImpl(IReferenceCounters* pRefCounters, + IMemoryAllocator& RawMemAllocator, + const EngineMtlCreateInfo& EngineAttribs, + void* pMtlDevice, + Uint32 NumDeferredContexts) : TRenderDeviceBase { pRefCounters, @@ -92,13 +92,13 @@ void RenderDeviceMtlImpl :: CreateBuffer(const BufferDesc& BuffDesc, const Buffe ); } -void RenderDeviceMtlImpl :: CreateShader(const ShaderCreationAttribs& ShaderCreationAttribs, IShader** ppShader) +void RenderDeviceMtlImpl :: CreateShader(const ShaderCreateInfo& ShaderCI, IShader** ppShader) { - CreateDeviceObject( "shader", ShaderCreationAttribs.Desc, ppShader, + CreateDeviceObject( "shader", ShaderCI.Desc, ppShader, [&]() { ShaderMtlImpl* pShaderMtl( NEW_RC_OBJ(m_ShaderObjAllocator, "ShaderMtlImpl instance", ShaderMtlImpl) - (this, ShaderCreationAttribs ) ); + (this, ShaderCI ) ); pShaderMtl->QueryInterface( IID_Shader, reinterpret_cast(ppShader) ); OnCreateDeviceObject( pShaderMtl ); -- cgit v1.2.3 From 33e1dca8e674e5e5a05c97151a4a8e1644f6b174 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Tue, 5 Mar 2019 21:22:48 -0800 Subject: Keep fixing metal backend --- .../include/PipelineStateMtlImpl.h | 24 +++++++++++++++++++++ .../include/RenderDeviceMtlImpl.h | 3 +-- .../GraphicsEngineMetal/include/ShaderMtlImpl.h | 25 ++++++---------------- Graphics/GraphicsEngineMetal/src/ShaderMtlImpl.mm | 8 +++---- 4 files changed, 36 insertions(+), 24 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineMetal/include/PipelineStateMtlImpl.h b/Graphics/GraphicsEngineMetal/include/PipelineStateMtlImpl.h index 5117cf28..49550369 100644 --- a/Graphics/GraphicsEngineMetal/include/PipelineStateMtlImpl.h +++ b/Graphics/GraphicsEngineMetal/include/PipelineStateMtlImpl.h @@ -54,6 +54,30 @@ public: virtual bool IsCompatibleWith(const IPipelineState *pPSO)const override final; + virtual void BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags)override final + { + LOG_ERROR_MESSAGE("PipelineStateMtlImpl::BindStaticResources() is not implemented"); + } + + virtual Uint32 GetStaticVariableCount(SHADER_TYPE ShaderType) const override final + { + LOG_ERROR_MESSAGE("PipelineStateMtlImpl::GetStaticVariableCount() is not implemented"); + return 0; + } + + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) override final; + { + LOG_ERROR_MESSAGE("PipelineStateMtlImpl::GetStaticShaderVariable() is not implemented"); + return nullptr; + } + + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) override final; + { + LOG_ERROR_MESSAGE("PipelineStateMtlImpl::GetStaticShaderVariable() is not implemented"); + return nullptr; + } + + private: }; diff --git a/Graphics/GraphicsEngineMetal/include/RenderDeviceMtlImpl.h b/Graphics/GraphicsEngineMetal/include/RenderDeviceMtlImpl.h index fbc40a0c..0f49380f 100644 --- a/Graphics/GraphicsEngineMetal/include/RenderDeviceMtlImpl.h +++ b/Graphics/GraphicsEngineMetal/include/RenderDeviceMtlImpl.h @@ -66,8 +66,7 @@ public: private: virtual void TestTextureFormat( TEXTURE_FORMAT TexFormat )override final; - EngineMtlAttribs m_EngineAttribs; - + EngineMtlCreateInfo m_EngineAttribs; }; } diff --git a/Graphics/GraphicsEngineMetal/include/ShaderMtlImpl.h b/Graphics/GraphicsEngineMetal/include/ShaderMtlImpl.h index 8d3f09a2..8b73035c 100644 --- a/Graphics/GraphicsEngineMetal/include/ShaderMtlImpl.h +++ b/Graphics/GraphicsEngineMetal/include/ShaderMtlImpl.h @@ -44,34 +44,23 @@ public: ShaderMtlImpl(IReferenceCounters* pRefCounters, class RenderDeviceMtlImpl* pRenderDeviceMtl, - const ShaderCreationAttribs& CreationAttribs); + const ShaderCreateInfo& ShaderCI); ~ShaderMtlImpl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject** ppInterface )override final; + virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface )override final; - virtual void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags )override final + virtual Uint32 GetResourceCount()const override final { - LOG_ERROR_MESSAGE("ShaderMtlImpl::BindResources() is not implemented"); - } - - virtual IShaderVariable* GetShaderVariable( const Char* Name )override final - { - LOG_ERROR_MESSAGE("ShaderMtlImpl::GetShaderVariable() is not implemented"); - return nullptr; - } - - virtual Uint32 GetVariableCount() const override final - { - LOG_ERROR_MESSAGE("ShaderMtlImpl::GetVariableCount() is not implemented"); + LOG_ERROR_MESSAGE("ShaderMtlImpl::GetResourceCount() is not implemented"); return 0; } - virtual IShaderVariable* GetShaderVariable(Uint32 Index)override final + virtual ShaderResourceDesc GetResource(Uint32 Index)const override final { - LOG_ERROR_MESSAGE("ShaderMtlImpl::GetShaderVariable() is not implemented"); + LOG_ERROR_MESSAGE("ShaderMtlImpl::GetResource() is not implemented"); return nullptr; } - + private: }; diff --git a/Graphics/GraphicsEngineMetal/src/ShaderMtlImpl.mm b/Graphics/GraphicsEngineMetal/src/ShaderMtlImpl.mm index 489c3004..7f9f04f6 100644 --- a/Graphics/GraphicsEngineMetal/src/ShaderMtlImpl.mm +++ b/Graphics/GraphicsEngineMetal/src/ShaderMtlImpl.mm @@ -28,10 +28,10 @@ namespace Diligent { -ShaderMtlImpl::ShaderMtlImpl(IReferenceCounters* pRefCounters, - RenderDeviceMtlImpl* pRenderDeviceMtl, - const ShaderCreationAttribs& CreationAttribs) : - TShaderBase(pRefCounters, pRenderDeviceMtl, CreationAttribs.Desc) +ShaderMtlImpl::ShaderMtlImpl(IReferenceCounters* pRefCounters, + RenderDeviceMtlImpl* pRenderDeviceMtl, + const ShaderCreateInfo& ShaderCI) : + TShaderBase(pRefCounters, pRenderDeviceMtl, ShaderCI.Desc) { LOG_ERROR_AND_THROW("Shaders are not implemented in Metal backend"); } -- cgit v1.2.3 From 75ceee9c24284c7c564e4c8f82069406184506e5 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Tue, 5 Mar 2019 21:37:35 -0800 Subject: Keep fixing metal back-end --- Graphics/GraphicsEngineMetal/include/PipelineStateMtlImpl.h | 4 ++-- Graphics/GraphicsEngineMetal/include/ShaderMtlImpl.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineMetal/include/PipelineStateMtlImpl.h b/Graphics/GraphicsEngineMetal/include/PipelineStateMtlImpl.h index 49550369..94a3a943 100644 --- a/Graphics/GraphicsEngineMetal/include/PipelineStateMtlImpl.h +++ b/Graphics/GraphicsEngineMetal/include/PipelineStateMtlImpl.h @@ -65,13 +65,13 @@ public: return 0; } - virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) override final; + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, const Char* Name) override final { LOG_ERROR_MESSAGE("PipelineStateMtlImpl::GetStaticShaderVariable() is not implemented"); return nullptr; } - virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) override final; + virtual IShaderResourceVariable* GetStaticShaderVariable(SHADER_TYPE ShaderType, Uint32 Index) override final { LOG_ERROR_MESSAGE("PipelineStateMtlImpl::GetStaticShaderVariable() is not implemented"); return nullptr; diff --git a/Graphics/GraphicsEngineMetal/include/ShaderMtlImpl.h b/Graphics/GraphicsEngineMetal/include/ShaderMtlImpl.h index 8b73035c..1752f59b 100644 --- a/Graphics/GraphicsEngineMetal/include/ShaderMtlImpl.h +++ b/Graphics/GraphicsEngineMetal/include/ShaderMtlImpl.h @@ -58,7 +58,7 @@ public: virtual ShaderResourceDesc GetResource(Uint32 Index)const override final { LOG_ERROR_MESSAGE("ShaderMtlImpl::GetResource() is not implemented"); - return nullptr; + return ShaderResourceDesc{}; } private: -- cgit v1.2.3 From 772ef0e6cfbb218814ad4e7d25dd94b697a6b4f3 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Tue, 5 Mar 2019 22:05:17 -0800 Subject: Keep fixing Metal backend + few other minor changes --- Graphics/GLSLTools/include/SPIRVShaderResources.h | 6 ++++-- Graphics/GLSLTools/src/SPIRVShaderResources.cpp | 9 ++++++--- Graphics/GraphicsEngine/interface/Shader.h | 2 +- Graphics/GraphicsEngineD3DBase/include/ShaderResources.h | 3 +++ Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp | 4 +++- .../GraphicsEngineMetal/include/ShaderResourceBindingMtlImpl.h | 4 ++-- Graphics/GraphicsEngineMetal/src/DeviceContextMtlImpl.mm | 1 - 7 files changed, 19 insertions(+), 10 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GLSLTools/include/SPIRVShaderResources.h b/Graphics/GLSLTools/include/SPIRVShaderResources.h index 523ccc29..b117c05a 100644 --- a/Graphics/GLSLTools/include/SPIRVShaderResources.h +++ b/Graphics/GLSLTools/include/SPIRVShaderResources.h @@ -28,8 +28,8 @@ // SPIRVShaderResources class uses continuous chunk of memory to store all resources, as follows: // -// m_MemoryBuffer m_TotalResources -// | | +// m_MemoryBuffer m_TotalResources end of names data may not be aligned +// | | | // | Uniform Buffers | Storage Buffers | Storage Images | Sampled Images | Atomic Counters | Separate Samplers | Separate Images | Stage Inputs | Resource Names | #include @@ -333,6 +333,8 @@ private: // Memory buffer that holds all resources as continuous chunk of memory: // | UBs | SBs | StrgImgs | SmplImgs | ACs | SepSamplers | SepImgs | Stage Inputs | Resource Names | + // | + // end of names data may not be aligned std::unique_ptr< void, STDDeleterRawMem > m_MemoryBuffer; StringPool m_ResourceNames; diff --git a/Graphics/GLSLTools/src/SPIRVShaderResources.cpp b/Graphics/GLSLTools/src/SPIRVShaderResources.cpp index 7289e9fd..82743cfd 100644 --- a/Graphics/GLSLTools/src/SPIRVShaderResources.cpp +++ b/Graphics/GLSLTools/src/SPIRVShaderResources.cpp @@ -28,6 +28,7 @@ #include "ShaderBase.h" #include "GraphicsAccessories.h" #include "StringTools.h" +#include "Align.h" namespace Diligent { @@ -439,10 +440,12 @@ void SPIRVShaderResources::Initialize(IMemoryAllocator& Allocator, VERIFY(NumShaderStageInputs <= MaxOffset, "Max offset exceeded"); m_NumShaderStageInputs = static_cast(NumShaderStageInputs); + auto AlignedResourceNamesPoolSize = Align(ResourceNamesPoolSize, sizeof(void*)); + static_assert(sizeof(SPIRVShaderResourceAttribs) % sizeof(void*) == 0, "Size of SPIRVShaderResourceAttribs struct must be multiple of sizeof(void*)"); - auto MemorySize = m_TotalResources * sizeof(SPIRVShaderResourceAttribs) + - m_NumShaderStageInputs * sizeof(SPIRVShaderStageInputAttribs) + - ResourceNamesPoolSize * sizeof(char); + auto MemorySize = m_TotalResources * sizeof(SPIRVShaderResourceAttribs) + + m_NumShaderStageInputs * sizeof(SPIRVShaderStageInputAttribs) + + AlignedResourceNamesPoolSize * sizeof(char); VERIFY_EXPR(GetNumUBs() == Counters.NumUBs); VERIFY_EXPR(GetNumSBs() == Counters.NumSBs); diff --git a/Graphics/GraphicsEngine/interface/Shader.h b/Graphics/GraphicsEngine/interface/Shader.h index d6c07629..efd4acb1 100644 --- a/Graphics/GraphicsEngine/interface/Shader.h +++ b/Graphics/GraphicsEngine/interface/Shader.h @@ -190,7 +190,7 @@ struct ShaderCreateInfo }; /// Describes shader resource type -enum SHADER_RESOURCE_TYPE +enum SHADER_RESOURCE_TYPE : Uint8 { /// Shader resource type is unknown SHADER_RESOURCE_TYPE_UNKNOWN = 0, diff --git a/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h b/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h index f8f6917b..e12049e4 100644 --- a/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h +++ b/Graphics/GraphicsEngineD3DBase/include/ShaderResources.h @@ -399,6 +399,9 @@ private: // Memory buffer that holds all resources as continuous chunk of memory: // | CBs | TexSRVs | TexUAVs | BufSRVs | BufUAVs | Samplers | Resource Names | + // | + // end of names data may not be aligned + std::unique_ptr< void, STDDeleterRawMem > m_MemoryBuffer; StringPool m_ResourceNames; diff --git a/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp b/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp index a3efe9f3..c52b2cee 100644 --- a/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp +++ b/Graphics/GraphicsEngineD3DBase/src/ShaderResources.cpp @@ -27,6 +27,7 @@ #include "ShaderResources.h" #include "HashUtils.h" #include "ShaderResourceVariableBase.h" +#include "Align.h" namespace Diligent { @@ -74,7 +75,8 @@ void ShaderResources::AllocateMemory(IMemoryAllocator& Allocator, m_SamplersOffset = AdvanceOffset(ResCounters.NumSamplers); m_TotalResources = AdvanceOffset(0); - auto MemorySize = m_TotalResources * sizeof(D3DShaderResourceAttribs) + ResourceNamesPoolSize * sizeof(char); + auto AlignedResourceNamesPoolSize = Align(ResourceNamesPoolSize, sizeof(void*)); + auto MemorySize = m_TotalResources * sizeof(D3DShaderResourceAttribs) + AlignedResourceNamesPoolSize * sizeof(char); VERIFY_EXPR(GetNumCBs() == ResCounters.NumCBs); VERIFY_EXPR(GetNumTexSRV() == ResCounters.NumTexSRVs); diff --git a/Graphics/GraphicsEngineMetal/include/ShaderResourceBindingMtlImpl.h b/Graphics/GraphicsEngineMetal/include/ShaderResourceBindingMtlImpl.h index 95642031..89431cee 100644 --- a/Graphics/GraphicsEngineMetal/include/ShaderResourceBindingMtlImpl.h +++ b/Graphics/GraphicsEngineMetal/include/ShaderResourceBindingMtlImpl.h @@ -50,11 +50,11 @@ public: virtual void BindResources(Uint32 ShaderFlags, IResourceMapping* pResMapping, Uint32 Flags)override final; - virtual IShaderVariable* GetVariable(SHADER_TYPE ShaderType, const char *Name)override final; + virtual IShaderResourceVariable* GetVariable(SHADER_TYPE ShaderType, const char *Name)override final; virtual Uint32 GetVariableCount(SHADER_TYPE ShaderType) const override final; - virtual IShaderVariable* GetVariable(SHADER_TYPE ShaderType, Uint32 Index)override final; + virtual IShaderResourceVariable* GetVariable(SHADER_TYPE ShaderType, Uint32 Index)override final; virtual void InitializeStaticResources(const IPipelineState* pPipelineState)override final; diff --git a/Graphics/GraphicsEngineMetal/src/DeviceContextMtlImpl.mm b/Graphics/GraphicsEngineMetal/src/DeviceContextMtlImpl.mm index 93532ab0..c861002b 100644 --- a/Graphics/GraphicsEngineMetal/src/DeviceContextMtlImpl.mm +++ b/Graphics/GraphicsEngineMetal/src/DeviceContextMtlImpl.mm @@ -30,7 +30,6 @@ #include "PipelineStateMtlImpl.h" #include "SwapChainMtl.h" #include "ShaderResourceBindingMtlImpl.h" -#include "EngineMtlAttribs.h" #include "CommandListMtlImpl.h" #include "RenderDeviceMtlImpl.h" #include "FenceMtlImpl.h" -- cgit v1.2.3 From cfb2cf3022ba3beacc3fb6a196ea72524cef55d6 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Tue, 5 Mar 2019 22:42:25 -0800 Subject: Still fixing metal back-end --- Graphics/GraphicsEngineMetal/interface/EngineFactoryMtl.h | 1 - 1 file changed, 1 deletion(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineMetal/interface/EngineFactoryMtl.h b/Graphics/GraphicsEngineMetal/interface/EngineFactoryMtl.h index 01888518..ca6088b6 100644 --- a/Graphics/GraphicsEngineMetal/interface/EngineFactoryMtl.h +++ b/Graphics/GraphicsEngineMetal/interface/EngineFactoryMtl.h @@ -31,7 +31,6 @@ #include "../../GraphicsEngine/interface/RenderDevice.h" #include "../../GraphicsEngine/interface/DeviceContext.h" #include "../../GraphicsEngine/interface/SwapChain.h" -#include "EngineMtlAttribs.h" // https://gcc.gnu.org/wiki/Visibility #define API_QUALIFIER __attribute__((visibility("default"))) -- cgit v1.2.3 From 03da14aa28a60c3275196dadfb3766f73097bd95 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Tue, 5 Mar 2019 23:03:49 -0800 Subject: Still keep fixing metal back-end --- Graphics/GraphicsEngineMetal/include/DeviceContextMtlImpl.h | 12 ++++++------ Graphics/GraphicsEngineMetal/src/DeviceContextMtlImpl.mm | 10 +++++----- 2 files changed, 11 insertions(+), 11 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineMetal/include/DeviceContextMtlImpl.h b/Graphics/GraphicsEngineMetal/include/DeviceContextMtlImpl.h index b6f26154..f3d711a2 100644 --- a/Graphics/GraphicsEngineMetal/include/DeviceContextMtlImpl.h +++ b/Graphics/GraphicsEngineMetal/include/DeviceContextMtlImpl.h @@ -49,13 +49,13 @@ class DeviceContextMtlImpl final : public DeviceContextBase; - DeviceContextMtlImpl(IReferenceCounters* pRefCounters, - IMemoryAllocator& Allocator, - IRenderDevice* pDevice, - const struct EngineMtlAttribs& EngineAttribs, - bool bIsDeferred); + DeviceContextMtlImpl(IReferenceCounters* pRefCounters, + IMemoryAllocator& Allocator, + IRenderDevice* pDevice, + const struct EngineMtlCreateInfo& EngineAttribs, + bool bIsDeferred); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + virtual void QueryInterface( const INTERFACE_ID &IID, IObject **ppInterface )override final; virtual void SetPipelineState(IPipelineState* pPipelineState)override final; diff --git a/Graphics/GraphicsEngineMetal/src/DeviceContextMtlImpl.mm b/Graphics/GraphicsEngineMetal/src/DeviceContextMtlImpl.mm index c861002b..978fccf7 100644 --- a/Graphics/GraphicsEngineMetal/src/DeviceContextMtlImpl.mm +++ b/Graphics/GraphicsEngineMetal/src/DeviceContextMtlImpl.mm @@ -36,11 +36,11 @@ namespace Diligent { - DeviceContextMtlImpl::DeviceContextMtlImpl( IReferenceCounters* pRefCounters, - IMemoryAllocator& Allocator, - IRenderDevice* pDevice, - const struct EngineMtlAttribs& EngineAttribs, - bool bIsDeferred ) : + DeviceContextMtlImpl::DeviceContextMtlImpl( IReferenceCounters* pRefCounters, + IMemoryAllocator& Allocator, + IRenderDevice* pDevice, + const struct EngineMtlCreateInfo& EngineAttribs, + bool bIsDeferred ) : TDeviceContextBase(pRefCounters, pDevice, bIsDeferred) { } -- cgit v1.2.3 From 87efb65472e80af337ed6545851da9bcb8d5fdee Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Tue, 5 Mar 2019 23:19:14 -0800 Subject: Keep fixing metal back-end --- Graphics/GraphicsEngineMetal/src/ShaderResourceBindingMtlImpl.mm | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineMetal/src/ShaderResourceBindingMtlImpl.mm b/Graphics/GraphicsEngineMetal/src/ShaderResourceBindingMtlImpl.mm index 1206c528..aa9cc788 100644 --- a/Graphics/GraphicsEngineMetal/src/ShaderResourceBindingMtlImpl.mm +++ b/Graphics/GraphicsEngineMetal/src/ShaderResourceBindingMtlImpl.mm @@ -55,7 +55,7 @@ void ShaderResourceBindingMtlImpl::InitializeStaticResources(const IPipelineStat LOG_ERROR_MESSAGE("ShaderResourceBindingMtlImpl::InitializeStaticResources() is not implemented"); } -IShaderVariable* ShaderResourceBindingMtlImpl::GetVariable(SHADER_TYPE ShaderType, const char* Name) +IShaderResourceVariable* ShaderResourceBindingMtlImpl::GetVariable(SHADER_TYPE ShaderType, const char* Name) { LOG_ERROR_MESSAGE("ShaderResourceBindingMtlImpl::GetVariable() is not implemented"); return nullptr; @@ -67,7 +67,7 @@ Uint32 ShaderResourceBindingMtlImpl::GetVariableCount(SHADER_TYPE ShaderType) co return 0; } -IShaderVariable* ShaderResourceBindingMtlImpl::GetVariable(SHADER_TYPE ShaderType, Uint32 Index) +IShaderResourceVariable* ShaderResourceBindingMtlImpl::GetVariable(SHADER_TYPE ShaderType, Uint32 Index) { LOG_ERROR_MESSAGE("ShaderResourceBindingMtlImpl::GetVariable() is not implemented"); return nullptr; -- cgit v1.2.3 From c87e69d08937a012ed00d9c5395b942a8f6de9b1 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Tue, 5 Mar 2019 23:40:05 -0800 Subject: Fixed swap chain build error on iOS --- Graphics/GraphicsEngineOpenGL/include/SwapChainGLIOS.h | 11 +++++------ Graphics/GraphicsEngineOpenGL/src/SwapChainGLIOS.mm | 11 +++++------ Graphics/GraphicsEngineOpenGL/src/SwapChainGLImpl.cpp | 10 +++++----- 3 files changed, 15 insertions(+), 17 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineOpenGL/include/SwapChainGLIOS.h b/Graphics/GraphicsEngineOpenGL/include/SwapChainGLIOS.h index 51d34a47..db321e70 100644 --- a/Graphics/GraphicsEngineOpenGL/include/SwapChainGLIOS.h +++ b/Graphics/GraphicsEngineOpenGL/include/SwapChainGLIOS.h @@ -23,7 +23,6 @@ #pragma once -#include "EngineGLAttribs.h" #include "SwapChainGL.h" #include "SwapChainBase.h" #include "GLObjectWrapper.h" @@ -38,11 +37,11 @@ class SwapChainGLIOS final : public SwapChainBase public: typedef SwapChainBase TSwapChainBase; - SwapChainGLIOS(IReferenceCounters *pRefCounters, - const EngineGLAttribs &InitAttribs, - const SwapChainDesc& SwapChainDesc, - class RenderDeviceGLImpl* pRenderDeviceGL, - class DeviceContextGLImpl* pImmediateContextGL); + SwapChainGLIOS(IReferenceCounters* pRefCounters, + const EngineGLCreateInfo& InitAttribs, + const SwapChainDesc& SwapChainDesc, + class RenderDeviceGLImpl* pRenderDeviceGL, + class DeviceContextGLImpl* pImmediateContextGL); SwapChainGLIOS(); virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; diff --git a/Graphics/GraphicsEngineOpenGL/src/SwapChainGLIOS.mm b/Graphics/GraphicsEngineOpenGL/src/SwapChainGLIOS.mm index 679ea021..7e285249 100644 --- a/Graphics/GraphicsEngineOpenGL/src/SwapChainGLIOS.mm +++ b/Graphics/GraphicsEngineOpenGL/src/SwapChainGLIOS.mm @@ -30,15 +30,14 @@ #include "DeviceContextGLImpl.h" #include "RenderDeviceGLImpl.h" #include "SwapChainGLIOS.h" -#include "EngineGLAttribs.h" namespace Diligent { -SwapChainGLIOS::SwapChainGLIOS(IReferenceCounters *pRefCounters, - const EngineGLAttribs &InitAttribs, - const SwapChainDesc& SCDesc, - RenderDeviceGLImpl* pRenderDeviceGL, - DeviceContextGLImpl* pImmediateContextGL) : +SwapChainGLIOS::SwapChainGLIOS(IReferenceCounters* pRefCounters, + const EngineGLCreateInfo& InitAttribs, + const SwapChainDesc& SCDesc, + RenderDeviceGLImpl* pRenderDeviceGL, + DeviceContextGLImpl* pImmediateContextGL) : TSwapChainBase( pRefCounters, pRenderDeviceGL, pImmediateContextGL, SCDesc), m_ColorRenderBuffer(false), m_DepthRenderBuffer(false), diff --git a/Graphics/GraphicsEngineOpenGL/src/SwapChainGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/SwapChainGLImpl.cpp index 9fb44c53..01f1e5ec 100644 --- a/Graphics/GraphicsEngineOpenGL/src/SwapChainGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/SwapChainGLImpl.cpp @@ -28,11 +28,11 @@ namespace Diligent { -SwapChainGLImpl::SwapChainGLImpl(IReferenceCounters *pRefCounters, - const EngineGLCreateInfo &InitAttribs, - const SwapChainDesc& SCDesc, - RenderDeviceGLImpl* pRenderDeviceGL, - DeviceContextGLImpl* pImmediateContextGL) : +SwapChainGLImpl::SwapChainGLImpl(IReferenceCounters* pRefCounters, + const EngineGLCreateInfo& InitAttribs, + const SwapChainDesc& SCDesc, + RenderDeviceGLImpl* pRenderDeviceGL, + DeviceContextGLImpl* pImmediateContextGL) : TSwapChainBase( pRefCounters, pRenderDeviceGL, pImmediateContextGL, SCDesc) { #if PLATFORM_WIN32 -- cgit v1.2.3 From 9c8f8d79c5cd62489b14127979e3cb0e2c08911f Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Wed, 6 Mar 2019 08:25:01 -0800 Subject: Reworked shader resource management in OpenGL --- Graphics/GraphicsEngineOpenGL/include/GLProgram.h | 5 +- .../include/GLProgramResources.h | 416 ++++++++---- .../GraphicsEngineOpenGL/include/ShaderGLImpl.h | 5 +- .../src/DeviceContextGLImpl.cpp | 68 +- Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp | 8 +- .../src/GLProgramResources.cpp | 726 +++++++++++++++------ .../src/PipelineStateGLImpl.cpp | 10 +- Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp | 4 +- .../src/ShaderResourceBindingGLImpl.cpp | 16 +- 9 files changed, 866 insertions(+), 392 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineOpenGL/include/GLProgram.h b/Graphics/GraphicsEngineOpenGL/include/GLProgram.h index dbc0c6c8..930e7aac 100644 --- a/Graphics/GraphicsEngineOpenGL/include/GLProgram.h +++ b/Graphics/GraphicsEngineOpenGL/include/GLProgram.h @@ -39,10 +39,7 @@ namespace Diligent void InitResources(RenderDeviceGLImpl* pDeviceGLImpl, SHADER_TYPE ShaderStage, - IObject& Owner, - const PipelineResourceLayoutDesc* pResourceLayout, - const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes); + IObject& Owner); void BindConstantResources(IResourceMapping* pResourceMapping, Uint32 Flags); diff --git a/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h b/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h index d75bb2a5..4a9b6efe 100644 --- a/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h +++ b/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h @@ -22,12 +22,16 @@ */ #pragma once + +#include + #include "GLObjectWrapper.h" #include "HashUtils.h" #include "ShaderBase.h" #include "SamplerGLImpl.h" #include "HashUtils.h" #include "ShaderResourceVariableBase.h" +#include "StringPool.h" #ifdef _DEBUG # define VERIFY_RESOURCE_BINDINGS @@ -39,18 +43,17 @@ namespace Diligent { public: GLProgramResources(){} + ~GLProgramResources(); GLProgramResources (GLProgramResources&& Program)noexcept; GLProgramResources (const GLProgramResources&) = delete; GLProgramResources& operator = (const GLProgramResources&) = delete; GLProgramResources& operator = ( GLProgramResources&&) = delete; - void LoadUniforms(class RenderDeviceGLImpl* pDeviceGLImpl, + void LoadUniforms(IObject& Owner, + class RenderDeviceGLImpl* pDeviceGLImpl, SHADER_TYPE ShaderStages, - GLuint GLProgram, - const PipelineResourceLayoutDesc* pResourceLayout, - const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes); + GLuint GLProgram); void Clone(class RenderDeviceGLImpl* pDeviceGLImpl, @@ -60,143 +63,223 @@ namespace Diligent const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes); - struct GLProgramVariableBase + struct GLProgramVariableBase : ShaderVariableBase { - GLProgramVariableBase(String _Name, - size_t _ArraySize, - SHADER_RESOURCE_VARIABLE_TYPE _VarType, - SHADER_RESOURCE_TYPE _ResourceType) : - Name ( std::move(_Name) ), - pResources (_ArraySize), - VarType (_VarType), - ResourceType(_ResourceType) +/* 0 */ // ShaderVariableBase +/* 16 */ const Char* Name; +/* 24 */ const SHADER_RESOURCE_VARIABLE_TYPE VariableType; +/* 25 */ const SHADER_RESOURCE_TYPE ResourceType; +/* 26 */ const Uint16 VariableIndex; +/* 28 */ Uint32 ArraySize; +/* 32 */ RefCntAutoPtr* const pResources; +/* 40 */ //End of data + + GLProgramVariableBase(IObject& _Owner, + const Char* _Name, + SHADER_RESOURCE_VARIABLE_TYPE _VariableType, + SHADER_RESOURCE_TYPE _ResourceType, + Uint16 _VariableIndex, + Uint32 _ArraySize, + RefCntAutoPtr* _pResources) : + ShaderVariableBase(_Owner), + Name (_Name), + ArraySize (_ArraySize), + VariableType (_VariableType), + VariableIndex (_VariableIndex), + ResourceType (_ResourceType), + pResources (_pResources) { VERIFY_EXPR(_ArraySize >= 1); } - bool IsCompatibleWith(const GLProgramVariableBase &Var)const + bool IsCompatibleWith(const GLProgramVariableBase& Var)const { - return VarType == Var.VarType && - pResources.size() == Var.pResources.size(); + return VariableType == Var.VariableType && + ResourceType == Var.ResourceType && + ArraySize == Var.ArraySize; } size_t GetHash()const { - return ComputeHash(static_cast(VarType), pResources.size()); + return ComputeHash(static_cast(VariableType), static_cast(ResourceType), ArraySize); + } + + virtual void Set(IDeviceObject* pObject)override final + { + VERIFY(pResources != nullptr, "This variable has no resource cache attached"); + pResources[0] = pObject; + } + + virtual void SetArray(IDeviceObject* const* ppObjects, Uint32 FirstElement, Uint32 NumElements)override final + { + VERIFY(pResources, "This variable has no resource cache attached"); + VERIFY(FirstElement + NumElements <= ArraySize, "Array indices are out of range"); + for (Uint32 i=0; i < NumElements; ++i) + pResources[FirstElement + i] = ppObjects[i]; + } + + virtual SHADER_RESOURCE_VARIABLE_TYPE GetType()const override final + { + return VariableType; + } + + virtual Uint32 GetArraySize()const override final + { + return ArraySize; + } + + virtual const Char* GetName()const override final + { + return Name; + } + + virtual Uint32 GetIndex()const override final + { + return VariableIndex; } ShaderResourceDesc GetResourceDesc()const { ShaderResourceDesc ResourceDesc; - ResourceDesc.Name = Name.c_str(); - ResourceDesc.ArraySize = static_cast(pResources.size()); + ResourceDesc.Name = Name; + ResourceDesc.ArraySize = ArraySize; ResourceDesc.Type = ResourceType; return ResourceDesc; } - - String Name; - std::vector< RefCntAutoPtr > pResources; - const SHADER_RESOURCE_VARIABLE_TYPE VarType; - const SHADER_RESOURCE_TYPE ResourceType; }; struct UniformBufferInfo : GLProgramVariableBase { - UniformBufferInfo(String _Name, - size_t _ArraySize, - SHADER_RESOURCE_VARIABLE_TYPE _VarType, - SHADER_RESOURCE_TYPE _ResourceType, - GLint _Index) : - GLProgramVariableBase(std::move(_Name), _ArraySize, _VarType, _ResourceType), - Index(_Index) + UniformBufferInfo (const UniformBufferInfo&) = delete; + UniformBufferInfo& operator= (const UniformBufferInfo&) = delete; + UniformBufferInfo ( UniformBufferInfo&&) = default; + UniformBufferInfo& operator= ( UniformBufferInfo&&) = default; + + UniformBufferInfo(IObject& _Owner, + const Char* _Name, + SHADER_RESOURCE_VARIABLE_TYPE _VariableType, + SHADER_RESOURCE_TYPE _ResourceType, + Uint16 _VariableIndex, + Uint32 _ArraySize, + RefCntAutoPtr* _pResources, + GLuint _UBIndex) : + GLProgramVariableBase(_Owner, _Name, _VariableType, _ResourceType, _VariableIndex, _ArraySize, _pResources), + UBIndex(_UBIndex) {} bool IsCompatibleWith(const UniformBufferInfo& UBI)const { - return Index == UBI.Index && + return UBIndex == UBI.UBIndex && GLProgramVariableBase::IsCompatibleWith(UBI); } size_t GetHash()const { - return ComputeHash(Index, GLProgramVariableBase::GetHash()); + return ComputeHash(UBIndex, GLProgramVariableBase::GetHash()); } - const GLuint Index; + const GLuint UBIndex; }; - std::vector& GetUniformBlocks(){ return m_UniformBlocks; } + static_assert( (sizeof(UniformBufferInfo) % sizeof(void*)) == 0, "sizeof(UniformBufferInfo) must be multiple of sizeof(void*)"); + struct SamplerInfo : GLProgramVariableBase { - SamplerInfo(String _Name, - size_t _ArraySize, - SHADER_RESOURCE_VARIABLE_TYPE _VarType, - SHADER_RESOURCE_TYPE _ResourceType, - GLint _Location, - GLenum _Type, - class SamplerGLImpl* _pStaticSampler) : - GLProgramVariableBase(std::move(_Name), _ArraySize, _VarType, _ResourceType), + SamplerInfo (const SamplerInfo&) = delete; + SamplerInfo& operator= (const SamplerInfo&) = delete; + SamplerInfo ( SamplerInfo&&) = default; + SamplerInfo& operator= ( SamplerInfo&&) = default; + + SamplerInfo(IObject& _Owner, + const Char* _Name, + SHADER_RESOURCE_VARIABLE_TYPE _VariableType, + SHADER_RESOURCE_TYPE _ResourceType, + Uint16 _VariableIndex, + Uint32 _ArraySize, + RefCntAutoPtr* _pResources, + GLint _Location, + GLenum _SamplerType, + class SamplerGLImpl* _pStaticSampler) : + GLProgramVariableBase(_Owner, _Name, _VariableType, _ResourceType, _VariableIndex, _ArraySize, _pResources), Location (_Location), - Type (_Type), + SamplerType (_SamplerType), pStaticSampler(_pStaticSampler) {} bool IsCompatibleWith(const SamplerInfo& SI)const { - return Location == SI.Location && - Type == SI.Type && + return Location == SI.Location && + pStaticSampler == SI.pStaticSampler && GLProgramVariableBase::IsCompatibleWith(SI); } size_t GetHash()const { - return ComputeHash(Location, Type, GLProgramVariableBase::GetHash()); + return ComputeHash(Location, SamplerType, GLProgramVariableBase::GetHash()); } const GLint Location; - const GLenum Type; + const GLenum SamplerType; RefCntAutoPtr pStaticSampler; }; - std::vector& GetSamplers(){ return m_Samplers; } - + static_assert( (sizeof(SamplerInfo) % sizeof(void*)) == 0, "sizeof(SamplerInfo) must be multiple of sizeof(void*)"); + + struct ImageInfo : GLProgramVariableBase { - ImageInfo(String _Name, - size_t _ArraySize, - SHADER_RESOURCE_VARIABLE_TYPE _VarType, - SHADER_RESOURCE_TYPE _ResourceType, - GLint _BindingPoint, - GLenum _Type) : - GLProgramVariableBase(std::move(_Name), _ArraySize, _VarType, _ResourceType), + ImageInfo (const ImageInfo&) = delete; + ImageInfo& operator= (const ImageInfo&) = delete; + ImageInfo ( ImageInfo&&) = default; + ImageInfo& operator= ( ImageInfo&&) = default; + + ImageInfo(IObject& _Owner, + const Char* _Name, + SHADER_RESOURCE_VARIABLE_TYPE _VariableType, + SHADER_RESOURCE_TYPE _ResourceType, + Uint16 _VariableIndex, + Uint32 _ArraySize, + RefCntAutoPtr* _pResources, + GLint _BindingPoint, + GLenum _ImageType) : + GLProgramVariableBase(_Owner, _Name, _VariableType, _ResourceType, _VariableIndex, _ArraySize, _pResources), BindingPoint(_BindingPoint), - Type (_Type) + ImageType (_ImageType) {} bool IsCompatibleWith(const ImageInfo& II)const { return BindingPoint == II.BindingPoint && - Type == II.Type && + ImageType == II.ImageType && GLProgramVariableBase::IsCompatibleWith(II); } size_t GetHash()const { - return ComputeHash(BindingPoint, Type, GLProgramVariableBase::GetHash()); + return ComputeHash(BindingPoint, ImageType, GLProgramVariableBase::GetHash()); } const GLint BindingPoint; - const GLenum Type; + const GLenum ImageType; }; - std::vector& GetImages(){ return m_Images; } + static_assert( (sizeof(ImageInfo) % sizeof(void*)) == 0, "sizeof(ImageInfo) must be multiple of sizeof(void*)"); + struct StorageBlockInfo : GLProgramVariableBase { - StorageBlockInfo(String _Name, - size_t _ArraySize, - SHADER_RESOURCE_VARIABLE_TYPE _VarType, - SHADER_RESOURCE_TYPE _ResourceType, - GLint _Binding) : - GLProgramVariableBase(std::move(_Name), _ArraySize, _VarType, _ResourceType), + StorageBlockInfo (const StorageBlockInfo&) = delete; + StorageBlockInfo& operator= (const StorageBlockInfo&) = delete; + StorageBlockInfo ( StorageBlockInfo&&) = default; + StorageBlockInfo& operator= ( StorageBlockInfo&&) = default; + + StorageBlockInfo(IObject& _Owner, + const Char* _Name, + SHADER_RESOURCE_VARIABLE_TYPE _VariableType, + SHADER_RESOURCE_TYPE _ResourceType, + Uint16 _VariableIndex, + Uint32 _ArraySize, + RefCntAutoPtr* _pResources, + GLint _Binding) : + GLProgramVariableBase(_Owner, _Name, _VariableType, _ResourceType, _VariableIndex, _ArraySize, _pResources), Binding(_Binding) {} @@ -213,99 +296,160 @@ namespace Diligent const GLint Binding; }; - std::vector& GetStorageBlocks(){ return m_StorageBlocks; } + static_assert( (sizeof(StorageBlockInfo) % sizeof(void*)) == 0, "sizeof(StorageBlockInfo) must be multiple of sizeof(void*)"); - struct CGLShaderVariable : ShaderVariableBase - { - CGLShaderVariable(IObject& Owner, GLProgramResources::GLProgramVariableBase& ProgVar, Uint32 _Index) : - ShaderVariableBase(Owner), - ProgramVar (ProgVar), - VariableIndex (_Index) - {} - - virtual void Set(IDeviceObject *pObject)override final - { - ProgramVar.pResources[0] = pObject; - } - - virtual void SetArray(IDeviceObject* const* ppObjects, Uint32 FirstElement, Uint32 NumElements)override final - { - for(Uint32 i=0; i < NumElements; ++i) - ProgramVar.pResources[FirstElement + i] = ppObjects[i]; - } + Uint32 GetNumUniformBuffers()const { return m_NumUniformBuffers; } + Uint32 GetNumSamplers() const { return m_NumSamplers; } + Uint32 GetNumImages() const { return m_NumImages; } + Uint32 GetNumStorageBlocks() const { return m_NumStorageBlocks; } - virtual SHADER_RESOURCE_VARIABLE_TYPE GetType()const override final - { - return ProgramVar.VarType; - } + UniformBufferInfo& GetUniformBuffer(Uint32 Index) + { + VERIFY(Index < m_NumUniformBuffers, "Uniform buffer index (", Index, ") is out of range"); + return m_UniformBuffers[Index]; + } - virtual Uint32 GetArraySize()const override final - { - return static_cast(ProgramVar.pResources.size()); - } + SamplerInfo& GetSampler(Uint32 Index) + { + VERIFY(Index < m_NumSamplers, "Sampler index (", Index, ") is out of range"); + return m_Samplers[Index]; + } - virtual const Char* GetName()const override final - { - return ProgramVar.Name.c_str(); - } + ImageInfo& GetImage(Uint32 Index) + { + VERIFY(Index < m_NumImages, "Image index (", Index, ") is out of range"); + return m_Images[Index]; + } - virtual Uint32 GetIndex()const override final - { - return VariableIndex; - } + StorageBlockInfo& GetStorageBlock(Uint32 Index) + { + VERIFY(Index < m_NumStorageBlocks, "Storage block index (", Index, ") is out of range"); + return m_StorageBlocks[Index]; + } - ShaderResourceDesc GetResourceDesc() const - { - return ProgramVar.GetResourceDesc(); - } - private: - GLProgramVariableBase& ProgramVar; - const Uint32 VariableIndex; - }; - void BindResources(IResourceMapping *pResourceMapping, Uint32 Flags); + const UniformBufferInfo& GetUniformBuffer(Uint32 Index)const + { + VERIFY(Index < m_NumUniformBuffers, "Uniform buffer index (", Index, ") is out of range"); + return m_UniformBuffers[Index]; + } -#ifdef VERIFY_RESOURCE_BINDINGS - void dbgVerifyResourceBindings(); -#endif + const SamplerInfo& GetSampler(Uint32 Index)const + { + VERIFY(Index < m_NumSamplers, "Sampler index (", Index, ") is out of range"); + return m_Samplers[Index]; + } - CGLShaderVariable* GetShaderVariable(const Char* Name); - CGLShaderVariable* GetShaderVariable(Uint32 Index) + const ImageInfo& GetImage(Uint32 Index)const { - return Index < m_VariablesByIndex.size() ? m_VariablesByIndex[Index] : nullptr; + VERIFY(Index < m_NumImages, "Image index (", Index, ") is out of range"); + return m_Images[Index]; } - const CGLShaderVariable* GetShaderVariable(Uint32 Index)const + + const StorageBlockInfo& GetStorageBlock(Uint32 Index)const { - return Index < m_VariablesByIndex.size() ? m_VariablesByIndex[Index] : nullptr; + VERIFY(Index < m_NumStorageBlocks, "Storage block index (", Index, ") is out of range"); + return m_StorageBlocks[Index]; } - const std::unordered_map& GetVariables(){return m_VariableHash;} - + Uint32 GetVariableCount()const { - return static_cast(m_VariableHash.size()); + return m_NumUniformBuffers + m_NumSamplers + m_NumImages + m_NumStorageBlocks; } + void BindResources(IResourceMapping* pResourceMapping, Uint32 Flags); + +#ifdef VERIFY_RESOURCE_BINDINGS + void dbgVerifyResourceBindings()const; +#endif + + GLProgramVariableBase* GetVariable(const Char* Name); + GLProgramVariableBase* GetVariable(Uint32 Index) + { + return const_cast(const_cast(this)->GetVariable(Index)); + } + const GLProgramVariableBase* GetVariable(Uint32 Index)const; + bool IsCompatibleWith(const GLProgramResources& Res)const; size_t GetHash()const; - void InitVariables(IObject &Owner); - SHADER_TYPE GetShaderStages() const {return m_ShaderStages;} + template + void ProcessConstResources(THandleUB HandleUB, + THandleSampler HandleSampler, + THandleImg HandleImg, + THandleSB HandleSB)const + { + for (Uint32 ub=0; ub < m_NumUniformBuffers; ++ub) + HandleUB(GetUniformBuffer(ub)); + + for (Uint32 s=0; s < m_NumSamplers; ++s) + HandleSampler(GetSampler(s)); + + for (Uint32 img=0; img < m_NumImages; ++img) + HandleImg(GetImage(img)); + + for (Uint32 sb=0; sb < m_NumStorageBlocks; ++sb) + HandleSB(GetStorageBlock(sb)); + } private: + void AllocateResources(IObject& Owner, + std::vector& UniformBlocks, + std::vector& Samplers, + std::vector& Images, + std::vector& StorageBlocks, + bool InitializeResourceCache); + + template + void ProcessResources(THandleUB HandleUB, + THandleSampler HandleSampler, + THandleImg HandleImg, + THandleSB HandleSB) + { + for (Uint32 ub=0; ub < m_NumUniformBuffers; ++ub) + HandleUB(GetUniformBuffer(ub)); + + for (Uint32 s=0; s < m_NumSamplers; ++s) + HandleSampler(GetSampler(s)); + + for (Uint32 img=0; img < m_NumImages; ++img) + HandleImg(GetImage(img)); + + for (Uint32 sb=0; sb < m_NumStorageBlocks; ++sb) + HandleSB(GetStorageBlock(sb)); + } + // There could be more than one stage is using non-separable programs - SHADER_TYPE m_ShaderStages = SHADER_TYPE_UNKNOWN; - - std::vector m_UniformBlocks; - std::vector m_Samplers; - std::vector m_Images; - std::vector m_StorageBlocks; - - /// Hash map to look up shader variables by name. - std::unordered_map m_VariableHash; - std::vector m_VariablesByIndex; + SHADER_TYPE m_ShaderStages = SHADER_TYPE_UNKNOWN; + + // Memory layout: + // + // | Uniform buffers | Samplers | Images | Storage Blocks | Resource Cache | String Pool Data | + // | + // end of string pool data may not be aligned + + UniformBufferInfo* m_UniformBuffers = nullptr; + SamplerInfo* m_Samplers = nullptr; + ImageInfo* m_Images = nullptr; + StorageBlockInfo* m_StorageBlocks = nullptr; + RefCntAutoPtr* m_ResourceCache = nullptr; + + StringPool m_StringPool; + + Uint32 m_NumUniformBuffers = 0; + Uint32 m_NumSamplers = 0; + Uint32 m_NumImages = 0; + Uint32 m_NumStorageBlocks = 0; + // When adding new member DO NOT FORGET TO UPDATE GLProgramResources( GLProgramResources&& ProgramResources )!!! }; } diff --git a/Graphics/GraphicsEngineOpenGL/include/ShaderGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/ShaderGLImpl.h index d579ef46..a9170c86 100644 --- a/Graphics/GraphicsEngineOpenGL/include/ShaderGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/ShaderGLImpl.h @@ -73,12 +73,11 @@ public: ShaderGLImpl( IReferenceCounters *pRefCounters, RenderDeviceGLImpl *pDeviceGL, const ShaderCreateInfo &ShaderCreateInfo, bool bIsDeviceInternal = false ); ~ShaderGLImpl(); + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final; + virtual Uint32 GetResourceCount()const override final; virtual ShaderResourceDesc GetResource(Uint32 Index)const override final; - virtual void QueryInterface( const INTERFACE_ID &IID, IObject **ppInterface )override final; - - GLProgram& GetGlProgram(){return m_GlProgObj;} private: diff --git a/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp index cddce1ea..619c0b55 100644 --- a/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp @@ -389,7 +389,7 @@ namespace Diligent #endif // When program pipelines are not supported, all resources are dynamic resources - for (int BindDynamicResources = (ProgramPipelineSupported ? 0 : 1); BindDynamicResources < (pShaderResBindingGL ? 2 : 1); ++BindDynamicResources) + for (int BindDynamicResources = 0; BindDynamicResources < (pShaderResBindingGL ? 2 : 1); ++BindDynamicResources) { GLProgramResources& ProgResources = BindDynamicResources ? *pDynamicResources : m_pPipelineState->GetStaticResources(ProgNum); @@ -398,12 +398,12 @@ namespace Diligent #endif GLuint GLProgID = GLProgramObj; - auto& UniformBlocks = ProgResources.GetUniformBlocks(); - for (auto it = UniformBlocks.begin(); it != UniformBlocks.end(); ++it) + for (Uint32 ub = 0; ub < ProgResources.GetNumUniformBuffers(); ++ub) { - for(Uint32 ArrInd = 0; ArrInd < it->pResources.size(); ++ArrInd) + auto& UB = ProgResources.GetUniformBuffer(ub); + for(Uint32 ArrInd = 0; ArrInd < UB.ArraySize; ++ArrInd) { - auto& Resource = it->pResources[ArrInd]; + auto& Resource = UB.pResources[ArrInd]; if (Resource) { auto* pBufferOGL = Resource.RawPtr(); @@ -416,7 +416,7 @@ namespace Diligent CHECK_GL_ERROR("Failed to bind uniform buffer"); //glBindBufferRange(GL_UNIFORM_BUFFER, it->Index, pBufferOGL->m_GlBuffer, 0, pBufferOGL->GetDesc().uiSizeInBytes); - glUniformBlockBinding(GLProgID, it->Index + ArrInd, UniformBuffBindPoint); + glUniformBlockBinding(GLProgID, UB.UBIndex + ArrInd, UniformBuffBindPoint); CHECK_GL_ERROR("glUniformBlockBinding() failed"); ++UniformBuffBindPoint; @@ -425,28 +425,28 @@ namespace Diligent { #define LOG_MISSING_BINDING(VarType, Res, ArrInd)\ do{ \ - if(Res->pResources.size()>1) \ - LOG_ERROR_MESSAGE( "No ", VarType, " is bound to '", Res->Name, '[', ArrInd, "]' variable in shader '", pShaderGL->GetDesc().Name, "'" );\ + if(Res.ArraySize > 1) \ + LOG_ERROR_MESSAGE( "No ", VarType, " is bound to '", Res.Name, '[', ArrInd, "]' variable in shader '", pShaderGL->GetDesc().Name, "'" );\ else \ - LOG_ERROR_MESSAGE( "No ", VarType, " is bound to '", Res->Name, "' variable in shader '", pShaderGL->GetDesc().Name, "'" );\ + LOG_ERROR_MESSAGE( "No ", VarType, " is bound to '", Res.Name, "' variable in shader '", pShaderGL->GetDesc().Name, "'" );\ }while(false) - LOG_MISSING_BINDING("uniform buffer", it, ArrInd); + LOG_MISSING_BINDING("uniform buffer", UB, ArrInd); } } } - auto& Samplers = ProgResources.GetSamplers(); - for (auto it = Samplers.begin(); it != Samplers.end(); ++it) + for (Uint32 sam = 0; sam < ProgResources.GetNumSamplers(); ++sam) { - for (Uint32 ArrInd = 0; ArrInd < it->pResources.size(); ++ArrInd) + auto& Sam = ProgResources.GetSampler(sam); + for (Uint32 ArrInd = 0; ArrInd < Sam.ArraySize; ++ArrInd) { - auto& Resource = it->pResources[ArrInd]; + auto& Resource = Sam.pResources[ArrInd]; if (Resource) { - if (it->Type == GL_SAMPLER_BUFFER || - it->Type == GL_INT_SAMPLER_BUFFER || - it->Type == GL_UNSIGNED_INT_SAMPLER_BUFFER) + if (Sam.SamplerType == GL_SAMPLER_BUFFER || + Sam.SamplerType == GL_INT_SAMPLER_BUFFER || + Sam.SamplerType == GL_UNSIGNED_INT_SAMPLER_BUFFER) { auto* pBufViewOGL = Resource.RawPtr(); auto* pBuffer = pBufViewOGL->GetBuffer(); @@ -473,9 +473,9 @@ namespace Diligent m_ContextState); SamplerGLImpl* pSamplerGL = nullptr; - if (it->pStaticSampler) + if (Sam.pStaticSampler) { - pSamplerGL = it->pStaticSampler; + pSamplerGL = Sam.pStaticSampler; } else { @@ -494,12 +494,12 @@ namespace Diligent if (ProgramPipelineSupported) { // glProgramUniform1i does not require program to be bound to the pipeline - glProgramUniform1i( GLProgramObj, it->Location + ArrInd, TextureIndex ); + glProgramUniform1i( GLProgramObj, Sam.Location + ArrInd, TextureIndex ); } else { // glUniform1i requires program to be bound to the pipeline - glUniform1i(it->Location + ArrInd, TextureIndex); + glUniform1i(Sam.Location + ArrInd, TextureIndex); } CHECK_GL_ERROR("Failed to bind sampler uniform to texture slot"); @@ -507,18 +507,18 @@ namespace Diligent } else { - LOG_MISSING_BINDING("texture sampler", it, ArrInd); + LOG_MISSING_BINDING("texture sampler", Sam, ArrInd); } } } #if GL_ARB_shader_image_load_store - auto& Images = ProgResources.GetImages(); - for (auto it = Images.begin(); it != Images.end(); ++it) + for (Uint32 img = 0; img < ProgResources.GetNumImages(); ++img) { - for (Uint32 ArrInd = 0; ArrInd < it->pResources.size(); ++ArrInd) + auto& Img = ProgResources.GetImage(img); + for (Uint32 ArrInd = 0; ArrInd < Img.ArraySize; ++ArrInd) { - auto& Resource = it->pResources[ArrInd]; + auto& Resource = Img.pResources[ArrInd]; if (Resource) { auto* pTexViewOGL = Resource.RawPtr(); @@ -566,23 +566,23 @@ namespace Diligent // That means that if an integer texture is being bound, its // GL_TEXTURE_MIN_FILTER and GL_TEXTURE_MAG_FILTER must be NEAREST, // otherwise it will be incomplete - m_ContextState.BindImage(it->BindingPoint + ArrInd, pTexViewOGL, ViewDesc.MostDetailedMip, Layered, Layer, GLAccess, GlTexFormat); + m_ContextState.BindImage(Img.BindingPoint + ArrInd, pTexViewOGL, ViewDesc.MostDetailedMip, Layered, Layer, GLAccess, GlTexFormat); } else { - LOG_MISSING_BINDING("image", it, ArrInd); + LOG_MISSING_BINDING("image", Img, ArrInd); } } } #endif #if GL_ARB_shader_storage_buffer_object - auto& StorageBlocks = ProgResources.GetStorageBlocks(); - for (auto it = StorageBlocks.begin(); it != StorageBlocks.end(); ++it) + for (Uint32 sb=0; sb < ProgResources.GetNumStorageBlocks(); ++sb) { - for (Uint32 ArrInd = 0; ArrInd < it->pResources.size(); ++ArrInd) + auto& SB = ProgResources.GetStorageBlock(sb); + for (Uint32 ArrInd = 0; ArrInd < SB.ArraySize; ++ArrInd) { - auto& Resource = it->pResources[ArrInd]; + auto& Resource = SB.pResources[ArrInd]; if (Resource) { auto* pBufferViewOGL = Resource.RawPtr(); @@ -595,7 +595,7 @@ namespace Diligent // will reflect writes prior to the barrier m_ContextState); - glBindBufferRange(GL_SHADER_STORAGE_BUFFER, it->Binding + ArrInd, pBufferOGL->m_GlBuffer, ViewDesc.ByteOffset, ViewDesc.ByteWidth); + glBindBufferRange(GL_SHADER_STORAGE_BUFFER, SB.Binding + ArrInd, pBufferOGL->m_GlBuffer, ViewDesc.ByteOffset, ViewDesc.ByteWidth); CHECK_GL_ERROR("Failed to bind shader storage buffer"); if (ViewDesc.ViewType == BUFFER_VIEW_UNORDERED_ACCESS) @@ -603,7 +603,7 @@ namespace Diligent } else { - LOG_MISSING_BINDING("shader storage block", it, ArrInd); + LOG_MISSING_BINDING("shader storage block", SB, ArrInd); } } } diff --git a/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp b/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp index f4650151..a49669ea 100644 --- a/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/GLProgram.cpp @@ -39,13 +39,9 @@ namespace Diligent void GLProgram::InitResources(RenderDeviceGLImpl* pDeviceGLImpl, SHADER_TYPE ShaderStage, - IObject& Owner, - const PipelineResourceLayoutDesc* pResourceLayout, - const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes) + IObject& Owner) { GLuint GLProgram = static_cast(*this); - m_AllResources.LoadUniforms(pDeviceGLImpl, ShaderStage, GLProgram, pResourceLayout, AllowedVarTypes, NumAllowedTypes); - m_AllResources.InitVariables(Owner); + m_AllResources.LoadUniforms(Owner, pDeviceGLImpl, ShaderStage, GLProgram); } } diff --git a/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp b/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp index 42dbf43f..21a2ac5d 100644 --- a/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/GLProgramResources.cpp @@ -22,20 +22,37 @@ */ #include "pch.h" +#include #include "GLProgramResources.h" #include "RenderDeviceGLImpl.h" #include "ShaderResourceBindingBase.h" +#include "Align.h" namespace Diligent { - GLProgramResources::GLProgramResources( GLProgramResources&& Program )noexcept : - m_UniformBlocks (std::move(Program.m_UniformBlocks)), - m_Samplers (std::move(Program.m_Samplers) ), - m_Images (std::move(Program.m_Images) ), - m_StorageBlocks (std::move(Program.m_StorageBlocks)), - m_VariableHash (std::move(Program.m_VariableHash) ), - m_VariablesByIndex(std::move(Program.m_VariablesByIndex) ) + GLProgramResources::GLProgramResources(GLProgramResources&& Program)noexcept : + m_ShaderStages (Program.m_ShaderStages), + m_UniformBuffers (Program.m_UniformBuffers), + m_Samplers (Program.m_Samplers), + m_Images (Program.m_Images), + m_StorageBlocks (Program.m_StorageBlocks), + m_ResourceCache (Program.m_ResourceCache), + m_StringPool (std::move(Program.m_StringPool)), + m_NumUniformBuffers(Program.m_NumUniformBuffers), + m_NumSamplers (Program.m_NumSamplers), + m_NumImages (Program.m_NumImages), + m_NumStorageBlocks (Program.m_NumStorageBlocks) { + Program.m_UniformBuffers = nullptr; + Program.m_Samplers = nullptr; + Program.m_Images = nullptr; + Program.m_StorageBlocks = nullptr; + Program.m_ResourceCache = nullptr; + + Program.m_NumUniformBuffers = 0; + Program.m_NumSamplers = 0; + Program.m_NumImages = 0; + Program.m_NumStorageBlocks = 0; } inline void RemoveArrayBrackets(char *Str) @@ -45,17 +62,237 @@ namespace Diligent *OpenBacketPtr = 0; } - void GLProgramResources::LoadUniforms(RenderDeviceGLImpl* pDeviceGLImpl, - SHADER_TYPE ShaderStages, - GLuint GLProgram, - const PipelineResourceLayoutDesc* pResourceLayout, - const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, - Uint32 NumAllowedTypes) + void GLProgramResources::AllocateResources(IObject& Owner, + std::vector& UniformBlocks, + std::vector& Samplers, + std::vector& Images, + std::vector& StorageBlocks, + bool InitializeResourceCache) { + VERIFY(m_UniformBuffers == nullptr, "Resources have already been allocated!"); + + m_NumUniformBuffers = static_cast(UniformBlocks.size()); + m_NumSamplers = static_cast(Samplers.size()); + m_NumImages = static_cast(Images.size()); + m_NumStorageBlocks = static_cast(StorageBlocks.size()); + + size_t StringPoolDataSize = 0; + size_t ResourceCacheSize = 0; + for (const auto& ub : UniformBlocks) + { + StringPoolDataSize += strlen(ub.Name) + 1; + ResourceCacheSize += ub.ArraySize; + } + + for (const auto& sam : Samplers) + { + StringPoolDataSize += strlen(sam.Name) + 1; + ResourceCacheSize += sam.ArraySize; + } + + for (const auto& img : Images) + { + StringPoolDataSize += strlen(img.Name) + 1; + ResourceCacheSize += img.ArraySize; + } + + for (const auto& sb : StorageBlocks) + { + StringPoolDataSize += strlen(sb.Name) + 1; + ResourceCacheSize += sb.ArraySize; + } + + auto AlignedStringPoolDataSize = Align(StringPoolDataSize, sizeof(void*)); + + size_t TotalMemorySize = + m_NumUniformBuffers * sizeof(UniformBufferInfo) + + m_NumSamplers * sizeof(SamplerInfo) + + m_NumImages * sizeof(ImageInfo) + + m_NumStorageBlocks * sizeof(StorageBlockInfo); + + if (TotalMemorySize == 0) + { + m_UniformBuffers = nullptr; + m_Samplers = nullptr; + m_Images = nullptr; + m_StorageBlocks = nullptr; + m_ResourceCache = nullptr; + + m_NumUniformBuffers = 0; + m_NumSamplers = 0; + m_NumImages = 0; + m_NumStorageBlocks = 0; + + return; + } + + if (InitializeResourceCache) + TotalMemorySize += ResourceCacheSize * sizeof(RefCntAutoPtr); + + TotalMemorySize += AlignedStringPoolDataSize * sizeof(Char); + + auto& MemAllocator = GetRawAllocator(); + void* RawMemory = ALLOCATE(MemAllocator, "Memory buffer for GLProgramResources", TotalMemorySize); + + m_UniformBuffers = reinterpret_cast(RawMemory); + m_Samplers = reinterpret_cast (m_UniformBuffers + m_NumUniformBuffers); + m_Images = reinterpret_cast (m_Samplers + m_NumSamplers); + m_StorageBlocks = reinterpret_cast(m_Images + m_NumImages); + void* EndOfResourceData = m_StorageBlocks + m_NumStorageBlocks; + Char* StringPoolData = nullptr; + if (InitializeResourceCache) + { + m_ResourceCache = reinterpret_cast*>(EndOfResourceData); + StringPoolData = reinterpret_cast(m_ResourceCache + ResourceCacheSize); + for (Uint32 res=0; res < ResourceCacheSize; ++res) + new (m_ResourceCache+res) RefCntAutoPtr{}; + } + else + { + m_ResourceCache = nullptr; + StringPoolData = reinterpret_cast(EndOfResourceData); + } + + m_StringPool.AssignMemory(StringPoolData, StringPoolDataSize); + + Uint16 VariableIndex = 0; + auto* pCurrResource = m_ResourceCache; + for (Uint32 ub=0; ub < m_NumUniformBuffers; ++ub) + { + auto& SrcUB = UniformBlocks[ub]; + new (m_UniformBuffers + ub) UniformBufferInfo + { + Owner, + m_StringPool.CopyString(SrcUB.Name), + SrcUB.VariableType, + SrcUB.ResourceType, + VariableIndex++, + SrcUB.ArraySize, + pCurrResource, + SrcUB.UBIndex + }; + if (pCurrResource != nullptr) + pCurrResource += SrcUB.ArraySize; + } + + for (Uint32 s=0; s < m_NumSamplers; ++s) + { + auto& SrcSam = Samplers[s]; + new (m_Samplers + s) SamplerInfo + { + Owner, + m_StringPool.CopyString(SrcSam.Name), + SrcSam.VariableType, + SrcSam.ResourceType, + VariableIndex++, + SrcSam.ArraySize, + pCurrResource, + SrcSam.Location, + SrcSam.SamplerType, + SrcSam.pStaticSampler + }; + if (pCurrResource != nullptr) + pCurrResource += SrcSam.ArraySize; + } + + for (Uint32 img=0; img < m_NumImages; ++img) + { + auto& SrcImg = Images[img]; + new (m_Images + img) ImageInfo + { + Owner, + m_StringPool.CopyString(SrcImg.Name), + SrcImg.VariableType, + SrcImg.ResourceType, + VariableIndex++, + SrcImg.ArraySize, + pCurrResource, + SrcImg.BindingPoint, + SrcImg.ImageType + }; + if (pCurrResource != nullptr) + pCurrResource += SrcImg.ArraySize; + } + + for (Uint32 sb=0; sb < m_NumStorageBlocks; ++sb) + { + auto& SrcSB = StorageBlocks[sb]; + new (m_StorageBlocks + sb) StorageBlockInfo + { + Owner, + m_StringPool.CopyString(SrcSB.Name), + SrcSB.VariableType, + SrcSB.ResourceType, + VariableIndex++, + SrcSB.ArraySize, + pCurrResource, + SrcSB.Binding + }; + + if (pCurrResource != nullptr) + pCurrResource += SrcSB.ArraySize; + } + + VERIFY_EXPR(VariableIndex == GetVariableCount()); + VERIFY_EXPR(m_StringPool.GetRemainingSize() == 0); + VERIFY_EXPR(pCurrResource == nullptr || static_cast(pCurrResource - m_ResourceCache) == ResourceCacheSize); + } + + GLProgramResources::~GLProgramResources() + { + Uint32 ResourceCacheSize = 0; + ProcessResources( + [&](UniformBufferInfo& UB) + { + ResourceCacheSize += UB.ArraySize; + UB.~UniformBufferInfo(); + }, + [&](SamplerInfo& Sam) + { + ResourceCacheSize += Sam.ArraySize; + Sam.~SamplerInfo(); + }, + [&](ImageInfo& Img) + { + ResourceCacheSize += Img.ArraySize; + Img.~ImageInfo(); + }, + [&](StorageBlockInfo& SB) + { + ResourceCacheSize += SB.ArraySize; + SB.~StorageBlockInfo(); + } + ); + + if (m_ResourceCache != nullptr) + { + for (Uint32 res=0; res < ResourceCacheSize; ++res) + m_ResourceCache[res].~RefCntAutoPtr(); + } + + void* RawMemory = m_UniformBuffers; + if (RawMemory != nullptr) + { + auto& MemAllocator = GetRawAllocator(); + MemAllocator.Free(RawMemory); + } + } + + + void GLProgramResources::LoadUniforms(IObject& Owner, + RenderDeviceGLImpl* pDeviceGLImpl, + SHADER_TYPE ShaderStages, + GLuint GLProgram) + { + std::vector UniformBlocks; + std::vector Samplers; + std::vector Images; + std::vector StorageBlocks; + std::unordered_set NamesPool; + VERIFY(GLProgram != 0, "Null GL program"); m_ShaderStages = ShaderStages; - const Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); GLint numActiveUniforms = 0; glGetProgramiv( GLProgram, GL_ACTIVE_UNIFORMS, &numActiveUniforms ); @@ -179,23 +416,19 @@ namespace Diligent // The latter is only available in GL 4.4 and GLES 3.1 RemoveArrayBrackets(Name.data()); - SHADER_RESOURCE_VARIABLE_TYPE VarType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC; - - RefCntAutoPtr pStaticSampler; - if (pResourceLayout != nullptr) - { - VarType = GetShaderVariableType(ShaderStages, Name.data(), *pResourceLayout); - for (Uint32 s = 0; s < pResourceLayout->NumStaticSamplers; ++s) - { - const auto& StSam = pResourceLayout->StaticSamplers[s]; - if (strcmp(Name.data(), StSam.SamplerOrTextureName) == 0) - { - pDeviceGLImpl->CreateSampler(StSam.Desc, reinterpret_cast(static_cast(&pStaticSampler)) ); - break; - } - } - } - m_Samplers.emplace_back( Name.data(), size, VarType, SHADER_RESOURCE_TYPE_TEXTURE_SRV, UniformLocation, dataType, pStaticSampler ); + + Samplers.emplace_back( + Owner, + NamesPool.emplace(Name.data()).first->c_str(), + SHADER_RESOURCE_VARIABLE_TYPE_STATIC, + SHADER_RESOURCE_TYPE_TEXTURE_SRV, + Uint16{0xFFFF}, // Variable index is assigned by AllocateResources + static_cast(size), + nullptr, // pResources + UniformLocation, + dataType, + nullptr + ); break; } @@ -243,10 +476,17 @@ namespace Diligent VERIFY( BindingPoint >= 0, "Incorrect binding point" ); RemoveArrayBrackets(Name.data()); - SHADER_RESOURCE_VARIABLE_TYPE VarType = (pResourceLayout != nullptr) ? - GetShaderVariableType(ShaderStages, Name.data(), *pResourceLayout) : - SHADER_RESOURCE_VARIABLE_TYPE_STATIC; - m_Images.emplace_back( Name.data(), size, VarType, SHADER_RESOURCE_TYPE_TEXTURE_UAV, BindingPoint, dataType ); + + Images.emplace_back( + Owner, + NamesPool.emplace(Name.data()).first->c_str(), + SHADER_RESOURCE_VARIABLE_TYPE_STATIC, + SHADER_RESOURCE_TYPE_TEXTURE_UAV, + Uint16{0xFFFF}, // Variable index is assigned by AllocateResources + static_cast(size), + nullptr, // pResources + BindingPoint, + dataType ); break; } #endif @@ -276,37 +516,42 @@ namespace Diligent GLint ArraySize = 1; auto* OpenBacketPtr = strchr(Name.data(), '['); - if(OpenBacketPtr != nullptr) + if (OpenBacketPtr != nullptr) { auto Ind = atoi(OpenBacketPtr+1); ArraySize = std::max(ArraySize, Ind+1); *OpenBacketPtr = 0; - if (m_UniformBlocks.size() > 0) + if (UniformBlocks.size() > 0) { // Look at previous uniform block to check if it is the same array - auto &LastBlock = m_UniformBlocks.back(); - if (LastBlock.Name.compare(Name.data()) == 0) + auto& LastBlock = UniformBlocks.back(); + if ( strcmp(LastBlock.Name, Name.data()) == 0) { - ArraySize = std::max(ArraySize, static_cast(LastBlock.pResources.size())); - VERIFY(UniformBlockIndex == LastBlock.Index + Ind, "Uniform block indices are expected to be continuous"); - LastBlock.pResources.resize(ArraySize); + ArraySize = std::max(ArraySize, static_cast(LastBlock.ArraySize)); + VERIFY(UniformBlockIndex == LastBlock.UBIndex + Ind, "Uniform block indices are expected to be continuous"); + LastBlock.ArraySize = ArraySize; continue; } else { #ifdef _DEBUG - for(const auto &ub : m_UniformBlocks) - VERIFY(ub.Name.compare(Name.data()) != 0, "Uniform block with the name \"", ub.Name, "\" has already been enumerated"); + for(const auto& ub : UniformBlocks) + VERIFY( strcmp(ub.Name, Name.data()) != 0, "Uniform block with the name \"", ub.Name, "\" has already been enumerated"); #endif } } } - - SHADER_RESOURCE_VARIABLE_TYPE VarType = (pResourceLayout != nullptr) ? - GetShaderVariableType(ShaderStages, Name.data(), *pResourceLayout) : - SHADER_RESOURCE_VARIABLE_TYPE_STATIC; - m_UniformBlocks.emplace_back( Name.data(), ArraySize, VarType, SHADER_RESOURCE_TYPE_CONSTANT_BUFFER, UniformBlockIndex ); + UniformBlocks.emplace_back( + Owner, + NamesPool.emplace(Name.data()).first->c_str(), + SHADER_RESOURCE_VARIABLE_TYPE_STATIC, + SHADER_RESOURCE_TYPE_CONSTANT_BUFFER, + Uint16{0xFFFF}, // Variable index is assigned by AllocateResources + static_cast(ArraySize), + nullptr, // pResources + UniformBlockIndex + ); } #if GL_ARB_shader_storage_buffer_object @@ -332,33 +577,40 @@ namespace Diligent auto Ind = atoi(OpenBacketPtr+1); ArraySize = std::max(ArraySize, Ind+1); *OpenBacketPtr = 0; - if (m_StorageBlocks.size() > 0) + if (StorageBlocks.size() > 0) { // Look at previous storage block to check if it is the same array - auto &LastBlock = m_StorageBlocks.back(); - if (LastBlock.Name.compare(Name.data()) == 0) + auto& LastBlock = StorageBlocks.back(); + if ( strcmp(LastBlock.Name, Name.data()) == 0) { - ArraySize = std::max(ArraySize, static_cast(LastBlock.pResources.size())); + ArraySize = std::max(ArraySize, static_cast(LastBlock.ArraySize)); VERIFY(Binding == LastBlock.Binding + Ind, "Storage block bindings are expected to be continuous"); - LastBlock.pResources.resize(ArraySize); + LastBlock.ArraySize = ArraySize; continue; } else { #ifdef _DEBUG - for(const auto &sb : m_StorageBlocks) - VERIFY(sb.Name.compare(Name.data()) != 0, "Storage block with the name \"", sb.Name, "\" has already been enumerated"); + for(const auto& sb : StorageBlocks) + VERIFY( strcmp(sb.Name, Name.data()) != 0, "Storage block with the name \"", sb.Name, "\" has already been enumerated"); #endif } } } - SHADER_RESOURCE_VARIABLE_TYPE VarType = (pResourceLayout != nullptr) ? - GetShaderVariableType(ShaderStages, Name.data(), *pResourceLayout) : - SHADER_RESOURCE_VARIABLE_TYPE_STATIC; - m_StorageBlocks.emplace_back( Name.data(), ArraySize, VarType, SHADER_RESOURCE_TYPE_BUFFER_UAV, Binding ); + StorageBlocks.emplace_back( + Owner, + NamesPool.emplace(Name.data()).first->c_str(), + SHADER_RESOURCE_VARIABLE_TYPE_STATIC, + SHADER_RESOURCE_TYPE_BUFFER_UAV, + Uint16{0xFFFF}, // Variable index is assigned by AllocateResources + static_cast(ArraySize), + nullptr, // pResources + Binding + ); } #endif + AllocateResources(Owner, UniformBlocks, Samplers, Images, StorageBlocks, false); } @@ -369,129 +621,200 @@ namespace Diligent const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes) { + std::vector UniformBlocks; + std::vector Samplers; + std::vector Images; + std::vector StorageBlocks; + m_ShaderStages = SrcResources.m_ShaderStages; const Uint32 AllowedTypeBits = GetAllowedTypeBits(AllowedVarTypes, NumAllowedTypes); - for (auto& ub : SrcResources.m_UniformBlocks) + for (Uint32 ub=0; ub < SrcResources.GetNumUniformBuffers(); ++ub) { - auto VarType = GetShaderVariableType(m_ShaderStages, ub.Name.data(), ResourceLayout); - if (IsAllowedType(VarType, VarType)) + const auto& SrcUB = SrcResources.GetUniformBuffer(ub); + auto VarType = GetShaderVariableType(m_ShaderStages, SrcUB.Name, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) { - m_UniformBlocks.emplace_back(ub.Name, ub.pResources.size(), ub.VarType, ub.ResourceType, ub.Index); + UniformBlocks.emplace_back( + Owner, + SrcUB.Name, + VarType, + SrcUB.ResourceType, + Uint16{0xFFFF}, // Variable index is assigned by AllocateResources + SrcUB.ArraySize, + nullptr, // pResources + SrcUB.UBIndex + ); } } - for (auto& sam : SrcResources.m_Samplers) + for (Uint32 sam = 0; sam < SrcResources.GetNumSamplers(); ++sam) { - auto VarType = GetShaderVariableType(m_ShaderStages, sam.Name.data(), ResourceLayout); - if (IsAllowedType(VarType, VarType)) + const auto& SrcSam = SrcResources.GetSampler(sam); + auto VarType = GetShaderVariableType(m_ShaderStages, SrcSam.Name, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) { RefCntAutoPtr pStaticSampler; for (Uint32 s = 0; s < ResourceLayout.NumStaticSamplers; ++s) { const auto& StSam = ResourceLayout.StaticSamplers[s]; - if (strcmp(sam.Name.data(), StSam.SamplerOrTextureName) == 0) + if (strcmp(SrcSam.Name, StSam.SamplerOrTextureName) == 0) { pDeviceGLImpl->CreateSampler(StSam.Desc, &pStaticSampler); break; } } - m_Samplers.emplace_back(sam.Name, sam.pResources.size(), sam.VarType, sam.ResourceType, sam.Location, sam.Type, pStaticSampler.RawPtr()); + Samplers.emplace_back( + Owner, + SrcSam.Name, + VarType, + SrcSam.ResourceType, + Uint16{0xFFFF}, // Variable index is assigned by AllocateResources + SrcSam.ArraySize, + nullptr, // pResources + SrcSam.Location, + SrcSam.SamplerType, + pStaticSampler.RawPtr() + ); } } - for (auto& img : SrcResources.m_Images) + for (Uint32 img = 0; img < SrcResources.GetNumImages(); ++img) { - auto VarType = GetShaderVariableType(m_ShaderStages, img.Name.data(), ResourceLayout); - if (IsAllowedType(VarType, VarType)) + const auto& SrcImg = SrcResources.GetImage(img); + auto VarType = GetShaderVariableType(m_ShaderStages, SrcImg.Name, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) { - m_Images.emplace_back(img.Name, img.pResources.size(), img.VarType, img.ResourceType, img.BindingPoint, img.Type); + Images.emplace_back( + Owner, + SrcImg.Name, + VarType, + SrcImg.ResourceType, + Uint16{0xFFFF}, // Variable index is assigned by AllocateResources + SrcImg.ArraySize, + nullptr, // pResources + SrcImg.BindingPoint, + SrcImg.ImageType + ); } } - for (auto& sb : SrcResources.m_StorageBlocks) + for (Uint32 sb = 0; sb < SrcResources.GetNumStorageBlocks(); ++sb) { - auto VarType = GetShaderVariableType(m_ShaderStages, sb.Name.data(), ResourceLayout); - if (IsAllowedType(VarType, VarType)) + const auto& SrcSB = SrcResources.GetStorageBlock(sb); + auto VarType = GetShaderVariableType(m_ShaderStages, SrcSB.Name, ResourceLayout); + if (IsAllowedType(VarType, AllowedTypeBits)) { - m_StorageBlocks.emplace_back(sb.Name, sb.pResources.size(), sb.VarType, sb.ResourceType, sb.Binding); + StorageBlocks.emplace_back( + Owner, + SrcSB.Name, + VarType, + SrcSB.ResourceType, + Uint16{0xFFFF}, // Variable index is assigned by AllocateResources + SrcSB.ArraySize, + nullptr, // pResources + SrcSB.Binding + ); } } - InitVariables(Owner); + AllocateResources(Owner, UniformBlocks, Samplers, Images, StorageBlocks, true); } - void GLProgramResources::InitVariables(IObject& Owner) - { - // After all program resources are loaded, we can populate shader variable hash map. - // The map contains raw pointers, but none of the arrays will ever change. - auto TotalVars = m_UniformBlocks.size() + m_Samplers.size() + m_Images.size() + m_StorageBlocks.size(); - m_VariablesByIndex.reserve(TotalVars); - m_VariableHash.reserve(TotalVars); -#define STORE_SHADER_VARIABLES(ResArr)\ - { \ - for( auto& ProgVar : ResArr) \ - { \ - /* HashMapStringKey will make a copy of the string*/ \ - auto it = m_VariableHash.insert( std::make_pair( Diligent::HashMapStringKey(ProgVar.Name), CGLShaderVariable(Owner, ProgVar, static_cast(m_VariablesByIndex.size())) ) ); \ - VERIFY_EXPR(it.second); \ - m_VariablesByIndex.push_back(&it.first->second); \ - } \ - } - - STORE_SHADER_VARIABLES(m_UniformBlocks) - STORE_SHADER_VARIABLES(m_Samplers) - STORE_SHADER_VARIABLES(m_Images) - STORE_SHADER_VARIABLES(m_StorageBlocks) -#undef STORE_SHADER_VARIABLES - } - GLProgramResources::CGLShaderVariable* GLProgramResources::GetShaderVariable( const Char* Name ) + + GLProgramResources::GLProgramVariableBase* GLProgramResources::GetVariable(const Char* Name) { // Name will be implicitly converted to HashMapStringKey without making a copy - auto it = m_VariableHash.find( Name ); - if( it == m_VariableHash.end() ) + for (Uint32 ub=0; ub < m_NumUniformBuffers; ++ub) { - return nullptr; + auto& UB = GetUniformBuffer(ub); + if (strcmp(UB.Name, Name) == 0) + return &UB; } - return &it->second; + + for (Uint32 s=0; s < m_NumSamplers; ++s) + { + auto& Sam = GetSampler(s); + if (strcmp(Sam.Name, Name) == 0) + return &Sam; + } + + for (Uint32 img=0; img < m_NumImages; ++img) + { + auto& Img = GetImage(img); + if (strcmp(Img.Name, Name) == 0) + return &Img; + } + + for (Uint32 sb=0; sb < m_NumStorageBlocks; ++sb) + { + auto& SB = GetStorageBlock(sb); + if (strcmp(SB.Name, Name) == 0) + return &SB; + } + + return nullptr; } - template - void BindResourcesHelper(TResArrayType &ResArr, IResourceMapping *pResourceMapping, Uint32 Flags) + const GLProgramResources::GLProgramVariableBase* GLProgramResources::GetVariable(Uint32 Index)const { - for (auto& res : ResArr) - { - if ( (Flags & (1 << res.VarType)) == 0 ) - continue; + if (Index < GetNumUniformBuffers()) + return &GetUniformBuffer(Index); + else + Index -= GetNumUniformBuffers(); + + if (Index < GetNumSamplers()) + return &GetSampler(Index); + else + Index -= GetNumSamplers(); + + if (Index < GetNumImages()) + return &GetImage(Index); + else + Index -= GetNumImages(); + + if (Index < GetNumStorageBlocks()) + return &GetStorageBlock(Index); + else + Index -= GetNumStorageBlocks(); + + return nullptr; + } - auto &Name = res.Name; - for(Uint32 ArrInd = 0; ArrInd < res.pResources.size(); ++ArrInd) - { - auto &CurrResource = res.pResources[ArrInd]; - if( (Flags & BIND_SHADER_RESOURCES_KEEP_EXISTING) && CurrResource ) - continue; // Skip already resolved resources + static void BindResourcesHelper(GLProgramResources::GLProgramVariableBase& res, IResourceMapping* pResourceMapping, Uint32 Flags) + { + if ( (Flags & (1 << res.VariableType)) == 0 ) + return; - RefCntAutoPtr pNewRes; - pResourceMapping->GetResource( Name.c_str(), static_cast(&pNewRes), ArrInd ); + auto& Name = res.Name; + for(Uint32 ArrInd = 0; ArrInd < res.ArraySize; ++ArrInd) + { + auto& CurrResource = res.pResources[ArrInd]; - if (pNewRes != nullptr) - { - if(res.VarType == SHADER_RESOURCE_VARIABLE_TYPE_STATIC && CurrResource != nullptr && CurrResource != pNewRes ) - LOG_ERROR_MESSAGE( "Updating binding for static variable \"", Name, "\" is invalid and may result in an undefined behavior" ); - CurrResource = pNewRes; - } - else - { - if ( CurrResource == nullptr && (Flags & BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED) ) - LOG_ERROR_MESSAGE("Resource \"", Name, "\" is not found in the resource mapping"); - } + if( (Flags & BIND_SHADER_RESOURCES_KEEP_EXISTING) != 0 && CurrResource ) + continue; // Skip already resolved resources + + RefCntAutoPtr pNewRes; + pResourceMapping->GetResource( Name, static_cast(&pNewRes), ArrInd ); + + if (pNewRes != nullptr) + { + if(res.VariableType == SHADER_RESOURCE_VARIABLE_TYPE_STATIC && CurrResource != nullptr && CurrResource != pNewRes ) + LOG_ERROR_MESSAGE( "Updating binding for static variable \"", Name, "\" is invalid and may result in an undefined behavior" ); + CurrResource = pNewRes; + } + else + { + if ( CurrResource == nullptr && (Flags & BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED) ) + LOG_ERROR_MESSAGE("Resource \"", Name, "\" is not found in the resource mapping"); } } } - void GLProgramResources::BindResources( IResourceMapping *pResourceMapping, Uint32 Flags ) + + void GLProgramResources::BindResources(IResourceMapping* pResourceMapping, Uint32 Flags ) { if( !pResourceMapping ) return; @@ -499,48 +822,63 @@ namespace Diligent if ( (Flags & BIND_SHADER_RESOURCES_UPDATE_ALL) == 0 ) Flags |= BIND_SHADER_RESOURCES_UPDATE_ALL; - BindResourcesHelper( m_UniformBlocks, pResourceMapping, Flags ); - BindResourcesHelper( m_Samplers, pResourceMapping, Flags ); - BindResourcesHelper( m_Images, pResourceMapping, Flags ); - BindResourcesHelper( m_StorageBlocks, pResourceMapping, Flags ); + ProcessResources( + [&](UniformBufferInfo& UB) + { + BindResourcesHelper(UB, pResourceMapping, Flags); + }, + [&](SamplerInfo& Sam) + { + BindResourcesHelper(Sam, pResourceMapping, Flags); + }, + [&](ImageInfo& Img) + { + BindResourcesHelper(Img, pResourceMapping, Flags); + }, + [&](StorageBlockInfo& SB) + { + BindResourcesHelper(SB, pResourceMapping, Flags); + } + ); } + bool GLProgramResources::IsCompatibleWith(const GLProgramResources& Res)const { - if (m_UniformBlocks.size() != Res.m_UniformBlocks.size() || - m_Samplers.size() != Res.m_Samplers.size() || - m_Images.size() != Res.m_Images.size() || - m_StorageBlocks.size() != Res.m_StorageBlocks.size()) + if (GetNumUniformBuffers() != Res.GetNumUniformBuffers() || + GetNumSamplers() != Res.GetNumSamplers() || + GetNumImages() != Res.GetNumImages() || + GetNumStorageBlocks() != Res.GetNumStorageBlocks()) return false; - for (size_t ub = 0; ub < m_UniformBlocks.size(); ++ub) + for (Uint32 ub = 0; ub < GetNumUniformBuffers(); ++ub) { - const auto &UB0 = m_UniformBlocks[ub]; - const auto &UB1 = Res.m_UniformBlocks[ub]; + const auto& UB0 = GetUniformBuffer(ub); + const auto& UB1 = Res.GetUniformBuffer(ub); if(!UB0.IsCompatibleWith(UB1)) return false; } - for (size_t sam = 0; sam < m_Samplers.size(); ++sam) + for (Uint32 sam = 0; sam < GetNumSamplers(); ++sam) { - const auto &Sam0 = m_Samplers[sam]; - const auto &Sam1 = Res.m_Samplers[sam]; + const auto& Sam0 = GetSampler(sam); + const auto& Sam1 = Res.GetSampler(sam); if (!Sam0.IsCompatibleWith(Sam1)) return false; } - for (size_t img = 0; img < m_Images.size(); ++img) + for (Uint32 img = 0; img < GetNumImages(); ++img) { - const auto &Img0 = m_Images[img]; - const auto &Img1 = Res.m_Images[img]; + const auto& Img0 = GetImage(img); + const auto& Img1 = Res.GetImage(img); if (!Img0.IsCompatibleWith(Img1)) return false; } - for (size_t sb = 0; sb < m_StorageBlocks.size(); ++sb) + for (Uint32 sb = 0; sb < GetNumStorageBlocks(); ++sb) { - const auto &SB0 = m_StorageBlocks[sb]; - const auto &SB1 = Res.m_StorageBlocks[sb]; + const auto& SB0 = GetStorageBlock(sb); + const auto& SB1 = Res.GetStorageBlock(sb); if (!SB0.IsCompatibleWith(SB1)) return false; } @@ -548,58 +886,68 @@ namespace Diligent return true; } + size_t GLProgramResources::GetHash()const { - size_t hash = ComputeHash(m_UniformBlocks.size(), m_Samplers.size(), m_Images.size(), m_StorageBlocks.size()); - - for (auto ub = m_UniformBlocks.begin(); ub != m_UniformBlocks.end(); ++ub) - { - HashCombine(hash, ub->GetHash()); - } - - for (auto sam = m_Samplers.begin(); sam != m_Samplers.end(); ++sam) - { - HashCombine(hash, sam->GetHash()); - } - - for (auto img = m_Images.begin(); img != m_Images.end(); ++img) - { - HashCombine(hash, img->GetHash()); - } + size_t hash = ComputeHash(GetNumUniformBuffers(), GetNumSamplers(), GetNumImages(), GetNumStorageBlocks()); - for (auto sb = m_StorageBlocks.begin(); sb != m_StorageBlocks.end(); ++sb) - { - HashCombine(hash, sb->GetHash()); - } + ProcessConstResources( + [&](const UniformBufferInfo& UB) + { + HashCombine(hash, UB.GetHash()); + }, + [&](const SamplerInfo& Sam) + { + HashCombine(hash, Sam.GetHash()); + }, + [&](const ImageInfo& Img) + { + HashCombine(hash, Img.GetHash()); + }, + [&](const StorageBlockInfo& SB) + { + HashCombine(hash, SB.GetHash()); + } + ); return hash; } #ifdef VERIFY_RESOURCE_BINDINGS - template - void dbgVerifyResourceBindingsHelper(TResArrayType &ResArr, const Char *VarType) + static void dbgVerifyResourceBindingsHelper(const GLProgramResources::GLProgramVariableBase& res, const Char* VarTypeName) { - for( auto res = ResArr.begin(); res != ResArr.end(); ++res ) + for(Uint32 ArrInd = 0; ArrInd < res.ArraySize; ++ArrInd) { - for(Uint32 ArrInd = 0; ArrInd < res->pResources.size(); ++ArrInd) + if( !res.pResources[ArrInd] ) { - if( !res->pResources[ArrInd] ) - { - if( res->pResources.size() > 1) - LOG_ERROR_MESSAGE( "No resource is bound to ", VarType, " variable \"", res->Name, "[", ArrInd, "]\"" ); - else - LOG_ERROR_MESSAGE( "No resource is bound to ", VarType, " variable \"", res->Name, "\"" ); - } + if( res.ArraySize > 1) + LOG_ERROR_MESSAGE( "No resource is bound to ", VarTypeName, " variable \"", res.Name, "[", ArrInd, "]\"" ); + else + LOG_ERROR_MESSAGE( "No resource is bound to ", VarTypeName, " variable \"", res.Name, "\"" ); } } } - void GLProgramResources::dbgVerifyResourceBindings() + void GLProgramResources::dbgVerifyResourceBindings()const { - dbgVerifyResourceBindingsHelper( m_UniformBlocks, "uniform block" ); - dbgVerifyResourceBindingsHelper( m_Samplers, "sampler" ); - dbgVerifyResourceBindingsHelper( m_Images, "image" ); - dbgVerifyResourceBindingsHelper( m_StorageBlocks, "shader storage block" ); + ProcessConstResources( + [&](const UniformBufferInfo& UB) + { + dbgVerifyResourceBindingsHelper(UB, "uniform block"); + }, + [&](const SamplerInfo& Sam) + { + dbgVerifyResourceBindingsHelper(Sam, "sampler"); + }, + [&](const ImageInfo& Img) + { + dbgVerifyResourceBindingsHelper(Img, "image"); + }, + [&](const StorageBlockInfo& SB) + { + dbgVerifyResourceBindingsHelper(SB, "shader storage block"); + } + ); } #endif diff --git a/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp index 25ee1d17..86109db4 100644 --- a/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp @@ -116,7 +116,7 @@ void PipelineStateGLImpl::LinkGLProgram(bool bIsProgramPipelineSupported) } auto pDeviceGL = GetDevice(); - m_GLProgram.InitResources(pDeviceGL, ShaderStages, *this, &m_Desc.ResourceLayout, nullptr, 0); + m_GLProgram.InitResources(pDeviceGL, ShaderStages, *this); m_StaticResources.resize(1); const SHADER_RESOURCE_VARIABLE_TYPE StaticVars[] = {SHADER_RESOURCE_VARIABLE_TYPE_STATIC}; @@ -212,12 +212,12 @@ IShaderResourceVariable* PipelineStateGLImpl::GetStaticShaderVariable(SHADER_TYP { if (m_GLProgram) { - return m_StaticResources[0].GetShaderVariable(Name); + return m_StaticResources[0].GetVariable(Name); } else { const auto LayoutInd = m_ResourceLayoutIndex[GetShaderTypeIndex(ShaderType)]; - return LayoutInd >= 0 ? m_StaticResources[LayoutInd].GetShaderVariable(Name) : nullptr; + return LayoutInd >= 0 ? m_StaticResources[LayoutInd].GetVariable(Name) : nullptr; } } @@ -225,12 +225,12 @@ IShaderResourceVariable* PipelineStateGLImpl::GetStaticShaderVariable(SHADER_TYP { if (m_GLProgram) { - return m_StaticResources[0].GetShaderVariable(Index); + return m_StaticResources[0].GetVariable(Index); } else { const auto LayoutInd = m_ResourceLayoutIndex[GetShaderTypeIndex(ShaderType)]; - return LayoutInd >= 0 ? m_StaticResources[LayoutInd].GetShaderVariable(Index) : nullptr; + return LayoutInd >= 0 ? m_StaticResources[LayoutInd].GetVariable(Index) : nullptr; } } diff --git a/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp index 278f79de..e42ca9ef 100644 --- a/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/ShaderGLImpl.cpp @@ -160,7 +160,7 @@ ShaderGLImpl::ShaderGLImpl(IReferenceCounters* pRefCounters, // boolean status bit DELETE_STATUS is set to true ShaderObj.Release(); - m_GlProgObj.InitResources(pDeviceGL, m_Desc.ShaderType, *this, nullptr, nullptr, 0); + m_GlProgObj.InitResources(pDeviceGL, m_Desc.ShaderType, *this); } else { @@ -194,7 +194,7 @@ ShaderResourceDesc ShaderGLImpl::GetResource(Uint32 Index)const if (m_GlProgObj) { DEV_CHECK_ERR(Index < GetResourceCount(), "Index is out of range"); - ResourceDesc = m_GlProgObj.GetResources().GetShaderVariable(Index)->GetResourceDesc(); + ResourceDesc = m_GlProgObj.GetResources().GetVariable(Index)->GetResourceDesc(); } else { diff --git a/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp index 15086b05..2028b5eb 100644 --- a/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp @@ -53,8 +53,7 @@ ShaderResourceBindingGLImpl::ShaderResourceBindingGLImpl(IReferenceCounters* pRe } else { - // Clone all variable types - SHADER_RESOURCE_VARIABLE_TYPE VarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_STATIC, SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; + SHADER_RESOURCE_VARIABLE_TYPE VarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; m_DynamicProgResources[0].Clone(pPSO->GetDevice(), *this, pPSO->GetGLProgram().GetResources(), pPSO->GetDesc().ResourceLayout, VarTypes, _countof(VarTypes)); } } @@ -97,7 +96,7 @@ void ShaderResourceBindingGLImpl::BindResources(Uint32 ShaderFlags, IResourceMap IShaderResourceVariable* ShaderResourceBindingGLImpl::GetVariable(SHADER_TYPE ShaderType, const char* Name) { auto ShaderInd = IsUsingSeparatePrograms() ? GetShaderTypeIndex(ShaderType) : 0; - return m_DynamicProgResources[ShaderInd].GetShaderVariable(Name); + return m_DynamicProgResources[ShaderInd].GetVariable(Name); } Uint32 ShaderResourceBindingGLImpl::GetVariableCount(SHADER_TYPE ShaderType) const @@ -109,7 +108,7 @@ Uint32 ShaderResourceBindingGLImpl::GetVariableCount(SHADER_TYPE ShaderType) con IShaderResourceVariable* ShaderResourceBindingGLImpl::GetVariable(SHADER_TYPE ShaderType, Uint32 Index) { auto ShaderInd = IsUsingSeparatePrograms() ? GetShaderTypeIndex(ShaderType) : 0; - return m_DynamicProgResources[ShaderInd].GetShaderVariable(Index); + return m_DynamicProgResources[ShaderInd].GetVariable(Index); } static GLProgramResources NullProgramResources; @@ -127,15 +126,6 @@ GLProgramResources& ShaderResourceBindingGLImpl::GetProgramResources(SHADER_TYPE void ShaderResourceBindingGLImpl::InitializeStaticResources(const IPipelineState* pPipelineState) { - if (!IsUsingSeparatePrograms()) - { - //if (pPipelineState != nullptr) - //{ - // const auto* PSOGL = ValidatedCast(pPipelineState); - // ResourceMappingProxy StaticResMapping(*PSOGL); - // m_DynamicProgResources[0].BindResources(&StaticResMapping, 0); - //} - } } } -- cgit v1.2.3 From 8d7f42f72200bd6462c5ef6037f77cb61398635d Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Wed, 6 Mar 2019 08:49:10 -0800 Subject: Updated Shader resource binding GL implementation --- .../include/ShaderResourceBindingGLImpl.h | 5 +- .../src/DeviceContextGLImpl.cpp | 6 +- .../src/ShaderResourceBindingGLImpl.cpp | 68 ++++++++-------------- 3 files changed, 30 insertions(+), 49 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineOpenGL/include/ShaderResourceBindingGLImpl.h b/Graphics/GraphicsEngineOpenGL/include/ShaderResourceBindingGLImpl.h index 243b7354..ebea5624 100644 --- a/Graphics/GraphicsEngineOpenGL/include/ShaderResourceBindingGLImpl.h +++ b/Graphics/GraphicsEngineOpenGL/include/ShaderResourceBindingGLImpl.h @@ -59,12 +59,13 @@ public: virtual void InitializeStaticResources(const IPipelineState* pPipelineState)override final; - GLProgramResources& GetProgramResources(SHADER_TYPE ShaderType, PipelineStateGLImpl* pdbgPSO); + GLProgramResources& GetResources(Uint32 Ind, PipelineStateGLImpl* pdbgPSO); private: bool IsUsingSeparatePrograms()const; - GLProgramResources m_DynamicProgResources[6]; + Int8 m_ResourceIndex[6] = {-1, -1, -1, -1, -1, -1}; + std::vector m_Resources; }; } diff --git a/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp index 619c0b55..938edfcc 100644 --- a/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp @@ -383,15 +383,15 @@ namespace Diligent auto* pShaderGL = m_pPipelineState->GetShader(ProgNum); auto& GLProgramObj = ProgramPipelineSupported ? pShaderGL->m_GlProgObj : Prog; - GLProgramResources* pDynamicResources = pShaderResBindingGL ? &pShaderResBindingGL->GetProgramResources(pShaderGL->GetDesc().ShaderType, m_pPipelineState) : nullptr; + GLProgramResources* pSRBResources = pShaderResBindingGL ? &pShaderResBindingGL->GetResources(ProgNum, m_pPipelineState) : nullptr; #ifdef VERIFY_RESOURCE_BINDINGS //GLProgramObj.dbgVerifyBindingCompleteness(pDynamicResources, m_pPipelineState); #endif // When program pipelines are not supported, all resources are dynamic resources - for (int BindDynamicResources = 0; BindDynamicResources < (pShaderResBindingGL ? 2 : 1); ++BindDynamicResources) + for (int BindSRBResources = 0; BindSRBResources < (pShaderResBindingGL ? 2 : 1); ++BindSRBResources) { - GLProgramResources& ProgResources = BindDynamicResources ? *pDynamicResources : m_pPipelineState->GetStaticResources(ProgNum); + GLProgramResources& ProgResources = BindSRBResources ? *pSRBResources : m_pPipelineState->GetStaticResources(ProgNum); #ifdef VERIFY_RESOURCE_BINDINGS ProgResources.dbgVerifyResourceBindings(); diff --git a/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp index 2028b5eb..653930ac 100644 --- a/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp @@ -31,30 +31,25 @@ namespace Diligent { ShaderResourceBindingGLImpl::ShaderResourceBindingGLImpl(IReferenceCounters* pRefCounters, PipelineStateGLImpl* pPSO) : - TBase (pRefCounters, pPSO) + TBase (pRefCounters, pPSO), + m_Resources(pPSO->GetGLProgram() == 0 ? pPSO->GetNumShaders() : 1) { + const SHADER_RESOURCE_VARIABLE_TYPE SRBVarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; if (IsUsingSeparatePrograms()) { - SHADER_RESOURCE_VARIABLE_TYPE VarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; -#define INIT_SHADER(SN)\ - if(auto p##SN = ValidatedCast( pPSO->Get##SN() )) \ - { \ - auto &GLProg = p##SN->GetGlProgram(); \ - m_DynamicProgResources[SN##Ind].Clone(pPSO->GetDevice(), *this, GLProg.GetResources(), pPSO->GetDesc().ResourceLayout, VarTypes, _countof(VarTypes)); \ + + for (Uint32 s = 0; s < pPSO->GetNumShaders(); ++s) + { + auto* pShaderGL = pPSO->GetShader(s); + m_Resources[s].Clone(pPSO->GetDevice(), *this, pShaderGL->GetGlProgram().GetResources(), pPSO->GetDesc().ResourceLayout, SRBVarTypes, _countof(SRBVarTypes)); + const auto ShaderType = pShaderGL->GetDesc().ShaderType; + const auto ShaderTypeInd = GetShaderTypeIndex(ShaderType); + m_ResourceIndex[ShaderTypeInd] = static_cast(s); } - - INIT_SHADER(VS) - INIT_SHADER(PS) - INIT_SHADER(GS) - INIT_SHADER(HS) - INIT_SHADER(DS) - INIT_SHADER(CS) -#undef INIT_SHADER } else { - SHADER_RESOURCE_VARIABLE_TYPE VarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE, SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}; - m_DynamicProgResources[0].Clone(pPSO->GetDevice(), *this, pPSO->GetGLProgram().GetResources(), pPSO->GetDesc().ResourceLayout, VarTypes, _countof(VarTypes)); + m_Resources[0].Clone(pPSO->GetDevice(), *this, pPSO->GetGLProgram().GetResources(), pPSO->GetDesc().ResourceLayout, SRBVarTypes, _countof(SRBVarTypes)); } } @@ -71,48 +66,33 @@ bool ShaderResourceBindingGLImpl::IsUsingSeparatePrograms()const void ShaderResourceBindingGLImpl::BindResources(Uint32 ShaderFlags, IResourceMapping* pResMapping, Uint32 Flags) { - if (IsUsingSeparatePrograms()) - { - if(ShaderFlags & SHADER_TYPE_VERTEX) - m_DynamicProgResources[VSInd].BindResources(pResMapping, Flags); - if(ShaderFlags & SHADER_TYPE_PIXEL) - m_DynamicProgResources[PSInd].BindResources(pResMapping, Flags); - if(ShaderFlags & SHADER_TYPE_GEOMETRY) - m_DynamicProgResources[GSInd].BindResources(pResMapping, Flags); - if(ShaderFlags & SHADER_TYPE_HULL) - m_DynamicProgResources[HSInd].BindResources(pResMapping, Flags); - if(ShaderFlags & SHADER_TYPE_DOMAIN) - m_DynamicProgResources[DSInd].BindResources(pResMapping, Flags); - if(ShaderFlags & SHADER_TYPE_COMPUTE) - m_DynamicProgResources[CSInd].BindResources(pResMapping, Flags); - } - else + for(auto& Resource : m_Resources) { - // Using non-separable program - m_DynamicProgResources[0].BindResources(pResMapping, Flags); + if ((Resource.GetShaderStages() & ShaderFlags)!=0) + Resource.BindResources(pResMapping, Flags); } } IShaderResourceVariable* ShaderResourceBindingGLImpl::GetVariable(SHADER_TYPE ShaderType, const char* Name) { - auto ShaderInd = IsUsingSeparatePrograms() ? GetShaderTypeIndex(ShaderType) : 0; - return m_DynamicProgResources[ShaderInd].GetVariable(Name); + auto ShaderInd = IsUsingSeparatePrograms() ? m_ResourceIndex[GetShaderTypeIndex(ShaderType)] : 0; + return ShaderInd >= 0 ? m_Resources[ShaderInd].GetVariable(Name) : nullptr; } Uint32 ShaderResourceBindingGLImpl::GetVariableCount(SHADER_TYPE ShaderType) const { - auto ShaderInd = IsUsingSeparatePrograms() ? GetShaderTypeIndex(ShaderType) : 0; - return m_DynamicProgResources[ShaderInd].GetVariableCount(); + auto ShaderInd = IsUsingSeparatePrograms() ? m_ResourceIndex[GetShaderTypeIndex(ShaderType)] : 0; + return ShaderInd >= 0 ? m_Resources[ShaderInd].GetVariableCount() : 0; } IShaderResourceVariable* ShaderResourceBindingGLImpl::GetVariable(SHADER_TYPE ShaderType, Uint32 Index) { - auto ShaderInd = IsUsingSeparatePrograms() ? GetShaderTypeIndex(ShaderType) : 0; - return m_DynamicProgResources[ShaderInd].GetVariable(Index); + auto ShaderInd = IsUsingSeparatePrograms() ? m_ResourceIndex[GetShaderTypeIndex(ShaderType)] : 0; + return ShaderInd >= 0 ? m_Resources[ShaderInd].GetVariable(Index) : 0; } static GLProgramResources NullProgramResources; -GLProgramResources& ShaderResourceBindingGLImpl::GetProgramResources(SHADER_TYPE ShaderType, PipelineStateGLImpl* pdbgPSO) +GLProgramResources& ShaderResourceBindingGLImpl::GetResources(Uint32 Ind, PipelineStateGLImpl* pdbgPSO) { #ifdef _DEBUG if (pdbgPSO->IsIncompatibleWith(GetPipelineState())) @@ -120,12 +100,12 @@ GLProgramResources& ShaderResourceBindingGLImpl::GetProgramResources(SHADER_TYPE LOG_ERROR("Shader resource binding is incompatible with the currently bound pipeline state."); } #endif - auto ShaderInd = IsUsingSeparatePrograms() ? GetShaderTypeIndex(ShaderType) : 0; - return m_DynamicProgResources[ShaderInd]; + return m_Resources[Ind]; } void ShaderResourceBindingGLImpl::InitializeStaticResources(const IPipelineState* pPipelineState) { + // Do nothing } } -- cgit v1.2.3 From 7d70b24758eb5d843f5d491ca305878f002b1a3a Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Wed, 6 Mar 2019 09:18:00 -0800 Subject: Fixed clang compiler warnings --- Graphics/GraphicsEngine/interface/Buffer.h | 2 +- Graphics/GraphicsEngine/interface/BufferView.h | 2 +- Graphics/GraphicsEngine/interface/Fence.h | 2 +- Graphics/GraphicsEngine/interface/PipelineState.h | 2 +- Graphics/GraphicsEngine/interface/Sampler.h | 2 +- Graphics/GraphicsEngine/interface/Shader.h | 2 +- Graphics/GraphicsEngine/interface/Texture.h | 2 +- Graphics/GraphicsEngine/interface/TextureView.h | 2 +- Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp | 1 - 9 files changed, 8 insertions(+), 9 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngine/interface/Buffer.h b/Graphics/GraphicsEngine/interface/Buffer.h index 7729df8d..d57b8f08 100644 --- a/Graphics/GraphicsEngine/interface/Buffer.h +++ b/Graphics/GraphicsEngine/interface/Buffer.h @@ -174,7 +174,7 @@ public: virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; /// Returns the buffer description used to create the object - virtual const BufferDesc& GetDesc()const = 0; + virtual const BufferDesc& GetDesc()const override = 0; /// Creates a new buffer view diff --git a/Graphics/GraphicsEngine/interface/BufferView.h b/Graphics/GraphicsEngine/interface/BufferView.h index d1a43ea2..2361a329 100644 --- a/Graphics/GraphicsEngine/interface/BufferView.h +++ b/Graphics/GraphicsEngine/interface/BufferView.h @@ -141,7 +141,7 @@ public: virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Returns the buffer view description used to create the object - virtual const BufferViewDesc& GetDesc()const = 0; + virtual const BufferViewDesc& GetDesc()const override = 0; /// Returns pointer to the referenced buffer object. diff --git a/Graphics/GraphicsEngine/interface/Fence.h b/Graphics/GraphicsEngine/interface/Fence.h index bdecd369..7a7ee8c5 100644 --- a/Graphics/GraphicsEngine/interface/Fence.h +++ b/Graphics/GraphicsEngine/interface/Fence.h @@ -51,7 +51,7 @@ public: virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Returns the fence description used to create the object - virtual const FenceDesc& GetDesc()const = 0; + virtual const FenceDesc& GetDesc()const override = 0; /// Returns the last completed value signaled by the GPU virtual Uint64 GetCompletedValue() = 0; diff --git a/Graphics/GraphicsEngine/interface/PipelineState.h b/Graphics/GraphicsEngine/interface/PipelineState.h index f562a2cd..3b749f60 100644 --- a/Graphics/GraphicsEngine/interface/PipelineState.h +++ b/Graphics/GraphicsEngine/interface/PipelineState.h @@ -246,7 +246,7 @@ public: /// Returns the blend state description used to create the object - virtual const PipelineStateDesc& GetDesc()const = 0; + virtual const PipelineStateDesc& GetDesc()const override = 0; /// Binds resources for all shaders in the pipeline state diff --git a/Graphics/GraphicsEngine/interface/Sampler.h b/Graphics/GraphicsEngine/interface/Sampler.h index 2ad99605..cee595c5 100644 --- a/Graphics/GraphicsEngine/interface/Sampler.h +++ b/Graphics/GraphicsEngine/interface/Sampler.h @@ -173,7 +173,7 @@ public: virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Returns the sampler description used to create the object - virtual const SamplerDesc& GetDesc()const = 0; + virtual const SamplerDesc& GetDesc()const override = 0; }; } diff --git a/Graphics/GraphicsEngine/interface/Shader.h b/Graphics/GraphicsEngine/interface/Shader.h index efd4acb1..c993bf4a 100644 --- a/Graphics/GraphicsEngine/interface/Shader.h +++ b/Graphics/GraphicsEngine/interface/Shader.h @@ -235,7 +235,7 @@ public: virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Returns the shader description - virtual const ShaderDesc& GetDesc()const = 0; + virtual const ShaderDesc& GetDesc()const override = 0; /// Returns the total number of shader resources virtual Uint32 GetResourceCount()const = 0; diff --git a/Graphics/GraphicsEngine/interface/Texture.h b/Graphics/GraphicsEngine/interface/Texture.h index 0b3cedbc..273e8f95 100644 --- a/Graphics/GraphicsEngine/interface/Texture.h +++ b/Graphics/GraphicsEngine/interface/Texture.h @@ -276,7 +276,7 @@ public: virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Returns the texture description used to create the object - virtual const TextureDesc& GetDesc()const = 0; + virtual const TextureDesc& GetDesc()const override = 0; /// Creates a new texture view diff --git a/Graphics/GraphicsEngine/interface/TextureView.h b/Graphics/GraphicsEngine/interface/TextureView.h index a1e2b439..dc03314f 100644 --- a/Graphics/GraphicsEngine/interface/TextureView.h +++ b/Graphics/GraphicsEngine/interface/TextureView.h @@ -166,7 +166,7 @@ public: virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Returns the texture view description used to create the object - virtual const TextureViewDesc& GetDesc()const = 0; + virtual const TextureViewDesc& GetDesc()const override = 0; /// Sets the texture sampler to use for filtering operations /// when accessing a texture from shaders. Only diff --git a/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp index 938edfcc..22823f51 100644 --- a/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/DeviceContextGLImpl.cpp @@ -388,7 +388,6 @@ namespace Diligent //GLProgramObj.dbgVerifyBindingCompleteness(pDynamicResources, m_pPipelineState); #endif - // When program pipelines are not supported, all resources are dynamic resources for (int BindSRBResources = 0; BindSRBResources < (pShaderResBindingGL ? 2 : 1); ++BindSRBResources) { GLProgramResources& ProgResources = BindSRBResources ? *pSRBResources : m_pPipelineState->GetStaticResources(ProgNum); -- cgit v1.2.3 From 192f9119bf3a6fe023e06795fd6f85745363c7f9 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Wed, 6 Mar 2019 09:29:43 -0800 Subject: Few improvements to managing static resources when sep programs are not supported in GL backend --- Graphics/GraphicsEngine/interface/Buffer.h | 2 +- .../GraphicsEngineOpenGL/src/GLContextWindows.cpp | 2 +- .../src/PipelineStateGLImpl.cpp | 6 ++-- .../src/ShaderResourceBindingGLImpl.cpp | 33 ++++++++++++++++++---- 4 files changed, 32 insertions(+), 11 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngine/interface/Buffer.h b/Graphics/GraphicsEngine/interface/Buffer.h index d57b8f08..d42c113c 100644 --- a/Graphics/GraphicsEngine/interface/Buffer.h +++ b/Graphics/GraphicsEngine/interface/Buffer.h @@ -171,7 +171,7 @@ class IBuffer : public IDeviceObject { public: /// Queries the specific interface, see IObject::QueryInterface() for details - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) = 0; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override = 0; /// Returns the buffer description used to create the object virtual const BufferDesc& GetDesc()const override = 0; diff --git a/Graphics/GraphicsEngineOpenGL/src/GLContextWindows.cpp b/Graphics/GraphicsEngineOpenGL/src/GLContextWindows.cpp index 9aa475ab..de1e6e60 100644 --- a/Graphics/GraphicsEngineOpenGL/src/GLContextWindows.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/GLContextWindows.cpp @@ -222,7 +222,7 @@ namespace Diligent glEnable(GL_FRAMEBUFFER_SRGB); if( glGetError() != GL_NO_ERROR ) LOG_ERROR_MESSAGE("Failed to enable SRGB framebuffers"); - +DeviceCaps.bSeparableProgramSupported = false; DeviceCaps.DevType = DeviceType::OpenGL; DeviceCaps.MajorVersion = MajorVersion; DeviceCaps.MinorVersion = MinorVersion; diff --git a/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp index 86109db4..8c8a106c 100644 --- a/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/PipelineStateGLImpl.cpp @@ -199,7 +199,7 @@ Uint32 PipelineStateGLImpl::GetStaticVariableCount(SHADER_TYPE ShaderType) const { if (m_GLProgram) { - return m_StaticResources[0].GetVariableCount(); + return (m_StaticResources[0].GetShaderStages() & ShaderType) != 0 ? m_StaticResources[0].GetVariableCount() : 0; } else { @@ -212,7 +212,7 @@ IShaderResourceVariable* PipelineStateGLImpl::GetStaticShaderVariable(SHADER_TYP { if (m_GLProgram) { - return m_StaticResources[0].GetVariable(Name); + return (m_StaticResources[0].GetShaderStages() & ShaderType) != 0 ? m_StaticResources[0].GetVariable(Name) : nullptr; } else { @@ -225,7 +225,7 @@ IShaderResourceVariable* PipelineStateGLImpl::GetStaticShaderVariable(SHADER_TYP { if (m_GLProgram) { - return m_StaticResources[0].GetVariable(Index); + return (m_StaticResources[0].GetShaderStages() & ShaderType) != 0 ? m_StaticResources[0].GetVariable(Index) : nullptr; } else { diff --git a/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp b/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp index 653930ac..b1099e09 100644 --- a/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/ShaderResourceBindingGLImpl.cpp @@ -75,20 +75,41 @@ void ShaderResourceBindingGLImpl::BindResources(Uint32 ShaderFlags, IResourceMap IShaderResourceVariable* ShaderResourceBindingGLImpl::GetVariable(SHADER_TYPE ShaderType, const char* Name) { - auto ShaderInd = IsUsingSeparatePrograms() ? m_ResourceIndex[GetShaderTypeIndex(ShaderType)] : 0; - return ShaderInd >= 0 ? m_Resources[ShaderInd].GetVariable(Name) : nullptr; + if (IsUsingSeparatePrograms()) + { + auto ShaderInd = m_ResourceIndex[GetShaderTypeIndex(ShaderType)]; + return ShaderInd >= 0 ? m_Resources[ShaderInd].GetVariable(Name) : nullptr; + } + else + { + return (m_Resources[0].GetShaderStages() & ShaderType) != 0 ? m_Resources[0].GetVariable(Name) : nullptr; + } } Uint32 ShaderResourceBindingGLImpl::GetVariableCount(SHADER_TYPE ShaderType) const { - auto ShaderInd = IsUsingSeparatePrograms() ? m_ResourceIndex[GetShaderTypeIndex(ShaderType)] : 0; - return ShaderInd >= 0 ? m_Resources[ShaderInd].GetVariableCount() : 0; + if (IsUsingSeparatePrograms()) + { + auto ShaderInd = m_ResourceIndex[GetShaderTypeIndex(ShaderType)]; + return ShaderInd >= 0 ? m_Resources[ShaderInd].GetVariableCount() : 0; + } + else + { + return (m_Resources[0].GetShaderStages() & ShaderType) != 0 ? m_Resources[0].GetVariableCount() : 0; + } } IShaderResourceVariable* ShaderResourceBindingGLImpl::GetVariable(SHADER_TYPE ShaderType, Uint32 Index) { - auto ShaderInd = IsUsingSeparatePrograms() ? m_ResourceIndex[GetShaderTypeIndex(ShaderType)] : 0; - return ShaderInd >= 0 ? m_Resources[ShaderInd].GetVariable(Index) : 0; + if (IsUsingSeparatePrograms()) + { + auto ShaderInd = m_ResourceIndex[GetShaderTypeIndex(ShaderType)]; + return ShaderInd >= 0 ? m_Resources[ShaderInd].GetVariable(Index) : 0; + } + else + { + return (m_Resources[0].GetShaderStages() & ShaderType) != 0 ? m_Resources[0].GetVariable(Index) : nullptr; + } } static GLProgramResources NullProgramResources; -- cgit v1.2.3 From ae1698683d9196ca836e116449ed0f39738acb06 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Wed, 6 Mar 2019 09:31:11 -0800 Subject: Removed debug code to disable separate programs in GL context --- Graphics/GraphicsEngineOpenGL/src/GLContextWindows.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineOpenGL/src/GLContextWindows.cpp b/Graphics/GraphicsEngineOpenGL/src/GLContextWindows.cpp index de1e6e60..9aa475ab 100644 --- a/Graphics/GraphicsEngineOpenGL/src/GLContextWindows.cpp +++ b/Graphics/GraphicsEngineOpenGL/src/GLContextWindows.cpp @@ -222,7 +222,7 @@ namespace Diligent glEnable(GL_FRAMEBUFFER_SRGB); if( glGetError() != GL_NO_ERROR ) LOG_ERROR_MESSAGE("Failed to enable SRGB framebuffers"); -DeviceCaps.bSeparableProgramSupported = false; + DeviceCaps.DevType = DeviceType::OpenGL; DeviceCaps.MajorVersion = MajorVersion; DeviceCaps.MinorVersion = MinorVersion; -- cgit v1.2.3 From 99e3118c5f041b0f1fc97eebe7a4fb645685c149 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Wed, 6 Mar 2019 09:34:16 -0800 Subject: Fixed few more clang warnings --- Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h b/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h index 4a9b6efe..1b650828 100644 --- a/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h +++ b/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h @@ -83,10 +83,10 @@ namespace Diligent RefCntAutoPtr* _pResources) : ShaderVariableBase(_Owner), Name (_Name), - ArraySize (_ArraySize), VariableType (_VariableType), - VariableIndex (_VariableIndex), ResourceType (_ResourceType), + VariableIndex (_VariableIndex), + ArraySize (_ArraySize), pResources (_pResources) { VERIFY_EXPR(_ArraySize >= 1); -- cgit v1.2.3 From 76a1a90ee26e3f2e78fab018bbbfc43ddc85d849 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Wed, 6 Mar 2019 10:03:57 -0800 Subject: Removed unused m_ResourceLayout member from ShaderVariableManagerVk and ShaderVariableManagerD3D12 plus a bunch of minor updates to fix clang warnings --- Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h | 10 ++++------ Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp | 7 +++---- Graphics/GraphicsEngineMetal/src/TextureMtlImpl.mm | 2 +- Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h | 8 ++++---- Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h | 10 ++++------ Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp | 1 - 6 files changed, 16 insertions(+), 22 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h b/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h index 85dc30c7..8b9f8fb8 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h @@ -66,7 +66,7 @@ namespace Diligent class ShaderVariableD3D12Impl; -// sizeof(ShaderVariableManagerD3D12) == 40 (x64, msvc, Release) +// sizeof(ShaderVariableManagerD3D12) == 32 (x64, msvc, Release) class ShaderVariableManagerD3D12 { public: @@ -99,11 +99,9 @@ private: IObject& m_Owner; - // Variable mgr is owned by either PSO object (in which case m_pResourceLayout points to - // static resource layout owned by the same PSO object), or by SRB object (in which case - // m_pResourceLayout points to corresponding layout in pipeline state). Since SRB keeps strong - // reference to PSO, the layout is guaranteed be alive while SRB is alive - const ShaderResourceLayoutD3D12& m_ResourceLayout; + // Variable mgr is owned by either Pipeline state object (in which case m_ResourceCache references + // static resource cache owned by the same PSO object), or by SRB object (in which case + // m_ResourceCache references the cache in the SRB). Thus the cache is guaranteed to be alive. ShaderResourceCacheD3D12& m_ResourceCache; // Memory is allocated through the allocator provided by the pipeline state. If allocation granularity > 1, fixed block diff --git a/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp b/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp index 3c14c461..de8e9855 100644 --- a/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp +++ b/Graphics/GraphicsEngineD3D12/src/ShaderVariableD3D12.cpp @@ -56,11 +56,10 @@ ShaderVariableManagerD3D12::ShaderVariableManagerD3D12(IObject& const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes, ShaderResourceCacheD3D12& ResourceCache) : - m_Owner (Owner), - m_ResourceLayout (SrcLayout), - m_ResourceCache (ResourceCache) + m_Owner (Owner), + m_ResourceCache (ResourceCache) #ifdef _DEBUG - , m_DbgAllocator(Allocator) + , m_DbgAllocator (Allocator) #endif { diff --git a/Graphics/GraphicsEngineMetal/src/TextureMtlImpl.mm b/Graphics/GraphicsEngineMetal/src/TextureMtlImpl.mm index 70f54ac8..b89b0c35 100644 --- a/Graphics/GraphicsEngineMetal/src/TextureMtlImpl.mm +++ b/Graphics/GraphicsEngineMetal/src/TextureMtlImpl.mm @@ -40,7 +40,7 @@ TextureMtlImpl :: TextureMtlImpl(IReferenceCounters* pRefCounters, { LOG_ERROR_AND_THROW("Textures are not implemented in Metal backend"); - if( TexDesc.Usage == USAGE_STATIC && pInitData == nullptr || pInitData->pSubResources == nullptr ) + if( (TexDesc.Usage == USAGE_STATIC && pInitData == nullptr) || pInitData->pSubResources == nullptr ) LOG_ERROR_AND_THROW("Static Texture must be initialized with data at creation time"); SetState(RESOURCE_STATE_UNDEFINED); } diff --git a/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h b/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h index 1b650828..95659276 100644 --- a/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h +++ b/Graphics/GraphicsEngineOpenGL/include/GLProgramResources.h @@ -148,7 +148,7 @@ namespace Diligent } }; - struct UniformBufferInfo : GLProgramVariableBase + struct UniformBufferInfo final : GLProgramVariableBase { UniformBufferInfo (const UniformBufferInfo&) = delete; UniformBufferInfo& operator= (const UniformBufferInfo&) = delete; @@ -183,7 +183,7 @@ namespace Diligent static_assert( (sizeof(UniformBufferInfo) % sizeof(void*)) == 0, "sizeof(UniformBufferInfo) must be multiple of sizeof(void*)"); - struct SamplerInfo : GLProgramVariableBase + struct SamplerInfo final : GLProgramVariableBase { SamplerInfo (const SamplerInfo&) = delete; SamplerInfo& operator= (const SamplerInfo&) = delete; @@ -225,7 +225,7 @@ namespace Diligent static_assert( (sizeof(SamplerInfo) % sizeof(void*)) == 0, "sizeof(SamplerInfo) must be multiple of sizeof(void*)"); - struct ImageInfo : GLProgramVariableBase + struct ImageInfo final : GLProgramVariableBase { ImageInfo (const ImageInfo&) = delete; ImageInfo& operator= (const ImageInfo&) = delete; @@ -264,7 +264,7 @@ namespace Diligent static_assert( (sizeof(ImageInfo) % sizeof(void*)) == 0, "sizeof(ImageInfo) must be multiple of sizeof(void*)"); - struct StorageBlockInfo : GLProgramVariableBase + struct StorageBlockInfo final : GLProgramVariableBase { StorageBlockInfo (const StorageBlockInfo&) = delete; StorageBlockInfo& operator= (const StorageBlockInfo&) = delete; diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h index 74dac81d..0b7e3aa0 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h @@ -64,7 +64,7 @@ namespace Diligent class ShaderVariableVkImpl; -// sizeof(ShaderVariableManagerVk) == 40 (x64, msvc, Release) +// sizeof(ShaderVariableManagerVk) == 32 (x64, msvc, Release) class ShaderVariableManagerVk { public: @@ -97,11 +97,9 @@ private: Uint32 GetVariableIndex(const ShaderVariableVkImpl& Variable); IObject& m_Owner; - // Variable mgr is owned by either Pipeline state object (in which case m_pResourceLayout points to - // static resource layout owned by the same PSO object), or by SRB object (in which case - // m_pResourceLayout points to corresponding layout in pipeline state). Since SRB keeps strong - // reference to PSO, the layout is guaranteed to be alive while SRB is alive - const ShaderResourceLayoutVk& m_ResourceLayout; + // Variable mgr is owned by either Pipeline state object (in which case m_ResourceCache references + // static resource cache owned by the same PSO object), or by SRB object (in which case + // m_ResourceCache references the cache in the SRB). Thus the cache is guaranteed to be alive. ShaderResourceCacheVk& m_ResourceCache; // Memory is allocated through the allocator provided by the pipeline state. If allocation granularity > 1, fixed block diff --git a/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp b/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp index d005dc26..9d6bbf96 100644 --- a/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp +++ b/Graphics/GraphicsEngineVulkan/src/ShaderVariableVk.cpp @@ -68,7 +68,6 @@ ShaderVariableManagerVk::ShaderVariableManagerVk(IObject& Uint32 NumAllowedTypes, ShaderResourceCacheVk& ResourceCache) : m_Owner(Owner), - m_ResourceLayout(SrcLayout), m_ResourceCache(ResourceCache) #ifdef _DEBUG , m_DbgAllocator(Allocator) -- cgit v1.2.3 From 5026a05381f82bbcdc2ff804363c96a3c1b9fa67 Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Wed, 6 Mar 2019 10:17:37 -0800 Subject: Minor comment updates --- Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h | 3 ++- Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) (limited to 'Graphics') diff --git a/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h b/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h index 8b9f8fb8..240493cc 100644 --- a/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h +++ b/Graphics/GraphicsEngineD3D12/include/ShaderVariableD3D12.h @@ -101,7 +101,8 @@ private: // Variable mgr is owned by either Pipeline state object (in which case m_ResourceCache references // static resource cache owned by the same PSO object), or by SRB object (in which case - // m_ResourceCache references the cache in the SRB). Thus the cache is guaranteed to be alive. + // m_ResourceCache references the cache in the SRB). Thus the cache and the resource layout + // (which the variables reference) are guaranteed to be alive while the manager is alive. ShaderResourceCacheD3D12& m_ResourceCache; // Memory is allocated through the allocator provided by the pipeline state. If allocation granularity > 1, fixed block diff --git a/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h b/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h index 0b7e3aa0..03f5018f 100644 --- a/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h +++ b/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.h @@ -99,7 +99,8 @@ private: IObject& m_Owner; // Variable mgr is owned by either Pipeline state object (in which case m_ResourceCache references // static resource cache owned by the same PSO object), or by SRB object (in which case - // m_ResourceCache references the cache in the SRB). Thus the cache is guaranteed to be alive. + // m_ResourceCache references the cache in the SRB). Thus the cache and the resource layout + // (which the variables reference) are guaranteed to be alive while the manager is alive. ShaderResourceCacheVk& m_ResourceCache; // Memory is allocated through the allocator provided by the pipeline state. If allocation granularity > 1, fixed block -- cgit v1.2.3