Updated all cpp files to new format
[platform/core/uifw/dali-toolkit.git] / dali-scene-loader / public-api / mesh-definition.cpp
1 /*
2  * Copyright (c) 2021 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 // INTERNAL INCLUDES
19 #include "dali-scene-loader/public-api/mesh-definition.h"
20
21 // EXTERNAL INCLUDES
22 #include <cstring>
23 #include <fstream>
24 #include "dali/devel-api/adaptor-framework/pixel-buffer.h"
25
26 namespace Dali
27 {
28 namespace SceneLoader
29 {
30 namespace
31 {
32 using Uint16Vector4 = uint16_t[4];
33
34 class IndexProvider
35 {
36 public:
37   IndexProvider(const uint16_t* indices)
38   : mData(reinterpret_cast<uintptr_t>(indices)),
39     mFunc(indices ? IncrementPointer : Increment)
40   {
41   }
42
43   uint16_t operator()()
44   {
45     return mFunc(mData);
46   }
47
48 private:
49   static uint16_t Increment(uintptr_t& data)
50   {
51     return static_cast<uint16_t>(data++);
52   }
53
54   static uint16_t IncrementPointer(uintptr_t& data)
55   {
56     auto iPtr   = reinterpret_cast<const uint16_t*>(data);
57     auto result = *iPtr;
58     data        = reinterpret_cast<uintptr_t>(++iPtr);
59     return result;
60   }
61
62   uintptr_t mData;
63   uint16_t (*mFunc)(uintptr_t&);
64 };
65
66 const std::string QUAD("quad");
67
68 ///@brief Reads a blob from the given stream @a source into @a target, which must have
69 /// at least @a descriptor.length bytes.
70 bool ReadBlob(const MeshDefinition::Blob& descriptor, std::istream& source, uint8_t* target)
71 {
72   if(!source.seekg(descriptor.mOffset, std::istream::beg))
73   {
74     return false;
75   }
76
77   if(descriptor.IsConsecutive())
78   {
79     return !!source.read(reinterpret_cast<char*>(target), descriptor.mLength);
80   }
81   else
82   {
83     DALI_ASSERT_DEBUG(descriptor.mStride > descriptor.mElementSizeHint);
84     const uint32_t diff     = descriptor.mStride - descriptor.mElementSizeHint;
85     uint32_t       readSize = 0;
86     while(readSize < descriptor.mLength &&
87           source.read(reinterpret_cast<char*>(target), descriptor.mElementSizeHint) &&
88           source.seekg(diff, std::istream::cur))
89     {
90       readSize += descriptor.mStride;
91       target += descriptor.mElementSizeHint;
92     }
93     return readSize == descriptor.mLength;
94   }
95 }
96
97 template<typename T>
98 void ReadValues(const std::vector<uint8_t>& valuesBuffer, const std::vector<uint8_t>& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint)
99 {
100   const T* const indicesPtr = reinterpret_cast<const T* const>(indicesBuffer.data());
101   for(uint32_t index = 0u; index < count; ++index)
102   {
103     uint32_t valuesIndex = indicesPtr[index] * elementSizeHint;
104     memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint);
105   }
106 }
107
108 bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source, uint8_t* target)
109 {
110   bool success = false;
111
112   if(accessor.mBlob.IsDefined())
113   {
114     success = ReadBlob(accessor.mBlob, source, target);
115     if(!success)
116     {
117       return false;
118     }
119   }
120
121   if(accessor.mSparse)
122   {
123     const MeshDefinition::Blob& indices = accessor.mSparse->mIndices;
124     const MeshDefinition::Blob& values  = accessor.mSparse->mValues;
125
126     if(!indices.IsDefined() || !values.IsDefined())
127     {
128       return false;
129     }
130
131     const auto           indicesBufferSize = indices.GetBufferSize();
132     std::vector<uint8_t> indicesBuffer(indicesBufferSize);
133     success = ReadBlob(indices, source, indicesBuffer.data());
134     if(!success)
135     {
136       return false;
137     }
138
139     const auto           valuesBufferSize = values.GetBufferSize();
140     std::vector<uint8_t> valuesBuffer(valuesBufferSize);
141     success = ReadBlob(values, source, valuesBuffer.data());
142     if(!success)
143     {
144       return false;
145     }
146
147     switch(indices.mElementSizeHint)
148     {
149       case 1u:
150       {
151         ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
152         break;
153       }
154       case 2u:
155       {
156         ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
157         break;
158       }
159       case 4u:
160       {
161         ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
162         break;
163       }
164       default:
165         DALI_ASSERT_DEBUG(!"Unsupported type for an index");
166     }
167   }
168
169   return success;
170 }
171
172 void GenerateNormals(MeshDefinition::RawData& raw)
173 {
174   auto& attribs = raw.mAttribs;
175   DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
176   IndexProvider getIndex(raw.mIndices.data());
177
178   const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size();
179
180   auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
181
182   std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
183   auto                 normals = reinterpret_cast<Vector3*>(buffer.data());
184
185   for(uint32_t i = 0; i < numIndices; i += 3)
186   {
187     uint16_t indices[]{getIndex(), getIndex(), getIndex()};
188     Vector3  pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
189
190     Vector3 a = pos[1] - pos[0];
191     Vector3 b = pos[2] - pos[0];
192
193     Vector3 normal(a.Cross(b));
194     normals[indices[0]] += normal;
195     normals[indices[1]] += normal;
196     normals[indices[2]] += normal;
197   }
198
199   auto iEnd = normals + attribs[0].mNumElements;
200   while(normals != iEnd)
201   {
202     normals->Normalize();
203     ++normals;
204   }
205
206   attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
207 }
208
209 void GenerateTangentsWithUvs(MeshDefinition::RawData& raw)
210 {
211   auto& attribs = raw.mAttribs;
212   DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs
213   IndexProvider getIndex(raw.mIndices.data());
214
215   const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size();
216
217   auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
218   auto* uvs       = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
219
220   std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
221   auto                 tangents = reinterpret_cast<Vector3*>(buffer.data());
222
223   for(uint32_t i = 0; i < numIndices; i += 3)
224   {
225     uint16_t indices[]{getIndex(), getIndex(), getIndex()};
226     Vector3  pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
227     Vector2  uv[]{uvs[indices[0]], uvs[indices[1]], uvs[indices[2]]};
228
229     float x0 = pos[1].x - pos[0].x;
230     float y0 = pos[1].y - pos[0].y;
231     float z0 = pos[1].z - pos[0].z;
232
233     float x1 = pos[2].x - pos[0].x;
234     float y1 = pos[2].y - pos[0].y;
235     float z1 = pos[2].z - pos[0].z;
236
237     float s0 = uv[1].x - uv[0].x;
238     float t0 = uv[1].y - uv[0].y;
239
240     float s1 = uv[2].x - uv[0].x;
241     float t1 = uv[2].y - uv[0].y;
242
243     float   r = 1.f / (s0 * t1 - t0 * s1);
244     Vector3 tangent((x0 * t1 - t0 * x1) * r, (y0 * t1 - t0 * y1) * r, (z0 * t1 - t0 * z1) * r);
245     tangents[indices[0]] += tangent;
246     tangents[indices[1]] += tangent;
247     tangents[indices[2]] += tangent;
248   }
249
250   auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
251   auto  iEnd    = normals + attribs[1].mNumElements;
252   while(normals != iEnd)
253   {
254     *tangents -= *normals * normals->Dot(*tangents);
255     tangents->Normalize();
256
257     ++tangents;
258     ++normals;
259   }
260   attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
261 }
262
263 void GenerateTangents(MeshDefinition::RawData& raw)
264 {
265   auto& attribs = raw.mAttribs;
266   DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals
267
268   auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
269
270   std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
271   auto                 tangents = reinterpret_cast<Vector3*>(buffer.data());
272
273   auto iEnd = normals + attribs[1].mNumElements;
274   while(normals != iEnd)
275   {
276     Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)};
277
278     *tangents = t[t[1].LengthSquared() > t[0].LengthSquared()];
279     *tangents -= *normals * normals->Dot(*tangents);
280     tangents->Normalize();
281
282     ++tangents;
283     ++normals;
284   }
285   attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
286 }
287
288 void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight)
289 {
290   DALI_ASSERT_DEBUG(0u != totalTextureSize && "totalTextureSize is zero.")
291
292   // Calculate the dimensions of the texture.
293   // The total size of the texture is the length of the blend shapes blob.
294
295   textureWidth  = 0u;
296   textureHeight = 0u;
297
298   if(0u == totalTextureSize)
299   {
300     // nothing to do.
301     return;
302   }
303
304   const uint32_t pow2      = static_cast<uint32_t>(ceil(log2(totalTextureSize)));
305   const uint32_t powWidth  = pow2 >> 1u;
306   const uint32_t powHeight = pow2 - powWidth;
307
308   textureWidth  = 1u << powWidth;
309   textureHeight = 1u << powHeight;
310 }
311
312 void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, std::ifstream& binFile, const std::vector<MeshDefinition::BlendShape>& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor)
313 {
314   uint32_t geometryBufferIndex = 0u;
315   float    maxDistance         = 0.f;
316   Vector3* geometryBufferV3    = reinterpret_cast<Vector3*>(geometryBuffer);
317   for(const auto& blendShape : blendShapes)
318   {
319     if(blendShape.deltas.IsDefined())
320     {
321       DALI_ASSERT_ALWAYS(((blendShape.deltas.mBlob.mLength % sizeof(Vector3) == 0u) ||
322                           blendShape.deltas.mBlob.mStride >= sizeof(Vector3)) &&
323                          "Blend Shape position buffer length not a multiple of element size");
324
325       const auto           bufferSize = blendShape.deltas.mBlob.GetBufferSize();
326       std::vector<uint8_t> buffer(bufferSize);
327       if(ReadAccessor(blendShape.deltas, binFile, buffer.data()))
328       {
329         blendShape.deltas.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
330         // Calculate the difference with the original mesh.
331         // Find the max distance to normalize the deltas.
332         const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
333
334         for(uint32_t index = 0u; index < numberOfVertices; ++index)
335         {
336           Vector3& delta = geometryBufferV3[geometryBufferIndex++];
337           delta          = deltasBuffer[index];
338
339           maxDistance = std::max(maxDistance, delta.LengthSquared());
340         }
341       }
342     }
343
344     if(blendShape.normals.IsDefined())
345     {
346       DALI_ASSERT_ALWAYS(((blendShape.normals.mBlob.mLength % sizeof(Vector3) == 0u) ||
347                           blendShape.normals.mBlob.mStride >= sizeof(Vector3)) &&
348                          "Blend Shape normals buffer length not a multiple of element size");
349
350       const auto           bufferSize = blendShape.normals.mBlob.GetBufferSize();
351       std::vector<uint8_t> buffer(bufferSize);
352       if(ReadAccessor(blendShape.normals, binFile, buffer.data()))
353       {
354         blendShape.normals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
355
356         // Calculate the difference with the original mesh, and translate to make all values positive.
357         const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
358
359         for(uint32_t index = 0u; index < numberOfVertices; ++index)
360         {
361           Vector3& delta = geometryBufferV3[geometryBufferIndex++];
362           delta          = deltasBuffer[index];
363
364           delta.x *= 0.5f;
365           delta.y *= 0.5f;
366           delta.z *= 0.5f;
367
368           delta.x += 0.5f;
369           delta.y += 0.5f;
370           delta.z += 0.5f;
371         }
372       }
373     }
374
375     if(blendShape.tangents.IsDefined())
376     {
377       DALI_ASSERT_ALWAYS(((blendShape.tangents.mBlob.mLength % sizeof(Vector3) == 0u) ||
378                           blendShape.tangents.mBlob.mStride >= sizeof(Vector3)) &&
379                          "Blend Shape tangents buffer length not a multiple of element size");
380
381       const auto           bufferSize = blendShape.tangents.mBlob.GetBufferSize();
382       std::vector<uint8_t> buffer(bufferSize);
383       if(ReadAccessor(blendShape.tangents, binFile, buffer.data()))
384       {
385         blendShape.tangents.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
386
387         // Calculate the difference with the original mesh, and translate to make all values positive.
388         const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
389
390         for(uint32_t index = 0u; index < numberOfVertices; ++index)
391         {
392           Vector3& delta = geometryBufferV3[geometryBufferIndex++];
393           delta          = deltasBuffer[index];
394
395           delta.x *= 0.5f;
396           delta.y *= 0.5f;
397           delta.z *= 0.5f;
398
399           delta.x += 0.5f;
400           delta.y += 0.5f;
401           delta.z += 0.5f;
402         }
403       }
404     }
405   }
406
407   geometryBufferIndex = 0u;
408   for(const auto& blendShape : blendShapes)
409   {
410     // Normalize all the deltas and translate to a possitive value.
411     // Deltas are going to be passed to the shader in a color texture
412     // whose values that are less than zero are clamped.
413     if(blendShape.deltas.IsDefined())
414     {
415       const float normalizeFactor = (fabsf(maxDistance) < Math::MACHINE_EPSILON_1000) ? 1.f : (0.5f / sqrtf(maxDistance));
416
417       for(uint32_t index = 0u; index < numberOfVertices; ++index)
418       {
419         Vector3& delta = geometryBufferV3[geometryBufferIndex++];
420         delta.x        = Clamp(((delta.x * normalizeFactor) + 0.5f), 0.f, 1.f);
421         delta.y        = Clamp(((delta.y * normalizeFactor) + 0.5f), 0.f, 1.f);
422         delta.z        = Clamp(((delta.z * normalizeFactor) + 0.5f), 0.f, 1.f);
423       }
424
425       // Calculate and store the unnormalize factor.
426       blendShapeUnnormalizeFactor = 1.f / normalizeFactor;
427     }
428
429     if(blendShape.normals.IsDefined())
430     {
431       geometryBufferIndex += numberOfVertices;
432     }
433
434     if(blendShape.tangents.IsDefined())
435     {
436       geometryBufferIndex += numberOfVertices;
437     }
438   }
439 }
440
441 } // namespace
442
443 MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count)
444 : mIndices{indices},
445   mValues{values},
446   mCount{count}
447 {
448 }
449
450 MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob&       blob,
451                                    const MeshDefinition::SparseBlob& sparse)
452 : mBlob{blob},
453   mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr}
454 {
455 }
456
457 void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values)
458 {
459   DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0);
460   const auto numComponents = std::max(min.size(), max.size());
461
462   using ClampFn   = void (*)(const float*, const float*, uint32_t, float&);
463   ClampFn clampFn = min.empty() ? (max.empty() ? static_cast<ClampFn>(nullptr) : [](const float* min, const float* max, uint32_t i, float& value) {
464     value = std::min(max[i], value);
465   })
466                                 : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) {
467                                     value = std::max(min[i], value);
468                                   }
469                                                : [](const float* min, const float* max, uint32_t i, float& value) {
470                                                    value = std::min(std::max(min[i], value), max[i]);
471                                                  });
472
473   auto end = values + count * numComponents;
474   while(values != end)
475   {
476     auto     nextElement = values + numComponents;
477     uint32_t i           = 0;
478     while(values != nextElement)
479     {
480       clampFn(min.data(), max.data(), i, *values);
481       ++values;
482       ++i;
483     }
484   }
485 }
486
487 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)
488 : mOffset(offset),
489   mLength(length),
490   mStride(stride),
491   mElementSizeHint(elementSizeHint),
492   mMin(min),
493   mMax(max)
494 {
495 }
496
497 uint32_t MeshDefinition::Blob::GetBufferSize() const
498 {
499   return IsConsecutive() ? mLength : (mLength * mElementSizeHint / mStride);
500 }
501
502 void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const
503 {
504   ApplyMinMax(mMin, mMax, count, values);
505 }
506
507 void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
508 {
509   Property::Map attribMap;
510   attribMap[mName]          = mType;
511   VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
512   attribBuffer.SetData(mData.data(), mNumElements);
513
514   g.AddVertexBuffer(attribBuffer);
515 }
516
517 bool MeshDefinition::IsQuad() const
518 {
519   return CaseInsensitiveStringCompare(QUAD, mUri);
520 }
521
522 bool MeshDefinition::IsSkinned() const
523 {
524   return mJoints0.IsDefined() && mWeights0.IsDefined();
525 }
526
527 bool MeshDefinition::HasBlendShapes() const
528 {
529   return !mBlendShapes.empty();
530 }
531
532 void MeshDefinition::RequestNormals()
533 {
534   mNormals.mBlob.mLength = mPositions.mBlob.GetBufferSize();
535 }
536
537 void MeshDefinition::RequestTangents()
538 {
539   mTangents.mBlob.mLength = mNormals.mBlob.GetBufferSize();
540 }
541
542 MeshDefinition::RawData
543 MeshDefinition::LoadRaw(const std::string& modelsPath) const
544 {
545   RawData raw;
546   if(IsQuad())
547   {
548     return raw;
549   }
550
551   const std::string meshPath = modelsPath + mUri;
552   std::ifstream     binFile(meshPath, std::ios::binary);
553   if(!binFile)
554   {
555     ExceptionFlinger(ASSERT_LOCATION) << "Failed to read geometry data from '" << meshPath << "'";
556   }
557
558   if(mIndices.IsDefined())
559   {
560     if(MaskMatch(mFlags, U32_INDICES))
561     {
562       DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint32_t) == 0) ||
563                           mIndices.mBlob.mStride >= sizeof(uint32_t)) &&
564                          "Index buffer length not a multiple of element size");
565       const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint32_t);
566       raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially.
567       if(!ReadAccessor(mIndices, binFile, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
568       {
569         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
570       }
571
572       auto u16s = raw.mIndices.data();
573       auto u32s = reinterpret_cast<uint32_t*>(raw.mIndices.data());
574       auto end  = u32s + indexCount;
575       while(u32s != end)
576       {
577         *u16s = static_cast<uint16_t>(*u32s);
578         ++u16s;
579         ++u32s;
580       }
581
582       raw.mIndices.resize(indexCount);
583     }
584     else
585     {
586       DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(unsigned short) == 0) ||
587                           mIndices.mBlob.mStride >= sizeof(unsigned short)) &&
588                          "Index buffer length not a multiple of element size");
589       raw.mIndices.resize(mIndices.mBlob.mLength / sizeof(unsigned short));
590       if(!ReadAccessor(mIndices, binFile, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
591       {
592         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
593       }
594     }
595   }
596
597   std::vector<Vector3> positions;
598   if(mPositions.IsDefined())
599   {
600     DALI_ASSERT_ALWAYS(((mPositions.mBlob.mLength % sizeof(Vector3) == 0) ||
601                         mPositions.mBlob.mStride >= sizeof(Vector3)) &&
602                        "Position buffer length not a multiple of element size");
603     const auto           bufferSize = mPositions.mBlob.GetBufferSize();
604     std::vector<uint8_t> buffer(bufferSize);
605     if(!ReadAccessor(mPositions, binFile, buffer.data()))
606     {
607       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << meshPath << "'.";
608     }
609
610     uint32_t numVector3 = bufferSize / sizeof(Vector3);
611     mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
612
613     if(HasBlendShapes())
614     {
615       positions.resize(numVector3);
616       std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
617     }
618
619     raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
620   }
621
622   const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
623   auto       hasNormals  = mNormals.IsDefined();
624   if(hasNormals)
625   {
626     DALI_ASSERT_ALWAYS(((mNormals.mBlob.mLength % sizeof(Vector3) == 0) ||
627                         mNormals.mBlob.mStride >= sizeof(Vector3)) &&
628                        "Normal buffer length not a multiple of element size");
629     const auto           bufferSize = mNormals.mBlob.GetBufferSize();
630     std::vector<uint8_t> buffer(bufferSize);
631     if(!ReadAccessor(mNormals, binFile, buffer.data()))
632     {
633       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << meshPath << "'.";
634     }
635
636     mNormals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
637
638     raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
639   }
640   else if(mNormals.mBlob.mLength != 0 && isTriangles)
641   {
642     DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
643     GenerateNormals(raw);
644     hasNormals = true;
645   }
646
647   const auto hasUvs = mTexCoords.IsDefined();
648   if(hasUvs)
649   {
650     DALI_ASSERT_ALWAYS(((mTexCoords.mBlob.mLength % sizeof(Vector2) == 0) ||
651                         mTexCoords.mBlob.mStride >= sizeof(Vector2)) &&
652                        "Normal buffer length not a multiple of element size");
653     const auto           bufferSize = mTexCoords.mBlob.GetBufferSize();
654     std::vector<uint8_t> buffer(bufferSize);
655     if(!ReadAccessor(mTexCoords, binFile, buffer.data()))
656     {
657       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << meshPath << "'.";
658     }
659
660     const auto uvCount = bufferSize / sizeof(Vector2);
661     if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
662     {
663       auto uv    = reinterpret_cast<Vector2*>(buffer.data());
664       auto uvEnd = uv + uvCount;
665       while(uv != uvEnd)
666       {
667         uv->y = 1.0f - uv->y;
668         ++uv;
669       }
670     }
671
672     mTexCoords.mBlob.ApplyMinMax(bufferSize / sizeof(Vector2), reinterpret_cast<float*>(buffer.data()));
673
674     raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
675   }
676
677   if(mTangents.IsDefined())
678   {
679     DALI_ASSERT_ALWAYS(((mTangents.mBlob.mLength % sizeof(Vector3) == 0) ||
680                         mTangents.mBlob.mStride >= sizeof(Vector3)) &&
681                        "Tangents buffer length not a multiple of element size");
682     const auto           bufferSize = mTangents.mBlob.GetBufferSize();
683     std::vector<uint8_t> buffer(bufferSize);
684     if(!ReadAccessor(mTangents, binFile, buffer.data()))
685     {
686       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << meshPath << "'.";
687     }
688
689     mTangents.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
690
691     raw.mAttribs.push_back({"aTangent", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
692   }
693   else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
694   {
695     DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
696     hasUvs ? GenerateTangentsWithUvs(raw) : GenerateTangents(raw);
697   }
698
699   if(IsSkinned())
700   {
701     if(MaskMatch(mFlags, U16_JOINT_IDS))
702     {
703       DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Uint16Vector4) == 0) ||
704                           mJoints0.mBlob.mStride >= sizeof(Uint16Vector4)) &&
705                          "Joints buffer length not a multiple of element size");
706       const auto           inBufferSize = mJoints0.mBlob.GetBufferSize();
707       std::vector<uint8_t> buffer(inBufferSize * 2);
708       auto                 u16s = buffer.data() + inBufferSize;
709       if(!ReadAccessor(mJoints0, binFile, u16s))
710       {
711         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
712       }
713
714       auto floats = reinterpret_cast<float*>(buffer.data());
715       auto end    = u16s + inBufferSize;
716       while(u16s != end)
717       {
718         auto value = *reinterpret_cast<uint16_t*>(u16s);
719         *floats    = static_cast<float>(value);
720
721         u16s += sizeof(uint16_t);
722         ++floats;
723       }
724       raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(buffer.size() / sizeof(Vector4)), std::move(buffer)});
725     }
726     else
727     {
728       DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Vector4) == 0) ||
729                           mJoints0.mBlob.mStride >= sizeof(Vector4)) &&
730                          "Joints buffer length not a multiple of element size");
731       const auto           bufferSize = mJoints0.mBlob.GetBufferSize();
732       std::vector<uint8_t> buffer(bufferSize);
733       if(!ReadAccessor(mJoints0, binFile, buffer.data()))
734       {
735         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
736       }
737
738       raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
739     }
740
741     DALI_ASSERT_ALWAYS(((mWeights0.mBlob.mLength % sizeof(Vector4) == 0) ||
742                         mWeights0.mBlob.mStride >= sizeof(Vector4)) &&
743                        "Weights buffer length not a multiple of element size");
744     const auto           bufferSize = mWeights0.mBlob.GetBufferSize();
745     std::vector<uint8_t> buffer(bufferSize);
746     if(!ReadAccessor(mWeights0, binFile, buffer.data()))
747     {
748       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << meshPath << "'.";
749     }
750
751     raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
752   }
753
754   // Calculate the Blob for the blend shapes.
755   Blob blendShapesBlob;
756   blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
757   blendShapesBlob.mLength = 0u;
758
759   for(const auto& blendShape : mBlendShapes)
760   {
761     for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
762     {
763       if(i->IsDefined())
764       {
765         blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
766         blendShapesBlob.mLength += i->mBlob.mLength;
767       }
768     }
769   }
770
771   if(HasBlendShapes())
772   {
773     const uint32_t numberOfVertices = mPositions.mBlob.mLength / sizeof(Vector3);
774
775     // Calculate the size of one buffer inside the texture.
776     raw.mBlendShapeBufferOffset = numberOfVertices;
777
778     bool     calculateGltf2BlendShapes = false;
779     uint32_t textureWidth              = 0u;
780     uint32_t textureHeight             = 0u;
781
782     if(!mBlendShapeHeader.IsDefined())
783     {
784       CalculateTextureSize(blendShapesBlob.mLength / sizeof(Vector3), textureWidth, textureHeight);
785       calculateGltf2BlendShapes = true;
786     }
787     else
788     {
789       uint16_t header[2u];
790       ReadBlob(mBlendShapeHeader, binFile, reinterpret_cast<uint8_t*>(header));
791       textureWidth  = header[0u];
792       textureHeight = header[1u];
793     }
794
795     const uint32_t numberOfBlendShapes = mBlendShapes.size();
796     raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
797
798     Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
799     uint8_t*           geometryBuffer      = geometryPixelBuffer.GetBuffer();
800
801     if(calculateGltf2BlendShapes)
802     {
803       CalculateGltf2BlendShapes(geometryBuffer, binFile, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u]);
804     }
805     else
806     {
807       Blob unnormalizeFactorBlob;
808       unnormalizeFactorBlob.mLength = sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes);
809
810       if(blendShapesBlob.IsDefined())
811       {
812         if(ReadBlob(blendShapesBlob, binFile, geometryBuffer))
813         {
814           unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
815         }
816       }
817
818       // Read the unnormalize factors.
819       if(unnormalizeFactorBlob.IsDefined())
820       {
821         ReadBlob(unnormalizeFactorBlob, binFile, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
822       }
823     }
824     raw.mBlendShapeData = Devel::PixelBuffer::Convert(geometryPixelBuffer);
825   }
826
827   return raw;
828 }
829
830 MeshGeometry MeshDefinition::Load(RawData&& raw) const
831 {
832   MeshGeometry meshGeometry;
833   meshGeometry.geometry = Geometry::New();
834   meshGeometry.geometry.SetType(mPrimitiveType);
835
836   if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
837   {
838     auto options          = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
839     meshGeometry.geometry = MakeTexturedQuadGeometry(options);
840   }
841   else
842   {
843     if(!raw.mIndices.empty())
844     {
845       meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
846     }
847
848     for(auto& a : raw.mAttribs)
849     {
850       a.AttachBuffer(meshGeometry.geometry);
851     }
852
853     if(HasBlendShapes())
854     {
855       meshGeometry.blendShapeBufferOffset      = raw.mBlendShapeBufferOffset;
856       meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
857
858       meshGeometry.blendShapeGeometry = Texture::New(TextureType::TEXTURE_2D,
859                                                      raw.mBlendShapeData.GetPixelFormat(),
860                                                      raw.mBlendShapeData.GetWidth(),
861                                                      raw.mBlendShapeData.GetHeight());
862       meshGeometry.blendShapeGeometry.Upload(raw.mBlendShapeData);
863     }
864   }
865
866   return meshGeometry;
867 }
868
869 } // namespace SceneLoader
870 } // namespace Dali