Merge "Let we allow to change AnimationDefinition property" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-scene3d / public-api / loader / mesh-definition.cpp
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali-scene3d/public-api/loader/mesh-definition.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/adaptor-framework/file-stream.h>
23 #include <dali/devel-api/adaptor-framework/pixel-buffer.h>
24 #include <dali/integration-api/debug.h>
25 #include <dali/public-api/math/compile-time-math.h>
26 #include <cstring>
27 #include <fstream>
28 #include <type_traits>
29
30 namespace Dali::Scene3D::Loader
31 {
32 namespace
33 {
34 template<bool use32BitIndices>
35 class IndexProvider
36 {
37 public:
38   using IndexType = typename std::conditional_t<use32BitIndices, uint32_t, uint16_t>;
39   IndexProvider(const uint16_t* indices)
40   : mData(reinterpret_cast<uintptr_t>(indices)),
41     mFunc(indices ? IncrementPointer : Increment)
42   {
43   }
44
45   IndexType operator()()
46   {
47     return mFunc(mData);
48   }
49
50 private:
51   static IndexType Increment(uintptr_t& data)
52   {
53     // mData was 'zero' at construct time. Just simply return counter start with 0.
54     return static_cast<IndexType>(data++);
55   }
56
57   static IndexType IncrementPointer(uintptr_t& data)
58   {
59     auto iPtr   = reinterpret_cast<const IndexType*>(data);
60     auto result = *iPtr;
61     data        = reinterpret_cast<uintptr_t>(++iPtr);
62     return result;
63   }
64
65   uintptr_t mData;
66   IndexType (*mFunc)(uintptr_t&);
67 };
68
69 const char* QUAD("quad");
70
71 ///@brief Reads a blob from the given stream @a source into @a target, which must have
72 /// at least @a descriptor.length bytes.
73 bool ReadBlob(const MeshDefinition::Blob& descriptor, std::istream& source, uint8_t* target)
74 {
75   source.clear();
76   if(!source.seekg(descriptor.mOffset, std::istream::beg))
77   {
78     return false;
79   }
80
81   if(descriptor.IsConsecutive())
82   {
83     return !!source.read(reinterpret_cast<char*>(target), static_cast<std::streamsize>(static_cast<size_t>(descriptor.mLength)));
84   }
85   else
86   {
87     if(descriptor.mStride > descriptor.mElementSizeHint)
88     {
89       const uint32_t diff      = descriptor.mStride - descriptor.mElementSizeHint;
90       uint32_t       readSize  = 0;
91       uint32_t       totalSize = (descriptor.mLength / descriptor.mElementSizeHint) * descriptor.mStride;
92       while(readSize < totalSize &&
93             source.read(reinterpret_cast<char*>(target), descriptor.mElementSizeHint))
94       {
95         readSize += descriptor.mStride;
96         target += descriptor.mElementSizeHint;
97         source.seekg(diff, std::istream::cur);
98       }
99       return readSize == totalSize;
100     }
101   }
102   return false;
103 }
104
105 template<typename T>
106 void ReadValues(const std::vector<uint8_t>& valuesBuffer, const std::vector<uint8_t>& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint)
107 {
108   const T* const indicesPtr = reinterpret_cast<const T* const>(indicesBuffer.data());
109   for(uint32_t index = 0u; index < count; ++index)
110   {
111     uint32_t valuesIndex = indicesPtr[index] * elementSizeHint;
112     memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint);
113   }
114 }
115
116 bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source, uint8_t* target)
117 {
118   bool success = false;
119
120   if(accessor.mBlob.IsDefined())
121   {
122     success = ReadBlob(accessor.mBlob, source, target);
123     if(!success)
124     {
125       return false;
126     }
127   }
128
129   if(accessor.mSparse)
130   {
131     const MeshDefinition::Blob& indices = accessor.mSparse->mIndices;
132     const MeshDefinition::Blob& values  = accessor.mSparse->mValues;
133
134     if(!indices.IsDefined() || !values.IsDefined())
135     {
136       return false;
137     }
138
139     const auto           indicesBufferSize = indices.GetBufferSize();
140     std::vector<uint8_t> indicesBuffer(indicesBufferSize);
141     success = ReadBlob(indices, source, indicesBuffer.data());
142     if(!success)
143     {
144       return false;
145     }
146
147     const auto           valuesBufferSize = values.GetBufferSize();
148     std::vector<uint8_t> valuesBuffer(valuesBufferSize);
149     success = ReadBlob(values, source, valuesBuffer.data());
150     if(!success)
151     {
152       return false;
153     }
154
155     switch(indices.mElementSizeHint)
156     {
157       case 1u:
158       {
159         ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
160         break;
161       }
162       case 2u:
163       {
164         ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
165         break;
166       }
167       case 4u:
168       {
169         ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
170         break;
171       }
172       default:
173         DALI_ASSERT_DEBUG(!"Unsupported type for an index");
174     }
175   }
176
177   return success;
178 }
179
180 template<typename T>
181 void ReadJointAccessor(MeshDefinition::RawData& raw, const MeshDefinition::Accessor& accessor, std::istream& source, const std::string& meshPath)
182 {
183   constexpr auto sizeofBlobUnit = sizeof(T) * 4;
184
185   DALI_ASSERT_ALWAYS(((accessor.mBlob.mLength % sizeofBlobUnit == 0) ||
186                       accessor.mBlob.mStride >= sizeofBlobUnit) &&
187                      "Joints buffer length not a multiple of element size");
188   const auto inBufferSize  = accessor.mBlob.GetBufferSize();
189   const auto outBufferSize = (sizeof(Vector4) / sizeofBlobUnit) * inBufferSize;
190
191   std::vector<uint8_t> buffer(outBufferSize);
192   auto                 inBuffer = buffer.data() + outBufferSize - inBufferSize;
193   if(!ReadAccessor(accessor, source, inBuffer))
194   {
195     ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
196   }
197
198   if constexpr(sizeofBlobUnit != sizeof(Vector4))
199   {
200     auto       floats = reinterpret_cast<float*>(buffer.data());
201     const auto end    = inBuffer + inBufferSize;
202     while(inBuffer != end)
203     {
204       const auto value = *reinterpret_cast<T*>(inBuffer);
205       *floats          = static_cast<float>(value);
206
207       inBuffer += sizeof(T);
208       ++floats;
209     }
210   }
211   raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(outBufferSize / sizeof(Vector4)), std::move(buffer)});
212 }
213
214 template<typename T>
215 void ReadWeightAccessor(MeshDefinition::RawData& raw, const MeshDefinition::Accessor& accessor, std::istream& source, const std::string& meshPath)
216 {
217   constexpr auto sizeofBlobUnit = sizeof(T) * 4;
218
219   DALI_ASSERT_ALWAYS(((accessor.mBlob.mLength % sizeofBlobUnit == 0) ||
220                       accessor.mBlob.mStride >= sizeofBlobUnit) &&
221                      "weights buffer length not a multiple of element size");
222   const auto inBufferSize  = accessor.mBlob.GetBufferSize();
223   const auto outBufferSize = (sizeof(Vector4) / sizeofBlobUnit) * inBufferSize;
224
225   std::vector<uint8_t> buffer(outBufferSize);
226   auto                 inBuffer = buffer.data() + outBufferSize - inBufferSize;
227   if(!ReadAccessor(accessor, source, inBuffer))
228   {
229     ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << meshPath << "'.";
230   }
231
232   if constexpr(sizeofBlobUnit != sizeof(Vector4))
233   {
234     auto       floats = reinterpret_cast<float*>(buffer.data());
235     const auto end    = inBuffer + inBufferSize;
236     while(inBuffer != end)
237     {
238       const auto value = *reinterpret_cast<T*>(inBuffer);
239       // Normalize weight value. value /= 255 for uint8_t weight, and value /= 65535 for uint16_t weight.
240       *floats = static_cast<float>(value) / static_cast<float>((1 << (sizeof(T) * 8)) - 1);
241
242       inBuffer += sizeof(T);
243       ++floats;
244     }
245   }
246   raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(outBufferSize / sizeof(Vector4)), std::move(buffer)});
247 }
248
249 template<bool use32BitsIndices, typename IndexProviderType = IndexProvider<use32BitsIndices>>
250 bool GenerateNormals(MeshDefinition::RawData& raw)
251 {
252   using IndexType = typename IndexProviderType::IndexType;
253
254   // mIndicies size must be even if we use 32bit indices.
255   if(DALI_UNLIKELY(use32BitsIndices && !raw.mIndices.empty() && !(raw.mIndices.size() % (sizeof(IndexType) / sizeof(uint16_t)) == 0)))
256   {
257     return false;
258   }
259
260   auto& attribs = raw.mAttribs;
261   DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
262
263   IndexProviderType getIndex(raw.mIndices.data());
264
265   const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(raw.mIndices.size() / (sizeof(IndexType) / sizeof(uint16_t)));
266
267   auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
268
269   std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
270   auto                 normals = reinterpret_cast<Vector3*>(buffer.data());
271
272   for(uint32_t i = 0; i < numIndices; i += 3)
273   {
274     IndexType indices[]{getIndex(), getIndex(), getIndex()};
275     Vector3   pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
276
277     Vector3 a = pos[1] - pos[0];
278     Vector3 b = pos[2] - pos[0];
279
280     Vector3 normal(a.Cross(b));
281     normals[indices[0]] += normal;
282     normals[indices[1]] += normal;
283     normals[indices[2]] += normal;
284   }
285
286   auto iEnd = normals + attribs[0].mNumElements;
287   while(normals != iEnd)
288   {
289     normals->Normalize();
290     ++normals;
291   }
292
293   attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
294
295   return true;
296 }
297
298 template<bool use32BitsIndices, bool useVec3, bool hasUvs, typename T = std::conditional_t<useVec3, Vector3, Vector4>, typename = std::enable_if_t<(std::is_same<T, Vector3>::value || std::is_same<T, Vector4>::value)>, typename IndexProviderType = IndexProvider<use32BitsIndices>>
299 bool GenerateTangents(MeshDefinition::RawData& raw)
300 {
301   using IndexType = typename IndexProviderType::IndexType;
302
303   // mIndicies size must be even if we use 32bit indices.
304   if(DALI_UNLIKELY(use32BitsIndices && !raw.mIndices.empty() && !(raw.mIndices.size() % (sizeof(IndexType) / sizeof(uint16_t)) == 0)))
305   {
306     return false;
307   }
308
309   auto& attribs = raw.mAttribs;
310   // Required positions, normals, uvs (if we have). If not, skip generation
311   if(DALI_UNLIKELY(attribs.size() < (2 + static_cast<size_t>(hasUvs))))
312   {
313     return false;
314   }
315
316   std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(T));
317   auto                 tangents = reinterpret_cast<T*>(buffer.data());
318
319   if constexpr(hasUvs)
320   {
321     IndexProviderType getIndex(raw.mIndices.data());
322
323     const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(raw.mIndices.size() / (sizeof(IndexType) / sizeof(uint16_t)));
324
325     auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
326     auto* uvs       = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
327
328     for(uint32_t i = 0; i < numIndices; i += 3)
329     {
330       IndexType indices[]{getIndex(), getIndex(), getIndex()};
331       Vector3   pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
332       Vector2   uv[]{uvs[indices[0]], uvs[indices[1]], uvs[indices[2]]};
333
334       float x0 = pos[1].x - pos[0].x;
335       float y0 = pos[1].y - pos[0].y;
336       float z0 = pos[1].z - pos[0].z;
337
338       float x1 = pos[2].x - pos[0].x;
339       float y1 = pos[2].y - pos[0].y;
340       float z1 = pos[2].z - pos[0].z;
341
342       float s0 = uv[1].x - uv[0].x;
343       float t0 = uv[1].y - uv[0].y;
344
345       float s1 = uv[2].x - uv[0].x;
346       float t1 = uv[2].y - uv[0].y;
347
348       float   det = (s0 * t1 - t0 * s1);
349       float   r   = 1.f / ((std::abs(det) < Dali::Epsilon<1000>::value) ? (Dali::Epsilon<1000>::value * (det > 0.0f ? 1.f : -1.f)) : det);
350       Vector3 tangent((x0 * t1 - t0 * x1) * r, (y0 * t1 - t0 * y1) * r, (z0 * t1 - t0 * z1) * r);
351       tangents[indices[0]] += T(tangent);
352       tangents[indices[1]] += T(tangent);
353       tangents[indices[2]] += T(tangent);
354     }
355   }
356
357   auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
358   auto  iEnd    = normals + attribs[1].mNumElements;
359   while(normals != iEnd)
360   {
361     Vector3 tangentVec3;
362     if constexpr(hasUvs)
363     {
364       // Calculated by indexs
365       tangentVec3 = Vector3((*tangents).x, (*tangents).y, (*tangents).z);
366     }
367     else
368     {
369       // Only choiced by normal vector. by indexs
370       Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)};
371       tangentVec3 = t[t[1].LengthSquared() > t[0].LengthSquared()];
372     }
373
374     tangentVec3 -= *normals * normals->Dot(tangentVec3);
375     tangentVec3.Normalize();
376     if constexpr(useVec3)
377     {
378       *tangents = tangentVec3;
379     }
380     else
381     {
382       *tangents = Vector4(tangentVec3.x, tangentVec3.y, tangentVec3.z, 1.0f);
383     }
384
385     ++tangents;
386     ++normals;
387   }
388   attribs.push_back({"aTangent", useVec3 ? Property::VECTOR3 : Property::VECTOR4, attribs[0].mNumElements, std::move(buffer)});
389
390   return true;
391 }
392
393 void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight)
394 {
395   DALI_ASSERT_DEBUG(0u != totalTextureSize && "totalTextureSize is zero.")
396
397   // Calculate the dimensions of the texture.
398   // The total size of the texture is the length of the blend shapes blob.
399
400   textureWidth  = 0u;
401   textureHeight = 0u;
402
403   if(0u == totalTextureSize)
404   {
405     // nothing to do.
406     return;
407   }
408
409   const uint32_t pow2      = static_cast<uint32_t>(ceil(log2(totalTextureSize)));
410   const uint32_t powWidth  = pow2 >> 1u;
411   const uint32_t powHeight = pow2 - powWidth;
412
413   textureWidth  = 1u << powWidth;
414   textureHeight = 1u << powHeight;
415 }
416
417 void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, const std::vector<MeshDefinition::BlendShape>& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor, BufferDefinition::Vector& buffers)
418 {
419   uint32_t geometryBufferIndex = 0u;
420   float    maxDistanceSquared  = 0.f;
421   Vector3* geometryBufferV3    = reinterpret_cast<Vector3*>(geometryBuffer);
422   for(const auto& blendShape : blendShapes)
423   {
424     if(blendShape.deltas.IsDefined())
425     {
426       DALI_ASSERT_ALWAYS(((blendShape.deltas.mBlob.mLength % sizeof(Vector3) == 0u) ||
427                           blendShape.deltas.mBlob.mStride >= sizeof(Vector3)) &&
428                          "Blend Shape position buffer length not a multiple of element size");
429
430       const auto           bufferSize = blendShape.deltas.mBlob.GetBufferSize();
431       std::vector<uint8_t> buffer(bufferSize);
432       if(ReadAccessor(blendShape.deltas, buffers[blendShape.deltas.mBufferIdx].GetBufferStream(), buffer.data()))
433       {
434         blendShape.deltas.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
435         // Calculate the difference with the original mesh.
436         // Find the max distance to normalize the deltas.
437         const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
438
439         for(uint32_t index = 0u; index < numberOfVertices; ++index)
440         {
441           Vector3& delta = geometryBufferV3[geometryBufferIndex++];
442           delta          = deltasBuffer[index];
443
444           maxDistanceSquared = std::max(maxDistanceSquared, delta.LengthSquared());
445         }
446       }
447     }
448
449     if(blendShape.normals.IsDefined())
450     {
451       DALI_ASSERT_ALWAYS(((blendShape.normals.mBlob.mLength % sizeof(Vector3) == 0u) ||
452                           blendShape.normals.mBlob.mStride >= sizeof(Vector3)) &&
453                          "Blend Shape normals buffer length not a multiple of element size");
454
455       const auto           bufferSize = blendShape.normals.mBlob.GetBufferSize();
456       std::vector<uint8_t> buffer(bufferSize);
457       if(ReadAccessor(blendShape.normals, buffers[blendShape.normals.mBufferIdx].GetBufferStream(), buffer.data()))
458       {
459         blendShape.normals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
460
461         // Calculate the difference with the original mesh, and translate to make all values positive.
462         const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
463
464         for(uint32_t index = 0u; index < numberOfVertices; ++index)
465         {
466           Vector3& delta = geometryBufferV3[geometryBufferIndex++];
467           delta          = deltasBuffer[index];
468
469           delta.x *= 0.5f;
470           delta.y *= 0.5f;
471           delta.z *= 0.5f;
472
473           delta.x += 0.5f;
474           delta.y += 0.5f;
475           delta.z += 0.5f;
476         }
477       }
478     }
479
480     if(blendShape.tangents.IsDefined())
481     {
482       DALI_ASSERT_ALWAYS(((blendShape.tangents.mBlob.mLength % sizeof(Vector3) == 0u) ||
483                           blendShape.tangents.mBlob.mStride >= sizeof(Vector3)) &&
484                          "Blend Shape tangents buffer length not a multiple of element size");
485
486       const auto           bufferSize = blendShape.tangents.mBlob.GetBufferSize();
487       std::vector<uint8_t> buffer(bufferSize);
488       if(ReadAccessor(blendShape.tangents, buffers[blendShape.tangents.mBufferIdx].GetBufferStream(), buffer.data()))
489       {
490         blendShape.tangents.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
491
492         // Calculate the difference with the original mesh, and translate to make all values positive.
493         const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
494
495         for(uint32_t index = 0u; index < numberOfVertices; ++index)
496         {
497           Vector3& delta = geometryBufferV3[geometryBufferIndex++];
498           delta          = deltasBuffer[index];
499
500           delta.x *= 0.5f;
501           delta.y *= 0.5f;
502           delta.z *= 0.5f;
503
504           delta.x += 0.5f;
505           delta.y += 0.5f;
506           delta.z += 0.5f;
507         }
508       }
509     }
510   }
511
512   geometryBufferIndex = 0u;
513
514   const float maxDistance = sqrtf(maxDistanceSquared);
515
516   const float normalizeFactor = (maxDistanceSquared < Math::MACHINE_EPSILON_1000) ? 1.f : (0.5f / maxDistance);
517
518   // Calculate and store the unnormalize factor.
519   blendShapeUnnormalizeFactor = maxDistance * 2.0f;
520
521   for(const auto& blendShape : blendShapes)
522   {
523     // Normalize all the deltas and translate to a possitive value.
524     // Deltas are going to be passed to the shader in a color texture
525     // whose values that are less than zero are clamped.
526     if(blendShape.deltas.IsDefined())
527     {
528       for(uint32_t index = 0u; index < numberOfVertices; ++index)
529       {
530         Vector3& delta = geometryBufferV3[geometryBufferIndex++];
531         delta.x        = Clamp(((delta.x * normalizeFactor) + 0.5f), 0.f, 1.f);
532         delta.y        = Clamp(((delta.y * normalizeFactor) + 0.5f), 0.f, 1.f);
533         delta.z        = Clamp(((delta.z * normalizeFactor) + 0.5f), 0.f, 1.f);
534       }
535     }
536
537     if(blendShape.normals.IsDefined())
538     {
539       geometryBufferIndex += numberOfVertices;
540     }
541
542     if(blendShape.tangents.IsDefined())
543     {
544       geometryBufferIndex += numberOfVertices;
545     }
546   }
547 }
548
549 std::iostream& GetAvailableData(std::fstream& meshStream, const std::string& meshPath, BufferDefinition& buffer, std::string& availablePath)
550 {
551   auto& stream  = (meshStream.is_open()) ? meshStream : buffer.GetBufferStream();
552   availablePath = (meshStream.is_open()) ? meshPath : buffer.GetUri();
553   return stream;
554 }
555
556 } // namespace
557
558 MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count)
559 : mIndices{indices},
560   mValues{values},
561   mCount{count}
562 {
563 }
564
565 MeshDefinition::SparseBlob::SparseBlob(Blob&& indices, Blob&& values, uint32_t count)
566 : mIndices(std::move(indices)),
567   mValues(std::move(values)),
568   mCount{count}
569 {
570 }
571
572 MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob&       blob,
573                                    const MeshDefinition::SparseBlob& sparse,
574                                    Index                             bufferIndex)
575 : mBlob{blob},
576   mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr},
577   mBufferIdx(bufferIndex)
578 {
579 }
580
581 MeshDefinition::Accessor::Accessor(MeshDefinition::Blob&&       blob,
582                                    MeshDefinition::SparseBlob&& sparse,
583                                    Index                        bufferIndex)
584 : mBlob{std::move(blob)},
585   mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{std::move(sparse)} : nullptr},
586   mBufferIdx(bufferIndex)
587 {
588 }
589
590 void MeshDefinition::Blob::ComputeMinMax(std::vector<float>& min, std::vector<float>& max, uint32_t numComponents, uint32_t count, const float* values)
591 {
592   min.assign(numComponents, MAXFLOAT);
593   max.assign(numComponents, -MAXFLOAT);
594   for(uint32_t i = 0; i < count; ++i)
595   {
596     for(uint32_t j = 0; j < numComponents; ++j)
597     {
598       min[j] = std::min(min[j], *values);
599       max[j] = std::max(max[j], *values);
600       values++;
601     }
602   }
603 }
604
605 void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values)
606 {
607   DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0);
608   const auto numComponents = std::max(min.size(), max.size());
609
610   using ClampFn   = void (*)(const float*, const float*, uint32_t, float&);
611   ClampFn clampFn = min.empty() ? (max.empty() ? static_cast<ClampFn>(nullptr) : [](const float* min, const float* max, uint32_t i, float& value) { value = std::min(max[i], value); })
612                                 : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) { value = std::max(min[i], value); }
613                                                : static_cast<ClampFn>([](const float* min, const float* max, uint32_t i, float& value) { value = std::min(std::max(min[i], value), max[i]); }));
614
615   if(!clampFn)
616   {
617     return;
618   }
619
620   auto end = values + count * numComponents;
621   while(values != end)
622   {
623     auto     nextElement = values + numComponents;
624     uint32_t i           = 0;
625     while(values != nextElement)
626     {
627       clampFn(min.data(), max.data(), i, *values);
628       ++values;
629       ++i;
630     }
631   }
632 }
633
634 MeshDefinition::Blob::Blob(uint32_t offset, uint32_t length, uint16_t stride, uint16_t elementSizeHint, const std::vector<float>& min, const std::vector<float>& max)
635 : mOffset(offset),
636   mLength(length),
637   mStride(stride),
638   mElementSizeHint(elementSizeHint),
639   mMin(min),
640   mMax(max)
641 {
642 }
643
644 uint32_t MeshDefinition::Blob::GetBufferSize() const
645 {
646   return mLength;
647 }
648
649 void MeshDefinition::Blob::ComputeMinMax(uint32_t numComponents, uint32_t count, float* values)
650 {
651   ComputeMinMax(mMin, mMax, numComponents, count, values);
652 }
653
654 void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const
655 {
656   ApplyMinMax(mMin, mMax, count, values);
657 }
658
659 void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
660 {
661   Property::Map attribMap;
662   attribMap[mName]          = mType;
663   VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
664   attribBuffer.SetData(mData.data(), mNumElements);
665
666   g.AddVertexBuffer(attribBuffer);
667 }
668
669 bool MeshDefinition::IsQuad() const
670 {
671   return CaseInsensitiveStringCompare(QUAD, mUri);
672 }
673
674 bool MeshDefinition::IsSkinned() const
675 {
676   return mJoints0.IsDefined() && mWeights0.IsDefined();
677 }
678
679 bool MeshDefinition::HasBlendShapes() const
680 {
681   return !mBlendShapes.empty();
682 }
683
684 void MeshDefinition::RequestNormals()
685 {
686   mNormals.mBlob.mLength = mPositions.mBlob.GetBufferSize();
687 }
688
689 void MeshDefinition::RequestTangents()
690 {
691   mTangents.mBlob.mLength = mNormals.mBlob.GetBufferSize();
692 }
693
694 MeshDefinition::RawData
695 MeshDefinition::LoadRaw(const std::string& modelsPath, BufferDefinition::Vector& buffers)
696 {
697   RawData raw;
698   if(IsQuad())
699   {
700     return raw;
701   }
702
703   std::string meshPath;
704   meshPath = modelsPath + mUri;
705   std::fstream fileStream;
706   if(!mUri.empty())
707   {
708     fileStream.open(meshPath, std::ios::in | std::ios::binary);
709     if(!fileStream.is_open())
710     {
711       DALI_LOG_ERROR("Fail to open buffer from %s.\n", meshPath.c_str());
712     }
713   }
714
715   if(mIndices.IsDefined())
716   {
717     if(MaskMatch(mFlags, U32_INDICES))
718     {
719       DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint32_t) == 0) ||
720                           mIndices.mBlob.mStride >= sizeof(uint32_t)) &&
721                          "Index buffer length not a multiple of element size");
722       const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint32_t);
723       raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially.
724
725       std::string path;
726       auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
727       if(!ReadAccessor(mIndices, stream, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
728       {
729         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
730       }
731     }
732     else if(MaskMatch(mFlags, U8_INDICES))
733     {
734       DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint8_t) == 0) ||
735                           mIndices.mBlob.mStride >= sizeof(uint8_t)) &&
736                          "Index buffer length not a multiple of element size");
737       const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint8_t);
738       raw.mIndices.resize(indexCount); // NOTE: we need space for uint16_ts initially.
739
740       std::string path;
741       auto        u8s    = reinterpret_cast<uint8_t*>(raw.mIndices.data()) + indexCount;
742       auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
743       if(!ReadAccessor(mIndices, stream, u8s))
744       {
745         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
746       }
747
748       auto u16s = raw.mIndices.data();
749       auto end  = u8s + indexCount;
750       while(u8s != end)
751       {
752         *u16s = static_cast<uint16_t>(*u8s);
753         ++u16s;
754         ++u8s;
755       }
756     }
757     else
758     {
759       DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(unsigned short) == 0) ||
760                           mIndices.mBlob.mStride >= sizeof(unsigned short)) &&
761                          "Index buffer length not a multiple of element size");
762       raw.mIndices.resize(mIndices.mBlob.mLength / sizeof(unsigned short));
763
764       std::string path;
765       auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
766       if(!ReadAccessor(mIndices, stream, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
767       {
768         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
769       }
770     }
771   }
772
773   std::vector<Vector3> positions;
774   if(mPositions.IsDefined())
775   {
776     DALI_ASSERT_ALWAYS(((mPositions.mBlob.mLength % sizeof(Vector3) == 0) ||
777                         mPositions.mBlob.mStride >= sizeof(Vector3)) &&
778                        "Position buffer length not a multiple of element size");
779     const auto           bufferSize = mPositions.mBlob.GetBufferSize();
780     std::vector<uint8_t> buffer(bufferSize);
781
782     std::string path;
783     auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mPositions.mBufferIdx], path);
784     if(!ReadAccessor(mPositions, stream, buffer.data()))
785     {
786       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << path << "'.";
787     }
788
789     uint32_t numVector3 = static_cast<uint32_t>(bufferSize / sizeof(Vector3));
790     if(mPositions.mBlob.mMin.size() != 3u || mPositions.mBlob.mMax.size() != 3u)
791     {
792       mPositions.mBlob.ComputeMinMax(3u, numVector3, reinterpret_cast<float*>(buffer.data()));
793     }
794     else
795     {
796       mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
797     }
798
799     if(HasBlendShapes())
800     {
801       positions.resize(numVector3);
802       std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
803     }
804
805     raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
806   }
807
808   const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
809   auto       hasNormals  = mNormals.IsDefined();
810   if(hasNormals)
811   {
812     DALI_ASSERT_ALWAYS(((mNormals.mBlob.mLength % sizeof(Vector3) == 0) ||
813                         mNormals.mBlob.mStride >= sizeof(Vector3)) &&
814                        "Normal buffer length not a multiple of element size");
815     const auto           bufferSize = mNormals.mBlob.GetBufferSize();
816     std::vector<uint8_t> buffer(bufferSize);
817
818     std::string path;
819     auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mNormals.mBufferIdx], path);
820     if(!ReadAccessor(mNormals, stream, buffer.data()))
821     {
822       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << path << "'.";
823     }
824
825     mNormals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
826
827     raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
828   }
829   else if(mNormals.mBlob.mLength != 0 && isTriangles)
830   {
831     DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
832     static const std::function<bool(RawData&)> GenerateNormalsFunction[2] =
833       {
834         GenerateNormals<false>,
835         GenerateNormals<true>,
836       };
837     const bool generateSuccessed = GenerateNormalsFunction[MaskMatch(mFlags, U32_INDICES)](raw);
838     if(!generateSuccessed)
839     {
840       DALI_LOG_ERROR("Failed to generate normal\n");
841     }
842     else
843     {
844       hasNormals = true;
845     }
846   }
847
848   const auto hasUvs = mTexCoords.IsDefined();
849   if(hasUvs)
850   {
851     DALI_ASSERT_ALWAYS(((mTexCoords.mBlob.mLength % sizeof(Vector2) == 0) ||
852                         mTexCoords.mBlob.mStride >= sizeof(Vector2)) &&
853                        "Normal buffer length not a multiple of element size");
854     const auto           bufferSize = mTexCoords.mBlob.GetBufferSize();
855     std::vector<uint8_t> buffer(bufferSize);
856
857     std::string path;
858     auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mTexCoords.mBufferIdx], path);
859     if(!ReadAccessor(mTexCoords, stream, buffer.data()))
860     {
861       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << path << "'.";
862     }
863
864     const auto uvCount = bufferSize / sizeof(Vector2);
865     if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
866     {
867       auto uv    = reinterpret_cast<Vector2*>(buffer.data());
868       auto uvEnd = uv + uvCount;
869       while(uv != uvEnd)
870       {
871         uv->y = 1.0f - uv->y;
872         ++uv;
873       }
874     }
875
876     mTexCoords.mBlob.ApplyMinMax(static_cast<uint32_t>(uvCount), reinterpret_cast<float*>(buffer.data()));
877
878     raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
879   }
880
881   if(mTangents.IsDefined())
882   {
883     uint32_t propertySize = static_cast<uint32_t>((mTangentType == Property::VECTOR4) ? sizeof(Vector4) : sizeof(Vector3));
884     DALI_ASSERT_ALWAYS(((mTangents.mBlob.mLength % propertySize == 0) ||
885                         mTangents.mBlob.mStride >= propertySize) &&
886                        "Tangents buffer length not a multiple of element size");
887     const auto           bufferSize = mTangents.mBlob.GetBufferSize();
888     std::vector<uint8_t> buffer(bufferSize);
889
890     std::string path;
891     auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mTangents.mBufferIdx], path);
892     if(!ReadAccessor(mTangents, stream, buffer.data()))
893     {
894       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << path << "'.";
895     }
896     mTangents.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
897
898     raw.mAttribs.push_back({"aTangent", mTangentType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
899   }
900   else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
901   {
902     DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
903     static const std::function<bool(RawData&)> GenerateTangentsFunction[2][2][2] =
904       {
905         {
906           {
907             GenerateTangents<false, false, false>,
908             GenerateTangents<false, false, true>,
909           },
910           {
911             GenerateTangents<false, true, false>,
912             GenerateTangents<false, true, true>,
913           },
914         },
915         {
916           {
917             GenerateTangents<true, false, false>,
918             GenerateTangents<true, false, true>,
919           },
920           {
921             GenerateTangents<true, true, false>,
922             GenerateTangents<true, true, true>,
923           },
924         }};
925     const bool generateSuccessed = GenerateTangentsFunction[MaskMatch(mFlags, U32_INDICES)][mTangentType == Property::VECTOR3][hasUvs](raw);
926     if(!generateSuccessed)
927     {
928       DALI_LOG_ERROR("Failed to generate tangents\n");
929     }
930   }
931
932   if(mColors.IsDefined())
933   {
934     uint32_t       propertySize = mColors.mBlob.mElementSizeHint;
935     Property::Type propertyType = (propertySize == sizeof(Vector4)) ? Property::VECTOR4 : ((propertySize == sizeof(Vector3)) ? Property::VECTOR3 : Property::NONE);
936     if(propertyType != Property::NONE)
937     {
938       DALI_ASSERT_ALWAYS(((mColors.mBlob.mLength % propertySize == 0) ||
939                           mColors.mBlob.mStride >= propertySize) &&
940                          "Colors buffer length not a multiple of element size");
941       const auto           bufferSize = mColors.mBlob.GetBufferSize();
942       std::vector<uint8_t> buffer(bufferSize);
943
944       std::string path;
945       auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mColors.mBufferIdx], path);
946       if(!ReadAccessor(mColors, stream, buffer.data()))
947       {
948         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read colors from '" << path << "'.";
949       }
950       mColors.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
951
952       raw.mAttribs.push_back({"aVertexColor", propertyType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
953     }
954   }
955   else
956   {
957     std::vector<uint8_t> buffer(raw.mAttribs[0].mNumElements * sizeof(Vector4));
958     auto                 colors = reinterpret_cast<Vector4*>(buffer.data());
959
960     for(uint32_t i = 0; i < raw.mAttribs[0].mNumElements; i++)
961     {
962       colors[i] = Vector4::ONE;
963     }
964
965     raw.mAttribs.push_back({"aVertexColor", Property::VECTOR4, raw.mAttribs[0].mNumElements, std::move(buffer)});
966   }
967
968   if(IsSkinned())
969   {
970     std::string pathJoint;
971     auto&       streamJoint = GetAvailableData(fileStream, meshPath, buffers[mJoints0.mBufferIdx], pathJoint);
972     if(MaskMatch(mFlags, U16_JOINT_IDS))
973     {
974       ReadJointAccessor<uint16_t>(raw, mJoints0, streamJoint, pathJoint);
975     }
976     else if(MaskMatch(mFlags, U8_JOINT_IDS))
977     {
978       ReadJointAccessor<uint8_t>(raw, mJoints0, streamJoint, pathJoint);
979     }
980     else
981     {
982       ReadJointAccessor<float>(raw, mJoints0, streamJoint, pathJoint);
983     }
984
985     std::string pathWeight;
986     auto&       streamWeight = GetAvailableData(fileStream, meshPath, buffers[mWeights0.mBufferIdx], pathWeight);
987     if(MaskMatch(mFlags, U16_WEIGHT))
988     {
989       ReadWeightAccessor<uint16_t>(raw, mWeights0, streamWeight, pathWeight);
990     }
991     else if(MaskMatch(mFlags, U8_WEIGHT))
992     {
993       ReadWeightAccessor<uint8_t>(raw, mWeights0, streamWeight, pathWeight);
994     }
995     else
996     {
997       ReadWeightAccessor<float>(raw, mWeights0, streamWeight, pathWeight);
998     }
999   }
1000
1001   // Calculate the Blob for the blend shapes.
1002   Blob blendShapesBlob;
1003   blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
1004   blendShapesBlob.mLength = 0u;
1005
1006   for(const auto& blendShape : mBlendShapes)
1007   {
1008     for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
1009     {
1010       if(i->IsDefined())
1011       {
1012         blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
1013         blendShapesBlob.mLength += i->mBlob.mLength;
1014       }
1015     }
1016   }
1017
1018   if(HasBlendShapes())
1019   {
1020     const uint32_t numberOfVertices = static_cast<uint32_t>(mPositions.mBlob.mLength / sizeof(Vector3));
1021
1022     // Calculate the size of one buffer inside the texture.
1023     raw.mBlendShapeBufferOffset = numberOfVertices;
1024
1025     bool     calculateGltf2BlendShapes = false;
1026     uint32_t textureWidth              = 0u;
1027     uint32_t textureHeight             = 0u;
1028
1029     if(!mBlendShapeHeader.IsDefined())
1030     {
1031       CalculateTextureSize(static_cast<uint32_t>(blendShapesBlob.mLength / sizeof(Vector3)), textureWidth, textureHeight);
1032       calculateGltf2BlendShapes = true;
1033     }
1034     else
1035     {
1036       uint16_t header[2u];
1037       ReadBlob(mBlendShapeHeader, fileStream, reinterpret_cast<uint8_t*>(header));
1038       textureWidth  = header[0u];
1039       textureHeight = header[1u];
1040     }
1041
1042     const uint32_t numberOfBlendShapes = mBlendShapes.size();
1043     raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
1044
1045     Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
1046     uint8_t*           geometryBuffer      = geometryPixelBuffer.GetBuffer();
1047
1048     if(calculateGltf2BlendShapes)
1049     {
1050       CalculateGltf2BlendShapes(geometryBuffer, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u], buffers);
1051     }
1052     else
1053     {
1054       Blob unnormalizeFactorBlob;
1055       unnormalizeFactorBlob.mLength = static_cast<uint32_t>(sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes));
1056
1057       if(blendShapesBlob.IsDefined())
1058       {
1059         if(ReadBlob(blendShapesBlob, fileStream, geometryBuffer))
1060         {
1061           unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
1062         }
1063       }
1064
1065       // Read the unnormalize factors.
1066       if(unnormalizeFactorBlob.IsDefined())
1067       {
1068         ReadBlob(unnormalizeFactorBlob, fileStream, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
1069       }
1070     }
1071     raw.mBlendShapeData = Devel::PixelBuffer::Convert(geometryPixelBuffer);
1072   }
1073
1074   return raw;
1075 }
1076
1077 MeshGeometry MeshDefinition::Load(RawData&& raw) const
1078 {
1079   MeshGeometry meshGeometry;
1080   meshGeometry.geometry = Geometry::New();
1081   meshGeometry.geometry.SetType(mPrimitiveType);
1082
1083   if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
1084   {
1085     auto options          = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
1086     meshGeometry.geometry = MakeTexturedQuadGeometry(options);
1087   }
1088   else
1089   {
1090     if(!raw.mIndices.empty())
1091     {
1092       if(MaskMatch(mFlags, U32_INDICES))
1093       {
1094         // TODO : We can only store indeces as uint16_type. Send Dali::Geometry that we use it as uint32_t actual.
1095         meshGeometry.geometry.SetIndexBuffer(reinterpret_cast<const uint32_t*>(raw.mIndices.data()), raw.mIndices.size() / 2);
1096       }
1097       else
1098       {
1099         meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
1100       }
1101     }
1102
1103     for(auto& a : raw.mAttribs)
1104     {
1105       a.AttachBuffer(meshGeometry.geometry);
1106     }
1107
1108     if(HasBlendShapes())
1109     {
1110       meshGeometry.blendShapeBufferOffset      = raw.mBlendShapeBufferOffset;
1111       meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
1112
1113       meshGeometry.blendShapeGeometry = Texture::New(TextureType::TEXTURE_2D,
1114                                                      raw.mBlendShapeData.GetPixelFormat(),
1115                                                      raw.mBlendShapeData.GetWidth(),
1116                                                      raw.mBlendShapeData.GetHeight());
1117       meshGeometry.blendShapeGeometry.Upload(raw.mBlendShapeData);
1118     }
1119   }
1120
1121   return meshGeometry;
1122 }
1123
1124 void MeshDefinition::RetrieveBlendShapeComponents(bool& hasPositions, bool& hasNormals, bool& hasTangents) const
1125 {
1126   for(const auto& blendShape : mBlendShapes)
1127   {
1128     hasPositions = hasPositions || blendShape.deltas.IsDefined();
1129     hasNormals   = hasNormals || blendShape.normals.IsDefined();
1130     hasTangents  = hasTangents || blendShape.tangents.IsDefined();
1131   }
1132 }
1133
1134 } // namespace Dali::Scene3D::Loader