summaryrefslogtreecommitdiffstats
path: root/Graphics/GraphicsEngineD3DBase/include/D3DShaderResourceLoader.hpp
blob: d5cf7e6ee1a6f5153126813d14b497ce3191bb4e (plain)
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
/*
 *  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.
 */

#pragma once

#include <string>
#include <vector>
#include <unordered_set>

#include "Shader.h"
#include "StringTools.hpp"

/// \file
/// D3D shader resource loading

namespace Diligent
{

struct D3DShaderResourceCounters
{
    Uint32 NumCBs          = 0;
    Uint32 NumTexSRVs      = 0;
    Uint32 NumTexUAVs      = 0;
    Uint32 NumBufSRVs      = 0;
    Uint32 NumBufUAVs      = 0;
    Uint32 NumSamplers     = 0;
    Uint32 NumAccelStructs = 0;
};

template <typename D3D_SHADER_DESC,
          typename D3D_SHADER_INPUT_BIND_DESC,

          typename TShaderReflection,
          typename THandleShaderDesc,
          typename TOnResourcesCounted,
          typename TOnNewCB,
          typename TOnNewTexUAV,
          typename TOnNewBuffUAV,
          typename TOnNewBuffSRV,
          typename TOnNewSampler,
          typename TOnNewTexSRV,
          typename TOnNewAccelStruct>
void LoadD3DShaderResources(TShaderReflection*  pShaderReflection,
                            THandleShaderDesc   HandleShaderDesc,
                            TOnResourcesCounted OnResourcesCounted,
                            TOnNewCB            OnNewCB,
                            TOnNewTexUAV        OnNewTexUAV,
                            TOnNewBuffUAV       OnNewBuffUAV,
                            TOnNewBuffSRV       OnNewBuffSRV,
                            TOnNewSampler       OnNewSampler,
                            TOnNewTexSRV        OnNewTexSRV,
                            TOnNewAccelStruct   OnNewAccelStruct)
{
    D3D_SHADER_DESC shaderDesc = {};
    pShaderReflection->GetDesc(&shaderDesc);

    HandleShaderDesc(shaderDesc);

    std::vector<D3DShaderResourceAttribs, STDAllocatorRawMem<D3DShaderResourceAttribs>> Resources(STD_ALLOCATOR_RAW_MEM(D3DShaderResourceAttribs, GetRawAllocator(), "Allocator for vector<D3DShaderResourceAttribs>"));
    Resources.reserve(shaderDesc.BoundResources);
    std::unordered_set<std::string> ResourceNamesTmpPool;

    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)
    {
        D3D_SHADER_INPUT_BIND_DESC BindingDesc = {};
        pShaderReflection->GetResourceBindingDesc(Res, &BindingDesc);

        if (BindingDesc.BindPoint == UINT32_MAX)
            BindingDesc.BindPoint = D3DShaderResourceAttribs::InvalidBindPoint;

        std::string Name(BindingDesc.Name);

        SkipCount = 1;

        UINT BindCount = BindingDesc.BindCount;
        if (BindCount == UINT_MAX)
        {
            // For some reason
            //      Texture2D g_Textures[]
            // produces BindCount == 0, but
            //      ConstantBuffer<CBData> g_ConstantBuffers[]
            // produces BindCount == UINT_MAX
            BindCount = 0;
        }

        // Handle arrays
        // For shader models 5_0 and before, every resource array element is enumerated individually.
        // For instance, if the following texture array is defined in the shader:
        //
        //     Texture2D<float3> g_tex2DDiffuse[4];
        //
        // The reflection system will enumerate 4 resources with the following names:
        // "g_tex2DDiffuse[0]"
        // "g_tex2DDiffuse[1]"
        // "g_tex2DDiffuse[2]"
        // "g_tex2DDiffuse[3]"
        //
        // Notice that if some array element is not used by the shader, it will not be enumerated

        auto OpenBracketPos = Name.find('[');
        if (String::npos != OpenBracketPos)
        {
            VERIFY(BindCount == 1, "When array elements are enumerated individually, BindCount is expected to always be 1");

            // Name == "g_tex2DDiffuse[0]"
            //                        ^
            //                   OpenBracketPos
            Name.erase(OpenBracketPos, Name.length() - OpenBracketPos);
            // Name == "g_tex2DDiffuse"
            VERIFY_EXPR(Name.length() == OpenBracketPos);
#ifdef DILIGENT_DEBUG
            for (const auto& ExistingRes : Resources)
            {
                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)
            {
                D3D_SHADER_INPUT_BIND_DESC ArrElemBindingDesc = {};
                pShaderReflection->GetResourceBindingDesc(ArrElem, &ArrElemBindingDesc);

                // Make sure this case is handled correctly:
                // "g_tex2DDiffuse[.]" != "g_tex2DDiffuse2[.]"
                if (strncmp(Name.c_str(), ArrElemBindingDesc.Name, OpenBracketPos) == 0 && ArrElemBindingDesc.Name[OpenBracketPos] == '[')
                {
                    //g_tex2DDiffuse[2]
                    //               ^
                    UINT Ind  = atoi(ArrElemBindingDesc.Name + OpenBracketPos + 1);
                    BindCount = std::max(BindCount, Ind + 1);
                    VERIFY(ArrElemBindingDesc.BindPoint == BindingDesc.BindPoint + Ind,
                           "Array elements are expected to use contigous bind points.\n",
                           BindingDesc.Name, " uses slot ", BindingDesc.BindPoint, ", so ", ArrElemBindingDesc.Name,
                           " is expected to use slot ", BindingDesc.BindPoint + Ind, " while ", ArrElemBindingDesc.BindPoint,
                           " is actually used");

                    // Note that skip count may not necessarily be the same as BindCount.
                    // If some array elements are not used by the shader, the reflection system skips them
                    ++SkipCount;
                }
                else
                {
                    break;
                }
            }
        }

        switch (BindingDesc.Type)
        {
            // clang-format off
            case D3D_SIT_CBUFFER:                       ++RC.NumCBs;                                                                           break;
            case D3D_SIT_TBUFFER:                       UNSUPPORTED( "TBuffers are not supported" );                                           break;
            case D3D_SIT_TEXTURE:                       ++(BindingDesc.Dimension == D3D_SRV_DIMENSION_BUFFER ? RC.NumBufSRVs : RC.NumTexSRVs); break;
            case D3D_SIT_SAMPLER:                       ++RC.NumSamplers;                                                                      break;
            case D3D_SIT_UAV_RWTYPED:                   ++(BindingDesc.Dimension == D3D_SRV_DIMENSION_BUFFER ? RC.NumBufUAVs : RC.NumTexUAVs); break;
            case D3D_SIT_STRUCTURED:                    ++RC.NumBufSRVs;                                                                       break;
            case D3D_SIT_UAV_RWSTRUCTURED:              ++RC.NumBufUAVs;                                                                       break;
            case D3D_SIT_BYTEADDRESS:                   ++RC.NumBufSRVs;                                                                       break;
            case D3D_SIT_UAV_RWBYTEADDRESS:             ++RC.NumBufUAVs;                                                                       break;
            case D3D_SIT_UAV_APPEND_STRUCTURED:         UNSUPPORTED( "Append structured buffers are not supported" );                          break;
            case D3D_SIT_UAV_CONSUME_STRUCTURED:        UNSUPPORTED( "Consume structured buffers are not supported" );                         break;
            case D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER: UNSUPPORTED( "RW structured buffers with counter are not supported" );                 break;
                // clang-format on

#pragma warning(push)
#pragma warning(disable : 4063)
            // D3D_SIT_RTACCELERATIONSTRUCTURE enum value is missing in Win SDK 17763, so we emulate it as #define, which
            // makes the compiler emit the following warning:
            //      warning C4063: case '12' is not a valid value for switch of enum '_D3D_SHADER_INPUT_TYPE'
            case D3D_SIT_RTACCELERATIONSTRUCTURE: ++RC.NumAccelStructs; break;
#pragma warning(pop)

            default: UNEXPECTED("Unexpected resource type");
        }
        ResourceNamesPoolSize += Name.length() + 1;
        auto it = ResourceNamesTmpPool.emplace(std::move(Name));
        Resources.emplace_back(
            it.first->c_str(),
            BindingDesc.BindPoint,
            BindCount,
            BindingDesc.Type,
            BindingDesc.Dimension,
            D3DShaderResourceAttribs::InvalidSamplerId);
    }

