2 * Copyright (c) 2023 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"
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>
28 #include <type_traits>
41 IndexProvider(const uint16_t* indices)
42 : mData(reinterpret_cast<uintptr_t>(indices)),
43 mFunc(indices ? IncrementPointer : Increment)
53 static uint16_t Increment(uintptr_t& data)
55 return static_cast<uint16_t>(data++);
58 static uint16_t IncrementPointer(uintptr_t& data)
60 auto iPtr = reinterpret_cast<const uint16_t*>(data);
62 data = reinterpret_cast<uintptr_t>(++iPtr);
67 uint16_t (*mFunc)(uintptr_t&);
70 const char* QUAD("quad");
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)
77 if(!source.seekg(descriptor.mOffset, std::istream::beg))
82 if(descriptor.IsConsecutive())
84 return !!source.read(reinterpret_cast<char*>(target), static_cast<std::streamsize>(static_cast<size_t>(descriptor.mLength)));
88 if(descriptor.mStride > descriptor.mElementSizeHint)
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))
97 readSize += descriptor.mStride;
98 target += descriptor.mElementSizeHint;
100 return readSize == totalSize;
107 void ReadValues(const std::vector<uint8_t>& valuesBuffer, const std::vector<uint8_t>& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint)
109 const T* const indicesPtr = reinterpret_cast<const T* const>(indicesBuffer.data());
110 for(uint32_t index = 0u; index < count; ++index)
112 uint32_t valuesIndex = indicesPtr[index] * elementSizeHint;
113 memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint);
117 bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source, uint8_t* target)
119 bool success = false;
121 if(accessor.mBlob.IsDefined())
123 success = ReadBlob(accessor.mBlob, source, target);
132 const MeshDefinition::Blob& indices = accessor.mSparse->mIndices;
133 const MeshDefinition::Blob& values = accessor.mSparse->mValues;
135 if(!indices.IsDefined() || !values.IsDefined())
140 const auto indicesBufferSize = indices.GetBufferSize();
141 std::vector<uint8_t> indicesBuffer(indicesBufferSize);
142 success = ReadBlob(indices, source, indicesBuffer.data());
148 const auto valuesBufferSize = values.GetBufferSize();
149 std::vector<uint8_t> valuesBuffer(valuesBufferSize);
150 success = ReadBlob(values, source, valuesBuffer.data());
156 switch(indices.mElementSizeHint)
160 ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
165 ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
170 ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
174 DALI_ASSERT_DEBUG(!"Unsupported type for an index");
182 void ReadJointAccessor(MeshDefinition::RawData& raw, const MeshDefinition::Accessor& accessor, std::istream& source, const std::string& meshPath)
184 constexpr auto sizeofBlobUnit = sizeof(T) * 4;
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;
192 std::vector<uint8_t> buffer(outBufferSize);
193 auto inBuffer = buffer.data() + outBufferSize - inBufferSize;
194 if(!ReadAccessor(accessor, source, inBuffer))
196 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
199 if constexpr(sizeofBlobUnit != sizeof(Vector4))
201 auto floats = reinterpret_cast<float*>(buffer.data());
202 const auto end = inBuffer + inBufferSize;
203 while(inBuffer != end)
205 const auto value = *reinterpret_cast<T*>(inBuffer);
206 *floats = static_cast<float>(value);
208 inBuffer += sizeof(T);
212 raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(outBufferSize / sizeof(Vector4)), std::move(buffer)});
215 void GenerateNormals(MeshDefinition::RawData& raw)
217 auto& attribs = raw.mAttribs;
218 DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
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());
225 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
226 auto normals = reinterpret_cast<Vector3*>(buffer.data());
228 for(uint32_t i = 0; i < numIndices; i += 3)
230 uint16_t indices[]{getIndex(), getIndex(), getIndex()};
231 Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
233 Vector3 a = pos[1] - pos[0];
234 Vector3 b = pos[2] - pos[0];
236 Vector3 normal(a.Cross(b));
237 normals[indices[0]] += normal;
238 normals[indices[1]] += normal;
239 normals[indices[2]] += normal;
242 auto iEnd = normals + attribs[0].mNumElements;
243 while(normals != iEnd)
245 normals->Normalize();
249 attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
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)
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)))
262 std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(T));
263 auto tangents = reinterpret_cast<T*>(buffer.data());
267 IndexProvider getIndex(raw.mIndices.data());
268 const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(raw.mIndices.size());
270 auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
271 auto* uvs = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
273 for(uint32_t i = 0; i < numIndices; i += 3)
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]]};
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;
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;
287 float s0 = uv[1].x - uv[0].x;
288 float t0 = uv[1].y - uv[0].y;
290 float s1 = uv[2].x - uv[0].x;
291 float t1 = uv[2].y - uv[0].y;
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);
302 auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
303 auto iEnd = normals + attribs[1].mNumElements;
304 while(normals != iEnd)
309 // Calculated by indexs
310 tangentVec3 = Vector3((*tangents).x, (*tangents).y, (*tangents).z);
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()];
319 tangentVec3 -= *normals * normals->Dot(tangentVec3);
320 tangentVec3.Normalize();
321 if constexpr(useVec3)
323 *tangents = tangentVec3;
327 *tangents = Vector4(tangentVec3.x, tangentVec3.y, tangentVec3.z, 1.0f);
333 attribs.push_back({"aTangent", useVec3 ? Property::VECTOR3 : Property::VECTOR4, attribs[0].mNumElements, std::move(buffer)});
338 void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight)
340 DALI_ASSERT_DEBUG(0u != totalTextureSize && "totalTextureSize is zero.")
342 // Calculate the dimensions of the texture.
343 // The total size of the texture is the length of the blend shapes blob.
348 if(0u == totalTextureSize)
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;
358 textureWidth = 1u << powWidth;
359 textureHeight = 1u << powHeight;
362 void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, const std::vector<MeshDefinition::BlendShape>& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor, BufferDefinition::Vector& buffers)
364 uint32_t geometryBufferIndex = 0u;
365 float maxDistance = 0.f;
366 Vector3* geometryBufferV3 = reinterpret_cast<Vector3*>(geometryBuffer);
367 for(const auto& blendShape : blendShapes)
369 if(blendShape.deltas.IsDefined())
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");
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()))
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());
384 for(uint32_t index = 0u; index < numberOfVertices; ++index)
386 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
387 delta = deltasBuffer[index];
389 maxDistance = std::max(maxDistance, delta.LengthSquared());
394 if(blendShape.normals.IsDefined())
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");
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()))
404 blendShape.normals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
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());
409 for(uint32_t index = 0u; index < numberOfVertices; ++index)
411 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
412 delta = deltasBuffer[index];
425 if(blendShape.tangents.IsDefined())
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");
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()))
435 blendShape.tangents.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
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());
440 for(uint32_t index = 0u; index < numberOfVertices; ++index)
442 Vector3& delta = geometryBufferV3[geometryBufferIndex++];
443 delta = deltasBuffer[index];
457 geometryBufferIndex = 0u;
458 for(const auto& blendShape : blendShapes)
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())
465 const float normalizeFactor = (fabsf(maxDistance) < Math::MACHINE_EPSILON_1000) ? 1.f : (0.5f / sqrtf(maxDistance));
467 for(uint32_t index = 0u; index < numberOfVertices; ++index)
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);
475 // Calculate and store the unnormalize factor.
476 blendShapeUnnormalizeFactor = 1.f / normalizeFactor;
479 if(blendShape.normals.IsDefined())
481 geometryBufferIndex += numberOfVertices;
484 if(blendShape.tangents.IsDefined())
486 geometryBufferIndex += numberOfVertices;
491 std::iostream& GetAvailableData(std::fstream& meshStream, const std::string& meshPath, BufferDefinition& buffer, std::string& availablePath)
493 auto& stream = (meshStream.is_open()) ? meshStream : buffer.GetBufferStream();
494 availablePath = (meshStream.is_open()) ? meshPath : buffer.GetUri();
500 MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count)
507 MeshDefinition::SparseBlob::SparseBlob(Blob&& indices, Blob&& values, uint32_t count)
508 : mIndices(std::move(indices)),
509 mValues(std::move(values)),
514 MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob& blob,
515 const MeshDefinition::SparseBlob& sparse,
518 mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr},
519 mBufferIdx(bufferIndex)
523 MeshDefinition::Accessor::Accessor(MeshDefinition::Blob&& blob,
524 MeshDefinition::SparseBlob&& sparse,
526 : mBlob{std::move(blob)},
527 mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{std::move(sparse)} : nullptr},
528 mBufferIdx(bufferIndex)
532 void MeshDefinition::Blob::ComputeMinMax(std::vector<float>& min, std::vector<float>& max, uint32_t numComponents, uint32_t count, const float* values)
534 min.assign(numComponents, MAXFLOAT);
535 max.assign(numComponents, -MAXFLOAT);
536 for(uint32_t i = 0; i < count; ++i)
538 for(uint32_t j = 0; j < numComponents; ++j)
540 min[j] = std::min(min[j], *values);
541 max[j] = std::max(max[j], *values);
547 void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values)
549 DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0);
550 const auto numComponents = std::max(min.size(), max.size());
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]); }));
562 auto end = values + count * numComponents;
565 auto nextElement = values + numComponents;
567 while(values != nextElement)
569 clampFn(min.data(), max.data(), i, *values);
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)
580 mElementSizeHint(elementSizeHint),
586 uint32_t MeshDefinition::Blob::GetBufferSize() const
591 void MeshDefinition::Blob::ComputeMinMax(uint32_t numComponents, uint32_t count, float* values)
593 ComputeMinMax(mMin, mMax, numComponents, count, values);
596 void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const
598 ApplyMinMax(mMin, mMax, count, values);
601 void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
603 Property::Map attribMap;
604 attribMap[mName] = mType;
605 VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
606 attribBuffer.SetData(mData.data(), mNumElements);
608 g.AddVertexBuffer(attribBuffer);
611 bool MeshDefinition::IsQuad() const
613 return CaseInsensitiveStringCompare(QUAD, mUri);
616 bool MeshDefinition::IsSkinned() const
618 return mJoints0.IsDefined() && mWeights0.IsDefined();
621 bool MeshDefinition::HasBlendShapes() const
623 return !mBlendShapes.empty();
626 void MeshDefinition::RequestNormals()
628 mNormals.mBlob.mLength = mPositions.mBlob.GetBufferSize();
631 void MeshDefinition::RequestTangents()
633 mTangents.mBlob.mLength = mNormals.mBlob.GetBufferSize();
636 MeshDefinition::RawData
637 MeshDefinition::LoadRaw(const std::string& modelsPath, BufferDefinition::Vector& buffers)
645 std::string meshPath;
646 meshPath = modelsPath + mUri;
647 std::fstream fileStream;
650 fileStream.open(meshPath, std::ios::in | std::ios::binary);
651 if(!fileStream.is_open())
653 DALI_LOG_ERROR("Fail to open buffer from %s.\n", meshPath.c_str());
657 if(mIndices.IsDefined())
659 if(MaskMatch(mFlags, U32_INDICES))
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.
668 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
669 if(!ReadAccessor(mIndices, stream, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
671 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
674 auto u16s = raw.mIndices.data();
675 auto u32s = reinterpret_cast<uint32_t*>(raw.mIndices.data());
676 auto end = u32s + indexCount;
679 *u16s = static_cast<uint16_t>(*u32s);
684 raw.mIndices.resize(indexCount);
686 else if(MaskMatch(mFlags, U8_INDICES))
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.
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))
699 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
702 auto u16s = raw.mIndices.data();
703 auto end = u8s + indexCount;
706 *u16s = static_cast<uint16_t>(*u8s);
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));
719 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mIndices.mBufferIdx], path);
720 if(!ReadAccessor(mIndices, stream, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
722 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << path << "'.";
727 std::vector<Vector3> positions;
728 if(mPositions.IsDefined())
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);
737 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mPositions.mBufferIdx], path);
738 if(!ReadAccessor(mPositions, stream, buffer.data()))
740 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << path << "'.";
743 uint32_t numVector3 = static_cast<uint32_t>(bufferSize / sizeof(Vector3));
744 if(mPositions.mBlob.mMin.size() != 3u || mPositions.mBlob.mMax.size() != 3u)
746 mPositions.mBlob.ComputeMinMax(3u, numVector3, reinterpret_cast<float*>(buffer.data()));
750 mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
755 positions.resize(numVector3);
756 std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
759 raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
762 const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
763 auto hasNormals = mNormals.IsDefined();
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);
773 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mNormals.mBufferIdx], path);
774 if(!ReadAccessor(mNormals, stream, buffer.data()))
776 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << path << "'.";
779 mNormals.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector3)), reinterpret_cast<float*>(buffer.data()));
781 raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
783 else if(mNormals.mBlob.mLength != 0 && isTriangles)
785 DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
786 GenerateNormals(raw);
790 const auto hasUvs = mTexCoords.IsDefined();
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);
800 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mTexCoords.mBufferIdx], path);
801 if(!ReadAccessor(mTexCoords, stream, buffer.data()))
803 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << path << "'.";
806 const auto uvCount = bufferSize / sizeof(Vector2);
807 if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
809 auto uv = reinterpret_cast<Vector2*>(buffer.data());
810 auto uvEnd = uv + uvCount;
813 uv->y = 1.0f - uv->y;
818 mTexCoords.mBlob.ApplyMinMax(static_cast<uint32_t>(bufferSize / sizeof(Vector2)), reinterpret_cast<float*>(buffer.data()));
820 raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
823 if(mTangents.IsDefined())
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);
833 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mTangents.mBufferIdx], path);
834 if(!ReadAccessor(mTangents, stream, buffer.data()))
836 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << path << "'.";
838 mTangents.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
840 raw.mAttribs.push_back({"aTangent", mTangentType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
842 else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
844 DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
845 static const std::function<bool(RawData&)> GenerateTangentsFunction[2][2] =
848 GenerateTangents<false, false>,
849 GenerateTangents<false, true>,
852 GenerateTangents<true, false>,
853 GenerateTangents<true, true>,
856 const bool generateSuccessed = GenerateTangentsFunction[mTangentType == Property::VECTOR3][hasUvs](raw);
857 if(!generateSuccessed)
859 DALI_LOG_ERROR("Failed to generate tangents\n");
863 if(mColors.IsDefined())
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)
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);
876 auto& stream = GetAvailableData(fileStream, meshPath, buffers[mColors.mBufferIdx], path);
877 if(!ReadAccessor(mColors, stream, buffer.data()))
879 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read colors from '" << path << "'.";
881 mColors.mBlob.ApplyMinMax(bufferSize / propertySize, reinterpret_cast<float*>(buffer.data()));
883 raw.mAttribs.push_back({"aVertexColor", propertyType, static_cast<uint32_t>(bufferSize / propertySize), std::move(buffer)});
889 std::string pathJoint;
890 auto& streamJoint = GetAvailableData(fileStream, meshPath, buffers[mJoints0.mBufferIdx], pathJoint);
891 if(MaskMatch(mFlags, U16_JOINT_IDS))
893 ReadJointAccessor<uint16_t>(raw, mJoints0, streamJoint, pathJoint);
895 else if(MaskMatch(mFlags, U8_JOINT_IDS))
897 ReadJointAccessor<uint8_t>(raw, mJoints0, streamJoint, pathJoint);
901 ReadJointAccessor<float>(raw, mJoints0, streamJoint, pathJoint);
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);
910 std::string pathWeight;
911 auto& streamWeight = GetAvailableData(fileStream, meshPath, buffers[mWeights0.mBufferIdx], pathWeight);
912 if(!ReadAccessor(mWeights0, streamWeight, buffer.data()))
914 ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << pathWeight << "'.";
917 raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
920 // Calculate the Blob for the blend shapes.
921 Blob blendShapesBlob;
922 blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
923 blendShapesBlob.mLength = 0u;
925 for(const auto& blendShape : mBlendShapes)
927 for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
931 blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
932 blendShapesBlob.mLength += i->mBlob.mLength;
939 const uint32_t numberOfVertices = static_cast<uint32_t>(mPositions.mBlob.mLength / sizeof(Vector3));
941 // Calculate the size of one buffer inside the texture.
942 raw.mBlendShapeBufferOffset = numberOfVertices;
944 bool calculateGltf2BlendShapes = false;
945 uint32_t textureWidth = 0u;
946 uint32_t textureHeight = 0u;
948 if(!mBlendShapeHeader.IsDefined())
950 CalculateTextureSize(static_cast<uint32_t>(blendShapesBlob.mLength / sizeof(Vector3)), textureWidth, textureHeight);
951 calculateGltf2BlendShapes = true;
956 ReadBlob(mBlendShapeHeader, fileStream, reinterpret_cast<uint8_t*>(header));
957 textureWidth = header[0u];
958 textureHeight = header[1u];
961 const uint32_t numberOfBlendShapes = mBlendShapes.size();
962 raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
964 Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
965 uint8_t* geometryBuffer = geometryPixelBuffer.GetBuffer();
967 if(calculateGltf2BlendShapes)
969 CalculateGltf2BlendShapes(geometryBuffer, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u], buffers);
973 Blob unnormalizeFactorBlob;
974 unnormalizeFactorBlob.mLength = static_cast<uint32_t>(sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes));
976 if(blendShapesBlob.IsDefined())
978 if(ReadBlob(blendShapesBlob, fileStream, geometryBuffer))
980 unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
984 // Read the unnormalize factors.
985 if(unnormalizeFactorBlob.IsDefined())
987 ReadBlob(unnormalizeFactorBlob, fileStream, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
990 raw.mBlendShapeData = Devel::PixelBuffer::Convert(geometryPixelBuffer);
996 MeshGeometry MeshDefinition::Load(RawData&& raw) const
998 MeshGeometry meshGeometry;
999 meshGeometry.geometry = Geometry::New();
1000 meshGeometry.geometry.SetType(mPrimitiveType);
1002 if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
1004 auto options = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
1005 meshGeometry.geometry = MakeTexturedQuadGeometry(options);
1009 if(!raw.mIndices.empty())
1011 meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
1014 for(auto& a : raw.mAttribs)
1016 a.AttachBuffer(meshGeometry.geometry);
1019 if(HasBlendShapes())
1021 meshGeometry.blendShapeBufferOffset = raw.mBlendShapeBufferOffset;
1022 meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
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);
1032 return meshGeometry;
1035 } // namespace Loader
1036 } // namespace Scene3D