75b19a7fa158e6219f67be87b92f7565bfd80d62
[platform/core/uifw/dali-toolkit.git] / dali-scene-loader / public-api / 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-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::ComputeMinMax(std::vector<float>& min, std::vector<float>& max, uint32_t numComponents, uint32_t count, const float* values)
458 {
459   min.assign(numComponents, MAXFLOAT);
460   max.assign(numComponents, -MAXFLOAT);
461   for(uint32_t i = 0; i < count; ++i)
462   {
463     for(uint32_t j = 0; j < numComponents; ++j)
464     {
465       min[j] = std::min(min[j], *values);
466       max[j] = std::max(max[j], *values);
467       values++;
468     }
469   }
470 }
471
472 void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values)
473 {
474   DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0);
475   const auto numComponents = std::max(min.size(), max.size());
476
477   using ClampFn   = void (*)(const float*, const float*, uint32_t, float&);
478   ClampFn clampFn = min.empty() ? (max.empty() ? static_cast<ClampFn>(nullptr) : [](const float* min, const float* max, uint32_t i, float& value) {
479     value = std::min(max[i], value);
480   })
481                                 : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) {
482                                     value = std::max(min[i], value);
483                                   }
484                                                : static_cast<ClampFn>([](const float* min, const float* max, uint32_t i, float& value) {
485                                                    value = std::min(std::max(min[i], value), max[i]);
486                                                  }));
487
488   if(!clampFn)
489   {
490     return;
491   }
492
493   auto end = values + count * numComponents;
494   while(values != end)
495   {
496     auto     nextElement = values + numComponents;
497     uint32_t i           = 0;
498     while(values != nextElement)
499     {
500       clampFn(min.data(), max.data(), i, *values);
501       ++values;
502       ++i;
503     }
504   }
505 }
506
507 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)
508 : mOffset(offset),
509   mLength(length),
510   mStride(stride),
511   mElementSizeHint(elementSizeHint),
512   mMin(min),
513   mMax(max)
514 {
515 }
516
517 uint32_t MeshDefinition::Blob::GetBufferSize() const
518 {
519   return IsConsecutive() ? mLength : (mLength * mElementSizeHint / mStride);
520 }
521
522 void MeshDefinition::Blob::ComputeMinMax(uint32_t numComponents, uint32_t count, float* values)
523 {
524   ComputeMinMax(mMin, mMax, numComponents, count, values);
525 }
526
527 void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const
528 {
529   ApplyMinMax(mMin, mMax, count, values);
530 }
531
532 void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
533 {
534   Property::Map attribMap;
535   attribMap[mName]          = mType;
536   VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
537   attribBuffer.SetData(mData.data(), mNumElements);
538
539   g.AddVertexBuffer(attribBuffer);
540 }
541
542 bool MeshDefinition::IsQuad() const
543 {
544   return CaseInsensitiveStringCompare(QUAD, mUri);
545 }
546
547 bool MeshDefinition::IsSkinned() const
548 {
549   return mJoints0.IsDefined() && mWeights0.IsDefined();
550 }
551
552 bool MeshDefinition::HasBlendShapes() const
553 {
554   return !mBlendShapes.empty();
555 }
556
557 void MeshDefinition::RequestNormals()
558 {
559   mNormals.mBlob.mLength = mPositions.mBlob.GetBufferSize();
560 }
561
562 void MeshDefinition::RequestTangents()
563 {
564   mTangents.mBlob.mLength = mNormals.mBlob.GetBufferSize();
565 }
566
567 MeshDefinition::RawData
568 MeshDefinition::LoadRaw(const std::string& modelsPath)
569 {
570   RawData raw;
571   if(IsQuad())
572   {
573     return raw;
574   }
575
576   const std::string meshPath = modelsPath + mUri;
577   std::ifstream     binFile(meshPath, std::ios::binary);
578   if(!binFile)
579   {
580     ExceptionFlinger(ASSERT_LOCATION) << "Failed to read geometry data from '" << meshPath << "'";
581   }
582
583   if(mIndices.IsDefined())
584   {
585     if(MaskMatch(mFlags, U32_INDICES))
586     {
587       DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint32_t) == 0) ||
588                           mIndices.mBlob.mStride >= sizeof(uint32_t)) &&
589                          "Index buffer length not a multiple of element size");
590       const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint32_t);
591       raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially.
592       if(!ReadAccessor(mIndices, binFile, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
593       {
594         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
595       }
596
597       auto u16s = raw.mIndices.data();
598       auto u32s = reinterpret_cast<uint32_t*>(raw.mIndices.data());
599       auto end  = u32s + indexCount;
600       while(u32s != end)
601       {
602         *u16s = static_cast<uint16_t>(*u32s);
603         ++u16s;
604         ++u32s;
605       }
606
607       raw.mIndices.resize(indexCount);
608     }
609     else
610     {
611       DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(unsigned short) == 0) ||
612                           mIndices.mBlob.mStride >= sizeof(unsigned short)) &&
613                          "Index buffer length not a multiple of element size");
614       raw.mIndices.resize(mIndices.mBlob.mLength / sizeof(unsigned short));
615       if(!ReadAccessor(mIndices, binFile, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
616       {
617         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
618       }
619     }
620   }
621
622   std::vector<Vector3> positions;
623   if(mPositions.IsDefined())
624   {
625     DALI_ASSERT_ALWAYS(((mPositions.mBlob.mLength % sizeof(Vector3) == 0) ||
626                         mPositions.mBlob.mStride >= sizeof(Vector3)) &&
627                        "Position buffer length not a multiple of element size");
628     const auto           bufferSize = mPositions.mBlob.GetBufferSize();
629     std::vector<uint8_t> buffer(bufferSize);
630     if(!ReadAccessor(mPositions, binFile, buffer.data()))
631     {
632       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << meshPath << "'.";
633     }
634
635     uint32_t numVector3 = bufferSize / sizeof(Vector3);
636     if(mPositions.mBlob.mMin.size() != 3u || mPositions.mBlob.mMax.size() != 3u)
637     {
638       mPositions.mBlob.ComputeMinMax(3u, numVector3, reinterpret_cast<float*>(buffer.data()));
639     }
640     else
641     {
642       mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
643     }
644
645     if(HasBlendShapes())
646     {
647       positions.resize(numVector3);
648       std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
649     }
650
651     raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
652   }
653
654   const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
655   auto       hasNormals  = mNormals.IsDefined();
656   if(hasNormals)
657   {
658     DALI_ASSERT_ALWAYS(((mNormals.mBlob.mLength % sizeof(Vector3) == 0) ||
659                         mNormals.mBlob.mStride >= sizeof(Vector3)) &&
660                        "Normal buffer length not a multiple of element size");
661     const auto           bufferSize = mNormals.mBlob.GetBufferSize();
662     std::vector<uint8_t> buffer(bufferSize);
663     if(!ReadAccessor(mNormals, binFile, buffer.data()))
664     {
665       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << meshPath << "'.";
666     }
667
668     mNormals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
669
670     raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
671   }
672   else if(mNormals.mBlob.mLength != 0 && isTriangles)
673   {
674     DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
675     GenerateNormals(raw);
676     hasNormals = true;
677   }
678
679   const auto hasUvs = mTexCoords.IsDefined();
680   if(hasUvs)
681   {
682     DALI_ASSERT_ALWAYS(((mTexCoords.mBlob.mLength % sizeof(Vector2) == 0) ||
683                         mTexCoords.mBlob.mStride >= sizeof(Vector2)) &&
684                        "Normal buffer length not a multiple of element size");
685     const auto           bufferSize = mTexCoords.mBlob.GetBufferSize();
686     std::vector<uint8_t> buffer(bufferSize);
687     if(!ReadAccessor(mTexCoords, binFile, buffer.data()))
688     {
689       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << meshPath << "'.";
690     }
691
692     const auto uvCount = bufferSize / sizeof(Vector2);
693     if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
694     {
695       auto uv    = reinterpret_cast<Vector2*>(buffer.data());
696       auto uvEnd = uv + uvCount;
697       while(uv != uvEnd)
698       {
699         uv->y = 1.0f - uv->y;
700         ++uv;
701       }
702     }
703
704     mTexCoords.mBlob.ApplyMinMax(bufferSize / sizeof(Vector2), reinterpret_cast<float*>(buffer.data()));
705
706     raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
707   }
708
709   if(mTangents.IsDefined())
710   {
711     uint32_t propertySize = (mTangentType == Property::VECTOR4) ? sizeof(Vector4) : sizeof(Vector3);
712     DALI_ASSERT_ALWAYS(((mTangents.mBlob.mLength % propertySize == 0) ||
713                         mTangents.mBlob.mStride >= propertySize) &&
714                        "Tangents buffer length not a multiple of element size");
715     const auto           bufferSize = mTangents.mBlob.GetBufferSize();
716     std::vector<uint8_t> buffer(bufferSize);
717     if(!ReadAccessor(mTangents, binFile, buffer.data()))
718     {
719       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << meshPath << "'.";
720     }
721     mTangents.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
722
723     raw.mAttribs.push_back({"aTangent", mTangentType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
724   }
725   else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
726   {
727     DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
728     hasUvs ? GenerateTangentsWithUvs(raw) : GenerateTangents(raw);
729   }
730
731   if(mColors.IsDefined())
732   {
733     uint32_t propertySize = mColors.mBlob.mElementSizeHint;
734     Property::Type propertyType = (propertySize == sizeof(Vector4)) ? Property::VECTOR4 : ((propertySize == sizeof(Vector3)) ? Property::VECTOR3 : Property::NONE);
735     if(propertyType != Property::NONE)
736     {
737       DALI_ASSERT_ALWAYS(((mColors.mBlob.mLength % propertySize == 0) ||
738                           mColors.mBlob.mStride >= propertySize) &&
739                          "Colors buffer length not a multiple of element size");
740       const auto           bufferSize = mColors.mBlob.GetBufferSize();
741       std::vector<uint8_t> buffer(bufferSize);
742       if(!ReadAccessor(mColors, binFile, buffer.data()))
743       {
744         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read colors from '" << meshPath << "'.";
745       }
746       mColors.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
747
748       raw.mAttribs.push_back({"aVertexColor", propertyType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
749     }
750   }
751
752   if(IsSkinned())
753   {
754     if(MaskMatch(mFlags, U16_JOINT_IDS))
755     {
756       DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Uint16Vector4) == 0) ||
757                           mJoints0.mBlob.mStride >= sizeof(Uint16Vector4)) &&
758                          "Joints buffer length not a multiple of element size");
759       const auto           inBufferSize = mJoints0.mBlob.GetBufferSize();
760       std::vector<uint8_t> buffer(inBufferSize * 2);
761       auto                 u16s = buffer.data() + inBufferSize;
762       if(!ReadAccessor(mJoints0, binFile, u16s))
763       {
764         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
765       }
766
767       auto floats = reinterpret_cast<float*>(buffer.data());
768       auto end    = u16s + inBufferSize;
769       while(u16s != end)
770       {
771         auto value = *reinterpret_cast<uint16_t*>(u16s);
772         *floats    = static_cast<float>(value);
773
774         u16s += sizeof(uint16_t);
775         ++floats;
776       }
777       raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(buffer.size() / sizeof(Vector4)), std::move(buffer)});
778     }
779     else
780     {
781       DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Vector4) == 0) ||
782                           mJoints0.mBlob.mStride >= sizeof(Vector4)) &&
783                          "Joints buffer length not a multiple of element size");
784       const auto           bufferSize = mJoints0.mBlob.GetBufferSize();
785       std::vector<uint8_t> buffer(bufferSize);
786       if(!ReadAccessor(mJoints0, binFile, buffer.data()))
787       {
788         ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
789       }
790
791       raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
792     }
793
794     DALI_ASSERT_ALWAYS(((mWeights0.mBlob.mLength % sizeof(Vector4) == 0) ||
795                         mWeights0.mBlob.mStride >= sizeof(Vector4)) &&
796                        "Weights buffer length not a multiple of element size");
797     const auto           bufferSize = mWeights0.mBlob.GetBufferSize();
798     std::vector<uint8_t> buffer(bufferSize);
799     if(!ReadAccessor(mWeights0, binFile, buffer.data()))
800     {
801       ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << meshPath << "'.";
802     }
803
804     raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
805   }
806
807   // Calculate the Blob for the blend shapes.
808   Blob blendShapesBlob;
809   blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
810   blendShapesBlob.mLength = 0u;
811
812   for(const auto& blendShape : mBlendShapes)
813   {
814     for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
815     {
816       if(i->IsDefined())
817       {
818         blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
819         blendShapesBlob.mLength += i->mBlob.mLength;
820       }
821     }
822   }
823
824   if(HasBlendShapes())
825   {
826     const uint32_t numberOfVertices = mPositions.mBlob.mLength / sizeof(Vector3);
827
828     // Calculate the size of one buffer inside the texture.
829     raw.mBlendShapeBufferOffset = numberOfVertices;
830
831     bool     calculateGltf2BlendShapes = false;
832     uint32_t textureWidth              = 0u;
833     uint32_t textureHeight             = 0u;
834
835     if(!mBlendShapeHeader.IsDefined())
836     {
837       CalculateTextureSize(blendShapesBlob.mLength / sizeof(Vector3), textureWidth, textureHeight);
838       calculateGltf2BlendShapes = true;
839     }
840     else
841     {
842       uint16_t header[2u];
843       ReadBlob(mBlendShapeHeader, binFile, reinterpret_cast<uint8_t*>(header));
844       textureWidth  = header[0u];
845       textureHeight = header[1u];
846     }
847
848     const uint32_t numberOfBlendShapes = mBlendShapes.size();
849     raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
850
851     Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
852     uint8_t*           geometryBuffer      = geometryPixelBuffer.GetBuffer();
853
854     if(calculateGltf2BlendShapes)
855     {
856       CalculateGltf2BlendShapes(geometryBuffer, binFile, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u]);
857     }
858     else
859     {
860       Blob unnormalizeFactorBlob;
861       unnormalizeFactorBlob.mLength = sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes);
862
863       if(blendShapesBlob.IsDefined())
864       {
865         if(ReadBlob(blendShapesBlob, binFile, geometryBuffer))
866         {
867           unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
868         }
869       }
870
871       // Read the unnormalize factors.
872       if(unnormalizeFactorBlob.IsDefined())
873       {
874         ReadBlob(unnormalizeFactorBlob, binFile, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
875       }
876     }
877     raw.mBlendShapeData = Devel::PixelBuffer::Convert(geometryPixelBuffer);
878   }
879
880   return raw;
881 }
882
883 MeshGeometry MeshDefinition::Load(RawData&& raw) const
884 {
885   MeshGeometry meshGeometry;
886   meshGeometry.geometry = Geometry::New();
887   meshGeometry.geometry.SetType(mPrimitiveType);
888
889   if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
890   {
891     auto options          = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
892     meshGeometry.geometry = MakeTexturedQuadGeometry(options);
893   }
894   else
895   {
896     if(!raw.mIndices.empty())
897     {
898       meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
899     }
900
901     for(auto& a : raw.mAttribs)
902     {
903       a.AttachBuffer(meshGeometry.geometry);
904     }
905
906     if(HasBlendShapes())
907     {
908       meshGeometry.blendShapeBufferOffset      = raw.mBlendShapeBufferOffset;
909       meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
910
911       meshGeometry.blendShapeGeometry = Texture::New(TextureType::TEXTURE_2D,
912                                                      raw.mBlendShapeData.GetPixelFormat(),
913                                                      raw.mBlendShapeData.GetWidth(),
914                                                      raw.mBlendShapeData.GetHeight());
915       meshGeometry.blendShapeGeometry.Upload(raw.mBlendShapeData);
916     }
917   }
918
919   return meshGeometry;
920 }
921
922 } // namespace SceneLoader
923 } // namespace Dali