Updated all header files to new format
[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) 2021 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 mVersion;
97 };
98
99 struct Component
100 {
101   enum Type
102   {
103     BYTE           = 5120,
104     UNSIGNED_BYTE  = 5121,
105     SHORT          = 5122,
106     UNSIGNED_SHORT = 5123,
107     UNSIGNED_INT   = 5125,
108     FLOAT          = 5126,
109     INVALID        = -1
110   };
111
112   static bool     IsUnsigned(Type t);
113   static uint32_t Size(Type t);
114
115   Component() = delete;
116 };
117
118 struct AccessorType
119 {
120   enum Type
121   {
122     SCALAR,
123     VEC2,
124     VEC3,
125     VEC4,
126     MAT2,
127     MAT3,
128     MAT4,
129     INVALID
130   };
131
132   static uint32_t ElementCount(Type t);
133
134   static Type FromString(const char* s, size_t len);
135
136   AccessorType() = delete;
137 };
138
139 struct AlphaMode
140 {
141   enum Type
142   {
143     OPAQUE,
144     MASK,
145     BLEND,
146     INVALID
147   };
148
149   static Type FromString(const char* s, size_t len);
150
151   AlphaMode() = delete;
152 };
153
154 struct Attribute
155 {
156   enum Type
157   {
158     POSITION,
159     NORMAL,
160     TANGENT,
161     TEXCOORD_0,
162     TEXCOORD_1,
163     COLOR_0,
164     JOINTS_0,
165     WEIGHTS_0,
166     INVALID
167   };
168
169   static Type FromString(const char* s, size_t len);
170
171   Attribute() = delete;
172 };
173
174 struct Buffer
175 {
176   uint32_t         mByteLength;
177   std::string_view mUri;
178   //TODO: extensions
179   //TODO: extras
180 };
181
182 struct BufferView
183 {
184   struct Target
185   {
186     enum Type
187     {
188       NONE,
189       ARRAY_BUFFER         = 34962,
190       ELEMENT_ARRAY_BUFFER = 34963
191     };
192
193     Target() = delete;
194   };
195
196   Ref<Buffer> mBuffer;
197   uint32_t    mByteOffset = 0;
198   uint32_t    mByteLength;
199   uint32_t    mByteStride = 0; // if 0 after reading, it needs to be calculated
200   uint32_t    mTarget;
201   //TODO: extensions
202   //TODO: extras
203 };
204
205 struct BufferViewClient
206 {
207   Ref<BufferView> mBufferView;
208   uint32_t        mByteOffset = 0;
209 };
210
211 struct ComponentTypedBufferViewClient : BufferViewClient
212 {
213   Component::Type mComponentType = Component::INVALID;
214
215   uint32_t GetBytesPerComponent() const;
216 };
217
218 struct Named
219 {
220   std::string_view mName;
221
222 protected:
223   Named() = default;
224 };
225
226 struct Accessor : ComponentTypedBufferViewClient, Named
227 {
228   struct Sparse
229   {
230     uint32_t                       mCount;
231     ComponentTypedBufferViewClient mIndices;
232     BufferViewClient               mValues;
233     //TODO: extensions
234     //TODO: extras
235   };
236
237   uint32_t                mCount;
238   bool                    mNormalized = false;
239   AccessorType::Type      mType       = AccessorType::INVALID;
240   std::vector<float>      mMin;
241   std::vector<float>      mMax;
242   std::unique_ptr<Sparse> mSparse;
243   //TODO: extensions
244   //TODO: extras
245
246   uint32_t GetElementSizeBytes() const
247   {
248     return GetBytesPerComponent() * AccessorType::ElementCount(mType);
249   }
250
251   uint32_t GetBytesLength() const
252   {
253     return GetElementSizeBytes() * mCount;
254   }
255
256   void SetSparse(const Sparse& s)
257   {
258     mSparse.reset(new Sparse(s));
259   }
260 };
261
262 struct Image : Named
263 {
264   std::string_view mUri;
265   std::string_view mMimeType;
266   Ref<BufferView>  mBufferView;
267   //TODO: extensions
268   //TODO: extras
269 };
270
271 struct Filter
272 {
273   enum Type
274   {
275     NEAREST                = 9728,
276     LINEAR                 = 9729,
277     NEAREST_MIPMAP_NEAREST = 9984,
278     NEAREST_MIPMAP_LINEAR  = 9985,
279     LINEAR_MIPMAP_NEAREST  = 9986,
280     LINEAR_MIPMAP_LINEAR   = 9987,
281   };
282
283   Filter() = delete;
284 };
285
286 struct Wrap
287 {
288   enum Type
289   {
290     REPEAT          = 10497,
291     CLAMP_TO_EDGE   = 33071,
292     MIRRORED_REPEAT = 33648,
293   };
294
295   Wrap() = delete;
296 };
297
298 struct Sampler
299 {
300   Filter::Type mMinFilter = Filter::LINEAR;
301   Filter::Type mMagFilter = Filter::LINEAR;
302   Wrap::Type   mWrapS     = Wrap::CLAMP_TO_EDGE;
303   Wrap::Type   mWrapT     = Wrap::CLAMP_TO_EDGE;
304   //TODO: extensions
305   //TODO: extras
306 };
307
308 struct Texture
309 {
310   Ref<Image>   mSource;
311   Ref<Sampler> mSampler;
312 };
313
314 struct TextureInfo
315 {
316   Ref<gltf2::Texture> mTexture;
317   uint32_t            mTexCoord = 0;
318   float               mScale    = 1.f;
319
320   operator bool() const
321   {
322     return !!mTexture;
323   }
324 };
325
326 struct Material : Named
327 {
328   struct Pbr //MetallicRoughness
329   {
330     Dali::Vector4 mBaseColorFactor = Dali::Vector4::ONE;
331     TextureInfo   mBaseColorTexture;
332     float         mMetallicFactor  = 1.f;
333     float         mRoughnessFactor = 1.f;
334     TextureInfo   mMetallicRoughnessTexture;
335     //TODO: extensions
336     //TODO: extras
337   };
338
339   Pbr             mPbrMetallicRoughness;
340   TextureInfo     mNormalTexture;
341   TextureInfo     mOcclusionTexture;
342   TextureInfo     mEmissiveTexture;
343   Dali::Vector3   mEmissiveFactor;
344   AlphaMode::Type mAlphaMode   = AlphaMode::OPAQUE;
345   float           mAlphaCutoff = .5f;
346   bool            mDoubleSided = false;
347   //TODO: extensions
348   //TODO: extras
349 };
350
351 struct Mesh : Named
352 {
353   struct Primitive
354   {
355     enum Mode
356     {
357       POINTS,
358       LINES,
359       LINE_LOOP,
360       LINE_STRIP,
361       TRIANGLES,
362       TRIANGLE_STRIP,
363       TRIANGLE_FAN,
364       INVALID
365     };
366
367     std::map<Attribute::Type, Ref<Accessor>>              mAttributes;
368     std::vector<std::map<Attribute::Type, Ref<Accessor>>> mTargets;
369     Ref<Accessor>                                         mIndices;
370     Ref<Material>                                         mMaterial;
371     Mode                                                  mMode = TRIANGLES;
372
373     //TODO: [morph] targets
374     //TODO: extras
375     //TODO: extensions
376   };
377
378   std::vector<Primitive> mPrimitives;
379   std::vector<float>     mWeights;
380   //TODO: extras
381   //TODO: extensions
382 };
383
384 struct Node;
385
386 struct Skin : Named
387 {
388   Ref<Accessor>          mInverseBindMatrices;
389   Ref<Node>              mSkeleton;
390   std::vector<Ref<Node>> mJoints;
391   //TODO: extras
392   //TODO: extensions
393 };
394
395 struct Camera : Named
396 {
397   struct Perspective
398   {
399     float mAspectRatio;
400     float mYFov;
401     float mZFar;
402     float mZNear;
403     //TODO: extras
404     //TODO: extensions
405   };
406
407   struct Orthographic
408   {
409     float mXMag;
410     float mYMag;
411     float mZFar;
412     float mZNear;
413     //TODO: extras
414     //TODO: extensions
415   };
416
417   std::string_view mType;
418   Perspective      mPerspective;
419   Orthographic     mOrthographic;
420   //TODO: extras
421   //TODO: extensions
422 };
423
424 struct Node : Named
425 {
426   Dali::Vector3    mTranslation = Dali::Vector3::ZERO;
427   Dali::Quaternion mRotation    = Dali::Quaternion::IDENTITY;
428   Dali::Vector3    mScale       = Dali::Vector3::ONE;
429
430   Ref<Camera>            mCamera;
431   std::vector<Ref<Node>> mChildren;
432   Ref<Mesh>              mMesh;
433
434   Ref<Skin> mSkin;
435   //TODO: [morph] weights
436   //TODO: extras
437   //TODO: extensions
438
439   void SetMatrix(const Dali::Matrix& m);
440 };
441
442 struct Animation : Named
443 {
444   struct Sampler
445   {
446     struct Interpolation
447     {
448       enum Type
449       {
450         STEP,
451         LINEAR,
452         CUBICSPLINE,
453         INVALID
454       };
455       static Type FromString(const char* s, size_t len);
456     };
457
458     Ref<Accessor>       mInput;
459     Ref<Accessor>       mOutput;
460     Interpolation::Type mInterpolation;
461
462     //TODO: extras
463     //TODO: extensions
464   };
465
466   struct Channel
467   {
468     struct Target
469     {
470       enum Type
471       {
472         TRANSLATION,
473         ROTATION,
474         SCALE,
475         WEIGHTS,
476         INVALID
477       };
478
479       static Type FromString(const char* s, size_t len);
480
481       Ref<Node> mNode;
482       Type      mPath;
483     };
484
485     Ref<Sampler> mSampler;
486     Target       mTarget;
487     //TODO: extras
488     //TODO: extensions
489   };
490
491   std::vector<Sampler> mSamplers;
492   std::vector<Channel> mChannels;
493 };
494
495 struct Scene : Named
496 {
497   std::vector<Ref<Node>> mNodes;
498 };
499
500 struct Document
501 {
502   Asset mAsset;
503
504   std::vector<Buffer>     mBuffers;
505   std::vector<BufferView> mBufferViews;
506   std::vector<Accessor>   mAccessors;
507
508   std::vector<Image>    mImages;
509   std::vector<Sampler>  mSamplers;
510   std::vector<Texture>  mTextures;
511   std::vector<Material> mMaterials;
512
513   std::vector<Mesh> mMeshes;
514   std::vector<Skin> mSkins;
515
516   std::vector<Camera> mCameras;
517   std::vector<Node>   mNodes;
518
519   std::vector<Animation> mAnimations;
520
521   std::vector<Scene> mScenes;
522   Ref<Scene>         mScene;
523
524   Document()                = default;
525   Document(const Document&) = delete;
526   Document(Document&&)      = default;
527
528   Document& operator=(const Document&) = delete;
529   Document& operator=(Document&&) = default;
530 };
531
532 /**
533  * @brief Provides a json::Property<T>::ReadFn for interpreting unsigned integers
534  *  as a Ref<U> into a std::vector<U> data member of a type T.
535  */
536 template<typename T>
537 struct RefReader
538 {
539   static T* sObject;
540
541   template<typename U, std::vector<U> T::*V>
542   static Ref<U> Read(const json_value_s& j)
543   {
544     uint32_t index = json::Read::Number<uint32_t>(j);
545     return Ref<U>(sObject->*V, index);
546   }
547 };
548
549 template<typename T>
550 T* RefReader<T>::sObject = nullptr;
551
552 /**
553  * @brief Convenience method to set the object for RefReader.
554  */
555 template<typename T>
556 void SetRefReaderObject(T& object)
557 {
558   RefReader<T>::sObject = &object;
559 }
560
561 /**
562  * @brief Reads a string and attempts to convert it to an enum.
563  * @note The enum must: 1, be called Type, nested to T, 2, provide a FromString static method taking a const char*
564  *  (string data) and a size_t (string length) and returning T::Type.
565  */
566 template<typename T> // T must have a nested enum called Type and a static Type FromString(const char*) method.
567 typename T::Type ReadStringEnum(const json_value_s& j)
568 {
569   auto str = json::Read::StringView(j);
570
571   return T::FromString(str.data(), str.size());
572 }
573
574 /**
575  * @brief Convenience method to attempt to create a Dali vector type T from an array of floats.
576  * @note T must provide an AsFloat() member method returning the non-const array of its
577  *  float components.
578  */
579 template<typename T>
580 inline T ReadDaliVector(const json_value_s& j)
581 {
582   std::vector<float> floats = json::Read::Array<float, json::Read::Number<float>>(j);
583   T                  result;
584   std::copy(floats.begin(), std::min(floats.end(), floats.begin() + sizeof(T) / sizeof(float)), result.AsFloat());
585   return result;
586 }
587
588 /**
589  * @brief Convenience method to attemt to read a Quaternion, which implicitly converts
590  *  to Vector4 but fails to provide an AsFloat() method.
591  */
592 Dali::Quaternion ReadQuaternion(const json_value_s& j);
593
594 } // namespace gltf2
595
596 #endif //DALI_SCENE_LOADER_GLTF2_ASSET_H_