Updated model loader to handle multiple attr sets
[platform/core/uifw/dali-toolkit.git] / dali-scene3d / public-api / loader / mesh-definition.h
1 #ifndef DALI_SCENE3D_LOADER_MESH_DEFINITION_H
2 #define DALI_SCENE3D_LOADER_MESH_DEFINITION_H
3 /*
4  * Copyright (c) 2023 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 // EXTERNAL INCLUDES
21 #include <dali/public-api/common/vector-wrapper.h>
22 #include <memory>
23
24 // INTERNAL INCLUDES
25 #include <dali-scene3d/public-api/api.h>
26 #include <dali-scene3d/public-api/loader/blend-shape-details.h>
27 #include <dali-scene3d/public-api/loader/buffer-definition.h>
28 #include <dali-scene3d/public-api/loader/index.h>
29 #include <dali-scene3d/public-api/loader/mesh-geometry.h>
30 #include <dali-scene3d/public-api/loader/utils.h>
31
32 namespace Dali::Scene3D::Loader
33 {
34 /**
35  * @brief Defines a mesh with its attributes, the primitive type to render it as,
36  *  and the file to load it from with the offset and length information for the
37  *  individual attribute buffers.
38  */
39 struct DALI_SCENE3D_API MeshDefinition
40 {
41   using Vector = std::vector<std::pair<MeshDefinition, MeshGeometry>>;
42
43   enum : uint32_t
44   {
45     INVALID = std::numeric_limits<uint32_t>::max()
46   };
47
48   enum Flags : uint32_t
49   {
50     FLIP_UVS_VERTICAL = NthBit(0),
51     U32_INDICES       = NthBit(1), // default is unsigned short
52     U8_INDICES        = NthBit(2), // default is unsigned short
53     U16_JOINT_IDS     = NthBit(3), // default is floats
54     U8_JOINT_IDS      = NthBit(4),
55     U16_WEIGHT        = NthBit(5), // default is floats
56     U8_WEIGHT         = NthBit(6),
57     S8_POSITION       = NthBit(7),  // default is floats
58     U8_POSITION       = NthBit(8),  // default is floats
59     S16_POSITION      = NthBit(9),  // default is floats
60     U16_POSITION      = NthBit(10), // default is floats
61     S8_NORMAL         = NthBit(11), // default is floats
62     S16_NORMAL        = NthBit(12), // default is floats
63     S8_TANGENT        = NthBit(13), // default is floats
64     S16_TANGENT       = NthBit(14), // default is floats
65     S8_TEXCOORD       = NthBit(15), // default is floats
66     U8_TEXCOORD       = NthBit(16), // default is floats
67     S16_TEXCOORD      = NthBit(17), // default is floats
68     U16_TEXCOORD      = NthBit(18), // default is floats
69   };
70
71   enum FlagMasks : uint32_t
72   {
73     POSITIONS_MASK = 0x780,
74     NORMALS_MASK   = 0x1800,
75     TANGENTS_MASK  = 0x6000,
76     TEXCOORDS_MASK = 0x78000,
77   };
78
79   enum Attributes
80   {
81     INDICES           = NthBit(0),
82     POSITIONS         = NthBit(1),
83     NORMALS           = NthBit(2),
84     TEX_COORDS        = NthBit(3),
85     TANGENTS          = NthBit(4),
86     LEGACY_BITANGENTS = NthBit(5), // these are ignored; we're calculating them in the (PBR) shader.
87     JOINTS_0          = NthBit(6),
88     WEIGHTS_0         = NthBit(7),
89   };
90
91   /**
92    * @brief Describes raw data in terms of its position and size in a buffer.
93    *  All units in bytes.
94    */
95   struct Blob
96   {
97     uint32_t           mOffset          = INVALID; // the default means that the blob is undefined.
98     uint32_t           mLength          = 0;       // if the blob is undefined, its data may still be generated. This is enabled by setting length to some non-0 value. Refer to MeshDefinition for details.
99     uint16_t           mStride          = 0;       // ignore if 0
100     uint16_t           mElementSizeHint = 0;       // ignore if 0 or stride == 0
101     std::vector<float> mMin;
102     std::vector<float> mMax;
103
104     static void ComputeMinMax(std::vector<float>& min, std::vector<float>& max, uint32_t numComponents, uint32_t count, const float* values);
105
106     static void ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values, std::vector<uint32_t>* sparseIndices = nullptr);
107
108     Blob() = default;
109
110     Blob(const Blob&) = default;
111     Blob& operator=(const Blob&) = default;
112
113     Blob(Blob&&)  = default;
114     Blob& operator=(Blob&&) = default;
115
116     Blob(uint32_t offset, uint32_t length, uint16_t stride = 0, uint16_t elementSizeHint = 0, const std::vector<float>& min = {}, const std::vector<float>& max = {});
117
118     /**
119      * @brief Calculates the size of a tightly-packed buffer for the elements from the blob.
120      */
121     uint32_t GetBufferSize() const;
122
123     /**
124      * @brief Convenience method to tell whether a Blob has meaningful data.
125      */
126     bool IsDefined() const
127     {
128       return mOffset != INVALID;
129     }
130
131     /**
132      * @brief Convenience method to tell whether the elements stored in the blob follow each
133      *  other tightly. The opposite would be interleaving.
134      */
135     bool IsConsecutive() const
136     {
137       return mStride == 0 || mStride == mElementSizeHint;
138     }
139
140     /**
141      * @brief Computes the min / max of the input value data.
142      * The min and max are stored in mMin and mMax.
143      *
144      * @param[in] numComponents number of components of data type. e.g., 3 for Vector3.
145      * @param[in] count The number of data.
146      * @param[in] values Data for the mesh.
147      */
148     void ComputeMinMax(uint32_t numComponents, uint32_t count, float* values);
149
150     /**
151      * @brief Applies the min / max values, if they're defined in the model
152      *
153      * @param[in] count The number of data.
154      * @param[in] values Data for the mesh that min / max values will be applied.
155      * @param[in] sparseIndices Pointer to array of sparse indices (or nullptr if not provided)
156      *
157      */
158     void ApplyMinMax(uint32_t count, float* values, std::vector<uint32_t>* sparseIndices = nullptr) const;
159   };
160
161   /**
162    * @brief A sparse blob describes a change in a reference Blob.
163    * @p indices describe what positions of the reference Blob change and
164    * @p values describe the new values.
165    */
166   struct SparseBlob
167   {
168     SparseBlob() = default;
169
170     SparseBlob(const SparseBlob&) = default;
171     SparseBlob& operator=(const SparseBlob&) = default;
172
173     SparseBlob(SparseBlob&&) = default;
174     SparseBlob& operator=(SparseBlob&&) = default;
175
176     SparseBlob(const Blob& indices, const Blob& values, uint32_t count);
177     SparseBlob(Blob&& indices, Blob&& values, uint32_t count);
178
179     Blob     mIndices;
180     Blob     mValues;
181     uint32_t mCount = 0u;
182   };
183
184   struct Accessor
185   {
186     Blob                        mBlob;
187     std::unique_ptr<SparseBlob> mSparse;
188     Index                       mBufferIdx = INVALID_INDEX;
189     bool                        mNormalized{false};
190
191     Accessor() = default;
192
193     Accessor(const Accessor&) = delete;
194     Accessor& operator=(const Accessor&) = delete;
195
196     Accessor(Accessor&&) = default;
197     Accessor& operator=(Accessor&&) = default;
198
199     Accessor(const MeshDefinition::Blob&       blob,
200              const MeshDefinition::SparseBlob& sparse,
201              Index                             bufferIndex = INVALID_INDEX,
202              bool                              normalized = false);
203
204     Accessor(MeshDefinition::Blob&&       blob,
205              MeshDefinition::SparseBlob&& sparse,
206              Index                        bufferIndex = INVALID_INDEX,
207              bool                         normalized = false);
208
209     bool IsDefined() const
210     {
211       return mBlob.IsDefined() || (mSparse && (mSparse->mIndices.IsDefined() && mSparse->mValues.IsDefined()));
212     }
213   };
214
215   /**
216    * @brief Stores a blend shape.
217    */
218   struct BlendShape
219   {
220     std::string name;
221     Accessor    deltas;
222     Accessor    normals;
223     Accessor    tangents;
224     float       weight = 0.f;
225     uint32_t    mFlags = 0x0;
226   };
227
228   struct RawData
229   {
230     struct Attrib
231     {
232       std::string          mName;
233       Property::Type       mType;
234       uint32_t             mNumElements;
235       std::vector<uint8_t> mData;
236
237       void AttachBuffer(Geometry& g) const;
238     };
239
240     std::vector<uint16_t> mIndices;
241     std::vector<Attrib>   mAttribs;
242
243     unsigned int        mBlendShapeBufferOffset{0};
244     Dali::Vector<float> mBlendShapeUnnormalizeFactor;
245     PixelData           mBlendShapeData;
246   };
247
248   MeshDefinition() = default;
249
250   MeshDefinition(const MeshDefinition&) = delete;
251   MeshDefinition& operator=(const MeshDefinition&) = delete;
252
253   MeshDefinition(MeshDefinition&&) = default;
254   MeshDefinition& operator=(MeshDefinition&&) = default;
255
256   /**
257    * @brief Determines whether the mesh definition is that of a quad.
258    */
259   bool IsQuad() const;
260
261   /**
262    * @brief Determines whether the mesh is used for skeletal animation.
263    */
264   bool IsSkinned() const;
265
266   /**
267    * @brief Whether the mesh has blend shapes.
268    */
269   bool HasBlendShapes() const;
270
271   /**
272    * @brief Requests normals to be generated.
273    * @note Generation happens in LoadRaw().
274    * @note Must have Vector3 positions defined.
275    */
276   void RequestNormals();
277
278   /**
279    * @brief Requests tangents to be generated.
280    * @note Generation happens in LoadRaw().
281    * @note Must have Vector3 normals defined.
282    */
283   void RequestTangents();
284
285   /**
286    * @brief Loads raw geometry data, which includes index (optional) and
287    *  attribute buffers, as well as blend shape data. This is then returned.
288    * @note This can be done on any thread.
289    */
290   RawData LoadRaw(const std::string& modelsPath, BufferDefinition::Vector& buffers);
291
292   /**
293    * @brief Creates a MeshGeometry based firstly on the value of the uri member:
294    *  if it is "quad", a textured quad is created; otherwise it uses the
295    *  attribute (and index) buffers and blend shape information (if available)
296    *  from @a raw.
297    *  If mFlipVertical was set, the UVs are flipped in Y, i.e. v = 1.0 - v.
298    */
299   MeshGeometry Load(RawData&& raw) const;
300
301   /**
302    * @brief Retrieves what Components information is in this mesh's BlendShape.
303    *
304    * @param[out] hasPositions True if the BlendShape has position components
305    * @param[out] hasNormals True if the BlendShape has normal components
306    * @param[out] hasTangents True if the BlendShape has tangent components
307    */
308   void RetrieveBlendShapeComponents(bool& hasPositions, bool& hasNormals, bool& hasTangents) const;
309
310 public: // DATA
311   std::shared_ptr<RawData> mRawData;
312   uint32_t                 mFlags         = 0x0;
313   Geometry::Type           mPrimitiveType = Geometry::TRIANGLES;
314   std::string              mUri; // When the mesh data is loaded from embedded resources, this URI is used as a data stream.
315   Accessor                 mIndices;
316   Accessor                 mPositions;
317   Accessor                 mNormals;  // data can be generated based on positions
318   Accessor                 mTangents; // data can be generated based on normals and texCoords (the latter isn't mandatory; the results will be better if available)
319   std::vector<Accessor>    mTexCoords;
320   std::vector<Accessor>    mColors;
321   std::vector<Accessor>    mJoints;
322   std::vector<Accessor>    mWeights;
323   Property::Type           mTangentType{Property::VECTOR3};
324
325   Blob                    mBlendShapeHeader;
326   std::vector<BlendShape> mBlendShapes;
327   BlendShapes::Version    mBlendShapeVersion = BlendShapes::Version::INVALID;
328
329   Index          mSkeletonIdx = INVALID_INDEX;
330   ModelPrimitive mModelPrimitive;
331 };
332
333 } // namespace Dali::Scene3D::Loader
334
335 #endif //DALI_SCENE3D_LOADER_MESH_DEFINITION_H