    OnResourcesCounted(RC, ResourceNamesPoolSize);

    std::vector<size_t, STDAllocatorRawMem<size_t>> TexSRVInds(STD_ALLOCATOR_RAW_MEM(size_t, GetRawAllocator(), "Allocator for vector<size_t>"));
    TexSRVInds.reserve(RC.NumTexSRVs);

    for (size_t ResInd = 0; ResInd < Resources.size(); ++ResInd)
    {
        const auto& Res = Resources[ResInd];
        switch (Res.GetInputType())
        {
            case D3D_SIT_CBUFFER:
            {
                OnNewCB(Res);
                break;
            }

            case D3D_SIT_TBUFFER:
            {
                UNSUPPORTED("TBuffers are not supported");
                break;
            }

            case D3D_SIT_TEXTURE:
            {
                if (Res.GetSRVDimension() == D3D_SRV_DIMENSION_BUFFER)
                {
                    OnNewBuffSRV(Res);
                }
                else
                {
                    // Texture SRVs must be processed all samplers are initialized
                    TexSRVInds.push_back(ResInd);
                }
                break;
            }

            case D3D_SIT_SAMPLER:
            {
                OnNewSampler(Res);
                break;
            }

            case D3D_SIT_UAV_RWTYPED:
            {
                if (Res.GetSRVDimension() == D3D_SRV_DIMENSION_BUFFER)
                {
                    OnNewBuffUAV(Res);
                }
                else
                {
                    OnNewTexUAV(Res);
                }
                break;
            }

            case D3D_SIT_STRUCTURED:
            {
                OnNewBuffSRV(Res);
                break;
            }

            case D3D_SIT_UAV_RWSTRUCTURED:
            {
                OnNewBuffUAV(Res);
                break;
            }

            case D3D_SIT_BYTEADDRESS:
            {
                OnNewBuffSRV(Res);
                break;
            }

            case D3D_SIT_UAV_RWBYTEADDRESS:
            {
                OnNewBuffUAV(Res);
                break;
            }

            case D3D_SIT_UAV_APPEND_STRUCTURED:
            {
                UNSUPPORTED("Append structured buffers are not supported");
                break;
            }

            case D3D_SIT_UAV_CONSUME_STRUCTURED:
            {
                UNSUPPORTED("Consume structured buffers are not supported");
                break;
            }

            case D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER:
            {
                UNSUPPORTED("RW structured buffers with counter are not supported");
                break;
            }

#pragma warning(push)
#pragma warning(disable : 4063)
            // D3D_SIT_RTACCELERATIONSTRUCTURE enum value is missing in Win SDK 17763, so we emulate it as #define, which
            // makes the compiler emit the following warning:
            //      warning C4063: case '12' is not a valid value for switch of enum '_D3D_SHADER_INPUT_TYPE'
            case D3D_SIT_RTACCELERATIONSTRUCTURE:
#pragma warning(pop)
            {
                OnNewAccelStruct(Res);
                break;
            }

            default:
            {
                UNEXPECTED("Unexpected resource input type");
            }
        }
    }

    // Process texture SRVs. We need to do this after all samplers are initialized
    for (auto TexSRVInd : TexSRVInds)
    {
        OnNewTexSRV(Resources[TexSRVInd]);
    }
}

} // namespace Diligent