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