git.s-ol.nu ~forks/DiligentCore / 96e2faa Graphics / GraphicsEngineOpenGL / src / PipelineStateGLImpl.cpp
96e2faa

Tree @96e2faa (Download .tar.gz)

PipelineStateGLImpl.cpp @96e2faaraw · history · blame

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
/*
 *  Copyright 2019-2021 Diligent Graphics LLC
 *  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
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  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.
 */

#include "pch.h"
#include "PipelineStateGLImpl.hpp"
#include "RenderDeviceGLImpl.hpp"
#include "ShaderGLImpl.hpp"
#include "ShaderResourceBindingGLImpl.hpp"
#include "EngineMemory.h"
#include "DeviceContextGLImpl.hpp"

namespace Diligent
{

void PipelineStateGLImpl::CreateDefaultSignature(const PipelineStateCreateInfo& CreateInfo,
                                                 const TShaderStages&           ShaderStages,
                                                 SHADER_TYPE                    ActiveStages,
                                                 IPipelineResourceSignature**   ppSignature)
{
    std::vector<PipelineResourceDesc> Resources;

    const auto&       LayoutDesc     = CreateInfo.PSODesc.ResourceLayout;
    const auto        DefaultVarType = LayoutDesc.DefaultVariableType;
    ShaderResourcesGL ProgramResources;

    struct UniqueResource
    {
        const ShaderResourcesGL::GLResourceAttribs& Attribs;
        const SHADER_TYPE                           ShaderStages;

        bool operator==(const UniqueResource& Res) const
        {
            return strcmp(Attribs.Name, Res.Attribs.Name) == 0 && ShaderStages == Res.ShaderStages;
        }

        struct Hasher
        {
            size_t operator()(const UniqueResource& Res) const
            {
                return ComputeHash(CStringHash<Char>{}(Res.Attribs.Name), Uint32{Res.ShaderStages});
            }
        };
    };
    std::unordered_set<UniqueResource, UniqueResource::Hasher> UniqueResources;

    const auto HandleResource = [&](const ShaderResourcesGL::GLResourceAttribs& Attribs, PIPELINE_RESOURCE_FLAGS Flags) //
    {
        PipelineResourceDesc ResDesc = {};

        ResDesc.Name         = Attribs.Name;
        ResDesc.ShaderStages = Attribs.ShaderStages;
        ResDesc.ArraySize    = Attribs.ArraySize;
        ResDesc.ResourceType = Attribs.ResourceType;
        ResDesc.VarType      = DefaultVarType;
        ResDesc.Flags        = Flags;

        if (m_IsProgramPipelineSupported)
        {
            const auto VarIndex = FindPipelineResourceLayoutVariable(LayoutDesc, Attribs.Name, ResDesc.ShaderStages, nullptr);
            if (VarIndex != InvalidPipelineResourceLayoutVariableIndex)
            {
                const auto& Var      = LayoutDesc.Variables[VarIndex];
                ResDesc.ShaderStages = Var.ShaderStages;
                ResDesc.VarType      = Var.Type;
            }

            auto IterAndAssigned = UniqueResources.emplace(UniqueResource{Attribs, ResDesc.ShaderStages});
            if (IterAndAssigned.second)
            {
                Resources.push_back(ResDesc);
            }
            else
            {
                DEV_CHECK_ERR(IterAndAssigned.first->Attribs.ResourceType == Attribs.ResourceType,
                              "Shader variable '", Attribs.Name,
                              "' exists in multiple shaders from the same shader stage, but its type is not consistent between "
                              "shaders. All variables with the same name from the same shader stage must have the same type.");
            }
        }
        else
        {
            for (Uint32 i = 0; i < LayoutDesc.NumVariables; ++i)
            {
                const auto& Var = LayoutDesc.Variables[i];
                if ((Var.ShaderStages & Attribs.ShaderStages) != 0 &&
                    std::strcmp(Attribs.Name, Var.Name) == 0)
                {
                    ResDesc.VarType = Var.Type;
                    break;
                }
            }
            Resources.push_back(ResDesc);
        }
    };
    const auto HandleUB = [&](const ShaderResourcesGL::UniformBufferInfo& Attribs) {
        HandleResource(Attribs, PIPELINE_RESOURCE_FLAG_UNKNOWN);
    };
    const auto HandleTexture = [&](const ShaderResourcesGL::TextureInfo& Attribs) {
        HandleResource(Attribs, Attribs.ResourceType == SHADER_RESOURCE_TYPE_TEXTURE_SRV ? PIPELINE_RESOURCE_FLAG_COMBINED_SAMPLER : PIPELINE_RESOURCE_FLAG_FORMATTED_BUFFER);
    };
    const auto HandleImage = [&](const ShaderResourcesGL::ImageInfo& Attribs) {
        HandleResource(Attribs, Attribs.ResourceType == SHADER_RESOURCE_TYPE_TEXTURE_UAV ? PIPELINE_RESOURCE_FLAG_UNKNOWN : PIPELINE_RESOURCE_FLAG_FORMATTED_BUFFER);
    };
    const auto HandleSB = [&](const ShaderResourcesGL::StorageBlockInfo& Attribs) {
        HandleResource(Attribs, PIPELINE_RESOURCE_FLAG_UNKNOWN);
    };

    if (m_IsProgramPipelineSupported)
    {
        for (size_t i = 0; i < ShaderStages.size(); ++i)
        {
            auto* pShaderGL = ShaderStages[i];
            pShaderGL->GetShaderResources()->ProcessConstResources(HandleUB, HandleTexture, HandleImage, HandleSB);
        }
    }
    else
    {
        auto pImmediateCtx = m_pDevice->GetImmediateContext();
        VERIFY_EXPR(pImmediateCtx);
        VERIFY_EXPR(m_GLPrograms[0] != 0);

        ProgramResources.LoadUniforms(ActiveStages, m_GLPrograms[0], pImmediateCtx.RawPtr<DeviceContextGLImpl>()->GetContextState());
        ProgramResources.ProcessConstResources(HandleUB, HandleTexture, HandleImage, HandleSB);
    }

    if (Resources.size())
    {
        String SignName = String{"Implicit signature for PSO '"} + m_Desc.Name + '\'';

        PipelineResourceSignatureDesc ResSignDesc = {};

        ResSignDesc.Name                       = SignName.c_str();
        ResSignDesc.Resources                  = Resources.data();
        ResSignDesc.NumResources               = static_cast<Uint32>(Resources.size());
        ResSignDesc.ImmutableSamplers          = LayoutDesc.ImmutableSamplers;
        ResSignDesc.NumImmutableSamplers       = LayoutDesc.NumImmutableSamplers;
        ResSignDesc.BindingIndex               = 0;
        ResSignDesc.SRBAllocationGranularity   = CreateInfo.PSODesc.SRBAllocationGranularity;
        ResSignDesc.UseCombinedTextureSamplers = true;

        GetDevice()->CreatePipelineResourceSignature(ResSignDesc, ppSignature, true);

        if (*ppSignature == nullptr)
            LOG_ERROR_AND_THROW("Failed to create resource signature for pipeline state");
    }
}

void PipelineStateGLImpl::InitResourceLayouts(const PipelineStateCreateInfo& CreateInfo,
                                              const TShaderStages&           ShaderStages,
                                              SHADER_TYPE                    ActiveStages)
{
    const Uint32                              SignatureCount = CreateInfo.ResourceSignaturesCount;
    RefCntAutoPtr<IPipelineResourceSignature> pImplicitSignature;

    if (SignatureCount == 0 || CreateInfo.ppResourceSignatures == nullptr)
    {
        CreateDefaultSignature(CreateInfo, ShaderStages, ActiveStages, &pImplicitSignature);
        if (pImplicitSignature != nullptr)
        {
            VERIFY_EXPR(pImplicitSignature->GetDesc().BindingIndex == 0);
            m_Signatures[0]  = ValidatedCast<PipelineResourceSignatureGLImpl>(pImplicitSignature.RawPtr());
            m_SignatureCount = 1;
        }
    }
    else
    {
        const auto MaxBindingIndex =
            PipelineResourceSignatureGLImpl::CopyResourceSignatures(CreateInfo.PSODesc.PipelineType, SignatureCount, CreateInfo.ppResourceSignatures,
                                                                    m_Signatures.data(), m_Signatures.size());
        m_SignatureCount = static_cast<decltype(m_SignatureCount)>(MaxBindingIndex + 1);
        VERIFY_EXPR(m_SignatureCount == MaxBindingIndex + 1);
    }

    // Apply resource bindings to programs.
    auto& CtxState = m_pDevice->GetImmediateContext().RawPtr<DeviceContextGLImpl>()->GetContextState();

    PipelineResourceSignatureGLImpl::TBindings Bindings = {};

    for (Uint32 s = 0; s < m_SignatureCount; ++s)
    {
        const auto& pSignature = m_Signatures[s];
        if (pSignature == nullptr)
            continue;

        if (m_IsProgramPipelineSupported)
        {
            for (Uint32 p = 0; p < m_NumPrograms; ++p)
                pSignature->ApplyBindings(m_GLPrograms[p], CtxState, GetShaderStageType(p), Bindings);
        }
        else
        {
            pSignature->ApplyBindings(m_GLPrograms[0], CtxState, ActiveStages, Bindings);
        }
        pSignature->AddBindings(Bindings);
    }

    const auto& Limits = GetDevice()->GetDeviceLimits();

    if (Bindings[BINDING_RANGE_UNIFORM_BUFFER] > static_cast<Uint32>(Limits.MaxUniformBlocks))
        LOG_ERROR_AND_THROW("The number of bindings in range '", GetBindingRangeName(BINDING_RANGE_UNIFORM_BUFFER), "' is greater than the maximum allowed (", Limits.MaxUniformBlocks, ").");
    if (Bindings[BINDING_RANGE_TEXTURE] > static_cast<Uint32>(Limits.MaxTextureUnits))
        LOG_ERROR_AND_THROW("The number of bindings in range '", GetBindingRangeName(BINDING_RANGE_TEXTURE), "' is greater than the maximum allowed (", Limits.MaxTextureUnits, ").");
    if (Bindings[BINDING_RANGE_STORAGE_BUFFER] > static_cast<Uint32>(Limits.MaxStorageBlock))
        LOG_ERROR_AND_THROW("The number of bindings in range '", GetBindingRangeName(BINDING_RANGE_STORAGE_BUFFER), "' is greater than the maximum allowed (", Limits.MaxStorageBlock, ").");
    if (Bindings[BINDING_RANGE_IMAGE] > static_cast<Uint32>(Limits.MaxImagesUnits))
        LOG_ERROR_AND_THROW("The number of bindings in range '", GetBindingRangeName(BINDING_RANGE_IMAGE), "' is greater than the maximum allowed (", Limits.MaxImagesUnits, ").");

    if (m_IsProgramPipelineSupported)
    {
        for (size_t i = 0; i < ShaderStages.size(); ++i)
        {
            auto* pShaderGL = ShaderStages[i];
            ValidateShaderResources(pShaderGL->GetShaderResources(), pShaderGL->GetDesc().Name, pShaderGL->GetDesc().ShaderType);
        }
    }
    else
    {
        auto* pImmediateCtx = m_pDevice->GetImmediateContext().RawPtr<DeviceContextGLImpl>();
        VERIFY_EXPR(pImmediateCtx != nullptr);
        VERIFY_EXPR(m_GLPrograms[0] != 0);

        std::shared_ptr<ShaderResourcesGL> pResources{new ShaderResourcesGL{}};
        pResources->LoadUniforms(ActiveStages, m_GLPrograms[0], pImmediateCtx->GetContextState());
        ValidateShaderResources(std::move(pResources), m_Desc.Name, ActiveStages);
    }
}

template <typename PSOCreateInfoType>
void PipelineStateGLImpl::InitInternalObjects(const PSOCreateInfoType& CreateInfo, const TShaderStages& ShaderStages)
{
    const auto& deviceCaps = GetDevice()->GetDeviceCaps();
    VERIFY(deviceCaps.DevType != RENDER_DEVICE_TYPE_UNDEFINED, "Device caps are not initialized");

    m_IsProgramPipelineSupported = deviceCaps.Features.SeparablePrograms != DEVICE_FEATURE_STATE_DISABLED;

    FixedLinearAllocator MemPool{GetRawAllocator()};

    ReserveSpaceForPipelineDesc(CreateInfo, MemPool);
    MemPool.AddSpace<GLProgramObj>(m_IsProgramPipelineSupported ? ShaderStages.size() : 1);

    MemPool.Reserve();

    InitializePipelineDesc(CreateInfo, MemPool);

    // Get active shader stages.
    SHADER_TYPE ActiveStages = SHADER_TYPE_UNKNOWN;
    for (auto* pShaderGL : ShaderStages)
    {
        const auto ShaderType = pShaderGL->GetDesc().ShaderType;
        VERIFY((ActiveStages & ShaderType) == 0, "Shader stage ", GetShaderTypeLiteralName(ShaderType), " is already active");
        ActiveStages |= ShaderType;
    }

    // Create programs.
    if (m_IsProgramPipelineSupported)
    {
        VERIFY_EXPR(m_ShaderTypes.size() >= ShaderStages.size());
        m_GLPrograms = MemPool.ConstructArray<GLProgramObj>(ShaderStages.size(), false);
        for (size_t i = 0; i < ShaderStages.size(); ++i)
        {
            auto* pShaderGL  = ShaderStages[i];
            m_GLPrograms[i]  = GLProgramObj{ShaderGLImpl::LinkProgram(&ShaderStages[i], 1, true)};
            m_ShaderTypes[i] = pShaderGL->GetDesc().ShaderType;
        }
        m_NumPrograms = static_cast<Uint8>(ShaderStages.size());
    }
    else
    {
        m_GLPrograms     = MemPool.ConstructArray<GLProgramObj>(1, false);
        m_GLPrograms[0]  = ShaderGLImpl::LinkProgram(ShaderStages.data(), static_cast<Uint32>(ShaderStages.size()), false);
        m_ShaderTypes[0] = ActiveStages;
        m_NumPrograms    = 1;
    }

    InitResourceLayouts(CreateInfo, ShaderStages, ActiveStages);
}

PipelineStateGLImpl::PipelineStateGLImpl(IReferenceCounters*                    pRefCounters,
                                         RenderDeviceGLImpl*                    pDeviceGL,
                                         const GraphicsPipelineStateCreateInfo& CreateInfo,
                                         bool                                   bIsDeviceInternal) :
    // clang-format off
    TPipelineStateBase
    {
        pRefCounters,
        pDeviceGL,
        CreateInfo,
        bIsDeviceInternal
    }
// clang-format on
{
    try
    {
        TShaderStages Shaders;
        ExtractShaders<ShaderGLImpl>(CreateInfo, Shaders);

        RefCntAutoPtr<ShaderGLImpl> pTempPS;
        if (CreateInfo.pPS == nullptr)
        {
            // Some OpenGL implementations fail if fragment shader is not present, so
            // create a dummy one.
            ShaderCreateInfo ShaderCI;
            ShaderCI.SourceLanguage  = SHADER_SOURCE_LANGUAGE_GLSL;
            ShaderCI.Source          = "void main(){}";
            ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL;
            ShaderCI.Desc.Name       = "Dummy fragment shader";
            pDeviceGL->CreateShader(ShaderCI, reinterpret_cast<IShader**>(static_cast<ShaderGLImpl**>(&pTempPS)));

            Shaders.emplace_back(pTempPS);
        }

        InitInternalObjects(CreateInfo, Shaders);
    }
    catch (...)
    {
        Destruct();
        throw;
    }
}

PipelineStateGLImpl::PipelineStateGLImpl(IReferenceCounters*                   pRefCounters,
                                         RenderDeviceGLImpl*                   pDeviceGL,
                                         const ComputePipelineStateCreateInfo& CreateInfo,
                                         bool                                  bIsDeviceInternal) :
    // clang-format off
    TPipelineStateBase
    {
        pRefCounters,
        pDeviceGL,
        CreateInfo,
        bIsDeviceInternal
    }
// clang-format on
{
    try
    {
        TShaderStages Shaders;
        ExtractShaders<ShaderGLImpl>(CreateInfo, Shaders);

        InitInternalObjects(CreateInfo, Shaders);
    }
    catch (...)
    {
        Destruct();
        throw;
    }
}

PipelineStateGLImpl::~PipelineStateGLImpl()
{
    Destruct();
}

void PipelineStateGLImpl::Destruct()
{
    GetDevice()->OnDestroyPSO(this);

    if (m_GLPrograms)
    {
        for (Uint32 i = 0; i < m_NumPrograms; ++i)
        {
            m_GLPrograms[i].~GLProgramObj();
        }
        m_GLPrograms = nullptr;
    }

    m_Signatures.fill({});

    m_SignatureCount = 0;
    m_NumPrograms    = 0;

    TPipelineStateBase::Destruct();
}

IMPLEMENT_QUERY_INTERFACE(PipelineStateGLImpl, IID_PipelineStateGL, TPipelineStateBase)

SHADER_TYPE PipelineStateGLImpl::GetShaderStageType(Uint32 Index) const
{
    VERIFY(Index < m_NumPrograms, "Index is out of range");
    return m_ShaderTypes[Index];
}

bool PipelineStateGLImpl::IsCompatibleWith(const IPipelineState* pPSO) const
{
    VERIFY_EXPR(pPSO != nullptr);

    if (pPSO == this)
        return true;

    const auto& lhs = *this;
    const auto& rhs = *ValidatedCast<const PipelineStateGLImpl>(pPSO);

    if (lhs.GetResourceSignatureCount() != rhs.GetResourceSignatureCount())
        return false;

    for (Uint32 s = 0, SigCount = lhs.GetResourceSignatureCount(); s < SigCount; ++s)
    {
        if (!lhs.GetSignature(s)->IsCompatibleWith(*rhs.GetSignature(s)))
            return false;
    }
    return true;
}

void PipelineStateGLImpl::CommitProgram(GLContextState& State)
{
    if (m_IsProgramPipelineSupported)
    {
        // WARNING: glUseProgram() overrides glBindProgramPipeline(). That is, if you have a program in use and
        // a program pipeline bound, all rendering will use the program that is in use, not the pipeline programs!
        // So make sure that glUseProgram(0) has been called if pipeline is in use
        State.SetProgram(GLObjectWrappers::GLProgramObj::Null());
        auto& Pipeline = GetGLProgramPipeline(State.GetCurrentGLContext());
        VERIFY(Pipeline != 0, "Program pipeline must not be null");
        State.SetPipeline(Pipeline);
    }
    else
    {
        VERIFY_EXPR(m_GLPrograms != nullptr);
        State.SetProgram(m_GLPrograms[0]);
    }
}

GLObjectWrappers::GLPipelineObj& PipelineStateGLImpl::GetGLProgramPipeline(GLContext::NativeGLContextType Context)
{
    ThreadingTools::LockHelper Lock(m_ProgPipelineLockFlag);
    for (auto& ctx_pipeline : m_GLProgPipelines)
    {
        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 i = 0; i < GetNumShaderStages(); ++i)
    {
        auto GLShaderBit = ShaderTypeToGLShaderBit(GetShaderStageType(i));
        // 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, m_GLPrograms[i]);
        CHECK_GL_ERROR("glUseProgramStages() failed");
    }
    return ctx_pipeline.second;
}

PipelineStateGLImpl::ResourceAttribution PipelineStateGLImpl::GetResourceAttribution(const char* Name, SHADER_TYPE Stage) const
{
    const auto SignCount = GetResourceSignatureCount();
    for (Uint32 sign = 0; sign < SignCount; ++sign)
    {
        const auto* const pSignature = GetSignature(sign);
        if (pSignature == nullptr)
            continue;

        const auto ResIndex = pSignature->FindResource(Stage, Name);
        if (ResIndex != ResourceAttribution::InvalidResourceIndex)
            return ResourceAttribution{pSignature, sign, ResIndex};
        else
        {
            const auto ImtblSamIndex = pSignature->FindImmutableSampler(Stage, Name);
            if (ImtblSamIndex != ResourceAttribution::InvalidSamplerIndex)
                return ResourceAttribution{pSignature, sign, ResourceAttribution::InvalidResourceIndex, ImtblSamIndex};
        }
    }
    return ResourceAttribution{};
}

void PipelineStateGLImpl::ValidateShaderResources(std::shared_ptr<const ShaderResourcesGL> pShaderResources, const char* ShaderName, SHADER_TYPE ShaderStages)
{
    const auto HandleResource = [&](const ShaderResourcesGL::GLResourceAttribs& Attribs, SHADER_RESOURCE_TYPE AltResourceType, PIPELINE_RESOURCE_FLAGS Flags) //
    {
        const auto ResAttribution = GetResourceAttribution(Attribs.Name, ShaderStages);

#ifdef DILIGENT_DEVELOPMENT
        m_ResourceAttibutions.emplace_back(ResAttribution);
#endif

        if (!ResAttribution)
        {
            LOG_ERROR_AND_THROW("Shader '", ShaderName, "' contains resource '", Attribs.Name,
                                "' that is not present in any pipeline resource signature used to create pipeline state '",
                                m_Desc.Name, "'.");
        }

        const auto* const pSignature = ResAttribution.pSignature;
        VERIFY_EXPR(pSignature != nullptr);

        if (ResAttribution.ResourceIndex != ResourceAttribution::InvalidResourceIndex)
        {
            const auto& ResDesc = pSignature->GetResourceDesc(ResAttribution.ResourceIndex);

            // Shader reflection does not contain read-only flag, so image and storage buffer can be UAV or SRV.
            // Texture SRV is same as input attachment.
            const auto Type = (AltResourceType == ResDesc.ResourceType ? AltResourceType : Attribs.ResourceType);

            ValidatePipelineResourceCompatibility(ResDesc, Type, Flags, Attribs.ArraySize, ShaderName, pSignature->GetDesc().Name);
        }
        else
        {
            UNEXPECTED("Resource index should be valid");
        }
    };

    const auto HandleUB = [&](const ShaderResourcesGL::UniformBufferInfo& Attribs) {
        HandleResource(Attribs, Attribs.ResourceType, PIPELINE_RESOURCE_FLAG_UNKNOWN);
    };

    const auto HandleTexture = [&](const ShaderResourcesGL::TextureInfo& Attribs) {
        const bool IsTexelBuffer = (Attribs.ResourceType != SHADER_RESOURCE_TYPE_TEXTURE_SRV);
        HandleResource(Attribs,
                       IsTexelBuffer ? Attribs.ResourceType : SHADER_RESOURCE_TYPE_INPUT_ATTACHMENT,
                       IsTexelBuffer ? PIPELINE_RESOURCE_FLAG_FORMATTED_BUFFER : PIPELINE_RESOURCE_FLAG_COMBINED_SAMPLER);
    };

    const auto HandleImage = [&](const ShaderResourcesGL::ImageInfo& Attribs) {
        const bool IsImageBuffer = (Attribs.ResourceType != SHADER_RESOURCE_TYPE_TEXTURE_UAV);
        HandleResource(Attribs,
                       IsImageBuffer ? SHADER_RESOURCE_TYPE_BUFFER_SRV : SHADER_RESOURCE_TYPE_TEXTURE_SRV,
                       IsImageBuffer ? PIPELINE_RESOURCE_FLAG_FORMATTED_BUFFER : PIPELINE_RESOURCE_FLAG_UNKNOWN);
    };

    const auto HandleSB = [&](const ShaderResourcesGL::StorageBlockInfo& Attribs) {
        HandleResource(Attribs, SHADER_RESOURCE_TYPE_BUFFER_SRV, PIPELINE_RESOURCE_FLAG_UNKNOWN);
    };

    pShaderResources->ProcessConstResources(HandleUB, HandleTexture, HandleImage, HandleSB);

#ifdef DILIGENT_DEVELOPMENT
    m_ShaderResources.emplace_back(std::move(pShaderResources));
    m_ShaderNames.emplace_back(ShaderName);
#endif
}

#ifdef DILIGENT_DEVELOPMENT
void PipelineStateGLImpl::DvpVerifySRBResources(ShaderResourceBindingGLImpl* pSRBs[],
                                                const TBindings              BoundResOffsets[],
                                                Uint32                       NumSRBs) const
{
    // Verify SRB compatibility with this pipeline
    const auto SignCount = GetResourceSignatureCount();
    TBindings  Bindings  = {};
    for (Uint32 sign = 0; sign < SignCount; ++sign)
    {
        // Get resource signature from the root signature
        const auto& pSignature = GetSignature(sign);
        if (pSignature == nullptr || pSignature->GetTotalResourceCount() == 0)
            continue; // Skip null and empty signatures

        VERIFY_EXPR(pSignature->GetDesc().BindingIndex == sign);
        const auto* const pSRB = pSRBs[sign];
        if (pSRB == nullptr)
        {
            LOG_ERROR_MESSAGE("Pipeline state '", m_Desc.Name, "' requires SRB at index ", sign, " but none is bound in the device context.");
            continue;
        }

        const auto* const pSRBSign = pSRB->GetSignature();
        if (!pSignature->IsCompatibleWith(pSRBSign))
        {
            LOG_ERROR_MESSAGE("Shader resource binding at index ", sign, " with signature '", pSRBSign->GetDesc().Name,
                              "' is not compatible with pipeline layout in current pipeline '", m_Desc.Name, "'.");
        }

        DEV_CHECK_ERR(Bindings == BoundResOffsets[sign],
                      "Bound resources has incorrect base binding indices, this may indicate a bug in resource signature compatibility comparison.");

        pSignature->AddBindings(Bindings);
    }


    using AttribIter = std::vector<ResourceAttribution>::const_iterator;
    struct HandleResourceHelper
    {
        PipelineStateGLImpl const&    PSO;
        ShaderResourceBindingGLImpl** ppSRBs;
        const Uint32                  NumSRBs;
        AttribIter                    attrib_it;
        Uint32&                       shader_ind;

        HandleResourceHelper(const PipelineStateGLImpl& _PSO, ShaderResourceBindingGLImpl** _ppSRBs, Uint32 _NumSRBs, AttribIter iter, Uint32& ind) :
            PSO{_PSO}, ppSRBs{_ppSRBs}, NumSRBs{_NumSRBs}, attrib_it{iter}, shader_ind{ind}
        {}

        void Validate(const ShaderResourcesGL::GLResourceAttribs& Attribs, RESOURCE_DIMENSION ResDim, bool IsMS)
        {
            if (*attrib_it && !attrib_it->IsImmutableSampler())
            {
                if (attrib_it->SignatureIndex >= NumSRBs || ppSRBs[attrib_it->SignatureIndex] == nullptr)
                {
                    LOG_ERROR_MESSAGE("No resource is bound to variable '", Attribs.Name, "' in shader '", PSO.m_ShaderNames[shader_ind],
                                      "' of PSO '", PSO.m_Desc.Name, "': SRB at index ", attrib_it->SignatureIndex, " is not bound in the context.");
                    return;
                }

                const auto& SRBCache = ppSRBs[attrib_it->SignatureIndex]->GetResourceCache();
                attrib_it->pSignature->DvpValidateCommittedResource(Attribs, ResDim, IsMS, attrib_it->ResourceIndex, SRBCache, PSO.m_ShaderNames[shader_ind].c_str(), PSO.m_Desc.Name);
            }
            ++attrib_it;
        }

        void operator()(const ShaderResourcesGL::GLResourceAttribs& Attribs) { Validate(Attribs, RESOURCE_DIM_UNDEFINED, false); }
        void operator()(const ShaderResourcesGL::TextureInfo& Attribs) { Validate(Attribs, Attribs.ResourceDim, Attribs.IsMultisample); }
        void operator()(const ShaderResourcesGL::ImageInfo& Attribs) { Validate(Attribs, Attribs.ResourceDim, Attribs.IsMultisample); }
    };

    Uint32               i = 0;
    HandleResourceHelper HandleResource{*this, pSRBs, NumSRBs, m_ResourceAttibutions.begin(), i};

    VERIFY_EXPR(m_ShaderResources.size() == m_ShaderNames.size());
    for (; i < m_ShaderResources.size(); ++i)
    {
        m_ShaderResources[i]->ProcessConstResources(std::ref(HandleResource), std::ref(HandleResource), std::ref(HandleResource), std::ref(HandleResource));
    }
    VERIFY_EXPR(HandleResource.attrib_it == m_ResourceAttibutions.end());
}
#endif // DILIGENT_DEVELOPMENT

} // namespace Diligent