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-scene3d/public-api/loader/mesh-definition.h"
24 #include "dali/devel-api/adaptor-framework/pixel-buffer.h"
34 using Uint16Vector4 = uint16_t[4];
39 IndexProvider(const uint16_t* indices)
40 : mData(reinterpret_cast<uintptr_t>(indices)),
41 mFunc(indices ? IncrementPointer : Increment)
51 static uint16_t Increment(uintptr_t& data)
53 return static_cast<uint16_t>(data++);
56 static uint16_t IncrementPointer(uintptr_t& data)
58 auto iPtr = reinterpret_cast<const uint16_t*>(data);
60 data = reinterpret_cast<uintptr_t>(++iPtr);
65 uint16_t (*mFunc)(uintptr_t&);
68 const std::string QUAD("quad");
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)
74 if(!source.seekg(descriptor.mOffset, std::istream::beg))
79 if(descriptor.IsConsecutive())
81 return !!source.read(reinterpret_cast<char*>(target), descriptor.mLength);
85 if(descriptor.mStride > descriptor.mElementSizeHint)
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))
94 readSize += descriptor.mStride;
95 target += descriptor.mElementSizeHint;
97 return readSize == totalSize;
104 void ReadValues(const std::vector<uint8_t>& valuesBuffer, const std::vector<uint8_t>& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint)
106 const T* const indicesPtr = reinterpret_cast<const T* const>(indicesBuffer.data());
107 for(uint32_t index = 0u; index < count; ++index)
109 uint32_t valuesIndex = indicesPtr[index] * elementSizeHint;
110 memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint);
114 bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source, uint8_t* target)
116 bool success = false;
118 if(accessor.mBlob.IsDefined())
120 success = ReadBlob(accessor.mBlob, source, target);
129 const MeshDefinition::Blob& indices = accessor.mSparse->mIndices;
130 const MeshDefinition::Blob& values = accessor.mSparse->mValues;
132 if(!indices.IsDefined() || !values.IsDefined())
137 const auto indicesBufferSize = indices.GetBufferSize();
138 std::vector<uint8_t> indicesBuffer(indicesBufferSize);
139 success = ReadBlob(indices, source, indicesBuffer.data());
145 const auto valuesBufferSize = values.GetBufferSize();
146 std::vector<uint8_t> valuesBuffer(valuesBufferSize);
147 success = ReadBlob(values, source, valuesBuffer.data());
153 switch(indices.mElementSizeHint)
157 ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
162 ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
167 ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
171 DALI_ASSERT_DEBUG(!"Unsupported type for an index");
178 void GenerateNormals(MeshDefinition::RawData& raw)
180 auto& attribs = raw.mAttribs;
181 DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
182 IndexProvider getIndex(raw.mIndices.data());
184 const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(raw.mIndices.size());
186 auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
188 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
189 auto normals = reinterpret_cast<Vector3*>(buffer.data());
191 for(uint32_t i = 0; i < numIndices; i += 3)
193 uint16_t indices[]{getIndex(), getIndex(), getIndex()};
194 Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
196 Vector3 a = pos[1] - pos[0];
197 Vector3 b = pos[2] - pos[0];
199 Vector3 normal(a.Cross(b));
200 normals[indices[0]] += normal;
201 normals[indices[1]] += normal;
202 normals[indices[2]] += normal;
205 auto iEnd = normals + attribs[0].mNumElements;
206 while(normals != iEnd)
208 normals->Normalize();
212 attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
215 void GenerateTangentsWithUvs(MeshDefinition::RawData& raw)
217 auto& attribs = raw.mAttribs;
218 DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs
219 IndexProvider getIndex(raw.mIndices.data());
221 const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(raw.mIndices.size());
223 auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
224 auto* uvs = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
226 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
227 auto tangents = reinterpret_cast<Vector3*>(buffer.data());
229 for(uint32_t i = 0; i < numIndices; i += 3)
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]]};
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;
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;
243 float s0 = uv[1].x - uv[0].x;
244 float t0 = uv[1].y - uv[0].y;
246 float s1 = uv[2].x - uv[0].x;
247 float t1 = uv[2].y - uv[0].y;
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;
256 auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
257 auto iEnd = normals + attribs[1].mNumElements;
258 while(normals != iEnd)
260 *tangents -= *normals * normals->Dot(*tangents);
261 tangents->Normalize();
266 attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
269 void GenerateTangents(MeshDefinition::RawData& raw)
271 auto& attribs = raw.mAttribs;
272 DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals
274 auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
276 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
277 auto tangents = reinterpret_cast<Vector3*>(buffer.data());
279 auto iEnd = normals + attribs[1].mNumElements;
280 while(normals != iEnd)
282 Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)};
284 *tangents = t[t[1].LengthSquared() > t[0].LengthSquared()];
285 *tangents -= *normals * normals->Dot(*tangents);
286 tangents->Normalize();
291 attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
294 void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight)
296 DALI_ASSERT_DEBUG(0u != totalTextureSize && "totalTextureSize is zero.")
298 // Calculate the dimensions of the texture.
299 // The total size of the texture is the length of the blend shapes blob.
304 if(0u == totalTextureSize)
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;
314 textureWidth = 1u << powWidth;
315 textureHeight = 1u << powHeight;
318 void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, std::ifstream& binFile, const std::vector<MeshDefinition::BlendShape>& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor)
320 uint32_t geometryBufferIndex = 0u;
321 float maxDistance = 0.f;
322 Vector3* geometryBufferV3 = reinterpret_cast<Vector3*>(geometryBuffer);
323 for(const auto& blendShape : blendShapes)
325 if(blendShape.deltas.IsDefined())
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");
331 const auto bufferSize = blendShape.deltas.mBlob.GetBufferSize();
332 std::vector<uint8_t> buffer(bufferSize);
333 if(ReadAccessor(blendShape.deltas, binFile, buffer.data()))
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());
340 for(uint32_t index = 0u; index < numberOfVertices; ++index)
342 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
343 delta = deltasBuffer[index];
345 maxDistance = std::max(maxDistance, delta.LengthSquared());
350 if(blendShape.normals.IsDefined())
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");
356 const auto bufferSize = blendShape.normals.mBlob.GetBufferSize();
357 std::vector<uint8_t> buffer(bufferSize);
358 if(ReadAccessor(blendShape.normals, binFile, buffer.data()))
360 blendShape.normals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
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());
365 for(uint32_t index = 0u; index < numberOfVertices; ++index)
367 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
368 delta = deltasBuffer[index];
381 if(blendShape.tangents.IsDefined())
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");
387 const auto bufferSize = blendShape.tangents.mBlob.GetBufferSize();
388 std::vector<uint8_t> buffer(bufferSize);
389 if(ReadAccessor(blendShape.tangents, binFile, buffer.data()))
391 blendShape.tangents.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
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());
396 for(uint32_t index = 0u; index < numberOfVertices; ++index)
398 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
399 delta = deltasBuffer[index];
413 geometryBufferIndex = 0u;
414 for(const auto& blendShape : blendShapes)
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())
421 const float normalizeFactor = (fabsf(maxDistance) < Math::MACHINE_EPSILON_1000) ? 1.f : (0.5f / sqrtf(maxDistance));
423 for(uint32_t index = 0u; index < numberOfVertices; ++index)
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);
431 // Calculate and store the unnormalize factor.
432 blendShapeUnnormalizeFactor = 1.f / normalizeFactor;
435 if(blendShape.normals.IsDefined())
437 geometryBufferIndex += numberOfVertices;
440 if(blendShape.tangents.IsDefined())
442 geometryBufferIndex += numberOfVertices;
449 MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count)
456 MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob& blob,
457 const MeshDefinition::SparseBlob& sparse)
459 mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr}
463 void MeshDefinition::Blob::ComputeMinMax(std::vector<float>& min, std::vector<float>& max, uint32_t numComponents, uint32_t count, const float* values)
465 min.assign(numComponents, MAXFLOAT);
466 max.assign(numComponents, -MAXFLOAT);
467 for(uint32_t i = 0; i < count; ++i)
469 for(uint32_t j = 0; j < numComponents; ++j)
471 min[j] = std::min(min[j], *values);
472 max[j] = std::max(max[j], *values);
478 void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values)
480 DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0);
481 const auto numComponents = std::max(min.size(), max.size());
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);
487 : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) {
488 value = std::max(min[i], value);
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]);
499 auto end = values + count * numComponents;
502 auto nextElement = values + numComponents;
504 while(values != nextElement)
506 clampFn(min.data(), max.data(), i, *values);
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)
517 mElementSizeHint(elementSizeHint),
523 uint32_t MeshDefinition::Blob::GetBufferSize() const
528 void MeshDefinition::Blob::ComputeMinMax(uint32_t numComponents, uint32_t count, float* values)
530 ComputeMinMax(mMin, mMax, numComponents, count, values);
533 void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const
535 ApplyMinMax(mMin, mMax, count, values);
538 void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
540 Property::Map attribMap;
541 attribMap[mName] = mType;
542 VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
543 attribBuffer.SetData(mData.data(), mNumElements);
545 g.AddVertexBuffer(attribBuffer);
548 bool MeshDefinition::IsQuad() const
550 return CaseInsensitiveStringCompare(QUAD, mUri);
553 bool MeshDefinition::IsSkinned() const
555 return mJoints0.IsDefined() && mWeights0.IsDefined();
558 bool MeshDefinition::HasBlendShapes() const
560 return !mBlendShapes.empty();
563 void MeshDefinition::RequestNormals()
565 mNormals.mBlob.mLength = mPositions.mBlob.GetBufferSize();
568 void MeshDefinition::RequestTangents()
570 mTangents.mBlob.mLength = mNormals.mBlob.GetBufferSize();
573 MeshDefinition::RawData
574 MeshDefinition::LoadRaw(const std::string& modelsPath)
582 const std::string meshPath = modelsPath + mUri;
583 std::ifstream binFile(meshPath, std::ios::binary);
586 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read geometry data from '" << meshPath << "'";
589 if(mIndices.IsDefined())
591 if(MaskMatch(mFlags, U32_INDICES))
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())))
600 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
603 auto u16s = raw.mIndices.data();
604 auto u32s = reinterpret_cast<uint32_t*>(raw.mIndices.data());
605 auto end = u32s + indexCount;
608 *u16s = static_cast<uint16_t>(*u32s);
613 raw.mIndices.resize(indexCount);
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())))
623 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
628 std::vector<Vector3> positions;
629 if(mPositions.IsDefined())
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()))
638 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << meshPath << "'.";
641 uint32_t numVector3 = static_cast<uint32_t>(bufferSize / sizeof(Vector3));
642 if(mPositions.mBlob.mMin.size() != 3u || mPositions.mBlob.mMax.size() != 3u)
644 mPositions.mBlob.ComputeMinMax(3u, numVector3, reinterpret_cast<float*>(buffer.data()));
648 mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
653 positions.resize(numVector3);
654 std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
657 raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
660 const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
661 auto hasNormals = mNormals.IsDefined();
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()))
671 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << meshPath << "'.";
674 mNormals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
676 raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
678 else if(mNormals.mBlob.mLength != 0 && isTriangles)
680 DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
681 GenerateNormals(raw);
685 const auto hasUvs = mTexCoords.IsDefined();
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()))
695 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << meshPath << "'.";
698 const auto uvCount = bufferSize / sizeof(Vector2);
699 if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
701 auto uv = reinterpret_cast<Vector2*>(buffer.data());
702 auto uvEnd = uv + uvCount;
705 uv->y = 1.0f - uv->y;
710 mTexCoords.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector2)), reinterpret_cast<float*>(buffer.data()));
712 raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
715 if(mTangents.IsDefined())
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()))
725 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << meshPath << "'.";
727 mTangents.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
729 raw.mAttribs.push_back({"aTangent", mTangentType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
731 else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
733 DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
734 hasUvs ? GenerateTangentsWithUvs(raw) : GenerateTangents(raw);
737 if(mColors.IsDefined())
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)
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()))
750 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read colors from '" << meshPath << "'.";
752 mColors.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
754 raw.mAttribs.push_back({"aVertexColor", propertyType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
760 if(MaskMatch(mFlags, U16_JOINT_IDS))
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))
770 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
773 auto floats = reinterpret_cast<float*>(buffer.data());
774 auto end = u16s + inBufferSize;
777 auto value = *reinterpret_cast<uint16_t*>(u16s);
778 *floats = static_cast<float>(value);
780 u16s += sizeof(uint16_t);
783 raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(buffer.size() / sizeof(Vector4)), std::move(buffer)});
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()))
794 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
797 raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
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()))
807 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << meshPath << "'.";
810 raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
813 // Calculate the Blob for the blend shapes.
814 Blob blendShapesBlob;
815 blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
816 blendShapesBlob.mLength = 0u;
818 for(const auto& blendShape : mBlendShapes)
820 for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
824 blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
825 blendShapesBlob.mLength += i->mBlob.mLength;
832 const uint32_t numberOfVertices = static_cast<uint32_t>(mPositions.mBlob.mLength / sizeof(Vector3));
834 // Calculate the size of one buffer inside the texture.
835 raw.mBlendShapeBufferOffset = numberOfVertices;
837 bool calculateGltf2BlendShapes = false;
838 uint32_t textureWidth = 0u;
839 uint32_t textureHeight = 0u;
841 if(!mBlendShapeHeader.IsDefined())
843 CalculateTextureSize(static_cast<uint32_t>(blendShapesBlob.mLength / sizeof(Vector3)), textureWidth, textureHeight);
844 calculateGltf2BlendShapes = true;
849 ReadBlob(mBlendShapeHeader, binFile, reinterpret_cast<uint8_t*>(header));
850 textureWidth = header[0u];
851 textureHeight = header[1u];
854 const uint32_t numberOfBlendShapes = mBlendShapes.size();
855 raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
857 Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
858 uint8_t* geometryBuffer = geometryPixelBuffer.GetBuffer();
860 if(calculateGltf2BlendShapes)
862 CalculateGltf2BlendShapes(geometryBuffer, binFile, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u]);
866 Blob unnormalizeFactorBlob;
867 unnormalizeFactorBlob.mLength = static_cast<uint32_t>(sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes));
869 if(blendShapesBlob.IsDefined())
871 if(ReadBlob(blendShapesBlob, binFile, geometryBuffer))
873 unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
877 // Read the unnormalize factors.
878 if(unnormalizeFactorBlob.IsDefined())
880 ReadBlob(unnormalizeFactorBlob, binFile, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
883 raw.mBlendShapeData = Devel::PixelBuffer::Convert(geometryPixelBuffer);
889 MeshGeometry MeshDefinition::Load(RawData&& raw) const
891 MeshGeometry meshGeometry;
892 meshGeometry.geometry = Geometry::New();
893 meshGeometry.geometry.SetType(mPrimitiveType);
895 if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
897 auto options = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
898 meshGeometry.geometry = MakeTexturedQuadGeometry(options);
902 if(!raw.mIndices.empty())
904 meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
907 for(auto& a : raw.mAttribs)
909 a.AttachBuffer(meshGeometry.geometry);
914 meshGeometry.blendShapeBufferOffset = raw.mBlendShapeBufferOffset;
915 meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
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);
928 } // namespace Loader
929 } // namespace Scene3D