f5bd6b9c6cfab0ec8ac3f00f695284e18bc448bf
[platform/core/uifw/dali-toolkit.git] / dali-scene-loader / internal / gltf2-asset.h
1 #ifndef DALI_SCENE_LOADER_GLTF2_ASSET_H_
2 #define DALI_SCENE_LOADER_GLTF2_ASSET_H_
3 /*
4  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  */
19
20 // INTERNAL INCLUDES
21 #include "dali-scene-loader/internal/json-reader.h"
22 #include "dali-scene-loader/public-api/index.h"
23
24 // EXTERNAL INCLUDES
25 #include <cstdint>
26 #include <memory>
27 #include "dali/devel-api/common/map-wrapper.h"
28 #include "dali/public-api/common/vector-wrapper.h"
29 #include "dali/public-api/math/quaternion.h"
30 #include "dali/public-api/math/vector4.h"
31
32 namespace gltf2
33 {
34 using Index = Dali::SceneLoader::Index;
35
36 template<typename T>
37 class Ref
38 {
39 public:
40   Ref() = default;
41   Ref(std::vector<T>& v, Index i)
42   : mVector(&v),
43     mIndex(i)
44   {
45   }
46
47   /**
48    * @return The index of the object into the vector.
49    * @note It is client code responsibility to ensure that the vector is unambiguous. It should be in
50    *  a glTF document, since there's one vector for each type.
51    */
52   Index GetIndex() const
53   {
54     return mIndex;
55   }
56
57   /**
58    * @brief There may be scenarios in which the object, whose vector we're populating, changes, e.g.
59    *  when we don't have a final one at the time of reading the references.
60    */
61   void UpdateVector(std::vector<T>& v)
62   {
63     mVector = &v;
64   }
65
66   operator bool() const
67   {
68     return mVector != nullptr;
69   }
70   T* operator->() const
71   {
72     return &(*mVector)[mIndex];
73   }
74   T& operator*() const
75   {
76     return (*mVector)[mIndex];
77   }
78
79   bool operator==(const Ref<T>& other) const
80   {
81     return mVector == other.mVector && mIndex == other.mIndex;
82   }
83
84   bool operator!=(const Ref<T>& other) const
85   {
86     return !operator==(other);
87   }
88
89 private:
90   std::vector<T>* mVector = nullptr;
91   Index           mIndex  = Dali::SceneLoader::INVALID_INDEX;
92 };
93
94 struct Asset
95 {
96   std::string_view mGenerator;
97   std::string_view mVersion;
98 };
99
100 struct Component
101 {
102   enum Type
103   {
104     BYTE           = 5120,
105     UNSIGNED_BYTE  = 5121,
106     SHORT          = 5122,
107     UNSIGNED_SHORT = 5123,
108     UNSIGNED_INT   = 5125,
109     FLOAT          = 5126,
110     INVALID        = -1
111   };
112
113   static bool     IsUnsigned(Type t);
114   static uint32_t Size(Type t);
115
116   Component() = delete;
117 };
118
119 struct AccessorType
120 {
121   enum Type
122   {
123     SCALAR,
124     VEC2,
125     VEC3,
126     VEC4,
127     MAT2,
128     MAT3,
129     MAT4,
130     INVALID
131   };
132
133   static uint32_t ElementCount(Type t);
134
135   static Type FromString(const char* s, size_t len);
136
137   AccessorType() = delete;
138 };
139
140 struct AlphaMode
141 {
142   enum Type
143   {
144     OPAQUE,
145     MASK,
146     BLEND,
147     INVALID
148   };
149
150   static Type FromString(const char* s, size_t len);
151
152   AlphaMode() = delete;
153 };
154
155 struct Attribute
156 {
157   enum Type
158   {
159     POSITION,
160     NORMAL,
161     TANGENT,
162     TEXCOORD_0,
163     TEXCOORD_1,
164     COLOR_0,
165     JOINTS_0,
166     WEIGHTS_0,
167     INVALID
168   };
169
170   static Type FromString(const char* s, size_t len);
171
172   Attribute() = delete;
173 };
174
175 struct Buffer
176 {
177   uint32_t         mByteLength;
178   std::string_view mUri;
179   //TODO: extensions
180   //TODO: extras
181 };
182
183 struct BufferView
184 {
185   struct Target
186   {
187     enum Type
188     {
189       NONE,
190       ARRAY_BUFFER         = 34962,
191       ELEMENT_ARRAY_BUFFER = 34963
192     };
193
194     Target() = delete;
195   };
196
197   Ref<Buffer> mBuffer;
198   uint32_t    mByteOffset = 0;
199   uint32_t    mByteLength;
200   uint32_t    mByteStride = 0; // if 0 after reading, it needs to be calculated
201   uint32_t    mTarget;
202   //TODO: extensions
203   //TODO: extras
204 };
205
206 struct BufferViewClient
207 {
208   Ref<BufferView> mBufferView;
209   uint32_t        mByteOffset = 0;
210 };
211
212 struct ComponentTypedBufferViewClient : BufferViewClient
213 {
214   Component::Type mComponentType = Component::INVALID;
215
216   uint32_t GetBytesPerComponent() const;
217 };
218
219 struct Named
220 {
221   std::string_view mName;
222
223 protected:
224   Named() = default;
225 };
226
227 struct Accessor : ComponentTypedBufferViewClient, Named
228 {
229   struct Sparse
230   {
231     uint32_t                       mCount;
232     ComponentTypedBufferViewClient mIndices;
233     BufferViewClient               mValues;
234     //TODO: extensions
235     //TODO: extras
236   };
237
238   uint32_t                mCount;
239   bool                    mNormalized = false;
240   AccessorType::Type      mType       = AccessorType::INVALID;
241   std::vector<float>      mMin;
242   std::vector<float>      mMax;
243   std::unique_ptr<Sparse> mSparse;
244   //TODO: extensions
245   //TODO: extras
246
247   uint32_t GetElementSizeBytes() const
248   {
249     return GetBytesPerComponent() * AccessorType::ElementCount(mType);
250   }
251
252   uint32_t GetBytesLength() const
253   {
254     return GetElementSizeBytes() * mCount;
255   }
256
257   void SetSparse(const Sparse& s)
258   {
259     mSparse.reset(new Sparse(s));
260   }
261 };
262
263 struct Image : Named
264 {
265   std::string_view mUri;
266   std::string_view mMimeType;
267   Ref<BufferView>  mBufferView;
268   //TODO: extensions
269   //TODO: extras
270 };
271
272 struct Filter
273 {
274   enum Type
275   {
276     NEAREST                = 9728,
277     LINEAR                 = 9729,
278     NEAREST_MIPMAP_NEAREST = 9984,
279     NEAREST_MIPMAP_LINEAR  = 9985,
280     LINEAR_MIPMAP_NEAREST  = 9986,
281     LINEAR_MIPMAP_LINEAR   = 9987,
282   };
283
284   Filter() = delete;
285 };
286
287 struct Wrap
288 {
289   enum Type
290   {
291     REPEAT          = 10497,
292     CLAMP_TO_EDGE   = 33071,
293     MIRRORED_REPEAT = 33648,
294   };
295
296   Wrap() = delete;
297 };
298
299 struct Sampler
300 {
301   Filter::Type mMinFilter = Filter::LINEAR;
302   Filter::Type mMagFilter = Filter::LINEAR;
303   Wrap::Type   mWrapS     = Wrap::CLAMP_TO_EDGE;
304   Wrap::Type   mWrapT     = Wrap::CLAMP_TO_EDGE;
305   //TODO: extensions
306   //TODO: extras
307 };
308
309 struct Texture
310 {
311   Ref<Image>   mSource;
312   Ref<Sampler> mSampler;
313 };
314
315 struct TextureInfo
316 {
317   Ref<gltf2::Texture> mTexture;
318   uint32_t            mTexCoord = 0;
319   float               mScale    = 1.f;
320
321   operator bool() const
322   {
323     return !!mTexture;
324   }
325 };
326
327 struct Material : Named
328 {
329   struct Pbr //MetallicRoughness
330   {
331     Dali::Vector4 mBaseColorFactor = Dali::Vector4::ONE;
332     TextureInfo   mBaseColorTexture;
333     float         mMetallicFactor  = 1.f;
334     float         mRoughnessFactor = 1.f;
335     TextureInfo   mMetallicRoughnessTexture;
336     //TODO: extensions
337     //TODO: extras
338   };
339
340   Pbr             mPbrMetallicRoughness;
341   TextureInfo     mNormalTexture;
342   TextureInfo     mOcclusionTexture;
343   TextureInfo     mEmissiveTexture;
344   Dali::Vector3   mEmissiveFactor;
345   AlphaMode::Type mAlphaMode   = AlphaMode::OPAQUE;
346   float           mAlphaCutoff = .5f;
347   bool            mDoubleSided = false;
348   //TODO: extensions
349   //TODO: extras
350 };
351
352 struct Mesh : Named
353 {
354   struct Primitive
355   {
356     enum Mode
357     {
358       POINTS,
359       LINES,
360       LINE_LOOP,
361       LINE_STRIP,
362       TRIANGLES,
363       TRIANGLE_STRIP,
364       TRIANGLE_FAN,
365       INVALID
366     };
367
368     std::map<Attribute::Type, Ref<Accessor>>              mAttributes;
369     std::vector<std::map<Attribute::Type, Ref<Accessor>>> mTargets;
370     Ref<Accessor>                                         mIndices;
371     Ref<Material>                                         mMaterial;
372     Mode                                                  mMode = TRIANGLES;
373
374     //TODO: [morph] targets
375     //TODO: extras
376     //TODO: extensions
377   };
378
379   std::vector<Primitive> mPrimitives;
380   std::vector<float>     mWeights;
381   //TODO: extras
382   //TODO: extensions
383 };
384
385 struct Node;
386
387 struct Skin : Named
388 {
389   Ref<Accessor>          mInverseBindMatrices;
390   Ref<Node>              mSkeleton;
391   std::vector<Ref<Node>> mJoints;
392   //TODO: extras
393   //TODO: extensions
394 };
395
396 struct Camera : Named
397 {
398   struct Perspective
399   {
400     float mAspectRatio;
401     float mYFov;
402     float mZFar;
403     float mZNear;
404     //TODO: extras
405     //TODO: extensions
406   };
407
408   struct Orthographic
409   {
410     float mXMag;
411     float mYMag;
412     float mZFar;
413     float mZNear;
414     //TODO: extras
415     //TODO: extensions
416   };
417
418   std::string_view mType;
419   Perspective      mPerspective;
420   Orthographic     mOrthographic;
421   //TODO: extras
422   //TODO: extensions
423 };
424
425 struct Node : Named
426 {
427   Dali::Vector3    mTranslation = Dali::Vector3::ZERO;
428   Dali::Quaternion mRotation    = Dali::Quaternion::IDENTITY;
429   Dali::Vector3    mScale       = Dali::Vector3::ONE;
430
431   Ref<Camera>            mCamera;
432   std::vector<Ref<Node>> mChildren;
433   Ref<Mesh>              mMesh;
434
435   Ref<Skin> mSkin;
436   //TODO: [morph] weights
437   //TODO: extras
438   //TODO: extensions
439
440   void SetMatrix(const Dali::Matrix& m);
441 };
442
443 struct Animation : Named
444 {
445   struct Sampler
446   {
447     struct Interpolation
448     {
449       enum Type
450       {
451         STEP,
452         LINEAR,
453         CUBICSPLINE,
454         INVALID
455       };
456       static Type FromString(const char* s, size_t len);
457     };
458
459     Ref<Accessor>       mInput;
460     Ref<Accessor>       mOutput;
461     Interpolation::Type mInterpolation;
462
463     //TODO: extras
464     //TODO: extensions
465   };
466
467   struct Channel
468   {
469     struct Target
470     {
471       enum Type
472       {
473         TRANSLATION,
474         ROTATION,
475         SCALE,
476         WEIGHTS,
477         INVALID
478       };
479
480       static Type FromString(const char* s, size_t len);
481
482       Ref<Node> mNode;
483       Type      mPath;
484     };
485
486     Ref<Sampler> mSampler;
487     Target       mTarget;
488     //TODO: extras
489     //TODO: extensions
490   };
491
492   std::vector<Sampler> mSamplers;
493   std::vector<Channel> mChannels;
494 };
495
496 struct Scene : Named
497 {
498   std::vector<Ref<Node>> mNodes;
499 };
500
501 struct Document
502 {
503   Asset mAsset;
504
505   std::vector<Buffer>     mBuffers;
506   std::vector<BufferView> mBufferViews;
507   std::vector<Accessor>   mAccessors;
508
509   std::vector<Image>    mImages;
510   std::vector<Sampler>  mSamplers;
511   std::vector<Texture>  mTextures;
512   std::vector<Material> mMaterials;
513
514   std::vector<Mesh> mMeshes;
515   std::vector<Skin> mSkins;
516
517   std::vector<Camera> mCameras;
518   std::vector<Node>   mNodes;
519
520   std::vector<Animation> mAnimations;
521
522   std::vector<Scene> mScenes;
523   Ref<Scene>         mScene;
524
525   Document()                = default;
526   Document(const Document&) = delete;
527   Document(Document&&)      = default;
528
529   Document& operator=(const Document&) = delete;
530   Document& operator=(Document&&) = default;
531 };
532
533 /**
534  * @brief Provides a json::Property<T>::ReadFn for interpreting unsigned integers
535  *  as a Ref<U> into a std::vector<U> data member of a type T.
536  */
537 template<typename T>
538 struct RefReader
539 {
540   static T* sObject;
541
542   template<typename U, std::vector<U> T::*V>
543   static Ref<U> Read(const json_value_s& j)
544   {
545     uint32_t index = json::Read::Number<uint32_t>(j);
546     return Ref<U>(sObject->*V, index);
547   }
548 };
549
550 template<typename T>
551 T* RefReader<T>::sObject = nullptr;
552
553 /**
554  * @brief Convenience method to set the object for RefReader.
555  */
556 template<typename T>
557 void SetRefReaderObject(T& object)
558 {
559   RefReader<T>::sObject = &object;
560 }
561
562 /**
563  * @brief Reads a string and attempts to convert it to an enum.
564  * @note The enum must: 1, be called Type, nested to T, 2, provide a FromString static method taking a const char*
565  *  (string data) and a size_t (string length) and returning T::Type.
566  */
567 template<typename T> // T must have a nested enum called Type and a static Type FromString(const char*) method.
568 typename T::Type ReadStringEnum(const json_value_s& j)
569 {
570   auto str = json::Read::StringView(j);
571
572   return T::FromString(str.data(), str.size());
573 }
574
575 /**
576  * @brief Convenience method to attempt to create a Dali vector type T from an array of floats.
577  * @note T must provide an AsFloat() member method returning the non-const array of its
578  *  float components.
579  */
580 template<typename T>
581 inline T ReadDaliVector(const json_value_s& j)
582 {
583   std::vector<float> floats = json::Read::Array<float, json::Read::Number<float>>(j);
584   T                  result;
585   std::copy(floats.begin(), std::min(floats.end(), floats.begin() + sizeof(T) / sizeof(float)), result.AsFloat());
586   return result;
587 }
588
589 /**
590  * @brief Convenience method to attemt to read a Quaternion, which implicitly converts
591  *  to Vector4 but fails to provide an AsFloat() method.
592  */
593 Dali::Quaternion ReadQuaternion(const json_value_s& j);
594
595 } // namespace gltf2
596
597 #endif //DALI_SCENE_LOADER_GLTF2_ASSET_H_