git.s-ol.nu ~forks/DiligentTools / dca9874 AssetLoader / interface / GLTFLoader.hpp
dca9874

Tree @dca9874 (Download .tar.gz)

GLTFLoader.hpp @dca9874raw · 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
/*
 *  Copyright 2019-2020 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 <vector>
#include <array>
#include <memory>
#include <cfloat>
#include <unordered_map>
#include <mutex>

#include "../../../DiligentCore/Graphics/GraphicsEngine/interface/RenderDevice.h"
#include "../../../DiligentCore/Graphics/GraphicsEngine/interface/DeviceContext.h"
#include "../../../DiligentCore/Common/interface/RefCntAutoPtr.hpp"
#include "../../../DiligentCore/Common/interface/AdvancedMath.hpp"
#include "GLTFResourceManager.hpp"

namespace tinygltf
{

class Node;
class Model;

} // namespace tinygltf

namespace Diligent
{

namespace GLTF
{

struct GLTFCacheInfo
{
    GLTFResourceManager* pResourceMgr = nullptr;

    Uint8 IndexBufferIdx   = 0;
    Uint8 VertexBuffer0Idx = 0;
    Uint8 VertexBuffer1Idx = 0;
};

struct Material
{
    Material() noexcept
    {
        TextureIds.fill(-1);
    }

    enum PBR_WORKFLOW
    {
        PBR_WORKFLOW_METALL_ROUGH = 0,
        PBR_WORKFLOW_SPEC_GLOSS
    };

    // Material attributes packed in a shader-friendly format
    struct ShaderAttribs
    {
        float4 BaseColorFactor = float4{1, 1, 1, 1};
        float4 EmissiveFactor  = float4{1, 1, 1, 1};
        float4 SpecularFactor  = float4{1, 1, 1, 1};

        int   Workflow                     = PBR_WORKFLOW_METALL_ROUGH;
        float BaseColorUVSelector          = -1;
        float PhysicalDescriptorUVSelector = -1;
        float NormalUVSelector             = -1;

        float OcclusionUVSelector     = -1;
        float EmissiveUVSelector      = -1;
        float BaseColorSlice          = 0;
        float PhysicalDescriptorSlice = 0;

        float NormalSlice    = 0;
        float OcclusionSlice = 0;
        float EmissiveSlice  = 0;
        float MetallicFactor = 1;

        float RoughnessFactor = 1;
        int   UseAlphaMask    = 0;
        float AlphaCutoff     = 0.5f;
        float Dummy0;

        // When texture atlas is used, UV scale and bias applied to
        // each texture coordinate set
        float4 BaseColorUVScaleBias          = float4{1, 1, 0, 0};
        float4 PhysicalDescriptorUVScaleBias = float4{1, 1, 0, 0};
        float4 NormalUVScaleBias             = float4{1, 1, 0, 0};
        float4 OcclusionUVScaleBias          = float4{1, 1, 0, 0};
        float4 EmissiveUVScaleBias           = float4{1, 1, 0, 0};
    };
    static_assert(sizeof(ShaderAttribs) % 16 == 0, "ShaderAttribs struct must be 16-byte aligned");
    ShaderAttribs Attribs;

    enum ALPHA_MODE
    {
        ALPHAMODE_OPAQUE,
        ALPHAMODE_MASK,
        ALPHAMODE_BLEND
    };
    ALPHA_MODE AlphaMode = ALPHAMODE_OPAQUE;

    bool DoubleSided = false;

    enum TEXTURE_ID
    {
        // Base color for metallic-roughness workflow or
        // diffuse color for specular-glossinees workflow
        TEXTURE_ID_BASE_COLOR = 0,

        // Metallic-roughness or specular-glossinees map
        TEXTURE_ID_PHYSICAL_DESC,

        TEXTURE_ID_NORMAL_MAP,
        TEXTURE_ID_OCCLUSION,
        TEXTURE_ID_EMISSIVE,
        TEXTURE_ID_NUM_TEXTURES
    };
    // Texture indices in Model.Textures array
    std::array<int, TEXTURE_ID_NUM_TEXTURES> TextureIds = {};
};


struct Primitive
{
    const Uint32 FirstIndex;
    const Uint32 IndexCount;
    const Uint32 VertexCount;
    const Uint32 MaterialId;

    const BoundBox BB;

    Primitive(Uint32        _FirstIndex,
              Uint32        _IndexCount,
              Uint32        _VertexCount,
              Uint32        _MaterialId,
              const float3& BBMin,
              const float3& BBMax) :
        FirstIndex{_FirstIndex},
        IndexCount{_IndexCount},
        VertexCount{_VertexCount},
        MaterialId{_MaterialId},
        BB{BBMin, BBMax}
    {
    }

    Primitive(Primitive&&) = default;

    bool HasIndices() const
    {
        return IndexCount > 0;
    }
};



struct Mesh
{
    std::vector<Primitive> Primitives;

    BoundBox BB;

    bool IsValidBB = false;

    struct TransformData
    {
        float4x4              matrix;
        std::vector<float4x4> jointMatrices;
    };

    TransformData Transforms;

    Mesh(IRenderDevice* pDevice, const float4x4& matrix);
    void SetBoundingBox(const float3& min, const float3& max);
};


struct Node;
struct Skin
{
    std::string           Name;
    Node*                 pSkeletonRoot = nullptr;
    std::vector<float4x4> InverseBindMatrices;
    std::vector<Node*>    Joints;
};


struct Node
{
    std::string Name;
    Node*       Parent = nullptr;
    Uint32      Index;

    std::vector<std::unique_ptr<Node>> Children;

    float4x4              Matrix;
    std::unique_ptr<Mesh> _Mesh;
    Skin*                 _Skin     = nullptr;
    Int32                 SkinIndex = -1;
    float3                Translation;
    float3                Scale = float3{1, 1, 1};
    Quaternion            Rotation;
    BoundBox              BVH;
    BoundBox              AABB;
    bool                  IsValidBVH = false;

    float4x4 LocalMatrix() const;
    float4x4 GetMatrix() const;
    void     Update();
};


struct AnimationChannel
{
    enum PATH_TYPE
    {
        TRANSLATION,
        ROTATION,
        SCALE
    };
    PATH_TYPE PathType;
    Node*     node         = nullptr;
    Uint32    SamplerIndex = static_cast<Uint32>(-1);
};


struct AnimationSampler
{
    enum INTERPOLATION_TYPE
    {
        LINEAR,
        STEP,
        CUBICSPLINE
    };
    INTERPOLATION_TYPE  Interpolation;
    std::vector<float>  Inputs;
    std::vector<float4> OutputsVec4;
};

struct Animation
{
    std::string                   Name;
    std::vector<AnimationSampler> Samplers;
    std::vector<AnimationChannel> Channels;

    float Start = std::numeric_limits<float>::max();
    float End   = std::numeric_limits<float>::min();
};


struct Model
{
    struct VertexAttribs0
    {
        float3 pos;
        float3 normal;
        float2 uv0;
        float2 uv1;
    };

    struct VertexAttribs1
    {
        float4 joint0;
        float4 weight0;
    };

    enum BUFFER_ID
    {
        BUFFER_ID_VERTEX0 = 0,
        BUFFER_ID_VERTEX1,
        BUFFER_ID_INDEX,
        BUFFER_ID_NUM_BUFFERS
    };

    Uint32 IndexCount = 0;

    /// Transformation matrix that transforms unit cube [0,1]x[0,1]x[0,1] into
    /// axis-aligned bounding box in model space.
    float4x4 AABBTransform;

    std::vector<std::unique_ptr<Node>> Nodes;
    std::vector<Node*>                 LinearNodes;

    std::vector<std::unique_ptr<Skin>> Skins;

    std::vector<RefCntAutoPtr<ISampler>> TextureSamplers;
    std::vector<Material>                Materials;
    std::vector<Animation>               Animations;
    std::vector<std::string>             Extensions;

    struct Dimensions
    {
        float3 min = float3{+FLT_MAX, +FLT_MAX, +FLT_MAX};
        float3 max = float3{-FLT_MAX, -FLT_MAX, -FLT_MAX};
    } dimensions;

    struct TextureCacheType
    {
        std::mutex TexturesMtx;

        std::unordered_map<std::string, RefCntWeakPtr<ITexture>> Textures;
    };

    Model(IRenderDevice*     pDevice,
          IDeviceContext*    pContext,
          const std::string& filename,
          TextureCacheType*  pTextureCache = nullptr,
          GLTFCacheInfo*     pCache        = nullptr);

    ~Model();

    void UpdateAnimation(Uint32 index, float time);

    void PrepareGPUResources(IRenderDevice* pDevice, IDeviceContext* pCtx);

    IBuffer* GetBuffer(BUFFER_ID BuffId, IRenderDevice* pDevice, IDeviceContext* pCtx)
    {
        VERIFY_EXPR(BuffId < BUFFER_ID_NUM_BUFFERS);
        auto& Buff = Buffers[BuffId];
        if (Buff.pBuffer)
            return Buff.pBuffer;
        else if (Buff.pCacheAllocation)
            return Buff.pCacheAllocation->GetBuffer(pDevice, pCtx);
        else
            return nullptr;
    }

    Uint32 GetFirstIndexLocation() const
    {
        auto& IndBuff = Buffers[BUFFER_ID_INDEX];
        VERIFY(!IndBuff.pCacheAllocation || IndBuff.pCacheAllocation->GetRegion().UnalignedOffset % sizeof(Uint32) == 0,
               "Allocation offset is not multiple of sizeof(Uint32)");
        return IndBuff.pCacheAllocation ?
            static_cast<Uint32>(IndBuff.pCacheAllocation->GetRegion().UnalignedOffset / sizeof(Uint32)) :
            0;
    }

    Uint32 GetBaseVertex() const
    {
        auto& VertBuff = Buffers[BUFFER_ID_VERTEX0];
        VERIFY(!VertBuff.pCacheAllocation || VertBuff.pCacheAllocation->GetRegion().UnalignedOffset % sizeof(VertexAttribs0) == 0,
               "Allocation offset is not multiple of sizeof(VertexAttribs0)");
        return VertBuff.pCacheAllocation ?
            static_cast<Uint32>(VertBuff.pCacheAllocation->GetRegion().UnalignedOffset / sizeof(VertexAttribs0)) :
            0;
    }

    ITexture* GetTexture(Uint32 Index, IRenderDevice* pDevice, IDeviceContext* pCtx)
    {
        auto& TexInfo = Textures[Index];
        if (TexInfo.pTexture)
            return TexInfo.pTexture;
        else if (TexInfo.pCacheAllocation)
            return TexInfo.pCacheAllocation->GetTexture(pDevice, pCtx);
        else
            return nullptr;
    }

    const float4& GetUVScaleBias(Uint32 Index)
    {
        return Textures[Index].UVScaleBias;
    }

private:
    void LoadFromFile(IRenderDevice*     pDevice,
                      IDeviceContext*    pContext,
                      const std::string& filename,
                      TextureCacheType*  pTextureCache,
                      GLTFCacheInfo*     pCache);

    void LoadNode(IRenderDevice*         pDevice,
                  Node*                  parent,
                  const tinygltf::Node&  gltf_node,
                  uint32_t               nodeIndex,
                  const tinygltf::Model& gltf_model);

    void LoadSkins(const tinygltf::Model& gltf_model);

    void LoadTextures(IRenderDevice*         pDevice,
                      const tinygltf::Model& gltf_model,
                      const std::string&     BaseDir,
                      TextureCacheType*      pTextureCache);

    void  LoadTextureSamplers(IRenderDevice* pDevice, const tinygltf::Model& gltf_model);
    void  LoadMaterials(const tinygltf::Model& gltf_model);
    void  LoadAnimations(const tinygltf::Model& gltf_model);
    void  CalculateBoundingBox(Node* node, const Node* parent);
    void  GetSceneDimensions();
    Node* FindNode(Node* parent, Uint32 index);
    Node* NodeFromIndex(uint32_t index);

    GLTFCacheInfo CacheInfo;

    struct ResourceInitData;
    std::unique_ptr<ResourceInitData> InitData;

    struct BufferInfo
    {
        RefCntAutoPtr<IBuffer> pBuffer;

        RefCntAutoPtr<GLTFResourceManager::BufferAllocation> pCacheAllocation;
    };
    std::array<BufferInfo, BUFFER_ID_NUM_BUFFERS> Buffers;

    struct TextureInfo
    {
        RefCntAutoPtr<ITexture> pTexture;
        float4                  UVScaleBias{1, 1, 0, 0};

        RefCntAutoPtr<GLTFResourceManager::TextureAllocation> pCacheAllocation;

        bool IsValid() const
        {
            return pTexture || pCacheAllocation;
        }
    };
    std::vector<TextureInfo> Textures;
};

} // namespace GLTF

} // namespace Diligent