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