Merge "Move the point of setting currentFocusControl to before FocusLost." into devel...
[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<bool use32BitsIndices, typename IndexProviderType = IndexProvider<use32BitsIndices>>
215 bool GenerateNormals(MeshDefinition::RawData& raw)
216 {
217   using IndexType = typename IndexProviderType::IndexType;
218
219   // mIndicies size must be even if we use 32bit indices.
220   if(DALI_UNLIKELY(use32BitsIndices && !raw.mIndices.empty() && !(raw.mIndices.size() % (sizeof(IndexType) / sizeof(uint16_t)) == 0)))
221   {
222     return false;
223   }
224
225   auto& attribs = raw.mAttribs;
226   DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
227
228   IndexProviderType getIndex(raw.mIndices.data());
229
230   const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(raw.mIndices.size() / (sizeof(IndexType) / sizeof(uint16_t)));
231
232   auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
233
234   std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
235   auto                 normals = reinterpret_cast<Vector3*>(buffer.data());
236
237   for(uint32_t i = 0; i < numIndices; i += 3)
238   {
239     IndexType indices[]{getIndex(), getIndex(), getIndex()};
240     Vector3   pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
241
242     Vector3 a = pos[1] - pos[0];
243     Vector3 b = pos[2] - pos[0];
244
245     Vector3 normal(a.Cross(b));
246     normals[indices[0]] += normal;
247     normals[indices[1]] += normal;
248     normals[indices[2]] += normal;
249   }
250
251   auto iEnd = normals + attribs[0].mNumElements;
252   while(normals != iEnd)
253   {
254     normals->Normalize();
255     ++normals;
256   }
257
258   attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
259
260   return true;
261 }
262
263 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>>
264 bool GenerateTangents(MeshDefinition::RawData& raw)
265 {
266   using IndexType = typename IndexProviderType::IndexType;
267
268   // mIndicies size must be even if we use 32bit indices.
269   if(DALI_UNLIKELY(use32BitsIndices && !raw.mIndices.empty() && !(raw.mIndices.size() % (sizeof(IndexType) / sizeof(uint16_t)) == 0)))
270   {
271     return false;
272   }
273
274   auto& attribs = raw.mAttribs;
275   // Required positions, normals, uvs (if we have). If not, skip generation
276   if(DALI_UNLIKELY(attribs.size() < (2 + static_cast<size_t>(hasUvs))))
277   {
278     return false;
279   }
280
281   std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(T));
282   auto                 tangents = reinterpret_cast<T*>(buffer.data());
283
284   if constexpr(hasUvs)
285   {
286     IndexProviderType getIndex(raw.mIndices.data());
287
288     const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(raw.mIndices.size() / (sizeof(IndexType) / sizeof(uint16_t)));
289
290     auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
291     auto* uvs       = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
292
293     for(uint32_t i = 0; i < numIndices; i += 3)
294     {
295       IndexType indices[]{getIndex(), getIndex(), getIndex()};
296       Vector3   pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
297       Vector2   uv[]{uvs[indices[0]], uvs[indices[1]], uvs[indices[2]]};
298
299       float x0 = pos[1].x - pos[0].x;
300       float y0 = pos[1].y - pos[0].y;
301       float z0 = pos[1].z - pos[0].z;
302
303       float x1 = pos[2].x - pos[0].x;
304       float y1 = pos[2].y - pos[0].y;
305       float z1 = pos[2].z - pos[0].z;
306
307       float s0 = uv[1].x - uv[0].x;
308       float t0 = uv[1].y - uv[0].y;
309
310       float s1 = uv[2].x - uv[0].x;
311       float t1 = uv[2].y - uv[0].y;
312
313       float   det = (s0 * t1 - t0 * s1);
314       float   r   = 1.f / ((std::abs(det) < Dali::Epsilon<1000>::value) ? (Dali::Epsilon<1000>::value * (det > 0.0f ? 1.f : -1.f)) : det);
315       Vector3 tangent((x0 * t1 - t0 * x1) * r, (y0 * t1 - t0 * y1) * r, (z0 * t1 - t0 * z1) * r);
316       tangents[indices[0]] += T(tangent);
317       tangents[indices[1]] += T(tangent);
318       tangents[indices[2]] += T(tangent);
319     }
320   }
321
322   auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
323   auto  iEnd    = normals + attribs[1].mNumElements;
324   while(normals != iEnd)
325   {
326     Vector3 tangentVec3;
327     if constexpr(hasUvs)
328     {
329       // Calculated by indexs
330       tangentVec3 = Vector3((*tangents).x, (*tangents).y, (*tangents).z);
331     }
332     else
333     {
334       // Only choiced by normal vector. by indexs
335       Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)};
336       tangentVec3 = t[t[1].LengthSquared() > t[0].LengthSquared()];
337     }
338
339     tangentVec3 -= *normals * normals->Dot(tangentVec3);
340     tangentVec3.Normalize();
341     if constexpr(useVec3)
342     {
343       *tangents = tangentVec3;
344     }
345     else
346     {
347       *tangents = Vector4(tangentVec3.x, tangentVec3.y, tangentVec3.z, 1.0f);
348     }
349
350     ++tangents;
351     ++normals;
352   }
353   attribs.push_back({"aTangent", useVec3 ? Property::VECTOR3 : Property::VECTOR4, attribs[0].mNumElements, std::move(buffer)});
354
355   return true;
356 }
357
358 void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight)
359 {
360   DALI_ASSERT_DEBUG(0u != totalTextureSize && "totalTextureSize is zero.")
361
362   // Calculate the dimensions of the texture.
363   // The total size of the texture is the length of the blend shapes blob.
364
365   textureWidth  = 0u;
366   textureHeight = 0u;
367
368   if(0u == totalTextureSize)
369   {
370     // nothing to do.
371     return;
372   }
373
374   const uint32_t pow2      = static_cast<uint32_t>(ceil(log2(totalTextureSize)));
375   const uint32_t powWidth  = pow2 >> 1u;
376   const uint32_t powHeight = pow2 - powWidth;
377
378   textureWidth  = 1u << powWidth;
379   textureHeight = 1u << powHeight;
380 }
381
382 void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, const std::vector<MeshDefinition::BlendShape>& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor, BufferDefinition::Vector& buffers)
383 {
384   uint32_t geometryBufferIndex = 0u;
385   float    maxDistanceSquared  = 0.f;
386   Vector3* geometryBufferV3    = reinterpret_cast<Vector3*>(geometryBuffer);
387   for(const auto& blendShape : blendShapes)
388   {
389     if(blendShape.deltas.IsDefined())
390     {
391       DALI_ASSERT_ALWAYS(((blendShape.deltas.mBlob.mLength % sizeof(Vector3) == 0u) ||
392                           blendShape.deltas.mBlob.mStride >= sizeof(Vector3)) &&
393                          "Blend Shape position buffer length not a multiple of element size");
394
395       const auto           bufferSize = blendShape.deltas.mBlob.GetBufferSize();
396       std::vector<uint8_t> buffer(bufferSize);
397       if(ReadAccessor(blendShape.deltas, buffers[blendShape.deltas.mBufferIdx].GetBufferStream(), buffer.data()))
398       {
399         blendShape.deltas.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
400         // Calculate the difference with the original mesh.
401         // Find the max distance to normalize the deltas.
402         const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
403
404         for(uint32_t index = 0u; index < numberOfVertices; ++index)
405         {
406           Vector3& delta = geometryBufferV3[geometryBufferIndex++];
407           delta          = deltasBuffer[index];
408
409           maxDistanceSquared = std::max(maxDistanceSquared, delta.LengthSquared());
410         }
411       }
412     }
413
414     if(blendShape.normals.IsDefined())
415     {
416       DALI_ASSERT_ALWAYS(((blendShape.normals.mBlob.mLength % sizeof(Vector3) == 0u) ||
417                           blendShape.normals.mBlob.mStride >= sizeof(Vector3)) &&
418                          "Blend Shape normals buffer length not a multiple of element size");
419
420       const auto           bufferSize = blendShape.normals.mBlob.GetBufferSize();
421       std::vector<uint8_t> buffer(bufferSize);
422       if(ReadAccessor(blendShape.normals, buffers[blendShape.normals.mBufferIdx].GetBufferStream(), buffer.data()))
423       {
424         blendShape.normals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
425
426         // Calculate the difference with the original mesh, and translate to make all values positive.
427         const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
428
429         for(uint32_t index = 0u; index < numberOfVertices; ++index)
430         {
431           Vector3& delta = geometryBufferV3[geometryBufferIndex++];
432           delta          = deltasBuffer[index];
433
434           delta.x *= 0.5f;
435           delta.y *= 0.5f;
436           delta.z *= 0.5f;
437
438           delta.x += 0.5f;
439           delta.y += 0.5f;
440           delta.z += 0.5f;
441         }
442       }
443     }
444
445     if(blendShape.tangents.IsDefined())
446     {
447       DALI_ASSERT_ALWAYS(((blendShape.tangents.mBlob.mLength % sizeof(Vector3) == 0u) ||
448                           blendShape.tangents.mBlob.mStride >= sizeof(Vector3)) &&
449                          "Blend Shape tangents buffer length not a multiple of element size");
450
451       const auto           bufferSize = blendShape.tangents.mBlob.GetBufferSize();
452       std::vector<uint8_t> buffer(bufferSize);
453       if(ReadAccessor(blendShape.tangents, buffers[blendShape.tangents.mBufferIdx].GetBufferStream(), buffer.data()))
454       {
455         blendShape.tangents.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
456
457         // Calculate the difference with the original mesh, and translate to make all values positive.
458         const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
459
460         for(uint32_t index = 0u; index < numberOfVertices; ++index)
461         {
462           Vector3& delta = geometryBufferV3[geometryBufferIndex++];
463           delta          = deltasBuffer[index];
464
465           delta.x *= 0.5f;
466           delta.y *= 0.5f;
467           delta.z *= 0.5f;
468
469           delta.x += 0.5f;
470           delta.y += 0.5f;
471           delta.z += 0.5f;
472         }
473       }
474     }
475   }
476
477   geometryBufferIndex = 0u;
478
479   const float maxDistance = sqrtf(maxDistanceSquared);
480
481   const float normalizeFactor = (maxDistanceSquared < Math::MACHINE_EPSILON_1000) ? 1.f : (0.5f / maxDistance);
482
483   // Calculate and store the unnormalize factor.
484   blendShapeUnnormalizeFactor = maxDistance * 2.0f;
485
486   for(const auto& blendShape : blendShapes)
487   {
488     // Normalize all the deltas and translate to a possitive value.
489     // Deltas are going to be passed to the shader in a color texture
490     // whose values that are less than zero are clamped.
491     if(blendShape.deltas.IsDefined())
492     {
493       for(uint32_t index = 0u; index < numberOfVertices; ++index)
494       {
495         Vector3& delta = geometryBufferV3[geometryBufferIndex++];
496         delta.x        = Clamp(((delta.x * normalizeFactor) + 0.5f), 0.f, 1.f);
497         delta.y        = Clamp(((delta.y * normalizeFactor) + 0.5f), 0.f, 1.f);
498         delta.z        = Clamp(((delta.z * normalizeFactor) + 0.5f), 0.f, 1.f);
499       }
500     }
501
502     if(blendShape.normals.IsDefined())
503     {
504       geometryBufferIndex += numberOfVertices;
505     }
506
507     if(blendShape.tangents.IsDefined())
508     {
509       geometryBufferIndex += numberOfVertices;
510     }
511   }
512 }
513
514 std::iostream& GetAvailableData(std::fstream& meshStream, const std::string& meshPath, BufferDefinition& buffer, std::string& availablePath)
515 {
516   auto& stream  = (meshStream.is_open()) ? meshStream : buffer.GetBufferStream();
517   availablePath = (meshStream.is_open()) ? meshPath : buffer.GetUri();
518   return stream;
519 }
520
521 } // namespace
522
523 MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count)
524 : mIndices{indices},
525   mValues{values},
526   mCount{count}
527 {
528 }
529
530 MeshDefinition::SparseBlob::SparseBlob(Blob&& indices, Blob&& values, uint32_t count)
531 : mIndices(std::move(indices)),
532   mValues(std::move(values)),
533   mCount{count}
534 {
535 }
536
537 MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob&       blob,
538                                    const MeshDefinition::SparseBlob& sparse,
539                                    Index                             bufferIndex)
540 : mBlob{blob},
541   mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr},
542   mBufferIdx(bufferIndex)
543 {
544 }
545
546 MeshDefinition::Accessor::Accessor(MeshDefinition::Blob&&       blob,
547                                    MeshDefinition::SparseBlob&& sparse,
548                                    Index                        bufferIndex)
549 : mBlob{std::move(blob)},
550   mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{std::move(sparse)} : nullptr},
551   mBufferIdx(bufferIndex)
552 {
553 }
554
555 void MeshDefinition::Blob::ComputeMinMax(std::vector<float>& min, std::vector<float>& max, uint32_t numComponents, uint32_t count, const float* values)
556 {
557   min.assign(numComponents, MAXFLOAT);
558   max.assign(numComponents, -MAXFLOAT);
559   for(uint32_t i = 0; i < count; ++i)
560   {
561     for(uint32_t j = 0; j < numComponents; ++j)
562     {
563       min[j] = std::min(min[j], *values);
564       max[j] = std::max(max[j], *values);
565       values++;
566     }
567   }
568 }
569
570 void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values)
571 {
572   DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0);
573   const auto numComponents = std::max(min.size(), max.size());
574
575   using ClampFn   = void (*)(const float*, const float*, uint32_t, float&);
576   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); })
577                                 : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) { value = std::max(min[i], value); }
578                                                : static_cast<ClampFn>([](const float* min, const float* max, uint32_t i, float& value) { value = std::min(std::max(min[i], value), max[i]); }));
579
580   if(!clampFn)
581   {
582     return;
583   }
584
585   auto end = values + count * numComponents;
586   while(values != end)
587   {
588     auto     nextElement = values + numComponents;
589     uint32_t i           = 0;
590     while(values != nextElement)
591     {
592       clampFn(min.data(), max.data(), i, *values);
593       ++values;
594       ++i;
595     }
596   }
597 }
598
599 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)
600 : mOffset(offset),
601   mLength(length),
602   mStride(stride),
603   mElementSizeHint(elementSizeHint),
604   mMin(min),
605   mMax(max)
606 {
607 }
608
609 uint32_t MeshDefinition::Blob::GetBufferSize() const
610 {
611   return mLength;
612 }
613
614 void MeshDefinition::Blob::ComputeMinMax(uint32_t numComponents, uint32_t count, float* values)
615 {
616   ComputeMinMax(mMin, mMax, numComponents, count, values);
617 }
618
619 void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const
620 {
621   ApplyMinMax(mMin, mMax, count, values);
622 }
623
624 void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
625 {
626   Property::Map attribMap;
627   attribMap[mName]          = mType;
628   VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
629   attribBuffer.SetData(mData.data(), mNumElements);
630
631   g.AddVertexBuffer(attribBuffer);
632 }
633
634 bool MeshDefinition::IsQuad() const
635 {
636   return CaseInsensitiveStringCompare(QUAD, mUri);
637 }
638
639 bool MeshDefinition::IsSkinned() const
640 {
641   return mJoints0.IsDefined() && mWeights0.IsDefined();
642 }
643
644 bool MeshDefinition::HasBlendShapes() const
645 {
646   return !mBlendShapes.empty();
647 }
648
649 void MeshDefinition::RequestNormals()
650 {
651   mNormals.mBlob.mLength = mPositions.mBlob.GetBufferSize();
652 }
653
654 void MeshDefinition::RequestTangents()
655 {
656   mTangents.mBlob.mLength = mNormals.mBlob.GetBufferSize();
657 }
658
659 MeshDefinition::RawData
660 MeshDefinition::LoadRaw(const std::string& modelsPath, BufferDefinition::Vector& buffers)
661 {
662   RawData raw;
663   if(IsQuad())
664   {
665     return raw;
666   }
667
668   std::string meshPath;
669   meshPath = modelsPath + mUri;
670   std::fstream fileStream;
671   if(!mUri.empty())
672   {
673     fileStream.open(meshPath, std::ios::in | std::ios::binary);
674     if(!fileStream.is_open())
675     {
676       DALI_LOG_ERROR("Fail to open buffer from %s.\n", meshPath.c_str());
677     }
678   }
679
680   if(mIndices.IsDefined())
681   {
682     if(MaskMatch(mFlags, U32_INDICES))
683     {
684       DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint32_t) == 0) ||
685                           mIndices.mBlob.mStride >= sizeof(uint32_t)) &&
686                          "Index buffer length not a multiple of element size");
687       const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint32_t);
688       raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially.
689
690       std::string path;
691       auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
692       if(!ReadAccessor(mIndices, stream, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
693       {
694         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
695       }
696     }
697     else if(MaskMatch(mFlags, U8_INDICES))
698     {
699       DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint8_t) == 0) ||
700                           mIndices.mBlob.mStride >= sizeof(uint8_t)) &&
701                          "Index buffer length not a multiple of element size");
702       const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint8_t);
703       raw.mIndices.resize(indexCount); // NOTE: we need space for uint16_ts initially.
704
705       std::string path;
706       auto        u8s    = reinterpret_cast<uint8_t*>(raw.mIndices.data()) + indexCount;
707       auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
708       if(!ReadAccessor(mIndices, stream, u8s))
709       {
710         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
711       }
712
713       auto u16s = raw.mIndices.data();
714       auto end  = u8s + indexCount;
715       while(u8s != end)
716       {
717         *u16s = static_cast<uint16_t>(*u8s);
718         ++u16s;
719         ++u8s;
720       }
721     }
722     else
723     {
724       DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(unsigned short) == 0) ||
725                           mIndices.mBlob.mStride >= sizeof(unsigned short)) &&
726                          "Index buffer length not a multiple of element size");
727       raw.mIndices.resize(mIndices.mBlob.mLength / sizeof(unsigned short));
728
729       std::string path;
730       auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
731       if(!ReadAccessor(mIndices, stream, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
732       {
733         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
734       }
735     }
736   }
737
738   std::vector<Vector3> positions;
739   if(mPositions.IsDefined())
740   {
741     DALI_ASSERT_ALWAYS(((mPositions.mBlob.mLength % sizeof(Vector3) == 0) ||
742                         mPositions.mBlob.mStride >= sizeof(Vector3)) &&
743                        "Position buffer length not a multiple of element size");
744     const auto           bufferSize = mPositions.mBlob.GetBufferSize();
745     std::vector<uint8_t> buffer(bufferSize);
746
747     std::string path;
748     auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mPositions.mBufferIdx], path);
749     if(!ReadAccessor(mPositions, stream, buffer.data()))
750     {
751       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << path << "'.";
752     }
753
754     uint32_t numVector3 = static_cast<uint32_t>(bufferSize / sizeof(Vector3));
755     if(mPositions.mBlob.mMin.size() != 3u || mPositions.mBlob.mMax.size() != 3u)
756     {
757       mPositions.mBlob.ComputeMinMax(3u, numVector3, reinterpret_cast<float*>(buffer.data()));
758     }
759     else
760     {
761       mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
762     }
763
764     if(HasBlendShapes())
765     {
766       positions.resize(numVector3);
767       std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
768     }
769
770     raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
771   }
772
773   const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
774   auto       hasNormals  = mNormals.IsDefined();
775   if(hasNormals)
776   {
777     DALI_ASSERT_ALWAYS(((mNormals.mBlob.mLength % sizeof(Vector3) == 0) ||
778                         mNormals.mBlob.mStride >= sizeof(Vector3)) &&
779                        "Normal buffer length not a multiple of element size");
780     const auto           bufferSize = mNormals.mBlob.GetBufferSize();
781     std::vector<uint8_t> buffer(bufferSize);
782
783     std::string path;
784     auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mNormals.mBufferIdx], path);
785     if(!ReadAccessor(mNormals, stream, buffer.data()))
786     {
787       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << path << "'.";
788     }
789
790     mNormals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
791
792     raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
793   }
794   else if(mNormals.mBlob.mLength != 0 && isTriangles)
795   {
796     DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
797     static const std::function<bool(RawData&)> GenerateNormalsFunction[2] =
798       {
799         GenerateNormals<false>,
800         GenerateNormals<true>,
801       };
802     const bool generateSuccessed = GenerateNormalsFunction[MaskMatch(mFlags, U32_INDICES)](raw);
803     if(!generateSuccessed)
804     {
805       DALI_LOG_ERROR("Failed to generate normal\n");
806     }
807     else
808     {
809       hasNormals = true;
810     }
811   }
812
813   const auto hasUvs = mTexCoords.IsDefined();
814   if(hasUvs)
815   {
816     DALI_ASSERT_ALWAYS(((mTexCoords.mBlob.mLength % sizeof(Vector2) == 0) ||
817                         mTexCoords.mBlob.mStride >= sizeof(Vector2)) &&
818                        "Normal buffer length not a multiple of element size");
819     const auto           bufferSize = mTexCoords.mBlob.GetBufferSize();
820     std::vector<uint8_t> buffer(bufferSize);
821
822     std::string path;
823     auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mTexCoords.mBufferIdx], path);
824     if(!ReadAccessor(mTexCoords, stream, buffer.data()))
825     {
826       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << path << "'.";
827     }
828
829     const auto uvCount = bufferSize / sizeof(Vector2);
830     if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
831     {
832       auto uv    = reinterpret_cast<Vector2*>(buffer.data());
833       auto uvEnd = uv + uvCount;
834       while(uv != uvEnd)
835       {
836         uv->y = 1.0f - uv->y;
837         ++uv;
838       }
839     }
840
841     mTexCoords.mBlob.ApplyMinMax(static_cast<uint32_t>(uvCount), reinterpret_cast<float*>(buffer.data()));
842
843     raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
844   }
845
846   if(mTangents.IsDefined())
847   {
848     uint32_t propertySize = static_cast<uint32_t>((mTangentType == Property::VECTOR4) ? sizeof(Vector4) : sizeof(Vector3));
849     DALI_ASSERT_ALWAYS(((mTangents.mBlob.mLength % propertySize == 0) ||
850                         mTangents.mBlob.mStride >= propertySize) &&
851                        "Tangents buffer length not a multiple of element size");
852     const auto           bufferSize = mTangents.mBlob.GetBufferSize();
853     std::vector<uint8_t> buffer(bufferSize);
854
855     std::string path;
856     auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mTangents.mBufferIdx], path);
857     if(!ReadAccessor(mTangents, stream, buffer.data()))
858     {
859       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << path << "'.";
860     }
861     mTangents.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
862
863     raw.mAttribs.push_back({"aTangent", mTangentType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
864   }
865   else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
866   {
867     DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
868     static const std::function<bool(RawData&)> GenerateTangentsFunction[2][2][2] =
869       {
870         {
871           {
872             GenerateTangents<false, false, false>,
873             GenerateTangents<false, false, true>,
874           },
875           {
876             GenerateTangents<false, true, false>,
877             GenerateTangents<false, true, true>,
878           },
879         },
880         {
881           {
882             GenerateTangents<true, false, false>,
883             GenerateTangents<true, false, true>,
884           },
885           {
886             GenerateTangents<true, true, false>,
887             GenerateTangents<true, true, true>,
888           },
889         }};
890     const bool generateSuccessed = GenerateTangentsFunction[MaskMatch(mFlags, U32_INDICES)][mTangentType == Property::VECTOR3][hasUvs](raw);
891     if(!generateSuccessed)
892     {
893       DALI_LOG_ERROR("Failed to generate tangents\n");
894     }
895   }
896
897   if(mColors.IsDefined())
898   {
899     uint32_t       propertySize = mColors.mBlob.mElementSizeHint;
900     Property::Type propertyType = (propertySize == sizeof(Vector4)) ? Property::VECTOR4 : ((propertySize == sizeof(Vector3)) ? Property::VECTOR3 : Property::NONE);
901     if(propertyType != Property::NONE)
902     {
903       DALI_ASSERT_ALWAYS(((mColors.mBlob.mLength % propertySize == 0) ||
904                           mColors.mBlob.mStride >= propertySize) &&
905                          "Colors buffer length not a multiple of element size");
906       const auto           bufferSize = mColors.mBlob.GetBufferSize();
907       std::vector<uint8_t> buffer(bufferSize);
908
909       std::string path;
910       auto&       stream = GetAvailableData(fileStream, meshPath, buffers[mColors.mBufferIdx], path);
911       if(!ReadAccessor(mColors, stream, buffer.data()))
912       {
913         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read colors from '" << path << "'.";
914       }
915       mColors.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
916
917       raw.mAttribs.push_back({"aVertexColor", propertyType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
918     }
919   }
920   else
921   {
922     std::vector<uint8_t> buffer(raw.mAttribs[0].mNumElements * sizeof(Vector4));
923     auto                 colors = reinterpret_cast<Vector4*>(buffer.data());
924
925     for(uint32_t i = 0; i < raw.mAttribs[0].mNumElements; i++)
926     {
927       colors[i] = Vector4::ONE;
928     }
929
930     raw.mAttribs.push_back({"aVertexColor", Property::VECTOR4, raw.mAttribs[0].mNumElements, std::move(buffer)});
931   }
932
933   if(IsSkinned())
934   {
935     std::string pathJoint;
936     auto&       streamJoint = GetAvailableData(fileStream, meshPath, buffers[mJoints0.mBufferIdx], pathJoint);
937     if(MaskMatch(mFlags, U16_JOINT_IDS))
938     {
939       ReadJointAccessor<uint16_t>(raw, mJoints0, streamJoint, pathJoint);
940     }
941     else if(MaskMatch(mFlags, U8_JOINT_IDS))
942     {
943       ReadJointAccessor<uint8_t>(raw, mJoints0, streamJoint, pathJoint);
944     }
945     else
946     {
947       ReadJointAccessor<float>(raw, mJoints0, streamJoint, pathJoint);
948     }
949
950     DALI_ASSERT_ALWAYS(((mWeights0.mBlob.mLength % sizeof(Vector4) == 0) ||
951                         mWeights0.mBlob.mStride >= sizeof(Vector4)) &&
952                        "Weights buffer length not a multiple of element size");
953     const auto           bufferSize = mWeights0.mBlob.GetBufferSize();
954     std::vector<uint8_t> buffer(bufferSize);
955
956     std::string pathWeight;
957     auto&       streamWeight = GetAvailableData(fileStream, meshPath, buffers[mWeights0.mBufferIdx], pathWeight);
958     if(!ReadAccessor(mWeights0, streamWeight, buffer.data()))
959     {
960       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << pathWeight << "'.";
961     }
962
963     raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
964   }
965
966   // Calculate the Blob for the blend shapes.
967   Blob blendShapesBlob;
968   blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
969   blendShapesBlob.mLength = 0u;
970
971   for(const auto& blendShape : mBlendShapes)
972   {
973     for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
974     {
975       if(i->IsDefined())
976       {
977         blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
978         blendShapesBlob.mLength += i->mBlob.mLength;
979       }
980     }
981   }
982
983   if(HasBlendShapes())
984   {
985     const uint32_t numberOfVertices = static_cast<uint32_t>(mPositions.mBlob.mLength / sizeof(Vector3));
986
987     // Calculate the size of one buffer inside the texture.
988     raw.mBlendShapeBufferOffset = numberOfVertices;
989
990     bool     calculateGltf2BlendShapes = false;
991     uint32_t textureWidth              = 0u;
992     uint32_t textureHeight             = 0u;
993
994     if(!mBlendShapeHeader.IsDefined())
995     {
996       CalculateTextureSize(static_cast<uint32_t>(blendShapesBlob.mLength / sizeof(Vector3)), textureWidth, textureHeight);
997       calculateGltf2BlendShapes = true;
998     }
999     else
1000     {
1001       uint16_t header[2u];
1002       ReadBlob(mBlendShapeHeader, fileStream, reinterpret_cast<uint8_t*>(header));
1003       textureWidth  = header[0u];
1004       textureHeight = header[1u];
1005     }
1006
1007     const uint32_t numberOfBlendShapes = mBlendShapes.size();
1008     raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
1009
1010     Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
1011     uint8_t*           geometryBuffer      = geometryPixelBuffer.GetBuffer();
1012
1013     if(calculateGltf2BlendShapes)
1014     {
1015       CalculateGltf2BlendShapes(geometryBuffer, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u], buffers);
1016     }
1017     else
1018     {
1019       Blob unnormalizeFactorBlob;
1020       unnormalizeFactorBlob.mLength = static_cast<uint32_t>(sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes));
1021
1022       if(blendShapesBlob.IsDefined())
1023       {
1024         if(ReadBlob(blendShapesBlob, fileStream, geometryBuffer))
1025         {
1026           unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
1027         }
1028       }
1029
1030       // Read the unnormalize factors.
1031       if(unnormalizeFactorBlob.IsDefined())
1032       {
1033         ReadBlob(unnormalizeFactorBlob, fileStream, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
1034       }
1035     }
1036     raw.mBlendShapeData = Devel::PixelBuffer::Convert(geometryPixelBuffer);
1037   }
1038
1039   return raw;
1040 }
1041
1042 MeshGeometry MeshDefinition::Load(RawData&& raw) const
1043 {
1044   MeshGeometry meshGeometry;
1045   meshGeometry.geometry = Geometry::New();
1046   meshGeometry.geometry.SetType(mPrimitiveType);
1047
1048   if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
1049   {
1050     auto options          = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
1051     meshGeometry.geometry = MakeTexturedQuadGeometry(options);
1052   }
1053   else
1054   {
1055     if(!raw.mIndices.empty())
1056     {
1057       if(MaskMatch(mFlags, U32_INDICES))
1058       {
1059         // TODO : We can only store indeces as uint16_type. Send Dali::Geometry that we use it as uint32_t actual.
1060         meshGeometry.geometry.SetIndexBuffer(reinterpret_cast<const uint32_t*>(raw.mIndices.data()), raw.mIndices.size() / 2);
1061       }
1062       else
1063       {
1064         meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
1065       }
1066     }
1067
1068     for(auto& a : raw.mAttribs)
1069     {
1070       a.AttachBuffer(meshGeometry.geometry);
1071     }
1072
1073     if(HasBlendShapes())
1074     {
1075       meshGeometry.blendShapeBufferOffset      = raw.mBlendShapeBufferOffset;
1076       meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
1077
1078       meshGeometry.blendShapeGeometry = Texture::New(TextureType::TEXTURE_2D,
1079                                                      raw.mBlendShapeData.GetPixelFormat(),
1080                                                      raw.mBlendShapeData.GetWidth(),
1081                                                      raw.mBlendShapeData.GetHeight());
1082       meshGeometry.blendShapeGeometry.Upload(raw.mBlendShapeData);
1083     }
1084   }
1085
1086   return meshGeometry;
1087 }
1088
1089 void MeshDefinition::RetrieveBlendShapeComponents(bool& hasPositions, bool& hasNormals, bool& hasTangents) const
1090 {
1091   for(const auto& blendShape : mBlendShapes)
1092   {
1093     hasPositions = hasPositions || blendShape.deltas.IsDefined();
1094     hasNormals   = hasNormals || blendShape.normals.IsDefined();
1095     hasTangents  = hasTangents || blendShape.tangents.IsDefined();
1096   }
1097 }
1098
1099 } // namespace Dali::Scene3D::Loader