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