2 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "dali-scene-loader/public-api/mesh-definition.h"
24 #include "dali/devel-api/adaptor-framework/pixel-buffer.h"
32 using Uint16Vector4 = uint16_t[4];
37 IndexProvider(const uint16_t* indices)
38 : mData(reinterpret_cast<uintptr_t>(indices)),
39 mFunc(indices ? IncrementPointer : Increment)
49 static uint16_t Increment(uintptr_t& data)
51 return static_cast<uint16_t>(data++);
54 static uint16_t IncrementPointer(uintptr_t& data)
56 auto iPtr = reinterpret_cast<const uint16_t*>(data);
58 data = reinterpret_cast<uintptr_t>(++iPtr);
63 uint16_t (*mFunc)(uintptr_t&);
66 const std::string QUAD("quad");
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)
72 if(!source.seekg(descriptor.mOffset, std::istream::beg))
77 if(descriptor.IsConsecutive())
79 return !!source.read(reinterpret_cast<char*>(target), descriptor.mLength);
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))
90 readSize += descriptor.mStride;
91 target += descriptor.mElementSizeHint;
93 return readSize == descriptor.mLength;
98 void ReadValues(const std::vector<uint8_t>& valuesBuffer, const std::vector<uint8_t>& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint)
100 const T* const indicesPtr = reinterpret_cast<const T* const>(indicesBuffer.data());
101 for(uint32_t index = 0u; index < count; ++index)
103 uint32_t valuesIndex = indicesPtr[index] * elementSizeHint;
104 memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint);
108 bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source, uint8_t* target)
110 bool success = false;
112 if(accessor.mBlob.IsDefined())
114 success = ReadBlob(accessor.mBlob, source, target);
123 const MeshDefinition::Blob& indices = accessor.mSparse->mIndices;
124 const MeshDefinition::Blob& values = accessor.mSparse->mValues;
126 if(!indices.IsDefined() || !values.IsDefined())
131 const auto indicesBufferSize = indices.GetBufferSize();
132 std::vector<uint8_t> indicesBuffer(indicesBufferSize);
133 success = ReadBlob(indices, source, indicesBuffer.data());
139 const auto valuesBufferSize = values.GetBufferSize();
140 std::vector<uint8_t> valuesBuffer(valuesBufferSize);
141 success = ReadBlob(values, source, valuesBuffer.data());
147 switch(indices.mElementSizeHint)
151 ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
156 ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
161 ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
165 DALI_ASSERT_DEBUG(!"Unsupported type for an index");
172 void GenerateNormals(MeshDefinition::RawData& raw)
174 auto& attribs = raw.mAttribs;
175 DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
176 IndexProvider getIndex(raw.mIndices.data());
178 const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size();
180 auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
182 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
183 auto normals = reinterpret_cast<Vector3*>(buffer.data());
185 for(uint32_t i = 0; i < numIndices; i += 3)
187 uint16_t indices[]{getIndex(), getIndex(), getIndex()};
188 Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
190 Vector3 a = pos[1] - pos[0];
191 Vector3 b = pos[2] - pos[0];
193 Vector3 normal(a.Cross(b));
194 normals[indices[0]] += normal;
195 normals[indices[1]] += normal;
196 normals[indices[2]] += normal;
199 auto iEnd = normals + attribs[0].mNumElements;
200 while(normals != iEnd)
202 normals->Normalize();
206 attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
209 void GenerateTangentsWithUvs(MeshDefinition::RawData& raw)
211 auto& attribs = raw.mAttribs;
212 DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs
213 IndexProvider getIndex(raw.mIndices.data());
215 const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size();
217 auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
218 auto* uvs = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
220 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
221 auto tangents = reinterpret_cast<Vector3*>(buffer.data());
223 for(uint32_t i = 0; i < numIndices; i += 3)
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]]};
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;
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;
237 float s0 = uv[1].x - uv[0].x;
238 float t0 = uv[1].y - uv[0].y;
240 float s1 = uv[2].x - uv[0].x;
241 float t1 = uv[2].y - uv[0].y;
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;
250 auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
251 auto iEnd = normals + attribs[1].mNumElements;
252 while(normals != iEnd)
254 *tangents -= *normals * normals->Dot(*tangents);
255 tangents->Normalize();
260 attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
263 void GenerateTangents(MeshDefinition::RawData& raw)
265 auto& attribs = raw.mAttribs;
266 DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals
268 auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
270 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
271 auto tangents = reinterpret_cast<Vector3*>(buffer.data());
273 auto iEnd = normals + attribs[1].mNumElements;
274 while(normals != iEnd)
276 Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)};
278 *tangents = t[t[1].LengthSquared() > t[0].LengthSquared()];
279 *tangents -= *normals * normals->Dot(*tangents);
280 tangents->Normalize();
285 attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
288 void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight)
290 DALI_ASSERT_DEBUG(0u != totalTextureSize && "totalTextureSize is zero.")
292 // Calculate the dimensions of the texture.
293 // The total size of the texture is the length of the blend shapes blob.
298 if(0u == totalTextureSize)
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;
308 textureWidth = 1u << powWidth;
309 textureHeight = 1u << powHeight;
312 void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, std::ifstream& binFile, const std::vector<MeshDefinition::BlendShape>& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor)
314 uint32_t geometryBufferIndex = 0u;
315 float maxDistance = 0.f;
316 Vector3* geometryBufferV3 = reinterpret_cast<Vector3*>(geometryBuffer);
317 for(const auto& blendShape : blendShapes)
319 if(blendShape.deltas.IsDefined())
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");
325 const auto bufferSize = blendShape.deltas.mBlob.GetBufferSize();
326 std::vector<uint8_t> buffer(bufferSize);
327 if(ReadAccessor(blendShape.deltas, binFile, buffer.data()))
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());
334 for(uint32_t index = 0u; index < numberOfVertices; ++index)
336 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
337 delta = deltasBuffer[index];
339 maxDistance = std::max(maxDistance, delta.LengthSquared());
344 if(blendShape.normals.IsDefined())
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");
350 const auto bufferSize = blendShape.normals.mBlob.GetBufferSize();
351 std::vector<uint8_t> buffer(bufferSize);
352 if(ReadAccessor(blendShape.normals, binFile, buffer.data()))
354 blendShape.normals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
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());
359 for(uint32_t index = 0u; index < numberOfVertices; ++index)
361 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
362 delta = deltasBuffer[index];
375 if(blendShape.tangents.IsDefined())
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");
381 const auto bufferSize = blendShape.tangents.mBlob.GetBufferSize();
382 std::vector<uint8_t> buffer(bufferSize);
383 if(ReadAccessor(blendShape.tangents, binFile, buffer.data()))
385 blendShape.tangents.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
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());
390 for(uint32_t index = 0u; index < numberOfVertices; ++index)
392 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
393 delta = deltasBuffer[index];
407 geometryBufferIndex = 0u;
408 for(const auto& blendShape : blendShapes)
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())
415 const float normalizeFactor = (fabsf(maxDistance) < Math::MACHINE_EPSILON_1000) ? 1.f : (0.5f / sqrtf(maxDistance));
417 for(uint32_t index = 0u; index < numberOfVertices; ++index)
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);
425 // Calculate and store the unnormalize factor.
426 blendShapeUnnormalizeFactor = 1.f / normalizeFactor;
429 if(blendShape.normals.IsDefined())
431 geometryBufferIndex += numberOfVertices;
434 if(blendShape.tangents.IsDefined())
436 geometryBufferIndex += numberOfVertices;
443 MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count)
450 MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob& blob,
451 const MeshDefinition::SparseBlob& sparse)
453 mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr}
457 void MeshDefinition::Blob::ComputeMinMax(std::vector<float>& min, std::vector<float>& max, uint32_t numComponents, uint32_t count, const float* values)
459 min.assign(numComponents, MAXFLOAT);
460 max.assign(numComponents, -MAXFLOAT);
461 for(uint32_t i = 0; i < count; ++i)
463 for(uint32_t j = 0; j < numComponents; ++j)
465 min[j] = std::min(min[j], *values);
466 max[j] = std::max(max[j], *values);
472 void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values)
474 DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0);
475 const auto numComponents = std::max(min.size(), max.size());
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);
481 : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) {
482 value = std::max(min[i], value);
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]);
493 auto end = values + count * numComponents;
496 auto nextElement = values + numComponents;
498 while(values != nextElement)
500 clampFn(min.data(), max.data(), i, *values);
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)
511 mElementSizeHint(elementSizeHint),
517 uint32_t MeshDefinition::Blob::GetBufferSize() const
519 return IsConsecutive() ? mLength : (mLength * mElementSizeHint / mStride);
522 void MeshDefinition::Blob::ComputeMinMax(uint32_t numComponents, uint32_t count, float* values)
524 ComputeMinMax(mMin, mMax, numComponents, count, values);
527 void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const
529 ApplyMinMax(mMin, mMax, count, values);
532 void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
534 Property::Map attribMap;
535 attribMap[mName] = mType;
536 VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
537 attribBuffer.SetData(mData.data(), mNumElements);
539 g.AddVertexBuffer(attribBuffer);
542 bool MeshDefinition::IsQuad() const
544 return CaseInsensitiveStringCompare(QUAD, mUri);
547 bool MeshDefinition::IsSkinned() const
549 return mJoints0.IsDefined() && mWeights0.IsDefined();
552 bool MeshDefinition::HasBlendShapes() const
554 return !mBlendShapes.empty();
557 void MeshDefinition::RequestNormals()
559 mNormals.mBlob.mLength = mPositions.mBlob.GetBufferSize();
562 void MeshDefinition::RequestTangents()
564 mTangents.mBlob.mLength = mNormals.mBlob.GetBufferSize();
567 MeshDefinition::RawData
568 MeshDefinition::LoadRaw(const std::string& modelsPath)
576 const std::string meshPath = modelsPath + mUri;
577 std::ifstream binFile(meshPath, std::ios::binary);
580 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read geometry data from '" << meshPath << "'";
583 if(mIndices.IsDefined())
585 if(MaskMatch(mFlags, U32_INDICES))
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())))
594 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
597 auto u16s = raw.mIndices.data();
598 auto u32s = reinterpret_cast<uint32_t*>(raw.mIndices.data());
599 auto end = u32s + indexCount;
602 *u16s = static_cast<uint16_t>(*u32s);
607 raw.mIndices.resize(indexCount);
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())))
617 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
622 std::vector<Vector3> positions;
623 if(mPositions.IsDefined())
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()))
632 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << meshPath << "'.";
635 uint32_t numVector3 = bufferSize / sizeof(Vector3);
636 if(mPositions.mBlob.mMin.size() != 3u || mPositions.mBlob.mMax.size() != 3u)
638 mPositions.mBlob.ComputeMinMax(3u, numVector3, reinterpret_cast<float*>(buffer.data()));
642 mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
647 positions.resize(numVector3);
648 std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
651 raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
654 const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
655 auto hasNormals = mNormals.IsDefined();
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()))
665 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << meshPath << "'.";
668 mNormals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
670 raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
672 else if(mNormals.mBlob.mLength != 0 && isTriangles)
674 DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
675 GenerateNormals(raw);
679 const auto hasUvs = mTexCoords.IsDefined();
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()))
689 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << meshPath << "'.";
692 const auto uvCount = bufferSize / sizeof(Vector2);
693 if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
695 auto uv = reinterpret_cast<Vector2*>(buffer.data());
696 auto uvEnd = uv + uvCount;
699 uv->y = 1.0f - uv->y;
704 mTexCoords.mBlob.ApplyMinMax(bufferSize / sizeof(Vector2), reinterpret_cast<float*>(buffer.data()));
706 raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
709 if(mTangents.IsDefined())
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()))
719 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << meshPath << "'.";
721 mTangents.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
723 raw.mAttribs.push_back({"aTangent", mTangentType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
725 else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
727 DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
728 hasUvs ? GenerateTangentsWithUvs(raw) : GenerateTangents(raw);
731 if(mColors.IsDefined())
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)
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()))
744 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read colors from '" << meshPath << "'.";
746 mColors.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
748 raw.mAttribs.push_back({"aVertexColor", propertyType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
754 if(MaskMatch(mFlags, U16_JOINT_IDS))
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))
764 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
767 auto floats = reinterpret_cast<float*>(buffer.data());
768 auto end = u16s + inBufferSize;
771 auto value = *reinterpret_cast<uint16_t*>(u16s);
772 *floats = static_cast<float>(value);
774 u16s += sizeof(uint16_t);
777 raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(buffer.size() / sizeof(Vector4)), std::move(buffer)});
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()))
788 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
791 raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
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()))
801 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << meshPath << "'.";
804 raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
807 // Calculate the Blob for the blend shapes.
808 Blob blendShapesBlob;
809 blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
810 blendShapesBlob.mLength = 0u;
812 for(const auto& blendShape : mBlendShapes)
814 for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
818 blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
819 blendShapesBlob.mLength += i->mBlob.mLength;
826 const uint32_t numberOfVertices = mPositions.mBlob.mLength / sizeof(Vector3);
828 // Calculate the size of one buffer inside the texture.
829 raw.mBlendShapeBufferOffset = numberOfVertices;
831 bool calculateGltf2BlendShapes = false;
832 uint32_t textureWidth = 0u;
833 uint32_t textureHeight = 0u;
835 if(!mBlendShapeHeader.IsDefined())
837 CalculateTextureSize(blendShapesBlob.mLength / sizeof(Vector3), textureWidth, textureHeight);
838 calculateGltf2BlendShapes = true;
843 ReadBlob(mBlendShapeHeader, binFile, reinterpret_cast<uint8_t*>(header));
844 textureWidth = header[0u];
845 textureHeight = header[1u];
848 const uint32_t numberOfBlendShapes = mBlendShapes.size();
849 raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
851 Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
852 uint8_t* geometryBuffer = geometryPixelBuffer.GetBuffer();
854 if(calculateGltf2BlendShapes)
856 CalculateGltf2BlendShapes(geometryBuffer, binFile, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u]);
860 Blob unnormalizeFactorBlob;
861 unnormalizeFactorBlob.mLength = sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes);
863 if(blendShapesBlob.IsDefined())
865 if(ReadBlob(blendShapesBlob, binFile, geometryBuffer))
867 unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
871 // Read the unnormalize factors.
872 if(unnormalizeFactorBlob.IsDefined())
874 ReadBlob(unnormalizeFactorBlob, binFile, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
877 raw.mBlendShapeData = Devel::PixelBuffer::Convert(geometryPixelBuffer);
883 MeshGeometry MeshDefinition::Load(RawData&& raw) const
885 MeshGeometry meshGeometry;
886 meshGeometry.geometry = Geometry::New();
887 meshGeometry.geometry.SetType(mPrimitiveType);
889 if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
891 auto options = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
892 meshGeometry.geometry = MakeTexturedQuadGeometry(options);
896 if(!raw.mIndices.empty())
898 meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
901 for(auto& a : raw.mAttribs)
903 a.AttachBuffer(meshGeometry.geometry);
908 meshGeometry.blendShapeBufferOffset = raw.mBlendShapeBufferOffset;
909 meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
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);
922 } // namespace SceneLoader