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