/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
}
catch (DaliException& e)
{
- DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION );
+ DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION );
}
try
}
catch (DaliException& e)
{
- DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION );
+ DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION );
}
try
}
catch (DaliException& e)
{
- DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION );
+ DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION );
}
try
}
catch (DaliException& e)
{
- DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION );
+ DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION );
}
END_TEST;
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
catch(Dali::DaliException& e)
{
DALI_TEST_PRINT_ASSERT( e );
- DALI_TEST_ASSERT(e, "density>0 && density<=9", TEST_LOCATION );
+ DALI_TEST_ASSERT(e, "density > 0 && density <= 9", TEST_LOCATION );
}
END_TEST;
}
/*
-* Copyright (c) 2020 Samsung Electronics Co., Ltd.
+* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
*/
#include "dali-scene-loader/internal/gltf2-asset.h"
-#include "dali/public-api/math/matrix.h"
#include <algorithm>
#include <map>
+#include "dali/public-api/math/matrix.h"
-#define ENUM_STRING_MAPPING(t, x) { #x, t::x }
+#define ENUM_STRING_MAPPING(t, x) \
+ { \
+#x, t::x \
+ }
using namespace Dali;
{
namespace
{
-
constexpr uint32_t ACCESSOR_TYPE_ELEMENT_COUNT[]{
1,
2,
4,
9,
16,
- static_cast<uint32_t>(-1)
-};
+ static_cast<uint32_t>(-1)};
const std::map<std::string_view, AccessorType::Type> ACCESSOR_TYPES{
ENUM_STRING_MAPPING(AccessorType, SCALAR),
ENUM_STRING_MAPPING(Animation::Channel::Target::Type, WEIGHTS),
};
-}
+} // namespace
bool Component::IsUnsigned(Type t)
{
uint32_t Component::Size(Type t)
{
- switch (t)
+ switch(t)
{
- case BYTE:
- case UNSIGNED_BYTE:
- return 1;
- case SHORT:
- case UNSIGNED_SHORT:
- return 2;
- case UNSIGNED_INT:
- case FLOAT:
- return 4;
- default:
- return -1;
+ case BYTE:
+ case UNSIGNED_BYTE:
+ return 1;
+ case SHORT:
+ case UNSIGNED_SHORT:
+ return 2;
+ case UNSIGNED_INT:
+ case FLOAT:
+ return 4;
+ default:
+ return -1;
}
}
AccessorType::Type AccessorType::FromString(const char* s, size_t len)
{
auto iFind = ACCESSOR_TYPES.find(std::string_view(s, len));
- if (iFind != ACCESSOR_TYPES.end())
+ if(iFind != ACCESSOR_TYPES.end())
{
return iFind->second;
}
AlphaMode::Type AlphaMode::FromString(const char* s, size_t len)
{
auto iFind = ALPHA_MODE_TYPES.find(std::string_view(s, len));
- if (iFind != ALPHA_MODE_TYPES.end())
+ if(iFind != ALPHA_MODE_TYPES.end())
{
return iFind->second;
}
Attribute::Type Attribute::FromString(const char* s, size_t len)
{
auto iFind = ATTRIBUTE_TYPES.find(std::string_view(s, len));
- if (iFind != ATTRIBUTE_TYPES.end())
+ if(iFind != ATTRIBUTE_TYPES.end())
{
return iFind->second;
}
Animation::Sampler::Interpolation::Type Animation::Sampler::Interpolation::FromString(const char* s, size_t len)
{
auto iFind = ANIMATION_SAMPLER_INTERPOLATION.find(std::string_view(s, len));
- if (iFind != ANIMATION_SAMPLER_INTERPOLATION.end())
+ if(iFind != ANIMATION_SAMPLER_INTERPOLATION.end())
{
return iFind->second;
}
std::transform(target.begin(), target.end(), target.begin(), ::toupper);
auto iFind = ANIMATION_CHANNEL_TARGET_PATH_TYPES.find(std::string_view(target.c_str(), len));
- if (iFind != ANIMATION_CHANNEL_TARGET_PATH_TYPES.end())
+ if(iFind != ANIMATION_CHANNEL_TARGET_PATH_TYPES.end())
{
return iFind->second;
}
m.GetTransformComponents(mTranslation, mRotation, mScale);
}
-Quaternion ReadQuaternion(const json_value_s & j)
+Quaternion ReadQuaternion(const json_value_s& j)
{
- return Quaternion(ReadDaliVector<Vector4>(j));
+ return Quaternion(ReadDaliVector<Vector4>(j));
}
-}
+} // namespace gltf2
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
Hash::Hash(uint64_t initial)
: mValue(initial)
-{}
+{
+}
Hash& Hash::Add(bool b)
{
return AddObjectBytes(f);
}
-Hash& Hash::Add(const char * cStr)
+Hash& Hash::Add(const char* cStr)
{
return Add(cStr, strlen(cStr));
}
-Hash& Hash::Add(const char * cStr, size_t len)
+Hash& Hash::Add(const char* cStr, size_t len)
{
auto i0 = reinterpret_cast<const uint8_t*>(cStr);
return AddBytes(i0, i0 + len);
}
-Hash& Hash::Add(const std::string & str)
+Hash& Hash::Add(const std::string& str)
{
auto i0 = reinterpret_cast<const uint8_t*>(str.c_str());
return AddBytes(i0, i0 + str.size());
}
-Hash& Hash::AddBytes(const uint8_t * i0, const uint8_t * i1)
+Hash& Hash::AddBytes(const uint8_t* i0, const uint8_t* i1)
{
- while (i0 != i1)
+ while(i0 != i1)
{
mValue = Concatenate(*i0);
++i0;
return mValue * 31 + value;
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
-* Copyright (c) 2020 Samsung Electronics Co., Ltd.
+* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace json
{
-
int StrCmp(const json_string_s& js, const char* s)
{
- auto sSize = strlen(s);
+ auto sSize = strlen(s);
auto shorter = std::min(js.string_size, sSize);
- auto base = strncmp(js.string, s, shorter);
- return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ?
- -s[shorter] : js.string[shorter]);
+ auto base = strncmp(js.string, s, shorter);
+ return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ? -s[shorter] : js.string[shorter]);
}
int StrCmp(const json_string_s& js, const std::string& s)
{
- auto sSize = s.size();
+ auto sSize = s.size();
auto shorter = std::min(js.string_size, sSize);
- auto base = strncmp(js.string, s.c_str(), shorter);
- return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ?
- -s[shorter] : js.string[shorter]);
+ auto base = strncmp(js.string, s.c_str(), shorter);
+ return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ? -s[shorter] : js.string[shorter]);
}
-void Validate(const json_value_s & jv, json_type_e type)
+void Validate(const json_value_s& jv, json_type_e type)
{
- if (jv.type != type)
+ if(jv.type != type)
{
throw std::runtime_error("Invalid type; expected: " + std::to_string(type) + ", got: " + std::to_string(jv.type));
}
json_value_s* FindObjectChild(const std::string& key, json_object_s& obj)
{
auto i = obj.start;
- while (i)
+ while(i)
{
- if (0 == StrCmp(*i->name, key))
+ if(0 == StrCmp(*i->name, key))
{
return i->value;
}
return nullptr;
}
-}
+} // namespace json
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "dali-scene-loader/internal/json-util.h"
// EXTERNAL INCLUDES
+#include <array>
+#include "dali/devel-api/common/map-wrapper.h"
#include "dali/public-api/common/extents.h"
-#include "dali/public-api/math/matrix3.h"
#include "dali/public-api/math/matrix.h"
+#include "dali/public-api/math/matrix3.h"
#include "dali/public-api/math/quaternion.h"
#include "dali/public-api/math/radian.h"
#include "dali/public-api/math/vector2.h"
#include "dali/public-api/math/vector3.h"
#include "dali/public-api/object/property-value.h"
-#include "dali/devel-api/common/map-wrapper.h"
-#include <array>
namespace Dali
{
{
namespace
{
-
-template <typename T>
-Property::Value ReadPrimitiveHelper(const TreeNode* tn, bool(*reader)(const TreeNode*, T&))
+template<typename T>
+Property::Value ReadPrimitiveHelper(const TreeNode* tn, bool (*reader)(const TreeNode*, T&))
{
T value;
- if (reader(tn, value))
+ if(reader(tn, value))
{
return Property::Value(value);
}
return Property::Value();
}
-template <typename T>
+template<typename T>
Property::Value ReadVectorHelper(const TreeNode* tn)
{
static_assert(sizeof(T) % sizeof(float) == 0, "");
T value;
- if (ReadVector(tn, value.AsFloat(), sizeof(T) / sizeof(float)))
+ if(ReadVector(tn, value.AsFloat(), sizeof(T) / sizeof(float)))
{
return Property::Value(value);
}
Property::Value ReadVectorSingleFloatHelper(const TreeNode* tn)
{
float value;
- if (ReadVector(tn, &value, 1u))
+ if(ReadVector(tn, &value, 1u))
{
return Property::Value(value);
}
Property::Value ReadRotationHelper(const TreeNode* tn)
{
- switch (tn->Size())
- {
- case 3:
- {
- // degrees as per spec
- Vector3 rotation;
- ReadVector(tn, rotation.AsFloat(), 3u);
- return Property::Value(Quaternion(Radian(Degree(rotation.x)),
- Radian(Degree(rotation.y)),
- Radian(Degree(rotation.z))));
- }
- case 4:
+ switch(tn->Size())
{
- Vector4 v;
- ReadVector(tn, v.AsFloat(), 4u);
- //Quaternion
- return Property::Value(Quaternion(v));
- }
- default:
- return Property::Value();
+ case 3:
+ {
+ // degrees as per spec
+ Vector3 rotation;
+ ReadVector(tn, rotation.AsFloat(), 3u);
+ return Property::Value(Quaternion(Radian(Degree(rotation.x)),
+ Radian(Degree(rotation.y)),
+ Radian(Degree(rotation.z))));
+ }
+ case 4:
+ {
+ Vector4 v;
+ ReadVector(tn, v.AsFloat(), 4u);
+ //Quaternion
+ return Property::Value(Quaternion(v));
+ }
+ default:
+ return Property::Value();
}
}
-template <typename T>
+template<typename T>
bool ReadQuadHelper(const TreeNode* tn, const std::array<T*, 4>& quad)
{
- auto i = quad.begin();
- auto iEnd = quad.end();
+ auto i = quad.begin();
+ auto iEnd = quad.end();
auto iJson = tn->CBegin();
- while (iJson != tn->CEnd() && i != iEnd)
+ while(iJson != tn->CEnd() && i != iEnd)
{
int value;
- if (ReadInt(&(*iJson).second, value) && value <= std::numeric_limits<T>::max())
+ if(ReadInt(&(*iJson).second, value) && value <= std::numeric_limits<T>::max())
{
**i = value;
++i;
return true;
}
-const std::map<std::string, Property::Value(*)(const TreeNode*)> kTypeIds {
+const std::map<std::string, Property::Value (*)(const TreeNode*)> kTypeIds{
// NONE
- { "boolean", [](const TreeNode* tn) {
- return ReadPrimitiveHelper<bool>(tn, ReadBool);
- }},
- { "float", [](const TreeNode* tn) {
- return ReadPrimitiveHelper<float>(tn, ReadFloat);
- }},
- { "integer", [](const TreeNode* tn) {
- return ReadPrimitiveHelper<int>(tn, ReadInt);
- }},
- { "vector2", ReadVectorHelper<Vector2> },
- { "vector3", ReadVectorHelper<Vector3> },
- { "vector4", ReadVectorHelper<Vector4> },
- { "matrix3", ReadVectorHelper<Matrix3> },
- { "matrix", ReadVectorHelper<Matrix> },
- { "rectangle", [](const TreeNode* tn) {
- Rect<int> value;
- if (ReadQuadHelper<int>(tn, { &value.x, &value.y, &value.width, &value.height }))
- {
- return Property::Value(value);
- }
- return Property::Value();
- }},
- { "rotation", ReadRotationHelper },
+ {"boolean", [](const TreeNode* tn) {
+ return ReadPrimitiveHelper<bool>(tn, ReadBool);
+ }},
+ {"float", [](const TreeNode* tn) {
+ return ReadPrimitiveHelper<float>(tn, ReadFloat);
+ }},
+ {"integer", [](const TreeNode* tn) {
+ return ReadPrimitiveHelper<int>(tn, ReadInt);
+ }},
+ {"vector2", ReadVectorHelper<Vector2>},
+ {"vector3", ReadVectorHelper<Vector3>},
+ {"vector4", ReadVectorHelper<Vector4>},
+ {"matrix3", ReadVectorHelper<Matrix3>},
+ {"matrix", ReadVectorHelper<Matrix>},
+ {"rectangle", [](const TreeNode* tn) {
+ Rect<int> value;
+ if(ReadQuadHelper<int>(tn, {&value.x, &value.y, &value.width, &value.height}))
+ {
+ return Property::Value(value);
+ }
+ return Property::Value();
+ }},
+ {"rotation", ReadRotationHelper},
// STRING - not particularly animatable
// ARRAY - not particularly animatable
// MAP - not particularly animatable
- { "extents", [](const TreeNode* tn) {
- Extents value;
- if (ReadQuadHelper<uint16_t>(tn, { &value.start, &value.end, &value.top, &value.bottom }))
- {
- return Property::Value(value);
- }
- return Property::Value();
- }},
+ {"extents", [](const TreeNode* tn) {
+ Extents value;
+ if(ReadQuadHelper<uint16_t>(tn, {&value.start, &value.end, &value.top, &value.bottom}))
+ {
+ return Property::Value(value);
+ }
+ return Property::Value();
+ }},
};
-Property::Value(* const kArrayPropertyProcessors[])(const TreeNode*) {
+Property::Value (*const kArrayPropertyProcessors[])(const TreeNode*){
ReadVectorHelper<Matrix>,
ReadVectorHelper<Matrix3>,
ReadVectorHelper<Vector4>,
ReadVectorHelper<Vector3>,
ReadVectorHelper<Vector2>,
- ReadVectorSingleFloatHelper
-};
+ ReadVectorSingleFloatHelper};
-} // nonamespace
+} // namespace
bool ReadBool(const TreeNode* node, bool& num)
{
- if (!node)
+ if(!node)
{
return false;
}
bool returnValue = false;
- if (node->GetType() == TreeNode::BOOLEAN)
+ if(node->GetType() == TreeNode::BOOLEAN)
{
- num = node->GetBoolean();
+ num = node->GetBoolean();
returnValue = true;
}
bool ReadInt(const TreeNode* node, int& num)
{
- if (!node)
+ if(!node)
{
return false;
}
bool returnValue = false;
- if (node->GetType() == TreeNode::INTEGER)
+ if(node->GetType() == TreeNode::INTEGER)
{
- num = node->GetInteger();
+ num = node->GetInteger();
returnValue = true;
}
- else if (node->GetType() == TreeNode::FLOAT)
+ else if(node->GetType() == TreeNode::FLOAT)
{
- num = static_cast<int>(node->GetFloat());
+ num = static_cast<int>(node->GetFloat());
returnValue = true;
}
bool ReadFloat(const TreeNode* node, float& num)
{
- if (!node)
+ if(!node)
{
return false;
}
bool returnValue = false;
- if (node->GetType() == TreeNode::FLOAT)
+ if(node->GetType() == TreeNode::FLOAT)
{
- num = node->GetFloat();
+ num = node->GetFloat();
returnValue = true;
}
- else if (node->GetType() == TreeNode::INTEGER)
+ else if(node->GetType() == TreeNode::INTEGER)
{
- num = static_cast<float>(node->GetInteger());
+ num = static_cast<float>(node->GetInteger());
returnValue = true;
}
bool ReadIndex(const Toolkit::TreeNode* node, Index& num)
{
bool returnValue = node && node->GetType() == TreeNode::INTEGER;
- if (returnValue)
+ if(returnValue)
{
num = static_cast<Index>(node->GetInteger());
}
bool ReadBlob(const Toolkit::TreeNode* node, unsigned int& offset, unsigned int& length)
{
- if (!node)
+ if(!node)
{
return false;
}
- int iOffset, iLength;
+ int iOffset, iLength;
bool success = ReadInt(node->GetChild("byteOffset"), iOffset) &&
- ReadInt(node->GetChild("byteLength"), iLength) &&
- iOffset >= 0 && iLength >= 0; // 0 length might not be sensible, but is not an error at this stage.
- if (success)
+ ReadInt(node->GetChild("byteLength"), iLength) &&
+ iOffset >= 0 && iLength >= 0; // 0 length might not be sensible, but is not an error at this stage.
+ if(success)
{
- offset = static_cast<unsigned int>( iOffset );
- length = static_cast<unsigned int>( iLength );
+ offset = static_cast<unsigned int>(iOffset);
+ length = static_cast<unsigned int>(iLength);
}
return success;
}
size_t GetNumericalArraySize(const TreeNode* node)
{
size_t size = 0;
- if (node->GetType() == TreeNode::ARRAY)
+ if(node->GetType() == TreeNode::ARRAY)
{
- for (auto i0 = node->CBegin(), i1 = node->CEnd(); i0 != i1 &&
- ((*i0).second.GetType() == TreeNode::FLOAT || (*i0).second.GetType() == TreeNode::INTEGER);
- ++i0)
+ for(auto i0 = node->CBegin(), i1 = node->CEnd(); i0 != i1 &&
+ ((*i0).second.GetType() == TreeNode::FLOAT || (*i0).second.GetType() == TreeNode::INTEGER);
+ ++i0)
{
++size;
}
bool ReadVector(const TreeNode* node, float* num, unsigned int size)
{
- if (!node)
+ if(!node)
{
return false;
}
bool returnValue = false;
- if ((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY))
+ if((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY))
{
unsigned int offset = 0u;
- for (TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset)
+ for(TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset)
{
const TreeNode& coord = (*it).second;
- if (!ReadFloat(&coord, *(num + offset)))
+ if(!ReadFloat(&coord, *(num + offset)))
{
return false;
}
bool ReadVector(const Toolkit::TreeNode* node, int* num, unsigned int size)
{
- if (!node)
+ if(!node)
{
return false;
}
bool returnValue = false;
- if ((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY))
+ if((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY))
{
unsigned int offset = 0u;
- for (TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset)
+ for(TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset)
{
const TreeNode& coord = (*it).second;
- if (!ReadInt(&coord, *(num + offset)))
+ if(!ReadInt(&coord, *(num + offset)))
{
return false;
}
bool ReadColor(const TreeNode* node, Vector4& color)
{
- if (nullptr == node)
+ if(nullptr == node)
{
return false;
}
- if (!ReadVector(node, color.AsFloat(), 4))
+ if(!ReadVector(node, color.AsFloat(), 4))
{
- if (!ReadVector(node, color.AsFloat(), 3))
+ if(!ReadVector(node, color.AsFloat(), 3))
{
return false;
}
bool ReadTimePeriod(const TreeNode* node, TimePeriod& timePeriod)
{
- if (!node)
+ if(!node)
{
return false;
}
- if (!ReadFloat(node->GetChild("delay"), timePeriod.delaySeconds) || !ReadFloat(node->GetChild("duration"), timePeriod.durationSeconds))
+ if(!ReadFloat(node->GetChild("delay"), timePeriod.delaySeconds) || !ReadFloat(node->GetChild("duration"), timePeriod.durationSeconds))
{
return false;
}
bool ReadString(const TreeNode* node, std::string& strValue)
{
- if (!node)
+ if(!node)
{
return false;
}
bool returnValue = false;
- if (node->GetType() == TreeNode::STRING)
+ if(node->GetType() == TreeNode::STRING)
{
- strValue = node->GetString();
+ strValue = node->GetString();
returnValue = true;
}
return returnValue;
bool ReadStringVector(const TreeNode* node, std::vector<std::string>& strvector)
{
- if (!node)
+ if(!node)
{
return false;
}
bool returnValue = false;
- if (node->GetType() == TreeNode::ARRAY)
+ if(node->GetType() == TreeNode::ARRAY)
{
- for (TreeNode::ConstIterator it = node->CBegin(); it != node->CEnd(); ++it)
+ for(TreeNode::ConstIterator it = node->CBegin(); it != node->CEnd(); ++it)
{
const TreeNode& strNode = (*it).second;
- if (strNode.GetType() == TreeNode::STRING)
+ if(strNode.GetType() == TreeNode::STRING)
{
strvector.push_back(strNode.GetString());
}
Property::Value ReadPropertyValue(const Property::Type& propType, const TreeNode& tn)
{
- switch (propType)
+ switch(propType)
{
- case Property::BOOLEAN:
- return ReadPrimitiveHelper<bool>(&tn, ReadBool);
+ case Property::BOOLEAN:
+ return ReadPrimitiveHelper<bool>(&tn, ReadBool);
- case Property::FLOAT:
- return ReadPrimitiveHelper<float>(&tn, ReadFloat);
+ case Property::FLOAT:
+ return ReadPrimitiveHelper<float>(&tn, ReadFloat);
- case Property::INTEGER:
- return ReadPrimitiveHelper<int>(&tn, ReadInt);
+ case Property::INTEGER:
+ return ReadPrimitiveHelper<int>(&tn, ReadInt);
- case Property::VECTOR2:
- return ReadVectorHelper<Vector2>(&tn);
+ case Property::VECTOR2:
+ return ReadVectorHelper<Vector2>(&tn);
- case Property::VECTOR3:
- return ReadVectorHelper<Vector3>(&tn);
+ case Property::VECTOR3:
+ return ReadVectorHelper<Vector3>(&tn);
- case Property::VECTOR4:
- return ReadVectorHelper<Vector4>(&tn);
+ case Property::VECTOR4:
+ return ReadVectorHelper<Vector4>(&tn);
- case Property::MATRIX3:
- return ReadVectorHelper<Matrix3>(&tn);
+ case Property::MATRIX3:
+ return ReadVectorHelper<Matrix3>(&tn);
- case Property::MATRIX:
- return ReadVectorHelper<Matrix>(&tn);
+ case Property::MATRIX:
+ return ReadVectorHelper<Matrix>(&tn);
- case Property::RECTANGLE:
- {
- Rect<int> value;
- if (ReadQuadHelper<int>(&tn, { &value.x, &value.y, &value.width, &value.height }))
+ case Property::RECTANGLE:
{
- return Property::Value(value);
+ Rect<int> value;
+ if(ReadQuadHelper<int>(&tn, {&value.x, &value.y, &value.width, &value.height}))
+ {
+ return Property::Value(value);
+ }
+ break;
}
- break;
- }
- case Property::ROTATION:
- return ReadRotationHelper(&tn);
+ case Property::ROTATION:
+ return ReadRotationHelper(&tn);
- case Property::EXTENTS:
- {
- Extents value;
- if (ReadQuadHelper<uint16_t>(&tn, { &value.start, &value.end, &value.top, &value.bottom }))
+ case Property::EXTENTS:
{
- return Property::Value(value);
+ Extents value;
+ if(ReadQuadHelper<uint16_t>(&tn, {&value.start, &value.end, &value.top, &value.bottom}))
+ {
+ return Property::Value(value);
+ }
+ break;
}
- break;
- }
- case Property::NONE: // fall
- default:
- {
- DALI_ASSERT_ALWAYS(!"Property type incorrect");
- }
+ case Property::NONE: // fall
+ default:
+ {
+ DALI_ASSERT_ALWAYS(!"Property type incorrect");
+ }
}
return Property::Value();
}
Property::Value ReadPropertyValue(const Toolkit::TreeNode& tn)
{
Property::Value propValue;
- if (tn.GetType() == TreeNode::OBJECT) // attempt to disambiguate type.
+ if(tn.GetType() == TreeNode::OBJECT) // attempt to disambiguate type.
{
auto jsonType = tn.GetChild("type");
- if (jsonType && jsonType->GetType() == TreeNode::STRING)
+ if(jsonType && jsonType->GetType() == TreeNode::STRING)
{
auto iFind = kTypeIds.find(jsonType->GetString());
- if (iFind != kTypeIds.end())
+ if(iFind != kTypeIds.end())
{
propValue = iFind->second(tn.GetChild("value"));
}
}
}
- if (propValue.GetType() == Property::NONE)
+ if(propValue.GetType() == Property::NONE)
{
- if (tn.Size() == 0)
+ if(tn.Size() == 0)
{
- switch (tn.GetType())
+ switch(tn.GetType())
{
- case TreeNode::BOOLEAN:
- propValue = ReadPrimitiveHelper<bool>(&tn, ReadBool);
- break;
+ case TreeNode::BOOLEAN:
+ propValue = ReadPrimitiveHelper<bool>(&tn, ReadBool);
+ break;
- case TreeNode::INTEGER:
- propValue = ReadPrimitiveHelper<int>(&tn, ReadInt);
- break;
+ case TreeNode::INTEGER:
+ propValue = ReadPrimitiveHelper<int>(&tn, ReadInt);
+ break;
- case TreeNode::FLOAT:
- propValue = ReadPrimitiveHelper<float>(&tn, ReadFloat);
- break;
+ case TreeNode::FLOAT:
+ propValue = ReadPrimitiveHelper<float>(&tn, ReadFloat);
+ break;
- default:
- break;
+ default:
+ break;
}
}
else
{
bool allNumbers = true;
- for (auto i0 = tn.CBegin(), i1 = tn.CEnd(); i0 != i1; ++i0)
+ for(auto i0 = tn.CBegin(), i1 = tn.CEnd(); i0 != i1; ++i0)
{
auto type = (*i0).second.GetType();
if(!(type == TreeNode::FLOAT || type == TreeNode::INTEGER))
}
}
- if (allNumbers)
+ if(allNumbers)
{
// NOTE: rotations / rectangles / extents must be disambiguated in all circumstances.
- for (auto& r : kArrayPropertyProcessors)
+ for(auto& r : kArrayPropertyProcessors)
{
propValue = r(&tn);
- if (propValue.GetType() != Property::NONE)
+ if(propValue.GetType() != Property::NONE)
{
break;
}
return propValue;
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace
{
-
+// clang-format off
#define DALI_ALPHA_FUNCTION_ENTRY(x) { #x, AlphaFunction::x }
+// clang-format on
-std::unordered_map<std::string, AlphaFunction> sFunctions {
+std::unordered_map<std::string, AlphaFunction> sFunctions{
DALI_ALPHA_FUNCTION_ENTRY(DEFAULT),
DALI_ALPHA_FUNCTION_ENTRY(LINEAR),
DALI_ALPHA_FUNCTION_ENTRY(REVERSE),
#undef DALI_ALPHA_FUNCTION_ENTRY
-} // nonamespace
+} // namespace
AlphaFunction GetAlphaFunction(const std::string& name, bool* found)
{
- auto iFind = sFunctions.find(name);
+ auto iFind = sFunctions.find(name);
bool success = iFind != sFunctions.end();
- if (found)
+ if(found)
{
*found = success;
}
return success ? iFind->second : AlphaFunction(AlphaFunction::DEFAULT);
}
-void RegisterAlphaFunction(const std::string & name, AlphaFunction alphaFn)
+void RegisterAlphaFunction(const std::string& name, AlphaFunction alphaFn)
{
- DALI_ASSERT_ALWAYS(sFunctions.insert({ name, alphaFn }).second &&
- "Function with given key already exists.");
+ DALI_ASSERT_ALWAYS(sFunctions.insert({name, alphaFn}).second &&
+ "Function with given key already exists.");
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
void AnimatedProperty::Animate(Animation& anim, GetActor getActor)
{
- if (Actor actor = getActor(mNodeName))
+ if(Actor actor = getActor(mNodeName))
{
Property prop = GetProperty(actor);
- if (mKeyFrames)
+ if(mKeyFrames)
{
anim.AnimateBetween(prop, mKeyFrames, mAlphaFunction, mTimePeriod);
}
- else if (mValue)
+ else if(mValue)
{
- if (mValue->mIsRelative)
+ if(mValue->mIsRelative)
{
anim.AnimateBy(prop, mValue->mValue, mAlphaFunction, mTimePeriod);
}
}
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
const float AnimationDefinition::DEFAULT_DURATION_SECONDS = 1.f;
-const float AnimationDefinition::MIN_DURATION_SECONDS = 1e-2f;
+const float AnimationDefinition::MIN_DURATION_SECONDS = 1e-2f;
Animation::EndAction AnimationDefinition::StopForModification(Animation& anim)
{
mSpeedFactor(other.mSpeedFactor),
mPlayRange(other.mPlayRange),
mProperties(std::move(other.mProperties))
-{}
+{
+}
void AnimationDefinition::Animate(Animation& animation, AnimatedProperty::GetActor getActor)
{
DALI_ASSERT_ALWAYS(animation);
- for (auto& ap : mProperties)
+ for(auto& ap : mProperties)
{
ap.Animate(animation, getActor);
}
AnimationDefinition& AnimationDefinition::operator=(AnimationDefinition&& other)
{
AnimationDefinition tmp(std::move(other));
- mName = std::move(tmp.mName);
- mDuration = tmp.mDuration;
- mLoopCount = tmp.mLoopCount;
+ mName = std::move(tmp.mName);
+ mDuration = tmp.mDuration;
+ mLoopCount = tmp.mLoopCount;
mDisconnectAction = tmp.mDisconnectAction;
- mEndAction = tmp.mEndAction;
- mSpeedFactor = tmp.mSpeedFactor;
- mPlayRange = tmp.mPlayRange;
+ mEndAction = tmp.mEndAction;
+ mSpeedFactor = tmp.mSpeedFactor;
+ mPlayRange = tmp.mPlayRange;
mProperties.swap(tmp.mProperties);
return *this;
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
-* Copyright (c) 2020 Samsung Electronics Co., Ltd.
+* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
const std::string BlendShapes::NUMBER_OF_BLEND_SHAPES("uNumberOfBlendShapes");
const std::string BlendShapes::UNNORMALIZE_FACTOR("uBlendShapeUnnormalizeFactor");
const std::string BlendShapes::COMPONENT_SIZE("uBlendShapeComponentSize");
{
unsigned int index = 0u;
- char weightNameBuffer[32];
- char unnormalizeFactorNameBuffer[64];
+ char weightNameBuffer[32];
+ char unnormalizeFactorNameBuffer[64];
char* const pWeightName = weightNameBuffer + snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s", WEIGHTS_UNIFORM.c_str());
char* const pFactorName = unnormalizeFactorNameBuffer + snprintf(unnormalizeFactorNameBuffer, sizeof(unnormalizeFactorNameBuffer), "%s", UNNORMALIZE_FACTOR.c_str());
- for (const auto& blendShape : mesh.first.mBlendShapes)
+ for(const auto& blendShape : mesh.first.mBlendShapes)
{
snprintf(pWeightName, sizeof(weightNameBuffer) - (pWeightName - weightNameBuffer), "[%d]", index);
- std::string weightName{ weightNameBuffer };
+ std::string weightName{weightNameBuffer};
actor.RegisterProperty(weightName, blendShape.weight);
- if (mesh.first.mBlendShapeVersion == Version::VERSION_1_0)
+ if(mesh.first.mBlendShapeVersion == Version::VERSION_1_0)
{
snprintf(pFactorName, sizeof(unnormalizeFactorNameBuffer) - (pFactorName - unnormalizeFactorNameBuffer), "[%d]", index);
- std::string factorName{ unnormalizeFactorNameBuffer };
+ std::string factorName{unnormalizeFactorNameBuffer};
shader.RegisterProperty(factorName, mesh.second.blendShapeUnnormalizeFactor[index]);
}
++index;
}
- if (Version::VERSION_2_0 == mesh.first.mBlendShapeVersion)
+ if(Version::VERSION_2_0 == mesh.first.mBlendShapeVersion)
{
shader.RegisterProperty(UNNORMALIZE_FACTOR, mesh.second.blendShapeUnnormalizeFactor[0u]);
}
// Create a read only property to preserve the components of the blend shape.
int32_t components = 0x0;
- for (auto& bs : mesh.first.mBlendShapes)
+ for(auto& bs : mesh.first.mBlendShapes)
{
components |= (bs.deltas.IsDefined() * Component::POSITIONS) |
- (bs.normals.IsDefined() * Component::NORMALS) | (bs.tangents.IsDefined() * Component::TANGENTS);
+ (bs.normals.IsDefined() * Component::NORMALS) | (bs.tangents.IsDefined() * Component::TANGENTS);
}
shader.RegisterProperty(COMPONENTS, components, Property::AccessMode::READ_ONLY);
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
#include "dali-scene-loader/public-api/camera-parameters.h"
#include "dali-scene-loader/public-api/utils.h"
+#include "dali/integration-api/debug.h"
#include "dali/public-api/actors/camera-actor.h"
#include "dali/public-api/math/quaternion.h"
-#include "dali/integration-api/debug.h"
namespace Dali
{
* @param[in] far The distance to the far depth clipping plane.
* @param[in] invertYAxis Whether to invert the 'Y' axis.
*/
-void Frustum( Matrix& result, float left, float right, float bottom, float top, float nearPlane, float farPlane, bool invertYAxis )
+void Frustum(Matrix& result, float left, float right, float bottom, float top, float nearPlane, float farPlane, bool invertYAxis)
{
float deltaZ = farPlane - nearPlane;
- if ((nearPlane <= 0.0f) || (farPlane <= 0.0f) || Equals(right, left) || Equals(bottom, top) || (deltaZ <= 0.0f))
+ if((nearPlane <= 0.0f) || (farPlane <= 0.0f) || Equals(right, left) || Equals(bottom, top) || (deltaZ <= 0.0f))
{
DALI_LOG_ERROR("Invalid parameters passed into Frustum!\n");
DALI_ASSERT_DEBUG("Invalid parameters passed into Frustum!");
result.SetIdentity();
float* m = result.AsFloat();
- m[0] = -2.0f * nearPlane / deltaX;
+ m[0] = -2.0f * nearPlane / deltaX;
m[1] = m[2] = m[3] = 0.0f;
m[5] = -2.0f * nearPlane / deltaY;
m[4] = m[6] = m[7] = 0.0f;
- m[8] = (right + left) / deltaX;
- m[9] = (top + bottom) / deltaY;
+ m[8] = (right + left) / deltaX;
+ m[9] = (top + bottom) / deltaY;
m[10] = (nearPlane + farPlane) / deltaZ;
m[11] = 1.0f;
* @param[in] farPlane The distance to the far depth clipping plane.
* @param[in] invertYAxis Whether to invert the 'Y' axis.
*/
-void Perspective( Matrix& result, float fovy, float aspect, float nearPlane, float farPlane, bool invertYAxis )
+void Perspective(Matrix& result, float fovy, float aspect, float nearPlane, float farPlane, bool invertYAxis)
{
- float frustumH = tanf( fovy * 0.5f ) * nearPlane;
+ float frustumH = tanf(fovy * 0.5f) * nearPlane;
float frustumW = frustumH * aspect;
- Frustum( result, -frustumW, frustumW, -frustumH, frustumH, nearPlane, farPlane, invertYAxis );
+ Frustum(result, -frustumW, frustumW, -frustumH, frustumH, nearPlane, farPlane, invertYAxis);
}
/**
*/
void Orthographic(Matrix& result, float left, float right, float bottom, float top, float nearPlane, float farPlane, bool invertYAxis)
{
- if (Equals(right, left) || Equals(top, bottom) || Equals(farPlane, nearPlane))
+ if(Equals(right, left) || Equals(top, bottom) || Equals(farPlane, nearPlane))
{
DALI_LOG_ERROR("Cannot create orthographic projection matrix with a zero dimension.\n");
DALI_ASSERT_DEBUG("Cannot create orthographic projection matrix with a zero dimension.");
float deltaY = invertYAxis ? bottom - top : top - bottom;
float deltaZ = farPlane - nearPlane;
- float *m = result.AsFloat();
- m[0] = -2.0f / deltaX;
- m[1] = 0.0f;
- m[2] = 0.0f;
- m[3] = 0.0f;
+ float* m = result.AsFloat();
+ m[0] = -2.0f / deltaX;
+ m[1] = 0.0f;
+ m[2] = 0.0f;
+ m[3] = 0.0f;
m[4] = 0.0f;
m[5] = -2.0f / deltaY;
m[6] = 0.0f;
m[7] = 0.0f;
- m[8] = 0.0f;
- m[9] = 0.0f;
+ m[8] = 0.0f;
+ m[9] = 0.0f;
m[10] = 2.0f / deltaZ;
m[11] = 0.0f;
m[12] = -(right + left) / deltaX;
m[15] = 1.0f;
}
-} // nonamespace
+} // namespace
ViewProjection CameraParameters::GetViewProjection() const
{
ViewProjection viewProjection;
// The projection matrix.
- if (isPerspective)
+ if(isPerspective)
{
Perspective(viewProjection.GetProjection(),
- Radian(Degree(yFov)),
- 1.f,
- zNear,
- zFar,
- true);
+ Radian(Degree(yFov)),
+ 1.f,
+ zNear,
+ zFar,
+ true);
}
else
{
Orthographic(viewProjection.GetProjection(),
- orthographicSize.x,
- orthographicSize.y,
- orthographicSize.z,
- orthographicSize.w,
- zNear,
- zFar,
- true);
-
+ orthographicSize.x,
+ orthographicSize.y,
+ orthographicSize.z,
+ orthographicSize.w,
+ zNear,
+ zFar,
+ true);
}
// The view matrix.
const Quaternion viewQuaternion(ANGLE_180, Vector3::YAXIS);
- Vector3 translation;
- Quaternion cameraOrientation;
- Vector3 scale;
+ Vector3 translation;
+ Quaternion cameraOrientation;
+ Vector3 scale;
matrix.GetTransformComponents(translation, cameraOrientation, scale);
cameraOrientation *= viewQuaternion;
viewProjection.GetView().SetInverseTransformComponents(scale,
- cameraOrientation,
- translation);
+ cameraOrientation,
+ translation);
viewProjection.Update();
return viewProjection;
}
-void CameraParameters::CalculateTransformComponents(Vector3 & position, Quaternion & orientation, Vector3 & scale) const
+void CameraParameters::CalculateTransformComponents(Vector3& position, Quaternion& orientation, Vector3& scale) const
{
matrix.GetTransformComponents(position, orientation, scale);
{
SetActorCentered(camera);
- if (isPerspective)
+ if(isPerspective)
{
camera.SetProjectionMode(Camera::PERSPECTIVE_PROJECTION);
camera.SetNearClippingPlane(zNear);
{
camera.SetProjectionMode(Camera::ORTHOGRAPHIC_PROJECTION);
camera.SetOrthographicProjection(orthographicSize.x,
- orthographicSize.y,
- orthographicSize.z,
- orthographicSize.w,
- zNear,
- zFar);
+ orthographicSize.y,
+ orthographicSize.z,
+ orthographicSize.w,
+ zNear,
+ zFar);
}
// model
- Vector3 camTranslation;
- Vector3 camScale;
+ Vector3 camTranslation;
+ Vector3 camScale;
Quaternion camOrientation;
CalculateTransformComponents(camTranslation, camOrientation, camScale);
camera.SetProperty(Actor::Property::SCALE, camScale);
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
-struct Customization::Map::Impl {
+struct Customization::Map::Impl
+{
std::map<Tag, Customization> mCustomizations;
};
Customization::Map::Map()
-: mImpl{ new Impl }
-{}
+: mImpl{new Impl}
+{
+}
Customization::Map::~Map() = default;
const Customization* Customization::Map::Get(Tag tag) const
{
auto& customizations = mImpl->mCustomizations;
- auto iFind = customizations.find(tag);
- if (iFind != customizations.end())
+ auto iFind = customizations.find(tag);
+ if(iFind != customizations.end())
{
return &iFind->second;
}
Customization* Customization::Map::Get(Tag tag)
{
auto& customizations = mImpl->mCustomizations;
- auto iFind = customizations.find(tag);
- if (iFind != customizations.end())
+ auto iFind = customizations.find(tag);
+ if(iFind != customizations.end())
{
return &iFind->second;
}
};
Customization::Choices::Choices()
-: mImpl{ new Impl }
-{}
+: mImpl{new Impl}
+{
+}
Customization::Choices::~Choices() = default;
Customization::OptionType Customization::Choices::Get(Tag tag) const
{
auto& options = mImpl->mOptions;
- auto iFind = options.find(tag);
- if (iFind != options.end())
+ auto iFind = options.find(tag);
+ if(iFind != options.end())
{
return iFind->second;
}
mImpl->mOptions.clear();
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "dali-scene-loader/public-api/dli-loader.h"
// EXTERNAL INCLUDES
-#include "dali/public-api/object/property-array.h"
-#include "dali/devel-api/common/map-wrapper.h"
-#include "dali-toolkit/devel-api/builder/json-parser.h"
-#include "dali/integration-api/debug.h"
+#include <algorithm>
+#include <cmath>
#include <fstream>
#include <limits>
-#include <algorithm>
#include <memory>
-#include <cmath>
+#include "dali-toolkit/devel-api/builder/json-parser.h"
+#include "dali/devel-api/common/map-wrapper.h"
+#include "dali/integration-api/debug.h"
+#include "dali/public-api/object/property-array.h"
// INTERNAL INCLUDES
-#include "dali-scene-loader/public-api/parse-renderer-state.h"
-#include "dali-scene-loader/public-api/skinning-details.h"
-#include "dali-scene-loader/public-api/load-result.h"
-#include "dali-scene-loader/public-api/scene-definition.h"
-#include "dali-scene-loader/public-api/animation-definition.h"
+#include "dali-scene-loader/internal/json-util.h"
#include "dali-scene-loader/public-api/alpha-function-helper.h"
-#include "dali-scene-loader/public-api/camera-parameters.h"
-#include "dali-scene-loader/public-api/light-parameters.h"
+#include "dali-scene-loader/public-api/animation-definition.h"
#include "dali-scene-loader/public-api/blend-shape-details.h"
+#include "dali-scene-loader/public-api/camera-parameters.h"
#include "dali-scene-loader/public-api/ktx-loader.h"
+#include "dali-scene-loader/public-api/light-parameters.h"
+#include "dali-scene-loader/public-api/load-result.h"
+#include "dali-scene-loader/public-api/parse-renderer-state.h"
+#include "dali-scene-loader/public-api/scene-definition.h"
+#include "dali-scene-loader/public-api/skinning-details.h"
#include "dali-scene-loader/public-api/utils.h"
-#include "dali-scene-loader/internal/json-util.h"
#define DLI_0_1_COMPATIBILITY
namespace SceneLoader
{
-
namespace rs = RendererState;
namespace
{
-const std::string NODES = "nodes";
-const std::string SCENES = "scenes";
-const std::string NODE = "node";
-const std::string URI = "uri";
-const std::string URL = "url";
+const std::string NODES = "nodes";
+const std::string SCENES = "scenes";
+const std::string NODE = "node";
+const std::string URI = "uri";
+const std::string URL = "url";
const std::string CUSTOMIZATION = "customization";
-const std::string HINTS = "hints";
+const std::string HINTS = "hints";
const std::string NAME("name");
const std::string BLEND_SHAPE_HEADER("blendShapeHeader");
const std::string BLEND_SHAPES("blendShapes");
const std::string BLEND_SHAPE_VERSION_2_0("2.0");
const std::string VERSION("version");
-const char* const SHADOW_MAP_SIZE = "shadowMapSize";
+const char* const SHADOW_MAP_SIZE = "shadowMapSize";
const char* const ORTHOGRAPHIC_SIZE = "orthographicSize";
-const char* const PIXEL_UNITS = "px";
+const char* const PIXEL_UNITS = "px";
const char SLASH = '/';
void ReadModelTransform(const TreeNode* node, Quaternion& orientation, Vector3& translation, Vector3& scale)
{
- float num[16u] = { .0f };
+ float num[16u] = {.0f};
- if (ReadVector(node->GetChild("matrix"), num, 16u))
+ if(ReadVector(node->GetChild("matrix"), num, 16u))
{
Matrix mat(num);
mat.GetTransformComponents(translation, orientation, scale);
}
else
{
- if (ReadVector(node->GetChild("angle"), num, 3u))
+ if(ReadVector(node->GetChild("angle"), num, 3u))
{
orientation = Quaternion(Radian(Degree(num[0u])), Radian(Degree(num[1u])), Radian(Degree(num[2u])));
}
- if (ReadVector(node->GetChild("position"), num, 3u))
+ if(ReadVector(node->GetChild("position"), num, 3u))
{
translation = Vector3(num);
}
return ReadBlob(node, accessor.mBlob.mOffset, accessor.mBlob.mLength);
}
-bool ReadColorCode(const TreeNode* node, Vector4& color,
- DliLoader::ConvertColorCode convertColorCode)
+bool ReadColorCode(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode)
{
- if (!node || !convertColorCode)
+ if(!node || !convertColorCode)
{
return false;
}
return true;
}
-bool ReadColorCodeOrColor(const TreeNode* node, Vector4& color,
- DliLoader::ConvertColorCode convertColorCode)
+bool ReadColorCodeOrColor(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode)
{
return ReadColorCode(node->GetChild("colorCode"), color, convertColorCode) ||
- ReadColor(node->GetChild("color"), color);
+ ReadColor(node->GetChild("color"), color);
}
RendererState::Type ReadRendererState(const TreeNode& tnRendererState)
{
- if (tnRendererState.GetType() == TreeNode::INTEGER)
+ if(tnRendererState.GetType() == TreeNode::INTEGER)
{
return static_cast<RendererState::Type>(tnRendererState.GetInteger());
}
- else if (tnRendererState.GetType() == TreeNode::STRING)
+ else if(tnRendererState.GetType() == TreeNode::STRING)
{
return RendererState::Parse(tnRendererState.GetString());
}
ReadFloat(eArc->GetChild("endAngle"), arc.mEndAngleDegrees);
}
-const TreeNode *GetNthChild(const TreeNode *node, uint32_t index)
+const TreeNode* GetNthChild(const TreeNode* node, uint32_t index)
{
uint32_t i = 0;
- for (TreeNode::ConstIterator it = (*node).CBegin(); it != (*node).CEnd(); ++it, ++i)
+ for(TreeNode::ConstIterator it = (*node).CBegin(); it != (*node).CEnd(); ++it, ++i)
{
- if (i == index)
+ if(i == index)
{
return &((*it).second);
}
const TreeNode* RequireChild(const TreeNode* node, const std::string& childName)
{
auto child = node->GetChild(childName);
- if (!child)
+ if(!child)
{
ExceptionFlinger flinger(ASSERT_LOCATION);
flinger << "Failed to find child node '" << childName << "'";
- if (auto nodeName = node->GetName())
+ if(auto nodeName = node->GetName())
{
flinger << " on '" << nodeName << "'";
}
void ParseProperties(const Toolkit::TreeNode& node, Property::Map& map)
{
DALI_ASSERT_DEBUG(node.GetType() == TreeNode::OBJECT);
- for (auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
+ for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
{
auto kv = *i0;
- switch (kv.second.GetType())
- {
- case TreeNode::ARRAY:
+ switch(kv.second.GetType())
{
- Property::Array array;
- ParseProperties(kv.second, array);
- map.Insert(kv.first, array);
- } break;
+ case TreeNode::ARRAY:
+ {
+ Property::Array array;
+ ParseProperties(kv.second, array);
+ map.Insert(kv.first, array);
+ break;
+ }
- case TreeNode::OBJECT:
- {
- Property::Map innerMap;
- ParseProperties(kv.second, innerMap);
- map.Insert(kv.first, innerMap);
- } break;
+ case TreeNode::OBJECT:
+ {
+ Property::Map innerMap;
+ ParseProperties(kv.second, innerMap);
+ map.Insert(kv.first, innerMap);
+ break;
+ }
- case TreeNode::STRING:
- map.Insert(kv.first, kv.second.GetString());
- break;
+ case TreeNode::STRING:
+ {
+ map.Insert(kv.first, kv.second.GetString());
+ break;
+ }
- case TreeNode::INTEGER:
- map.Insert(kv.first, kv.second.GetInteger());
- break;
+ case TreeNode::INTEGER:
+ {
+ map.Insert(kv.first, kv.second.GetInteger());
+ break;
+ }
- case TreeNode::BOOLEAN:
- map.Insert(kv.first, kv.second.GetBoolean());
- break;
+ case TreeNode::BOOLEAN:
+ {
+ map.Insert(kv.first, kv.second.GetBoolean());
+ break;
+ }
- case TreeNode::FLOAT:
- map.Insert(kv.first, kv.second.GetFloat());
- break;
+ case TreeNode::FLOAT:
+ {
+ map.Insert(kv.first, kv.second.GetFloat());
+ break;
+ }
- case TreeNode::IS_NULL:
- break;
+ case TreeNode::IS_NULL:
+ {
+ break;
+ }
}
}
}
void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array)
{
DALI_ASSERT_DEBUG(node.GetType() == TreeNode::ARRAY);
- for (auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
+ for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
{
auto kv = *i0;
- switch (kv.second.GetType())
- {
- case TreeNode::ARRAY:
+ switch(kv.second.GetType())
{
- Property::Array innerArray;
- ParseProperties(kv.second, innerArray);
- array.PushBack(innerArray);
- } break;
+ case TreeNode::ARRAY:
+ {
+ Property::Array innerArray;
+ ParseProperties(kv.second, innerArray);
+ array.PushBack(innerArray);
+ break;
+ }
- case TreeNode::OBJECT:
- {
- Property::Map map;
- ParseProperties(kv.second, map);
- array.PushBack(map);
- } break;
+ case TreeNode::OBJECT:
+ {
+ Property::Map map;
+ ParseProperties(kv.second, map);
+ array.PushBack(map);
+ break;
+ }
- case TreeNode::STRING:
- array.PushBack(kv.second.GetString());
- break;
+ case TreeNode::STRING:
+ {
+ array.PushBack(kv.second.GetString());
+ break;
+ }
- case TreeNode::INTEGER:
- array.PushBack(kv.second.GetInteger());
- break;
+ case TreeNode::INTEGER:
+ {
+ array.PushBack(kv.second.GetInteger());
+ break;
+ }
- case TreeNode::BOOLEAN:
- array.PushBack(kv.second.GetBoolean());
- break;
+ case TreeNode::BOOLEAN:
+ {
+ array.PushBack(kv.second.GetBoolean());
+ break;
+ }
- case TreeNode::FLOAT:
- array.PushBack(kv.second.GetFloat());
- break;
+ case TreeNode::FLOAT:
+ {
+ array.PushBack(kv.second.GetFloat());
+ break;
+ }
- case TreeNode::IS_NULL:
- break;
+ case TreeNode::IS_NULL:
+ {
+ break;
+ }
}
}
}
-}//namespace
+} //namespace
struct DliLoader::Impl
{
- StringCallback mOnError = DefaultErrorCallback;
+ StringCallback mOnError = DefaultErrorCallback;
Toolkit::JsonParser mParser;
void ParseScene(LoadParams& params);
private:
- std::map<Index, Matrix> mInverseBindMatrices;
+ std::map<Index, Matrix> mInverseBindMatrices;
/**
* @brief Due to .dli nodes being processed in depth-first traversal with orphans being
* index.
* @return Whether the operation was successful.
*/
- virtual bool Map(Index iDli, Index iScene) =0;
+ virtual bool Map(Index iDli, Index iScene) = 0;
/**
* @return The scene index for the node's @a dli index.
*/
- virtual Index Resolve(Index iDli) =0;
+ virtual Index Resolve(Index iDli) = 0;
};
/**
* @brief Traverses the DOM tree created by LoadDocument() in an attempt to create
* an intermediate representation of resources and nodes.
*/
- void ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes,
- const Toolkit::TreeNode* tnNodes, LoadParams& params);
+ void ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params);
void ParseSkeletons(const Toolkit::TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources);
void ParseEnvironments(const Toolkit::TreeNode* environments, ResourceBundle& resources);
- void ParseMaterials(const Toolkit::TreeNode* materials, ConvertColorCode convertColorCode,
- ResourceBundle& resources);
+ void ParseMaterials(const Toolkit::TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources);
void ParseNodes(const Toolkit::TreeNode* nodes, Index index, LoadParams& params);
- void ParseNodesInternal(const Toolkit::TreeNode* nodes, Index index,
- std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& indexMapper);
+ void ParseNodesInternal(const Toolkit::TreeNode* nodes, Index index, std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& indexMapper);
void ParseAnimations(const Toolkit::TreeNode* animations, LoadParams& params);
void ParseAnimationGroups(const Toolkit::TreeNode* animationGroups, LoadParams& params);
};
DliLoader::DliLoader()
-: mImpl{ new Impl }
-{}
+: mImpl{new Impl}
+{
+}
DliLoader::~DliLoader() = default;
std::string daliBuffer = LoadTextFile(uri.c_str());
auto& parser = mImpl->mParser;
- parser = JsonParser::New();
- if (!parser.Parse(daliBuffer))
+ parser = JsonParser::New();
+ if(!parser.Parse(daliBuffer))
{
return false;
}
std::stringstream stream;
auto& parser = mImpl->mParser;
- if (parser.ParseError())
+ if(parser.ParseError())
{
stream << "position: " << parser.GetErrorPosition() << ", line: " << parser.GetErrorLineNumber() << ", column: " << parser.GetErrorColumn() << ", description: " << parser.GetErrorDescription() << ".";
}
void DliLoader::Impl::ParseScene(LoadParams& params)
{
- auto& input = params.input;
+ auto& input = params.input;
auto& output = params.output;
// get index of root node.
auto docRoot = mParser.GetRoot();
// Process resources first - these are shared
- if (auto environments = docRoot->GetChild("environment"))
+ if(auto environments = docRoot->GetChild("environment"))
{
- ParseEnvironments(environments, output.mResources); // NOTE: must precede parsing of materials
+ ParseEnvironments(environments, output.mResources); // NOTE: must precede parsing of materials
}
- if (auto meshes = docRoot->GetChild("meshes"))
+ if(auto meshes = docRoot->GetChild("meshes"))
{
ParseMeshes(meshes, output.mResources);
}
- if (auto shaders = docRoot->GetChild("shaders"))
+ if(auto shaders = docRoot->GetChild("shaders"))
{
ParseShaders(shaders, output.mResources);
}
- if (auto materials = docRoot->GetChild("materials"))
+ if(auto materials = docRoot->GetChild("materials"))
{
ParseMaterials(materials, input.mConvertColorCode, output.mResources);
}
- for (auto& c : input.mPreNodeCategoryProcessors)
+ for(auto& c : input.mPreNodeCategoryProcessors)
{
- if (auto node = docRoot->GetChild(c.first))
+ if(auto node = docRoot->GetChild(c.first))
{
Property::Array array;
ParseProperties(*node, array);
}
// Process scenes
- Index iScene = 0; // default scene
+ Index iScene = 0; // default scene
ReadIndex(docRoot->GetChild("scene"), iScene);
auto tnScenes = RequireChild(docRoot, "scenes");
- auto tnNodes = RequireChild(docRoot, "nodes");
+ auto tnNodes = RequireChild(docRoot, "nodes");
ParseSceneInternal(iScene, tnScenes, tnNodes, params);
ParseSkeletons(docRoot->GetChild("skeletons"), output.mScene, output.mResources);
GetLightParameters(output.mLightParameters);
// Post-node processors and animations last
- for (auto& c : input.mPostNodeCategoryProcessors)
+ for(auto& c : input.mPostNodeCategoryProcessors)
{
- if (auto node = docRoot->GetChild(c.first))
+ if(auto node = docRoot->GetChild(c.first))
{
Property::Array array;
ParseProperties(*node, array);
}
}
- if (auto animations = docRoot->GetChild("animations"))
+ if(auto animations = docRoot->GetChild("animations"))
{
ParseAnimations(animations, params);
}
- if (!output.mAnimationDefinitions.empty())
+ if(!output.mAnimationDefinitions.empty())
{
- if (auto animationGroups = docRoot->GetChild("animationGroups"))
+ if(auto animationGroups = docRoot->GetChild("animationGroups"))
{
ParseAnimationGroups(animationGroups, params);
}
}
}
-void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes,
- const Toolkit::TreeNode* tnNodes, LoadParams& params)
+void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params)
{
auto getSceneRootIdx = [tnScenes, tnNodes](Index iScene) {
- auto tn = GetNthChild(tnScenes, iScene); // now a "scene" object
- if (!tn)
+ auto tn = GetNthChild(tnScenes, iScene); // now a "scene" object
+ if(!tn)
{
ExceptionFlinger(ASSERT_LOCATION) << iScene << " is out of bounds access into " << SCENES << ".";
}
- tn = RequireChild(tn, NODES); // now a "nodes" array
- if (tn->GetType() != TreeNode::ARRAY)
+ tn = RequireChild(tn, NODES); // now a "nodes" array
+ if(tn->GetType() != TreeNode::ARRAY)
{
- ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES <<
- " has an invalid type; array required.";
+ ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid type; array required.";
}
- if (tn->Size() < 1)
+ if(tn->Size() < 1)
{
- ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES <<
- " must define a node id.";
+ ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " must define a node id.";
}
- tn = GetNthChild(tn, 0); // now the first element of the array
+ tn = GetNthChild(tn, 0); // now the first element of the array
Index iRootNode;
- if (!ReadIndex(tn, iRootNode))
+ if(!ReadIndex(tn, iRootNode))
{
- ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES <<
- " has an invalid value for root node index: '" << iRootNode << "'.";
+ ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid value for root node index: '" << iRootNode << "'.";
}
- if (iRootNode >= tnNodes->Size())
+ if(iRootNode >= tnNodes->Size())
{
ExceptionFlinger(ASSERT_LOCATION) << "Root node index << " << iRootNode << " of scene " << iScene << " is out of bounds.";
}
- tn = GetNthChild(tnNodes, iRootNode); // now a "node" object
- if (tn->GetType() != TreeNode::OBJECT)
+ tn = GetNthChild(tnNodes, iRootNode); // now a "node" object
+ if(tn->GetType() != TreeNode::OBJECT)
{
ExceptionFlinger(ASSERT_LOCATION) << "Root node of scene " << iScene << " is of invalid JSON type; object required";
}
auto& scene = params.output.mScene;
scene.AddRootNode(0);
- for (Index i = 0; i < iScene; ++i)
+ for(Index i = 0; i < iScene; ++i)
{
- Index iRootNode = getSceneRootIdx(i);
- const Index iRoot = scene.GetNodeCount();
+ Index iRootNode = getSceneRootIdx(i);
+ const Index iRoot = scene.GetNodeCount();
ParseNodes(tnNodes, iRootNode, params);
scene.AddRootNode(iRoot);
}
auto numScenes = tnScenes->Size();
- for (Index i = iScene + 1; i < numScenes; ++i)
+ for(Index i = iScene + 1; i < numScenes; ++i)
{
- Index iRootNode = getSceneRootIdx(i);
- const Index iRoot = scene.GetNodeCount();
+ Index iRootNode = getSceneRootIdx(i);
+ const Index iRoot = scene.GetNodeCount();
ParseNodes(tnNodes, iRootNode, params);
scene.AddRootNode(iRoot);
}
void DliLoader::Impl::ParseSkeletons(const TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources)
{
- if (skeletons)
+ if(skeletons)
{
auto iStart = skeletons->CBegin();
- for (auto i0 = iStart, i1 = skeletons->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = iStart, i1 = skeletons->CEnd(); i0 != i1; ++i0)
{
- auto& node = (*i0).second;
+ auto& node = (*i0).second;
std::string skeletonRootName;
- if (ReadString(node.GetChild(NODE), skeletonRootName))
+ if(ReadString(node.GetChild(NODE), skeletonRootName))
{
SkeletonDefinition skeleton;
- if (!scene.FindNode(skeletonRootName, &skeleton.mRootNodeIdx))
+ if(!scene.FindNode(skeletonRootName, &skeleton.mRootNodeIdx))
{
ExceptionFlinger(ASSERT_LOCATION) << FormatString("Skeleton %d: node '%s' not defined.", resources.mSkeletons.size(), skeletonRootName.c_str());
}
- uint32_t jointCount = 0;
+ uint32_t jointCount = 0;
std::function<void(Index)> visitFn;
- auto& ibms = mInverseBindMatrices;
- visitFn = [&](Index id) {
+ auto& ibms = mInverseBindMatrices;
+ visitFn = [&](Index id) {
auto node = scene.GetNode(id);
jointCount += ibms.find(id) != ibms.end();
- for (auto i : node->mChildren)
+ for(auto i : node->mChildren)
{
visitFn(i);
}
};
visitFn(skeleton.mRootNodeIdx);
- if (jointCount > Skinning::MAX_JOINTS)
+ if(jointCount > Skinning::MAX_JOINTS)
{
mOnError(FormatString("Skeleton %d: joint count exceeds supported limit.", resources.mSkeletons.size()));
jointCount = Skinning::MAX_JOINTS;
visitFn = [&](Index id) {
auto iFind = ibms.find(id);
- if (iFind != ibms.end() && skeleton.mJoints.size() < Skinning::MAX_JOINTS)
+ if(iFind != ibms.end() && skeleton.mJoints.size() < Skinning::MAX_JOINTS)
{
- skeleton.mJoints.push_back({ id, iFind->second });
+ skeleton.mJoints.push_back({id, iFind->second});
}
auto node = scene.GetNode(id);
- for (auto i : node->mChildren)
+ for(auto i : node->mChildren)
{
visitFn(i);
}
}
else
{
- ExceptionFlinger(ASSERT_LOCATION) << "skeleton " << std::distance(iStart, i0) <<
- ": Missing required attribute '"<< NODE <<"'.";
+ ExceptionFlinger(ASSERT_LOCATION) << "skeleton " << std::distance(iStart, i0) << ": Missing required attribute '" << NODE << "'.";
}
}
}
{
Matrix cubeOrientation(Matrix::IDENTITY);
- for (auto i0 = environments->CBegin(), i1 = environments->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = environments->CBegin(), i1 = environments->CEnd(); i0 != i1; ++i0)
{
auto& node = (*i0).second;
ToUnixFileSeparators(envDef.mDiffuseMapPath);
envDef.mIblIntensity = 1.0f;
ReadFloat(node.GetChild("iblIntensity"), envDef.mIblIntensity);
- if (ReadVector(node.GetChild("cubeInitialOrientation"), cubeOrientation.AsFloat(), 16u))
+ if(ReadVector(node.GetChild("cubeInitialOrientation"), cubeOrientation.AsFloat(), 16u))
{
envDef.mCubeOrientation = Quaternion(cubeOrientation);
}
}
// NOTE: guarantees environmentMaps to have an empty environment.
- if (resources.mEnvironmentMaps.empty())
+ if(resources.mEnvironmentMaps.empty())
{
resources.mEnvironmentMaps.emplace_back(EnvironmentDefinition(), EnvironmentDefinition::Textures());
}
void DliLoader::Impl::ParseShaders(const TreeNode* shaders, ResourceBundle& resources)
{
uint32_t iShader = 0;
- for (auto i0 = shaders->CBegin(), i1 = shaders->CEnd(); i0 != i1; ++i0, ++iShader)
+ for(auto i0 = shaders->CBegin(), i1 = shaders->CEnd(); i0 != i1; ++i0, ++iShader)
{
- auto& node = (*i0).second;
+ auto& node = (*i0).second;
ShaderDefinition shaderDef;
ReadStringVector(node.GetChild("defines"), shaderDef.mDefines);
// "OUTPUT_IS_TRANSPARENT" Might generate transparent alpha from opaque inputs.
// "MODIFIES_GEOMETRY" Might change position of vertices, this option disables any culling optimizations.
- ReadStringVector(node.GetChild( HINTS ), shaderDef.mHints);
+ ReadStringVector(node.GetChild(HINTS), shaderDef.mHints);
- if (ReadString(node.GetChild("vertex"), shaderDef.mVertexShaderPath) &&
- ReadString(node.GetChild("fragment"), shaderDef.mFragmentShaderPath))
+ if(ReadString(node.GetChild("vertex"), shaderDef.mVertexShaderPath) &&
+ ReadString(node.GetChild("fragment"), shaderDef.mFragmentShaderPath))
{
ToUnixFileSeparators(shaderDef.mVertexShaderPath);
ToUnixFileSeparators(shaderDef.mFragmentShaderPath);
- for (TreeNode::ConstIterator j0 = node.CBegin(), j1 = node.CEnd(); j0 != j1; ++j0)
+ for(TreeNode::ConstIterator j0 = node.CBegin(), j1 = node.CEnd(); j0 != j1; ++j0)
{
const TreeNode::KeyNodePair& keyValue = *j0;
- const std::string& key = keyValue.first;
- const TreeNode& value = keyValue.second;
+ const std::string& key = keyValue.first;
+ const TreeNode& value = keyValue.second;
Property::Value uniformValue;
- if (key.compare("vertex") == 0 || key.compare("fragment") == 0 || key.compare("defines") == 0 || key.compare(HINTS) == 0)
+ if(key.compare("vertex") == 0 || key.compare("fragment") == 0 || key.compare("defines") == 0 || key.compare(HINTS) == 0)
{
continue;
}
- else if (key.compare("rendererState") == 0)
+ else if(key.compare("rendererState") == 0)
{
shaderDef.mRendererState = ReadRendererState(keyValue.second);
}
- else if (value.GetType() == TreeNode::INTEGER || value.GetType() == TreeNode::FLOAT)
+ else if(value.GetType() == TreeNode::INTEGER || value.GetType() == TreeNode::FLOAT)
{
float f = 0.f;
ReadFloat(&value, f);
uniformValue = f;
}
- else if (value.GetType() == TreeNode::BOOLEAN)
+ else if(value.GetType() == TreeNode::BOOLEAN)
{
DALI_LOG_WARNING("\"bool\" uniforms are handled as floats in shader");
bool value = false;
- if (ReadBool(&keyValue.second, value))
+ if(ReadBool(&keyValue.second, value))
{
uniformValue = value ? 1.0f : 0.0f;
}
}
- else switch (auto size = GetNumericalArraySize(&value))
- {
- case 16:
- {
- Matrix m;
- ReadVector(&value, m.AsFloat(), size);
- uniformValue = m;
- break;
- }
+ else
+ switch(auto size = GetNumericalArraySize(&value))
+ {
+ case 16:
+ {
+ Matrix m;
+ ReadVector(&value, m.AsFloat(), size);
+ uniformValue = m;
+ break;
+ }
- case 9:
- {
- Matrix3 m;
- ReadVector(&value, m.AsFloat(), size);
- uniformValue = m;
- break;
- }
+ case 9:
+ {
+ Matrix3 m;
+ ReadVector(&value, m.AsFloat(), size);
+ uniformValue = m;
+ break;
+ }
- case 4:
- {
- Vector4 v;
- ReadVector(&value, v.AsFloat(), size);
- uniformValue = v;
- break;
- }
+ case 4:
+ {
+ Vector4 v;
+ ReadVector(&value, v.AsFloat(), size);
+ uniformValue = v;
+ break;
+ }
- case 3:
- {
- Vector3 v;
- ReadVector(&value, v.AsFloat(), size);
- uniformValue = v;
- break;
- }
+ case 3:
+ {
+ Vector3 v;
+ ReadVector(&value, v.AsFloat(), size);
+ uniformValue = v;
+ break;
+ }
- case 2:
- {
- Vector2 v;
- ReadVector(&value, v.AsFloat(), size);
- uniformValue = v;
- break;
- }
+ case 2:
+ {
+ Vector2 v;
+ ReadVector(&value, v.AsFloat(), size);
+ uniformValue = v;
+ break;
+ }
- default:
- mOnError(FormatString(
- "shader %d: Ignoring uniform '%s': failed to infer type from %d elements.",
- iShader, key.c_str()));
- break;
- }
+ default:
+ mOnError(FormatString(
+ "shader %d: Ignoring uniform '%s': failed to infer type from %d elements.",
+ iShader,
+ key.c_str()));
+ break;
+ }
- if (Property::NONE != uniformValue.GetType())
+ if(Property::NONE != uniformValue.GetType())
{
shaderDef.mUniforms.Insert(key, uniformValue);
}
}
else
{
- ExceptionFlinger(ASSERT_LOCATION) << "shader " << iShader <<
- ": Missing vertex / fragment shader definition.";
+ ExceptionFlinger(ASSERT_LOCATION) << "shader " << iShader << ": Missing vertex / fragment shader definition.";
}
}
}
void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resources)
{
- for (auto i0 = meshes->CBegin(), i1 = meshes->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = meshes->CBegin(), i1 = meshes->CEnd(); i0 != i1; ++i0)
{
auto& node = (*i0).second;
- MeshDefinition meshDef;
- if (!ReadString(node.GetChild(URI), meshDef.mUri))
+ MeshDefinition meshDef;
+ if(!ReadString(node.GetChild(URI), meshDef.mUri))
{
- ExceptionFlinger(ASSERT_LOCATION) << "mesh " << resources.mMeshes.size() <<
- ": Missing required attribute '" << URI << "'.";
+ ExceptionFlinger(ASSERT_LOCATION) << "mesh " << resources.mMeshes.size() << ": Missing required attribute '" << URI << "'.";
}
ToUnixFileSeparators(meshDef.mUri);
std::string primitive;
- if (ReadString(node.GetChild("primitive"), primitive))
+ if(ReadString(node.GetChild("primitive"), primitive))
{
- if (primitive == "LINES")
+ if(primitive == "LINES")
{
meshDef.mPrimitiveType = Geometry::LINES;
}
- else if (primitive == "POINTS")
+ else if(primitive == "POINTS")
{
meshDef.mPrimitiveType = Geometry::POINTS;
}
- else if (primitive != "TRIANGLES")
+ else if(primitive != "TRIANGLES")
{
mOnError(FormatString(
"mesh %d: Using TRIANGLES instead of unsupported primitive type '%s'.",
- resources.mMeshes.size(), primitive.c_str()));
+ resources.mMeshes.size(),
+ primitive.c_str()));
}
}
int attributes;
- if (ReadInt(node.GetChild("attributes"), attributes))
+ if(ReadInt(node.GetChild("attributes"), attributes))
{
- if (MaskMatch(attributes, MeshDefinition::INDICES) &&
- !ReadAttribAccessor(node.GetChild("indices"), meshDef.mIndices))
+ if(MaskMatch(attributes, MeshDefinition::INDICES) &&
+ !ReadAttribAccessor(node.GetChild("indices"), meshDef.mIndices))
{
ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
- resources.mMeshes.size(), "indices");
+ resources.mMeshes.size(),
+ "indices");
}
- if (MaskMatch(attributes, MeshDefinition::POSITIONS) &&
- !ReadAttribAccessor(node.GetChild("positions"), meshDef.mPositions))
+ if(MaskMatch(attributes, MeshDefinition::POSITIONS) &&
+ !ReadAttribAccessor(node.GetChild("positions"), meshDef.mPositions))
{
ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
- resources.mMeshes.size(), "positions");
+ resources.mMeshes.size(),
+ "positions");
}
- if (MaskMatch(attributes, MeshDefinition::NORMALS) &&
- !ReadAttribAccessor(node.GetChild("normals"), meshDef.mNormals))
+ if(MaskMatch(attributes, MeshDefinition::NORMALS) &&
+ !ReadAttribAccessor(node.GetChild("normals"), meshDef.mNormals))
{
- mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(),
- "normals"));
+ mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "normals"));
}
- if (MaskMatch(attributes, MeshDefinition::TEX_COORDS) &&
- !ReadAttribAccessor(node.GetChild("textures"), meshDef.mTexCoords))
+ if(MaskMatch(attributes, MeshDefinition::TEX_COORDS) &&
+ !ReadAttribAccessor(node.GetChild("textures"), meshDef.mTexCoords))
{
- mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(),
- "textures"));
+ mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "textures"));
}
- if (MaskMatch(attributes, MeshDefinition::TANGENTS) &&
- !ReadAttribAccessor(node.GetChild("tangents"), meshDef.mTangents))
+ if(MaskMatch(attributes, MeshDefinition::TANGENTS) &&
+ !ReadAttribAccessor(node.GetChild("tangents"), meshDef.mTangents))
{
- mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(),
- "tangents"));
+ mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "tangents"));
}
// NOTE: we're no longer reading bitangents as these are calculated in the shaders.
- if (ReadIndex(node.GetChild("skeleton"), meshDef.mSkeletonIdx))
+ if(ReadIndex(node.GetChild("skeleton"), meshDef.mSkeletonIdx))
{
- if (!MaskMatch(attributes, MeshDefinition::JOINTS_0) &&
- !MaskMatch(attributes, MeshDefinition::WEIGHTS_0))
+ if(!MaskMatch(attributes, MeshDefinition::JOINTS_0) &&
+ !MaskMatch(attributes, MeshDefinition::WEIGHTS_0))
{
mOnError(FormatString("mesh %d: Expected joints0 / weights0 attribute(s) missing.",
- resources.mMeshes.size()));
+ resources.mMeshes.size()));
}
- else if (!ReadAttribAccessor(node.GetChild("joints0"), meshDef.mJoints0) ||
- !ReadAttribAccessor(node.GetChild("weights0"), meshDef.mWeights0))
+ else if(!ReadAttribAccessor(node.GetChild("joints0"), meshDef.mJoints0) ||
+ !ReadAttribAccessor(node.GetChild("weights0"), meshDef.mWeights0))
{
mOnError(FormatString("mesh %d: Failed to read skinning information.",
- resources.mMeshes.size()));
+ resources.mMeshes.size()));
}
}
- if (auto blendshapeHeader = node.GetChild(BLEND_SHAPE_HEADER))
+ if(auto blendshapeHeader = node.GetChild(BLEND_SHAPE_HEADER))
{
std::string blendShapeVersion;
ReadString(blendshapeHeader->GetChild(VERSION), blendShapeVersion);
- if (0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_1_0))
+ if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_1_0))
{
meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_1_0;
}
- else if (0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_2_0))
+ else if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_2_0))
{
meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
}
- switch (meshDef.mBlendShapeVersion)
+ switch(meshDef.mBlendShapeVersion)
{
case BlendShapes::Version::VERSION_1_0:
case BlendShapes::Version::VERSION_2_0: // FALL THROUGH
}
}
- if (auto blendShapes = node.GetChild(BLEND_SHAPES) )
+ if(auto blendShapes = node.GetChild(BLEND_SHAPES))
{
meshDef.mBlendShapes.resize(blendShapes->Size());
auto index = 0u;
- for (auto it = blendShapes->CBegin(), endIt = blendShapes->CEnd(); it != endIt; ++it, ++index)
+ for(auto it = blendShapes->CBegin(), endIt = blendShapes->CEnd(); it != endIt; ++it, ++index)
{
// Each blend shape is stored as the difference with the original mesh.
auto& blendShape = meshDef.mBlendShapes[index];
ReadString(blendShapeNode.GetChild("name"), blendShape.name);
- if (auto position = blendShapeNode.GetChild("positions"))
+ if(auto position = blendShapeNode.GetChild("positions"))
{
ReadAttribAccessor(position, blendShape.deltas);
}
- if (auto normals = blendShapeNode.GetChild("normals"))
+ if(auto normals = blendShapeNode.GetChild("normals"))
{
ReadAttribAccessor(normals, blendShape.normals);
}
- if (auto tangents = blendShapeNode.GetChild("tangents"))
+ if(auto tangents = blendShapeNode.GetChild("tangents"))
{
ReadAttribAccessor(tangents, blendShape.tangents);
}
}
bool flipV;
- if (ReadBool(node.GetChild("flipV"), flipV))
+ if(ReadBool(node.GetChild("flipV"), flipV))
{
meshDef.mFlags |= flipV * MeshDefinition::FLIP_UVS_VERTICAL;
}
}
}
-void DliLoader::Impl::ParseMaterials(const TreeNode* materials, ConvertColorCode convertColorCode,
- ResourceBundle& resources)
+void DliLoader::Impl::ParseMaterials(const TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources)
{
- for (auto i0 = materials->CBegin(), i1 = materials->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = materials->CBegin(), i1 = materials->CEnd(); i0 != i1; ++i0)
{
auto& node = (*i0).second;
MaterialDefinition materialDef;
- if (auto eEnvironment = node.GetChild("environment"))
+ if(auto eEnvironment = node.GetChild("environment"))
{
ReadIndex(eEnvironment, materialDef.mEnvironmentIdx);
- if (static_cast<unsigned int>(materialDef.mEnvironmentIdx) >= resources.mEnvironmentMaps.size())
+ if(static_cast<unsigned int>(materialDef.mEnvironmentIdx) >= resources.mEnvironmentMaps.size())
{
- ExceptionFlinger(ASSERT_LOCATION) << "material " << resources.mMaterials.size() <<
- ": Environment index " << materialDef.mEnvironmentIdx << " out of bounds (" <<
- resources.mEnvironmentMaps.size() << ").";
+ ExceptionFlinger(ASSERT_LOCATION) << "material " << resources.mMaterials.size() << ": Environment index " << materialDef.mEnvironmentIdx << " out of bounds (" << resources.mEnvironmentMaps.size() << ").";
}
}
//TODO : need to consider AGIF
std::vector<std::string> texturePaths;
- std::string texturePath;
- if (ReadString(node.GetChild("albedoMap"), texturePath))
+ std::string texturePath;
+ if(ReadString(node.GetChild("albedoMap"), texturePath))
{
ToUnixFileSeparators(texturePath);
const auto semantic = MaterialDefinition::ALBEDO;
- materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } });
- materialDef.mFlags |= semantic | MaterialDefinition::TRANSPARENCY; // NOTE: only in dli does single / separate ALBEDO texture mean TRANSPARENCY.
+ materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
+ materialDef.mFlags |= semantic | MaterialDefinition::TRANSPARENCY; // NOTE: only in dli does single / separate ALBEDO texture mean TRANSPARENCY.
}
- if (ReadString(node.GetChild("albedoMetallicMap"), texturePath))
+ if(ReadString(node.GetChild("albedoMetallicMap"), texturePath))
{
ToUnixFileSeparators(texturePath);
- if (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO))
+ if(MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO))
{
mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "albedo"));
}
const auto semantic = MaterialDefinition::ALBEDO | MaterialDefinition::METALLIC;
- materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } });
+ materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
materialDef.mFlags |= semantic;
}
- if (ReadString(node.GetChild("metallicRoughnessMap"), texturePath))
+ if(ReadString(node.GetChild("metallicRoughnessMap"), texturePath))
{
ToUnixFileSeparators(texturePath);
- if (MaskMatch(materialDef.mFlags, MaterialDefinition::METALLIC))
+ if(MaskMatch(materialDef.mFlags, MaterialDefinition::METALLIC))
{
mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "metallic"));
}
const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS;
- materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } });
+ materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
materialDef.mFlags |= semantic |
- // We have a metallic-roughhness map and the first texture did not have albedo semantics - we're in the transparency workflow.
- (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
+ // We have a metallic-roughhness map and the first texture did not have albedo semantics - we're in the transparency workflow.
+ (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
}
- if (ReadString(node.GetChild("normalMap"), texturePath))
+ if(ReadString(node.GetChild("normalMap"), texturePath))
{
ToUnixFileSeparators(texturePath);
const auto semantic = MaterialDefinition::NORMAL;
- materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } });
+ materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
materialDef.mFlags |= semantic |
- // We have a standalone normal map and the first texture did not have albedo semantics - we're in the transparency workflow.
- (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
+ // We have a standalone normal map and the first texture did not have albedo semantics - we're in the transparency workflow.
+ (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
}
- if (ReadString(node.GetChild("normalRoughnessMap"), texturePath))
+ if(ReadString(node.GetChild("normalRoughnessMap"), texturePath))
{
ToUnixFileSeparators(texturePath);
- if (MaskMatch(materialDef.mFlags, MaterialDefinition::NORMAL))
+ if(MaskMatch(materialDef.mFlags, MaterialDefinition::NORMAL))
{
mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "normal"));
}
- if (MaskMatch(materialDef.mFlags, MaterialDefinition::ROUGHNESS))
+ if(MaskMatch(materialDef.mFlags, MaterialDefinition::ROUGHNESS))
{
mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "roughness"));
}
- if (MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY))
+ if(MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY))
{
mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "transparency"));
}
const auto semantic = MaterialDefinition::NORMAL | MaterialDefinition::ROUGHNESS;
- materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } });
+ materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
materialDef.mFlags |= semantic;
}
- if (ReadString(node.GetChild("subsurfaceMap"), texturePath))
+ if(ReadString(node.GetChild("subsurfaceMap"), texturePath))
{
ToUnixFileSeparators(texturePath);
const auto semantic = MaterialDefinition::SUBSURFACE;
- materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } });
+ materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
materialDef.mFlags |= semantic;
}
- if (ReadColorCodeOrColor(&node, materialDef.mColor, convertColorCode) &&
- materialDef.mColor.a < 1.0f)
+ if(ReadColorCodeOrColor(&node, materialDef.mColor, convertColorCode) &&
+ materialDef.mColor.a < 1.0f)
{
materialDef.mFlags |= MaterialDefinition::TRANSPARENCY;
}
ReadFloat(node.GetChild("roughness"), materialDef.mRoughness);
bool mipmaps;
- if (ReadBool(node.GetChild("mipmap"), mipmaps) && mipmaps)
+ if(ReadBool(node.GetChild("mipmap"), mipmaps) && mipmaps)
{
- for (auto& ts : materialDef.mTextureStages)
+ for(auto& ts : materialDef.mTextureStages)
{
ts.mTexture.mSamplerFlags |= SamplerFlags::FILTER_MIPMAP_LINEAR;
}
virtual bool Map(Index iDli, Index iScene) override
{
- Entry idx{ iDli, iScene };
- auto iInsert = std::lower_bound(mIndices.begin(), mIndices.end(), idx);
- if (iInsert == mIndices.end() || iInsert->iDli != iDli)
+ Entry idx{iDli, iScene};
+ auto iInsert = std::lower_bound(mIndices.begin(), mIndices.end(), idx);
+ if(iInsert == mIndices.end() || iInsert->iDli != iDli)
{
mIndices.insert(iInsert, idx);
}
- else if (iInsert->iScene != iScene)
+ else if(iInsert->iScene != iScene)
{
return false;
}
virtual unsigned int Resolve(Index iDli) override
{
- auto iFind = std::lower_bound(mIndices.begin(), mIndices.end(), iDli,
- [](const Entry& idx, Index iDli) {
- return idx.iDli < iDli;
- });
+ auto iFind = std::lower_bound(mIndices.begin(), mIndices.end(), iDli, [](const Entry& idx, Index iDli) {
+ return idx.iDli < iDli;
+ });
DALI_ASSERT_ALWAYS(iFind != mIndices.end());
return iFind->iScene;
}
ParseNodesInternal(nodes, index, parents, params, mapper);
auto& scene = params.output.mScene;
- for (size_t i0 = 0, i1 = scene.GetNodeCount(); i0 < i1; ++i0)
+ for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 < i1; ++i0)
{
- for (auto& c : scene.GetNode(i0)->mConstraints)
+ for(auto& c : scene.GetNode(i0)->mConstraints)
{
c.mSourceIdx = mapper.Resolve(c.mSourceIdx);
}
}
}
-void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index index,
- std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& mapper)
+void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index index, std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& mapper)
{
// Properties that may be resolved from a JSON value with ReadInt() -- or default to 0.
- struct IndexProperty { ResourceType::Value type; const TreeNode* source; Index& target; };
+ struct IndexProperty
+ {
+ ResourceType::Value type;
+ const TreeNode* source;
+ Index& target;
+ };
std::vector<IndexProperty> resourceIds;
resourceIds.reserve(4);
- if (auto node = GetNthChild(nodes, index))
+ if(auto node = GetNthChild(nodes, index))
{
NodeDefinition nodeDef;
nodeDef.mParentIdx = inOutParentStack.empty() ? INVALID_INDEX : inOutParentStack.back();
// not successful then reads it as a vector2.
ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 3) ||
ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 2) ||
- ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 3) ||
- ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 2);
+ ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 3) ||
+ ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 2);
// visibility
ReadBool(node->GetChild("visible"), nodeDef.mIsVisible);
// type classification
- if (auto eCustomization = node->GetChild("customization")) // customization
+ if(auto eCustomization = node->GetChild("customization")) // customization
{
std::string tag;
- if (ReadString(eCustomization->GetChild("tag"), tag))
+ if(ReadString(eCustomization->GetChild("tag"), tag))
{
- nodeDef.mCustomization.reset(new NodeDefinition::CustomizationDefinition{ tag });
+ nodeDef.mCustomization.reset(new NodeDefinition::CustomizationDefinition{tag});
}
}
else // something renderable maybe
{
std::unique_ptr<NodeDefinition::Renderable> renderable;
- ModelNode* modelNode = nullptr; // no ownership, aliasing renderable for the right type.
+ ModelNode* modelNode = nullptr; // no ownership, aliasing renderable for the right type.
- const TreeNode* eRenderable = nullptr;
- if ((eRenderable = node->GetChild("model")))
+ const TreeNode* eRenderable = nullptr;
+ if((eRenderable = node->GetChild("model")))
{
// check for mesh before allocating - this can't be missing.
auto eMesh = eRenderable->GetChild("mesh");
- if (!eMesh)
+ if(!eMesh)
{
ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
}
modelNode = new ModelNode();
renderable.reset(modelNode);
- resourceIds.push_back({ ResourceType::Mesh, eMesh, modelNode->mMeshIdx });
+ resourceIds.push_back({ResourceType::Mesh, eMesh, modelNode->mMeshIdx});
}
- else if ((eRenderable = node->GetChild("arc")))
+ else if((eRenderable = node->GetChild("arc")))
{
// check for mesh before allocating - this can't be missing.
auto eMesh = eRenderable->GetChild("mesh");
- if (!eMesh)
+ if(!eMesh)
{
ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
}
renderable.reset(arcNode);
modelNode = arcNode;
- resourceIds.push_back({ ResourceType::Mesh, eMesh, arcNode->mMeshIdx });
+ resourceIds.push_back({ResourceType::Mesh, eMesh, arcNode->mMeshIdx});
ReadArcField(eRenderable, *arcNode);
}
- if (renderable) // process common properties of all renderables + register payload
+ if(renderable) // process common properties of all renderables + register payload
{
// shader
renderable->mShaderIdx = 0;
- auto eShader = eRenderable->GetChild("shader");
- resourceIds.push_back({ ResourceType::Shader, eShader, renderable->mShaderIdx });
+ auto eShader = eRenderable->GetChild("shader");
+ resourceIds.push_back({ResourceType::Shader, eShader, renderable->mShaderIdx});
// color
- if (modelNode)
+ if(modelNode)
{
- modelNode->mMaterialIdx = 0; // must offer default of 0
- auto eMaterial = eRenderable->GetChild("material");
- resourceIds.push_back({ ResourceType::Material, eMaterial, modelNode->mMaterialIdx });
+ modelNode->mMaterialIdx = 0; // must offer default of 0
+ auto eMaterial = eRenderable->GetChild("material");
+ resourceIds.push_back({ResourceType::Material, eMaterial, modelNode->mMaterialIdx});
- if (!ReadColorCodeOrColor(eRenderable, modelNode->mColor, params.input.mConvertColorCode))
+ if(!ReadColorCodeOrColor(eRenderable, modelNode->mColor, params.input.mConvertColorCode))
{
ReadColorCodeOrColor(node, modelNode->mColor, params.input.mConvertColorCode);
}
// Resolve ints - default to 0 if undefined
auto& output = params.output;
- for (auto& idRes : resourceIds)
+ for(auto& idRes : resourceIds)
{
Index iCheck = 0;
- switch (idRes.type)
+ switch(idRes.type)
{
- case ResourceType::Shader:
- iCheck = output.mResources.mShaders.size();
- break;
+ case ResourceType::Shader:
+ iCheck = output.mResources.mShaders.size();
+ break;
- case ResourceType::Mesh:
- iCheck = output.mResources.mMeshes.size();
- break;
+ case ResourceType::Mesh:
+ iCheck = output.mResources.mMeshes.size();
+ break;
- case ResourceType::Material:
- iCheck = output.mResources.mMaterials.size();
- break;
+ case ResourceType::Material:
+ iCheck = output.mResources.mMaterials.size();
+ break;
- default:
- ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid resource type: " <<
- idRes.type << " (Programmer error)";
+ default:
+ ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid resource type: " << idRes.type << " (Programmer error)";
}
- if (!idRes.source)
+ if(!idRes.source)
{
idRes.target = 0;
}
- else if (idRes.source->GetType() != TreeNode::INTEGER)
+ else if(idRes.source->GetType() != TreeNode::INTEGER)
{
- ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid " <<
- GetResourceTypeName(idRes.type) << " index type.";
+ ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid " << GetResourceTypeName(idRes.type) << " index type.";
}
else
{
idRes.target = idRes.source->GetInteger();
}
- if (idRes.target >= iCheck)
+ if(idRes.target >= iCheck)
{
- ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": " <<
- GetResourceTypeName(idRes.type) << " index " << idRes.target << " out of bounds (" <<
- iCheck << ").";
+ ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": " << GetResourceTypeName(idRes.type) << " index " << idRes.target << " out of bounds (" << iCheck << ").";
}
}
resourceIds.clear();
// Extra properties
- if (auto eExtras = node->GetChild("extras"))
+ if(auto eExtras = node->GetChild("extras"))
{
auto& extras = nodeDef.mExtras;
extras.reserve(eExtras->Size());
NodeDefinition::Extra e;
- for (auto i0 = eExtras->CBegin(), i1 = eExtras->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = eExtras->CBegin(), i1 = eExtras->CEnd(); i0 != i1; ++i0)
{
auto eExtra = *i0;
- e.mKey = eExtra.first;
- if (e.mKey.empty())
+ e.mKey = eExtra.first;
+ if(e.mKey.empty())
{
mOnError(FormatString("node %d: empty string is invalid for name of extra %d; ignored.",
- index, extras.size()));
+ index,
+ extras.size()));
continue;
}
e.mValue = ReadPropertyValue(eExtra.second);
- if (e.mValue.GetType() == Property::Type::NONE)
+ if(e.mValue.GetType() == Property::Type::NONE)
{
mOnError(FormatString("node %d: failed to interpret value of extra '%s' : %s; ignored.",
- index, e.mKey.c_str(), eExtra.second.GetString()));
+ index,
+ e.mKey.c_str(),
+ eExtra.second.GetString()));
}
else
{
auto iInsert = std::lower_bound(extras.begin(), extras.end(), e);
- if (iInsert != extras.end() && iInsert->mKey == e.mKey)
+ if(iInsert != extras.end() && iInsert->mKey == e.mKey)
{
mOnError(FormatString("node %d: extra '%s' already defined; overriding with %s.",
- index, e.mKey.c_str(), eExtra.second.GetString()));
+ index,
+ e.mKey.c_str(),
+ eExtra.second.GetString()));
*iInsert = std::move(e);
}
else
}
// Constraints
- if (auto eConstraints = node->GetChild("constraints"))
+ if(auto eConstraints = node->GetChild("constraints"))
{
auto& constraints = nodeDef.mConstraints;
constraints.reserve(eConstraints->Size());
ConstraintDefinition cDef;
- for (auto i0 = eConstraints->CBegin(), i1 = eConstraints->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = eConstraints->CBegin(), i1 = eConstraints->CEnd(); i0 != i1; ++i0)
{
auto eConstraint = *i0;
- if (!ReadIndex(&eConstraint.second, cDef.mSourceIdx))
+ if(!ReadIndex(&eConstraint.second, cDef.mSourceIdx))
{
mOnError(FormatString("node %d: node ID %s for constraint %d is invalid; ignored.",
- index, eConstraint.second.GetString(), constraints.size()));
+ index,
+ eConstraint.second.GetString(),
+ constraints.size()));
}
else
{
cDef.mProperty = eConstraint.first;
auto iInsert = std::lower_bound(constraints.begin(), constraints.end(), cDef);
- if (iInsert != constraints.end() && *iInsert == cDef)
+ if(iInsert != constraints.end() && *iInsert == cDef)
{
mOnError(FormatString("node %d: constraint %s@%d already defined; ignoring.",
- index, cDef.mProperty.c_str(), cDef.mSourceIdx));
+ index,
+ cDef.mProperty.c_str(),
+ cDef.mSourceIdx));
}
else
{
// Determine index for mapping
const unsigned int myIndex = output.mScene.GetNodeCount();
- if (!mapper.Map(index, myIndex))
+ if(!mapper.Map(index, myIndex))
{
mOnError(FormatString("node %d: error mapping dli index %d: node has multiple parents. Ignoring subtree."));
return;
}
// if the node is a bone in a skeletal animation, it will have the inverse bind pose matrix.
- Matrix invBindMatrix{ false };
- if (ReadVector(node->GetChild("inverseBindPoseMatrix"), invBindMatrix.AsFloat(), 16u)) // TODO: more robust error checking?
+ Matrix invBindMatrix{false};
+ if(ReadVector(node->GetChild("inverseBindPoseMatrix"), invBindMatrix.AsFloat(), 16u)) // TODO: more robust error checking?
{
mInverseBindMatrices[myIndex] = invBindMatrix;
}
// Register nodeDef
auto rawDef = output.mScene.AddNode(std::make_unique<NodeDefinition>(std::move(nodeDef)));
- if (rawDef) // NOTE: no ownership. Guaranteed to stay in scope.
+ if(rawDef) // NOTE: no ownership. Guaranteed to stay in scope.
{
// ...And only then parse children.
- if (auto children = node->GetChild("children"))
+ if(auto children = node->GetChild("children"))
{
inOutParentStack.push_back(myIndex);
rawDef->mChildren.reserve(children->Size());
uint32_t iChild = 0;
- for (auto j0 = children->CBegin(), j1 = children->CEnd(); j0 != j1; ++j0, ++iChild)
+ for(auto j0 = children->CBegin(), j1 = children->CEnd(); j0 != j1; ++j0, ++iChild)
{
auto& child = (*j0).second;
- if (child.GetType() == TreeNode::INTEGER)
+ if(child.GetType() == TreeNode::INTEGER)
{
ParseNodesInternal(nodes, child.GetInteger(), inOutParentStack, params, mapper); // child object is created in scene definition.
}
else
{
- ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ", child " << iChild <<
- ": invalid index type.";
+ ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ", child " << iChild << ": invalid index type.";
}
}
inOutParentStack.pop_back();
}
- else if (rawDef->mCustomization)
+ else if(rawDef->mCustomization)
{
mOnError(FormatString("node %d: not an actual customization without children.", index));
}
- if (auto proc = params.input.mNodePropertyProcessor) // optional processing
+ if(auto proc = params.input.mNodePropertyProcessor) // optional processing
{
// WARNING: constraint IDs are not resolved at this point.
Property::Map nodeData;
auto& definitions = params.output.mAnimationDefinitions;
definitions.reserve(definitions.size() + tnAnimations->Size());
- for (TreeNode::ConstIterator iAnim = tnAnimations->CBegin(), iAnimEnd = tnAnimations->CEnd();
- iAnim != iAnimEnd; ++iAnim)
+ for(TreeNode::ConstIterator iAnim = tnAnimations->CBegin(), iAnimEnd = tnAnimations->CEnd();
+ iAnim != iAnimEnd;
+ ++iAnim)
{
- const TreeNode& tnAnim = (*iAnim).second;
+ const TreeNode& tnAnim = (*iAnim).second;
AnimationDefinition animDef;
ReadString(tnAnim.GetChild(NAME), animDef.mName);
- auto iFind = std::lower_bound(definitions.begin(), definitions.end(), animDef,
- [](const AnimationDefinition& ad0, const AnimationDefinition& ad1) {
+ auto iFind = std::lower_bound(definitions.begin(), definitions.end(), animDef, [](const AnimationDefinition& ad0, const AnimationDefinition& ad1) {
return ad0.mName < ad1.mName;
});
const bool overwrite = iFind != definitions.end() && iFind->mName == animDef.mName;
- if (overwrite)
+ if(overwrite)
{
mOnError(FormatString("Pre-existing animation with name '%s' is being overwritten.", animDef.mName.c_str()));
}
// than our frame delay) to not be restrictive WRT replaying. If anything needs
// to occur more frequently, then Animations are likely not your solution anyway.
animDef.mDuration = AnimationDefinition::MIN_DURATION_SECONDS;
- if (!ReadFloat(tnAnim.GetChild("duration"), animDef.mDuration))
+ if(!ReadFloat(tnAnim.GetChild("duration"), animDef.mDuration))
{
mOnError(FormatString("Animation '%s' fails to define '%s', defaulting to %f.",
- animDef.mName.c_str(), "duration", animDef.mDuration));
+ animDef.mName.c_str(),
+ "duration",
+ animDef.mDuration));
}
// Get loop count - # of playbacks. Default is once. 0 means repeat indefinitely.
animDef.mLoopCount = 1;
- if (ReadInt(tnAnim.GetChild("loopCount"), animDef.mLoopCount) &&
- animDef.mLoopCount < 0)
+ if(ReadInt(tnAnim.GetChild("loopCount"), animDef.mLoopCount) &&
+ animDef.mLoopCount < 0)
{
animDef.mLoopCount = 0;
}
std::string endAction;
- if (ReadString(tnAnim.GetChild("endAction"), endAction))
+ if(ReadString(tnAnim.GetChild("endAction"), endAction))
{
- if ("BAKE" == endAction)
+ if("BAKE" == endAction)
{
animDef.mEndAction = Animation::BAKE;
}
- else if ("DISCARD" == endAction)
+ else if("DISCARD" == endAction)
{
animDef.mEndAction = Animation::DISCARD;
}
- else if ("BAKE_FINAL" == endAction)
+ else if("BAKE_FINAL" == endAction)
{
animDef.mEndAction = Animation::BAKE_FINAL;
}
}
- if (ReadString(tnAnim.GetChild("disconnectAction"), endAction))
+ if(ReadString(tnAnim.GetChild("disconnectAction"), endAction))
{
- if ("BAKE" == endAction)
+ if("BAKE" == endAction)
{
animDef.mDisconnectAction = Animation::BAKE;
}
- else if ("DISCARD" == endAction)
+ else if("DISCARD" == endAction)
{
animDef.mDisconnectAction = Animation::DISCARD;
}
- else if ("BAKE_FINAL" == endAction)
+ else if("BAKE_FINAL" == endAction)
{
animDef.mDisconnectAction = Animation::BAKE_FINAL;
}
}
- if (const TreeNode* tnProperties = tnAnim.GetChild("properties"))
+ if(const TreeNode* tnProperties = tnAnim.GetChild("properties"))
{
animDef.mProperties.reserve(tnProperties->Size());
- for (TreeNode::ConstIterator iProperty = tnProperties->CBegin(), iPropertyEnd = tnProperties->CEnd();
- iProperty != iPropertyEnd; ++iProperty)
+ for(TreeNode::ConstIterator iProperty = tnProperties->CBegin(), iPropertyEnd = tnProperties->CEnd();
+ iProperty != iPropertyEnd;
+ ++iProperty)
{
- const TreeNode &tnProperty = (*iProperty).second;
+ const TreeNode& tnProperty = (*iProperty).second;
AnimatedProperty animProp;
- if (!ReadString(tnProperty.GetChild("node"), animProp.mNodeName))
+ if(!ReadString(tnProperty.GetChild("node"), animProp.mNodeName))
{
mOnError(FormatString("Animation '%s': Failed to read the 'node' tag.", animDef.mName.c_str()));
continue;
}
- if (!ReadString(tnProperty.GetChild("property"), animProp.mPropertyName))
+ if(!ReadString(tnProperty.GetChild("property"), animProp.mPropertyName))
{
mOnError(FormatString("Animation '%s': Failed to read the 'property' tag", animDef.mName.c_str()));
continue;
}
// these are the defaults
- animProp.mTimePeriod.delaySeconds = 0.f;
+ animProp.mTimePeriod.delaySeconds = 0.f;
animProp.mTimePeriod.durationSeconds = animDef.mDuration;
- if (!ReadTimePeriod(tnProperty.GetChild("timePeriod"), animProp.mTimePeriod))
+ if(!ReadTimePeriod(tnProperty.GetChild("timePeriod"), animProp.mTimePeriod))
{
mOnError(FormatString("Animation '%s': timePeriod missing in Property #%d: defaulting to %f.",
- animDef.mName.c_str(), animDef.mProperties.size(), animProp.mTimePeriod.durationSeconds));
+ animDef.mName.c_str(),
+ animDef.mProperties.size(),
+ animProp.mTimePeriod.durationSeconds));
}
std::string alphaFunctionValue;
- if (ReadString(tnProperty.GetChild("alphaFunction"), alphaFunctionValue))
+ if(ReadString(tnProperty.GetChild("alphaFunction"), alphaFunctionValue))
{
animProp.mAlphaFunction = GetAlphaFunction(alphaFunctionValue);
}
- if (const TreeNode* tnKeyFramesBin = tnProperty.GetChild("keyFramesBin"))
+ if(const TreeNode* tnKeyFramesBin = tnProperty.GetChild("keyFramesBin"))
{
DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
std::ifstream binAniFile;
- std::string animationFilename;
- if (ReadString(tnKeyFramesBin->GetChild(URL), animationFilename))
+ std::string animationFilename;
+ if(ReadString(tnKeyFramesBin->GetChild(URL), animationFilename))
{
std::string animationFullPath = params.input.mAnimationsPath + animationFilename;
binAniFile.open(animationFullPath, std::ios::binary);
- if (binAniFile.fail())
+ if(binAniFile.fail())
{
- ExceptionFlinger(ASSERT_LOCATION) << "Failed to open animation data '" <<
- animationFullPath << "'";
+ ExceptionFlinger(ASSERT_LOCATION) << "Failed to open animation data '" << animationFullPath << "'";
}
}
//so, if it is vector3 we assume is position or scale keys, if it is vector4 we assume is rotation,
// otherwise are blend shape weight keys.
// TODO support for binary header with size information
- Property::Type propType = Property::FLOAT; // assume blend shape weights
- if (animProp.mPropertyName == "orientation")
+ Property::Type propType = Property::FLOAT; // assume blend shape weights
+ if(animProp.mPropertyName == "orientation")
{
propType = Property::VECTOR4;
}
- else if ((animProp.mPropertyName == "position") || (animProp.mPropertyName == "scale"))
+ else if((animProp.mPropertyName == "position") || (animProp.mPropertyName == "scale"))
{
propType = Property::VECTOR3;
}
// NOTE: right now we're just using AlphaFunction::LINEAR.
unsigned char dummyAlphaFunction;
- float progress;
+ float progress;
Property::Value propValue;
- for (int key = 0; key < numKeys; key++)
+ for(int key = 0; key < numKeys; key++)
{
binAniFile.read(reinterpret_cast<char*>(&progress), sizeof(float));
- if (propType == Property::VECTOR3)
+ if(propType == Property::VECTOR3)
{
Vector3 value;
binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 3);
propValue = Property::Value(value);
}
- else if (propType == Property::VECTOR4)
+ else if(propType == Property::VECTOR4)
{
Vector4 value;
binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 4);
animProp.mKeyFrames.Add(progress, propValue, AlphaFunction::LINEAR);
}
}
- else if (const TreeNode* tnKeyFrames = tnProperty.GetChild("keyFrames"))
+ else if(const TreeNode* tnKeyFrames = tnProperty.GetChild("keyFrames"))
{
DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
animProp.mKeyFrames = KeyFrames::New();
float progress = 0.0f;
- for (auto i0 = tnKeyFrames->CBegin(), i1 = tnKeyFrames->CEnd(); i1 != i0; ++i0)
+ for(auto i0 = tnKeyFrames->CBegin(), i1 = tnKeyFrames->CEnd(); i1 != i0; ++i0)
{
const TreeNode::KeyNodePair& kfKeyChild = *i0;
- bool readResult = ReadFloat(kfKeyChild.second.GetChild("progress"), progress);
+ bool readResult = ReadFloat(kfKeyChild.second.GetChild("progress"), progress);
DALI_ASSERT_ALWAYS(readResult && "Key frame entry must have 'progress'");
const TreeNode* tnValue = kfKeyChild.second.GetChild("value");
// For the "orientation" property, convert from Vector4 -> Rotation value
// This work-around is preferable to a null-pointer exception in the DALi update thread
Property::Value propValue(ReadPropertyValue(*tnValue));
- if (propValue.GetType() == Property::VECTOR4 &&
- animProp.mPropertyName == "orientation")
+ if(propValue.GetType() == Property::VECTOR4 &&
+ animProp.mPropertyName == "orientation")
{
Vector4 v;
propValue.Get(v);
}
AlphaFunction kfAlphaFunction(AlphaFunction::DEFAULT);
- std::string alphaFuncStr;
- if (ReadString(kfKeyChild.second.GetChild("alphaFunction"), alphaFuncStr))
+ std::string alphaFuncStr;
+ if(ReadString(kfKeyChild.second.GetChild("alphaFunction"), alphaFuncStr))
{
kfAlphaFunction = GetAlphaFunction(alphaFuncStr);
}
else
{
const TreeNode* tnValue = tnProperty.GetChild("value");
- if (tnValue)
+ if(tnValue)
{
- animProp.mValue.reset(new AnimatedProperty::Value{ ReadPropertyValue(*tnValue) });
+ animProp.mValue.reset(new AnimatedProperty::Value{ReadPropertyValue(*tnValue)});
}
else
{
mOnError(FormatString("Property '%s' fails to define target value.",
- animProp.mPropertyName.c_str()));
+ animProp.mPropertyName.c_str()));
}
ReadBool(tnProperty.GetChild("relative"), animProp.mValue->mIsRelative);
}
}
- if (overwrite)
+ if(overwrite)
{
*iFind = std::move(animDef);
}
iFind = definitions.insert(iFind, std::move(animDef));
}
- if (auto proc = params.input.mAnimationPropertyProcessor) // optional processing
+ if(auto proc = params.input.mAnimationPropertyProcessor) // optional processing
{
Property::Map map;
ParseProperties(tnAnim, map);
auto& animGroups = params.output.mAnimationGroupDefinitions;
int numGroups = 0;
- for (auto iGroups = tnAnimationGroups->CBegin(), iGroupsEnd = tnAnimationGroups->CEnd();
- iGroups != iGroupsEnd; ++iGroups, ++numGroups)
+ for(auto iGroups = tnAnimationGroups->CBegin(), iGroupsEnd = tnAnimationGroups->CEnd();
+ iGroups != iGroupsEnd;
+ ++iGroups, ++numGroups)
{
const auto& tnGroup = *iGroups;
- auto tnName = tnGroup.second.GetChild(NAME);
+ auto tnName = tnGroup.second.GetChild(NAME);
std::string groupName;
- if (!tnName || !ReadString(tnName, groupName))
+ if(!tnName || !ReadString(tnName, groupName))
{
mOnError(FormatString("Failed to get the name for the Animation group %d; ignoring.", numGroups));
continue;
}
- auto iFind = std::lower_bound(animGroups.begin(), animGroups.end(), groupName,
- [](const AnimationGroupDefinition& group, const std::string& name) {
+ auto iFind = std::lower_bound(animGroups.begin(), animGroups.end(), groupName, [](const AnimationGroupDefinition& group, const std::string& name) {
return group.mName < name;
});
- if (iFind != animGroups.end() && iFind->mName == groupName)
+ if(iFind != animGroups.end() && iFind->mName == groupName)
{
mOnError(FormatString("Animation group with name '%s' already exists; new entries will be merged.", groupName.c_str()));
}
iFind->mName = groupName;
auto tnAnims = tnGroup.second.GetChild("animations");
- if (tnAnims && tnAnims->Size() > 0)
+ if(tnAnims && tnAnims->Size() > 0)
{
auto& anims = iFind->mAnimations;
anims.reserve(anims.size() + tnAnims->Size());
- for (auto iAnims = tnAnims->CBegin(), iAnimsEnd = tnAnims->CEnd(); iAnims != iAnimsEnd; ++iAnims)
+ for(auto iAnims = tnAnims->CBegin(), iAnimsEnd = tnAnims->CEnd(); iAnims != iAnimsEnd; ++iAnims)
{
anims.push_back((*iAnims).second.GetString());
}
void DliLoader::Impl::GetCameraParameters(std::vector<CameraParameters>& cameras) const
{
- if (const TreeNode* jsonCameras = mParser.GetRoot()->GetChild("cameras"))
+ if(const TreeNode* jsonCameras = mParser.GetRoot()->GetChild("cameras"))
{
cameras.resize(jsonCameras->Size());
auto iCamera = cameras.begin();
- for (auto i0 = jsonCameras->CBegin(), i1 = jsonCameras->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = jsonCameras->CBegin(), i1 = jsonCameras->CEnd(); i0 != i1; ++i0)
{
auto& jsonCamera = (*i0).second;
ReadFloat(jsonCamera.GetChild("fov"), iCamera->yFov);
ReadFloat(jsonCamera.GetChild("near"), iCamera->zNear);
ReadFloat(jsonCamera.GetChild("far"), iCamera->zFar);
- if (ReadVector(jsonCamera.GetChild("orthographic"), iCamera->orthographicSize.AsFloat(), 4u))
+ if(ReadVector(jsonCamera.GetChild("orthographic"), iCamera->orthographicSize.AsFloat(), 4u))
{
iCamera->isPerspective = false;
}
- if (auto jsonMatrix = jsonCamera.GetChild("matrix"))
+ if(auto jsonMatrix = jsonCamera.GetChild("matrix"))
{
ReadVector(jsonMatrix, iCamera->matrix.AsFloat(), 16u);
}
void DliLoader::Impl::GetLightParameters(std::vector<LightParameters>& lights) const
{
- if (const TreeNode* jsonLights = mParser.GetRoot()->GetChild("lights"))
+ if(const TreeNode* jsonLights = mParser.GetRoot()->GetChild("lights"))
{
lights.resize(jsonLights->Size());
auto iLight = lights.begin();
- for (auto i0 = jsonLights->CBegin(), i1 = jsonLights->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = jsonLights->CBegin(), i1 = jsonLights->CEnd(); i0 != i1; ++i0)
{
auto& jsonLight = (*i0).second;
- if (!ReadVector(jsonLight.GetChild("matrix"), iLight->transform.AsFloat(), 16))
+ if(!ReadVector(jsonLight.GetChild("matrix"), iLight->transform.AsFloat(), 16))
{
mOnError(
FormatString("Failed to parse light %d - \"matrix\" child with 16 floats expected.\n",
- std::distance(jsonLights->CBegin(), i0)));
+ std::distance(jsonLights->CBegin(), i0)));
continue;
}
int shadowMapSize = 0;
- if (ReadInt(jsonLight.GetChild(SHADOW_MAP_SIZE), shadowMapSize) && shadowMapSize < 0)
+ if(ReadInt(jsonLight.GetChild(SHADOW_MAP_SIZE), shadowMapSize) && shadowMapSize < 0)
{
mOnError(
FormatString("Failed to parse light %d - %s has an invalid value.",
- std::distance(jsonLights->CBegin(), i0), SHADOW_MAP_SIZE));
+ std::distance(jsonLights->CBegin(), i0),
+ SHADOW_MAP_SIZE));
continue;
}
iLight->shadowMapSize = shadowMapSize;
float orthoSize = 0.f;
- if (ReadFloat(jsonLight.GetChild(ORTHOGRAPHIC_SIZE), orthoSize) &&
- (orthoSize < .0f || std::isnan(orthoSize) || std::isinf(orthoSize)))
+ if(ReadFloat(jsonLight.GetChild(ORTHOGRAPHIC_SIZE), orthoSize) &&
+ (orthoSize < .0f || std::isnan(orthoSize) || std::isinf(orthoSize)))
{
mOnError(
FormatString("Failed to parse light %d - %s has an invalid value.",
- std::distance(jsonLights->CBegin(), i0), ORTHOGRAPHIC_SIZE));
+ std::distance(jsonLights->CBegin(), i0),
+ ORTHOGRAPHIC_SIZE));
continue;
}
iLight->orthographicSize = orthoSize;
- if ((iLight->shadowMapSize > 0) != (iLight->orthographicSize > .0f))
+ if((iLight->shadowMapSize > 0) != (iLight->orthographicSize > .0f))
{
mOnError(FormatString(
"Light %d: Both shadow map size and orthographic size must be set for shadows to work.",
- std::distance(jsonLights->CBegin(), i0)));
+ std::distance(jsonLights->CBegin(), i0)));
}
- if (!ReadVector(jsonLight.GetChild("color"), iLight->color.AsFloat(), 3)) // color is optional
+ if(!ReadVector(jsonLight.GetChild("color"), iLight->color.AsFloat(), 3)) // color is optional
{
- iLight->color = Vector3::ONE; // default to white
+ iLight->color = Vector3::ONE; // default to white
}
- if (!ReadFloat(jsonLight.GetChild("intensity"), iLight->intensity)) // intensity is optional
+ if(!ReadFloat(jsonLight.GetChild("intensity"), iLight->intensity)) // intensity is optional
{
- iLight->intensity = 1.0f; // default to 1.0
+ iLight->intensity = 1.0f; // default to 1.0
}
- if (!ReadFloat(jsonLight.GetChild("shadowIntensity"), iLight->shadowIntensity)) // intensity is optional
+ if(!ReadFloat(jsonLight.GetChild("shadowIntensity"), iLight->shadowIntensity)) // intensity is optional
{
- iLight->shadowIntensity = 1.0f; // default to 1.0
+ iLight->shadowIntensity = 1.0f; // default to 1.0
}
++iLight;
}
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
EnvironmentDefinition::RawData
- EnvironmentDefinition::LoadRaw(const std::string& environmentsPath) const
+EnvironmentDefinition::LoadRaw(const std::string& environmentsPath) const
{
RawData raw;
- auto loadFn = [&environmentsPath](const std::string& path, CubeData& cd) {
- if (path.empty())
+ auto loadFn = [&environmentsPath](const std::string& path, CubeData& cd) {
+ if(path.empty())
{
cd.data.resize(6);
- for (auto& face : cd.data)
+ for(auto& face : cd.data)
{
- face.push_back(PixelData::New(new uint8_t[3]{ 0xff, 0xff, 0xff }, 3, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY));
+ face.push_back(PixelData::New(new uint8_t[3]{0xff, 0xff, 0xff}, 3, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY));
}
}
else if(!LoadCubeMapData(environmentsPath + path, cd))
{
- ExceptionFlinger(ASSERT_LOCATION) << "Failed to load cubemap texture from '" <<
- path << "'.";
+ ExceptionFlinger(ASSERT_LOCATION) << "Failed to load cubemap texture from '" << path << "'.";
}
};
Textures textures;
// This texture should have 6 faces and only one mipmap
- if (!raw.mDiffuse.data.empty())
+ if(!raw.mDiffuse.data.empty())
{
textures.mDiffuse = raw.mDiffuse.CreateTexture();
}
// This texture should have 6 faces and 6 mipmaps
- if (!raw.mSpecular.data.empty())
+ if(!raw.mSpecular.data.empty())
{
textures.mSpecular = raw.mSpecular.CreateTexture();
}
return textures;
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*
*/
+#include "dali-scene-loader/public-api/gltf2-loader.h"
+#include <fstream>
+#include "dali-scene-loader/internal/gltf2-asset.h"
#include "dali-scene-loader/public-api/load-result.h"
-#include "dali-scene-loader/public-api/scene-definition.h"
#include "dali-scene-loader/public-api/resource-bundle.h"
-#include "dali-scene-loader/public-api/gltf2-loader.h"
-#include "dali-scene-loader/public-api/utils.h"
+#include "dali-scene-loader/public-api/scene-definition.h"
#include "dali-scene-loader/public-api/shader-definition-factory.h"
-#include "dali-scene-loader/internal/gltf2-asset.h"
+#include "dali-scene-loader/public-api/utils.h"
#include "dali/public-api/math/quaternion.h"
-#include <fstream>
-#define ENUM_STRING_MAPPING(t, x) { #x, t::x }
+#define ENUM_STRING_MAPPING(t, x) \
+ { \
+#x, t::x \
+ }
namespace gt = gltf2;
namespace js = json;
Geometry::LINE_STRIP,
Geometry::TRIANGLES,
Geometry::TRIANGLE_STRIP,
- Geometry::TRIANGLE_FAN
-}; //...because Dali swaps the last two.
+ Geometry::TRIANGLE_FAN}; //...because Dali swaps the last two.
struct AttributeMapping
{
- gt::Attribute::Type mType;
- MeshDefinition::Accessor MeshDefinition::* mAccessor;
- uint16_t mElementSizeRequired;
+ gt::Attribute::Type mType;
+ MeshDefinition::Accessor MeshDefinition::*mAccessor;
+ uint16_t mElementSizeRequired;
} ATTRIBUTE_MAPPINGS[]{
- { gt::Attribute::NORMAL, &MeshDefinition::mNormals, sizeof(Vector3) },
- { gt::Attribute::TANGENT, &MeshDefinition::mTangents, sizeof(Vector3) },
- { gt::Attribute::TEXCOORD_0, &MeshDefinition::mTexCoords, sizeof(Vector2) },
- { gt::Attribute::JOINTS_0, &MeshDefinition::mJoints0, sizeof(Vector4) },
- { gt::Attribute::WEIGHTS_0, &MeshDefinition::mWeights0, sizeof(Vector4) },
+ {gt::Attribute::NORMAL, &MeshDefinition::mNormals, sizeof(Vector3)},
+ {gt::Attribute::TANGENT, &MeshDefinition::mTangents, sizeof(Vector3)},
+ {gt::Attribute::TEXCOORD_0, &MeshDefinition::mTexCoords, sizeof(Vector2)},
+ {gt::Attribute::JOINTS_0, &MeshDefinition::mJoints0, sizeof(Vector4)},
+ {gt::Attribute::WEIGHTS_0, &MeshDefinition::mWeights0, sizeof(Vector4)},
};
std::vector<gt::Animation> ReadAnimationArray(const json_value_s& j)
auto results = js::Read::Array<gt::Animation, js::ObjectReader<gt::Animation>::Read>(j);
- for (auto& animation : results)
+ for(auto& animation : results)
{
- for (auto& channel : animation.mChannels)
+ for(auto& channel : animation.mChannels)
{
channel.mSampler.UpdateVector(animation.mSamplers);
}
}
const auto BUFFER_READER = std::move(js::Reader<gt::Buffer>()
- .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::Buffer::mByteLength))
- .Register(*js::MakeProperty("uri", js::Read::StringView, >::Buffer::mUri))
-);
+ .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::Buffer::mByteLength))
+ .Register(*js::MakeProperty("uri", js::Read::StringView, >::Buffer::mUri)));
const auto BUFFER_VIEW_READER = std::move(js::Reader<gt::BufferView>()
- .Register(*js::MakeProperty("buffer", gt::RefReader<gt::Document>::Read<gt::Buffer, >::Document::mBuffers>, >::BufferView::mBuffer))
- .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferView::mByteOffset))
- .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::BufferView::mByteLength))
- .Register(*js::MakeProperty("byteStride", js::Read::Number<uint32_t>, >::BufferView::mByteStride))
- .Register(*js::MakeProperty("target", js::Read::Number<uint32_t>, >::BufferView::mTarget))
-);
+ .Register(*js::MakeProperty("buffer", gt::RefReader<gt::Document>::Read<gt::Buffer, >::Document::mBuffers>, >::BufferView::mBuffer))
+ .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferView::mByteOffset))
+ .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::BufferView::mByteLength))
+ .Register(*js::MakeProperty("byteStride", js::Read::Number<uint32_t>, >::BufferView::mByteStride))
+ .Register(*js::MakeProperty("target", js::Read::Number<uint32_t>, >::BufferView::mTarget)));
const auto BUFFER_VIEW_CLIENT_READER = std::move(js::Reader<gt::BufferViewClient>()
- .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::BufferViewClient::mBufferView))
- .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferViewClient::mByteOffset))
-);
+ .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::BufferViewClient::mBufferView))
+ .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferViewClient::mByteOffset)));
const auto COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER = std::move(js::Reader<gt::ComponentTypedBufferViewClient>()
- .Register(*new js::Property<gt::ComponentTypedBufferViewClient, gt::Ref<gt::BufferView>>("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::ComponentTypedBufferViewClient::mBufferView))
- .Register(*new js::Property<gt::ComponentTypedBufferViewClient, uint32_t>("byteOffset", js::Read::Number<uint32_t>, >::ComponentTypedBufferViewClient::mByteOffset))
- .Register(*js::MakeProperty("componentType", js::Read::Enum<gt::Component::Type>, >::ComponentTypedBufferViewClient::mComponentType))
-);
+ .Register(*new js::Property<gt::ComponentTypedBufferViewClient, gt::Ref<gt::BufferView>>("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::ComponentTypedBufferViewClient::mBufferView))
+ .Register(*new js::Property<gt::ComponentTypedBufferViewClient, uint32_t>("byteOffset", js::Read::Number<uint32_t>, >::ComponentTypedBufferViewClient::mByteOffset))
+ .Register(*js::MakeProperty("componentType", js::Read::Enum<gt::Component::Type>, >::ComponentTypedBufferViewClient::mComponentType)));
const auto ACCESSOR_SPARSE_READER = std::move(js::Reader<gt::Accessor::Sparse>()
- .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::Sparse::mCount))
- .Register(*js::MakeProperty("indices", js::ObjectReader<gt::ComponentTypedBufferViewClient>::Read,
- >::Accessor::Sparse::mIndices))
- .Register(*js::MakeProperty("values", js::ObjectReader<gt::BufferViewClient>::Read,
- >::Accessor::Sparse::mValues))
-);
+ .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::Sparse::mCount))
+ .Register(*js::MakeProperty("indices", js::ObjectReader<gt::ComponentTypedBufferViewClient>::Read, >::Accessor::Sparse::mIndices))
+ .Register(*js::MakeProperty("values", js::ObjectReader<gt::BufferViewClient>::Read, >::Accessor::Sparse::mValues)));
const auto ACCESSOR_READER = std::move(js::Reader<gt::Accessor>()
- .Register(*new js::Property<gt::Accessor, gt::Ref<gt::BufferView>>("bufferView",
- gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::Accessor::mBufferView))
- .Register(*new js::Property<gt::Accessor, uint32_t>("byteOffset",
- js::Read::Number<uint32_t>, >::Accessor::mByteOffset))
- .Register(*new js::Property<gt::Accessor, gt::Component::Type>("componentType",
- js::Read::Enum<gt::Component::Type>, >::Accessor::mComponentType))
- .Register(*new js::Property<gt::Accessor, std::string_view>("name", js::Read::StringView, >::Accessor::mName))
- .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::mCount))
- .Register(*js::MakeProperty("normalized", js::Read::Boolean, >::Accessor::mNormalized))
- .Register(*js::MakeProperty("type", gt::ReadStringEnum<gt::AccessorType>, >::Accessor::mType))
- .Register(*js::MakeProperty("min", js::Read::Array<float, js::Read::Number>, >::Accessor::mMin))
- .Register(*js::MakeProperty("max", js::Read::Array<float, js::Read::Number>, >::Accessor::mMax))
- .Register(*new js::Property<gt::Accessor, gt::Accessor::Sparse>("sparse", js::ObjectReader<gt::Accessor::Sparse>::Read,
- >::Accessor::SetSparse))
-);
+ .Register(*new js::Property<gt::Accessor, gt::Ref<gt::BufferView>>("bufferView",
+ gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>,
+ >::Accessor::mBufferView))
+ .Register(*new js::Property<gt::Accessor, uint32_t>("byteOffset",
+ js::Read::Number<uint32_t>,
+ >::Accessor::mByteOffset))
+ .Register(*new js::Property<gt::Accessor, gt::Component::Type>("componentType",
+ js::Read::Enum<gt::Component::Type>,
+ >::Accessor::mComponentType))
+ .Register(*new js::Property<gt::Accessor, std::string_view>("name", js::Read::StringView, >::Accessor::mName))
+ .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::mCount))
+ .Register(*js::MakeProperty("normalized", js::Read::Boolean, >::Accessor::mNormalized))
+ .Register(*js::MakeProperty("type", gt::ReadStringEnum<gt::AccessorType>, >::Accessor::mType))
+ .Register(*js::MakeProperty("min", js::Read::Array<float, js::Read::Number>, >::Accessor::mMin))
+ .Register(*js::MakeProperty("max", js::Read::Array<float, js::Read::Number>, >::Accessor::mMax))
+ .Register(*new js::Property<gt::Accessor, gt::Accessor::Sparse>("sparse", js::ObjectReader<gt::Accessor::Sparse>::Read, >::Accessor::SetSparse)));
const auto IMAGE_READER = std::move(js::Reader<gt::Image>()
- .Register(*new js::Property<gt::Image, std::string_view>("name", js::Read::StringView, >::Material::mName))
- .Register(*js::MakeProperty("uri", js::Read::StringView, >::Image::mUri))
- .Register(*js::MakeProperty("mimeType", js::Read::StringView, >::Image::mMimeType))
- .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::Image::mBufferView))
-);
+ .Register(*new js::Property<gt::Image, std::string_view>("name", js::Read::StringView, >::Material::mName))
+ .Register(*js::MakeProperty("uri", js::Read::StringView, >::Image::mUri))
+ .Register(*js::MakeProperty("mimeType", js::Read::StringView, >::Image::mMimeType))
+ .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::Image::mBufferView)));
const auto SAMPLER_READER = std::move(js::Reader<gt::Sampler>()
- .Register(*js::MakeProperty("minFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMinFilter))
- .Register(*js::MakeProperty("magFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMagFilter))
- .Register(*js::MakeProperty("wrapS", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapS))
- .Register(*js::MakeProperty("wrapT", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapT))
-);
+ .Register(*js::MakeProperty("minFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMinFilter))
+ .Register(*js::MakeProperty("magFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMagFilter))
+ .Register(*js::MakeProperty("wrapS", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapS))
+ .Register(*js::MakeProperty("wrapT", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapT)));
const auto TEXURE_READER = std::move(js::Reader<gt::Texture>()
- .Register(*js::MakeProperty("source", gt::RefReader<gt::Document>::Read<gt::Image, >::Document::mImages>, >::Texture::mSource))
- .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Document>::Read<gt::Sampler, >::Document::mSamplers>, >::Texture::mSampler))
-);
+ .Register(*js::MakeProperty("source", gt::RefReader<gt::Document>::Read<gt::Image, >::Document::mImages>, >::Texture::mSource))
+ .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Document>::Read<gt::Sampler, >::Document::mSamplers>, >::Texture::mSampler)));
const auto TEXURE_INFO_READER = std::move(js::Reader<gt::TextureInfo>()
- .Register(*js::MakeProperty("index", gt::RefReader<gt::Document>::Read<gt::Texture, >::Document::mTextures>, >::TextureInfo::mTexture))
- .Register(*js::MakeProperty("texCoord", js::Read::Number<uint32_t>, >::TextureInfo::mTexCoord))
- .Register(*js::MakeProperty("scale", js::Read::Number<float>, >::TextureInfo::mScale))
-);
+ .Register(*js::MakeProperty("index", gt::RefReader<gt::Document>::Read<gt::Texture, >::Document::mTextures>, >::TextureInfo::mTexture))
+ .Register(*js::MakeProperty("texCoord", js::Read::Number<uint32_t>, >::TextureInfo::mTexCoord))
+ .Register(*js::MakeProperty("scale", js::Read::Number<float>, >::TextureInfo::mScale)));
const auto MATERIAL_PBR_READER = std::move(js::Reader<gt::Material::Pbr>()
- .Register(*js::MakeProperty("baseColorFactor", gt::ReadDaliVector<Vector4>, >::Material::Pbr::mBaseColorFactor))
- .Register(*js::MakeProperty("baseColorTexture", js::ObjectReader<gt::TextureInfo>::Read,
- >::Material::Pbr::mBaseColorTexture))
- .Register(*js::MakeProperty("metallicFactor", js::Read::Number<float>, >::Material::Pbr::mMetallicFactor))
- .Register(*js::MakeProperty("roughnessFactor", js::Read::Number<float>, >::Material::Pbr::mRoughnessFactor))
- .Register(*js::MakeProperty("metallicRoughnessTexture", js::ObjectReader<gt::TextureInfo>::Read,
- >::Material::Pbr::mMetallicRoughnessTexture))
-);
+ .Register(*js::MakeProperty("baseColorFactor", gt::ReadDaliVector<Vector4>, >::Material::Pbr::mBaseColorFactor))
+ .Register(*js::MakeProperty("baseColorTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::Pbr::mBaseColorTexture))
+ .Register(*js::MakeProperty("metallicFactor", js::Read::Number<float>, >::Material::Pbr::mMetallicFactor))
+ .Register(*js::MakeProperty("roughnessFactor", js::Read::Number<float>, >::Material::Pbr::mRoughnessFactor))
+ .Register(*js::MakeProperty("metallicRoughnessTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::Pbr::mMetallicRoughnessTexture)));
const auto MATERIAL_READER = std::move(js::Reader<gt::Material>()
- .Register(*new js::Property<gt::Material, std::string_view>("name", js::Read::StringView, >::Material::mName))
- .Register(*js::MakeProperty("pbrMetallicRoughness", js::ObjectReader<gt::Material::Pbr>::Read, >::Material::mPbrMetallicRoughness))
- .Register(*js::MakeProperty("normalTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mNormalTexture))
- .Register(*js::MakeProperty("occlusionTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mOcclusionTexture))
- .Register(*js::MakeProperty("emissiveTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mEmissiveTexture))
- .Register(*js::MakeProperty("emissiveFactor", gt::ReadDaliVector<Vector3>, >::Material::mEmissiveFactor))
- .Register(*js::MakeProperty("alphaMode", gt::ReadStringEnum<gt::AlphaMode>, >::Material::mAlphaMode))
- .Register(*js::MakeProperty("alphaCutoff", js::Read::Number<float>, >::Material::mAlphaCutoff))
-);
+ .Register(*new js::Property<gt::Material, std::string_view>("name", js::Read::StringView, >::Material::mName))
+ .Register(*js::MakeProperty("pbrMetallicRoughness", js::ObjectReader<gt::Material::Pbr>::Read, >::Material::mPbrMetallicRoughness))
+ .Register(*js::MakeProperty("normalTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mNormalTexture))
+ .Register(*js::MakeProperty("occlusionTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mOcclusionTexture))
+ .Register(*js::MakeProperty("emissiveTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mEmissiveTexture))
+ .Register(*js::MakeProperty("emissiveFactor", gt::ReadDaliVector<Vector3>, >::Material::mEmissiveFactor))
+ .Register(*js::MakeProperty("alphaMode", gt::ReadStringEnum<gt::AlphaMode>, >::Material::mAlphaMode))
+ .Register(*js::MakeProperty("alphaCutoff", js::Read::Number<float>, >::Material::mAlphaCutoff)));
std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>> ReadMeshPrimitiveAttributes(const json_value_s& j)
{
- auto& jo = js::Cast<json_object_s>(j);
+ auto& jo = js::Cast<json_object_s>(j);
std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>> result;
auto i = jo.start;
- while (i)
+ while(i)
{
- auto jstr = *i->name;
+ auto jstr = *i->name;
result[gt::Attribute::FromString(jstr.string, jstr.string_size)] = gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>(*i->value);
- i = i->next;
+ i = i->next;
}
return result;
}
std::vector<std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>>> ReadMeshPrimitiveTargets(const json_value_s& j)
{
- auto& jo = js::Cast<json_array_s>(j);
+ auto& jo = js::Cast<json_array_s>(j);
std::vector<std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>>> result;
result.reserve(jo.length);
auto i = jo.start;
- while (i)
+ while(i)
{
result.push_back(std::move(ReadMeshPrimitiveAttributes(*i->value)));
i = i->next;
}
const auto MESH_PRIMITIVE_READER = std::move(js::Reader<gt::Mesh::Primitive>()
- .Register(*js::MakeProperty("attributes", ReadMeshPrimitiveAttributes, >::Mesh::Primitive::mAttributes))
- .Register(*js::MakeProperty("indices", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Mesh::Primitive::mIndices))
- .Register(*js::MakeProperty("material", gt::RefReader<gt::Document>::Read<gt::Material, >::Document::mMaterials>, >::Mesh::Primitive::mMaterial))
- .Register(*js::MakeProperty("mode", js::Read::Enum<gt::Mesh::Primitive::Mode>, >::Mesh::Primitive::mMode))
- .Register(*js::MakeProperty("targets", ReadMeshPrimitiveTargets, >::Mesh::Primitive::mTargets))
-);
+ .Register(*js::MakeProperty("attributes", ReadMeshPrimitiveAttributes, >::Mesh::Primitive::mAttributes))
+ .Register(*js::MakeProperty("indices", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Mesh::Primitive::mIndices))
+ .Register(*js::MakeProperty("material", gt::RefReader<gt::Document>::Read<gt::Material, >::Document::mMaterials>, >::Mesh::Primitive::mMaterial))
+ .Register(*js::MakeProperty("mode", js::Read::Enum<gt::Mesh::Primitive::Mode>, >::Mesh::Primitive::mMode))
+ .Register(*js::MakeProperty("targets", ReadMeshPrimitiveTargets, >::Mesh::Primitive::mTargets)));
const auto MESH_READER = std::move(js::Reader<gt::Mesh>()
- .Register(*new js::Property<gt::Mesh, std::string_view>("name", js::Read::StringView, >::Mesh::mName))
- .Register(*js::MakeProperty("primitives",
- js::Read::Array<gt::Mesh::Primitive, js::ObjectReader<gt::Mesh::Primitive>::Read>, >::Mesh::mPrimitives))
- .Register(*js::MakeProperty("weights", js::Read::Array<float, js::Read::Number>, >::Mesh::mWeights))
-);
+ .Register(*new js::Property<gt::Mesh, std::string_view>("name", js::Read::StringView, >::Mesh::mName))
+ .Register(*js::MakeProperty("primitives",
+ js::Read::Array<gt::Mesh::Primitive, js::ObjectReader<gt::Mesh::Primitive>::Read>,
+ >::Mesh::mPrimitives))
+ .Register(*js::MakeProperty("weights", js::Read::Array<float, js::Read::Number>, >::Mesh::mWeights)));
const auto SKIN_READER = std::move(js::Reader<gt::Skin>()
- .Register(*new js::Property<gt::Skin, std::string_view>("name", js::Read::StringView, >::Skin::mName))
- .Register(*js::MakeProperty("inverseBindMatrices",
- gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Skin::mInverseBindMatrices))
- .Register(*js::MakeProperty("skeleton",
- gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>, >::Skin::mSkeleton))
- .Register(*js::MakeProperty("joints",
- js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>, >::Skin::mJoints))
-);
+ .Register(*new js::Property<gt::Skin, std::string_view>("name", js::Read::StringView, >::Skin::mName))
+ .Register(*js::MakeProperty("inverseBindMatrices",
+ gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>,
+ >::Skin::mInverseBindMatrices))
+ .Register(*js::MakeProperty("skeleton",
+ gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>,
+ >::Skin::mSkeleton))
+ .Register(*js::MakeProperty("joints",
+ js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>,
+ >::Skin::mJoints)));
const auto CAMERA_PERSPECTIVE_READER = std::move(js::Reader<gt::Camera::Perspective>()
- .Register(*js::MakeProperty("aspectRatio", js::Read::Number<float>, >::Camera::Perspective::mAspectRatio))
- .Register(*js::MakeProperty("yfov", js::Read::Number<float>, >::Camera::Perspective::mYFov))
- .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Perspective::mZFar))
- .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Perspective::mZNear))
-); // TODO: infinite perspective projection, where znear is omitted
+ .Register(*js::MakeProperty("aspectRatio", js::Read::Number<float>, >::Camera::Perspective::mAspectRatio))
+ .Register(*js::MakeProperty("yfov", js::Read::Number<float>, >::Camera::Perspective::mYFov))
+ .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Perspective::mZFar))
+ .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Perspective::mZNear))); // TODO: infinite perspective projection, where znear is omitted
const auto CAMERA_ORTHOGRAPHIC_READER = std::move(js::Reader<gt::Camera::Orthographic>()
- .Register(*js::MakeProperty("xmag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
- .Register(*js::MakeProperty("ymag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
- .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Orthographic::mZFar))
- .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Orthographic::mZNear))
-);
+ .Register(*js::MakeProperty("xmag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
+ .Register(*js::MakeProperty("ymag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
+ .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Orthographic::mZFar))
+ .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Orthographic::mZNear)));
const auto CAMERA_READER = std::move(js::Reader<gt::Camera>()
- .Register(*new js::Property<gt::Camera, std::string_view>("name", js::Read::StringView, >::Camera::mName))
- .Register(*js::MakeProperty("type", js::Read::StringView, >::Camera::mType))
- .Register(*js::MakeProperty("perspective", js::ObjectReader<gt::Camera::Perspective>::Read, >::Camera::mPerspective))
- .Register(*js::MakeProperty("orthographic", js::ObjectReader<gt::Camera::Orthographic>::Read, >::Camera::mOrthographic))
-);
+ .Register(*new js::Property<gt::Camera, std::string_view>("name", js::Read::StringView, >::Camera::mName))
+ .Register(*js::MakeProperty("type", js::Read::StringView, >::Camera::mType))
+ .Register(*js::MakeProperty("perspective", js::ObjectReader<gt::Camera::Perspective>::Read, >::Camera::mPerspective))
+ .Register(*js::MakeProperty("orthographic", js::ObjectReader<gt::Camera::Orthographic>::Read, >::Camera::mOrthographic)));
const auto NODE_READER = std::move(js::Reader<gt::Node>()
- .Register(*new js::Property<gt::Node, std::string_view>("name", js::Read::StringView, >::Node::mName))
- .Register(*js::MakeProperty("translation", gt::ReadDaliVector<Vector3>, >::Node::mTranslation))
- .Register(*js::MakeProperty("rotation", gt::ReadQuaternion, >::Node::mRotation))
- .Register(*js::MakeProperty("scale", gt::ReadDaliVector<Vector3>, >::Node::mScale))
- .Register(*new js::Property<gt::Node, Matrix>("matrix", gt::ReadDaliVector<Matrix>, >::Node::SetMatrix))
- .Register(*js::MakeProperty("camera", gt::RefReader<gt::Document>::Read<gt::Camera, >::Document::mCameras>,
- >::Node::mCamera))
- .Register(*js::MakeProperty("children", js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>,
- >::Node::mChildren))
- .Register(*js::MakeProperty("mesh", gt::RefReader<gt::Document>::Read<gt::Mesh, >::Document::mMeshes>, >::Node::mMesh))
- .Register(*js::MakeProperty("skin", gt::RefReader<gt::Document>::Read<gt::Skin, >::Document::mSkins>, >::Node::mSkin))
-);
+ .Register(*new js::Property<gt::Node, std::string_view>("name", js::Read::StringView, >::Node::mName))
+ .Register(*js::MakeProperty("translation", gt::ReadDaliVector<Vector3>, >::Node::mTranslation))
+ .Register(*js::MakeProperty("rotation", gt::ReadQuaternion, >::Node::mRotation))
+ .Register(*js::MakeProperty("scale", gt::ReadDaliVector<Vector3>, >::Node::mScale))
+ .Register(*new js::Property<gt::Node, Matrix>("matrix", gt::ReadDaliVector<Matrix>, >::Node::SetMatrix))
+ .Register(*js::MakeProperty("camera", gt::RefReader<gt::Document>::Read<gt::Camera, >::Document::mCameras>, >::Node::mCamera))
+ .Register(*js::MakeProperty("children", js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>, >::Node::mChildren))
+ .Register(*js::MakeProperty("mesh", gt::RefReader<gt::Document>::Read<gt::Mesh, >::Document::mMeshes>, >::Node::mMesh))
+ .Register(*js::MakeProperty("skin", gt::RefReader<gt::Document>::Read<gt::Skin, >::Document::mSkins>, >::Node::mSkin)));
const auto ANIMATION_SAMPLER_READER = std::move(js::Reader<gt::Animation::Sampler>()
- .Register(*js::MakeProperty("input", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>,
- >::Animation::Sampler::mInput))
- .Register(*js::MakeProperty("output", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>,
- >::Animation::Sampler::mOutput))
- .Register(*js::MakeProperty("interpolation", gt::ReadStringEnum<gt::Animation::Sampler::Interpolation>, >::Animation::Sampler::mInterpolation))
-);
+ .Register(*js::MakeProperty("input", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Animation::Sampler::mInput))
+ .Register(*js::MakeProperty("output", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Animation::Sampler::mOutput))
+ .Register(*js::MakeProperty("interpolation", gt::ReadStringEnum<gt::Animation::Sampler::Interpolation>, >::Animation::Sampler::mInterpolation)));
const auto ANIMATION_TARGET_READER = std::move(js::Reader<gt::Animation::Channel::Target>()
- .Register(*js::MakeProperty("node", gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>,
- >::Animation::Channel::Target::mNode))
- .Register(*js::MakeProperty("path", gt::ReadStringEnum<gt::Animation::Channel::Target>,
- >::Animation::Channel::Target::mPath))
-);
+ .Register(*js::MakeProperty("node", gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>, >::Animation::Channel::Target::mNode))
+ .Register(*js::MakeProperty("path", gt::ReadStringEnum<gt::Animation::Channel::Target>, >::Animation::Channel::Target::mPath)));
const auto ANIMATION_CHANNEL_READER = std::move(js::Reader<gt::Animation::Channel>()
- .Register(*js::MakeProperty("target", js::ObjectReader<gt::Animation::Channel::Target>::Read, >::Animation::Channel::mTarget))
- .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Animation>::Read<gt::Animation::Sampler, >::Animation::mSamplers>, >::Animation::Channel::mSampler))
-);
+ .Register(*js::MakeProperty("target", js::ObjectReader<gt::Animation::Channel::Target>::Read, >::Animation::Channel::mTarget))
+ .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Animation>::Read<gt::Animation::Sampler, >::Animation::mSamplers>, >::Animation::Channel::mSampler)));
const auto ANIMATION_READER = std::move(js::Reader<gt::Animation>()
- .Register(*new js::Property<gt::Animation, std::string_view>("name", js::Read::StringView, >::Animation::mName))
- .Register(*js::MakeProperty("samplers",
- js::Read::Array<gt::Animation::Sampler, js::ObjectReader<gt::Animation::Sampler>::Read>, >::Animation::mSamplers))
- .Register(*js::MakeProperty("channels",
- js::Read::Array<gt::Animation::Channel, js::ObjectReader<gt::Animation::Channel>::Read>, >::Animation::mChannels))
-);
+ .Register(*new js::Property<gt::Animation, std::string_view>("name", js::Read::StringView, >::Animation::mName))
+ .Register(*js::MakeProperty("samplers",
+ js::Read::Array<gt::Animation::Sampler, js::ObjectReader<gt::Animation::Sampler>::Read>,
+ >::Animation::mSamplers))
+ .Register(*js::MakeProperty("channels",
+ js::Read::Array<gt::Animation::Channel, js::ObjectReader<gt::Animation::Channel>::Read>,
+ >::Animation::mChannels)));
const auto SCENE_READER = std::move(js::Reader<gt::Scene>()
- .Register(*new js::Property<gt::Scene, std::string_view>("name", js::Read::StringView, >::Scene::mName))
- .Register(*js::MakeProperty("nodes",
- js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>, >::Scene::mNodes))
-);
+ .Register(*new js::Property<gt::Scene, std::string_view>("name", js::Read::StringView, >::Scene::mName))
+ .Register(*js::MakeProperty("nodes",
+ js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>,
+ >::Scene::mNodes)));
const auto DOCUMENT_READER = std::move(js::Reader<gt::Document>()
- .Register(*js::MakeProperty("buffers",
- js::Read::Array<gt::Buffer, js::ObjectReader<gt::Buffer>::Read>, >::Document::mBuffers))
- .Register(*js::MakeProperty("bufferViews",
- js::Read::Array<gt::BufferView, js::ObjectReader<gt::BufferView>::Read>, >::Document::mBufferViews))
- .Register(*js::MakeProperty("accessors",
- js::Read::Array<gt::Accessor, js::ObjectReader<gt::Accessor>::Read>, >::Document::mAccessors))
- .Register(*js::MakeProperty("images",
- js::Read::Array<gt::Image, js::ObjectReader<gt::Image>::Read>, >::Document::mImages))
- .Register(*js::MakeProperty("samplers",
- js::Read::Array<gt::Sampler, js::ObjectReader<gt::Sampler>::Read>, >::Document::mSamplers))
- .Register(*js::MakeProperty("textures",
- js::Read::Array<gt::Texture, js::ObjectReader<gt::Texture>::Read>, >::Document::mTextures))
- .Register(*js::MakeProperty("materials",
- js::Read::Array<gt::Material, js::ObjectReader<gt::Material>::Read>, >::Document::mMaterials))
- .Register(*js::MakeProperty("meshes",
- js::Read::Array<gt::Mesh, js::ObjectReader<gt::Mesh>::Read>, >::Document::mMeshes))
- .Register(*js::MakeProperty("skins",
- js::Read::Array<gt::Skin, js::ObjectReader<gt::Skin>::Read>, >::Document::mSkins))
- .Register(*js::MakeProperty("cameras",
- js::Read::Array<gt::Camera, js::ObjectReader<gt::Camera>::Read>, >::Document::mCameras))
- .Register(*js::MakeProperty("nodes",
- js::Read::Array<gt::Node, js::ObjectReader<gt::Node>::Read>, >::Document::mNodes))
- .Register(*js::MakeProperty("animations",
- ReadAnimationArray, >::Document::mAnimations))
- .Register(*js::MakeProperty("scenes",
- js::Read::Array<gt::Scene, js::ObjectReader<gt::Scene>::Read>, >::Document::mScenes))
- .Register(*js::MakeProperty("scene", gt::RefReader<gt::Document>::Read<gt::Scene, >::Document::mScenes>, >::Document::mScene))
-);
+ .Register(*js::MakeProperty("buffers",
+ js::Read::Array<gt::Buffer, js::ObjectReader<gt::Buffer>::Read>,
+ >::Document::mBuffers))
+ .Register(*js::MakeProperty("bufferViews",
+ js::Read::Array<gt::BufferView, js::ObjectReader<gt::BufferView>::Read>,
+ >::Document::mBufferViews))
+ .Register(*js::MakeProperty("accessors",
+ js::Read::Array<gt::Accessor, js::ObjectReader<gt::Accessor>::Read>,
+ >::Document::mAccessors))
+ .Register(*js::MakeProperty("images",
+ js::Read::Array<gt::Image, js::ObjectReader<gt::Image>::Read>,
+ >::Document::mImages))
+ .Register(*js::MakeProperty("samplers",
+ js::Read::Array<gt::Sampler, js::ObjectReader<gt::Sampler>::Read>,
+ >::Document::mSamplers))
+ .Register(*js::MakeProperty("textures",
+ js::Read::Array<gt::Texture, js::ObjectReader<gt::Texture>::Read>,
+ >::Document::mTextures))
+ .Register(*js::MakeProperty("materials",
+ js::Read::Array<gt::Material, js::ObjectReader<gt::Material>::Read>,
+ >::Document::mMaterials))
+ .Register(*js::MakeProperty("meshes",
+ js::Read::Array<gt::Mesh, js::ObjectReader<gt::Mesh>::Read>,
+ >::Document::mMeshes))
+ .Register(*js::MakeProperty("skins",
+ js::Read::Array<gt::Skin, js::ObjectReader<gt::Skin>::Read>,
+ >::Document::mSkins))
+ .Register(*js::MakeProperty("cameras",
+ js::Read::Array<gt::Camera, js::ObjectReader<gt::Camera>::Read>,
+ >::Document::mCameras))
+ .Register(*js::MakeProperty("nodes",
+ js::Read::Array<gt::Node, js::ObjectReader<gt::Node>::Read>,
+ >::Document::mNodes))
+ .Register(*js::MakeProperty("animations",
+ ReadAnimationArray,
+ >::Document::mAnimations))
+ .Register(*js::MakeProperty("scenes",
+ js::Read::Array<gt::Scene, js::ObjectReader<gt::Scene>::Read>,
+ >::Document::mScenes))
+ .Register(*js::MakeProperty("scene", gt::RefReader<gt::Document>::Read<gt::Scene, >::Document::mScenes>, >::Document::mScene)));
struct NodeMapping
{
class NodeIndexMapper
{
public:
- NodeIndexMapper() = default;
+ NodeIndexMapper() = default;
NodeIndexMapper(const NodeIndexMapper&) = delete;
NodeIndexMapper& operator=(const NodeIndexMapper&) = delete;
/// save growing a vector.
void RegisterMapping(Index gltfIdx, Index runtimeIdx)
{
- if (gltfIdx != runtimeIdx)
+ if(gltfIdx != runtimeIdx)
{
auto iInsert = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx);
DALI_ASSERT_DEBUG(iInsert == mNodes.end() || iInsert->gltfIdx != gltfIdx);
- mNodes.insert(iInsert, NodeMapping{ gltfIdx, runtimeIdx });
+ mNodes.insert(iInsert, NodeMapping{gltfIdx, runtimeIdx});
}
}
///@brief Retrieves the runtime index of a Node, mapped to the given @a gltfIdx.
Index GetRuntimeId(Index gltfIdx) const
{
- auto iFind = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx); // using custom operator<
+ auto iFind = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx); // using custom operator<
return (iFind != mNodes.end() && iFind->gltfIdx == gltfIdx) ? iFind->runtimeIdx : gltfIdx;
}
struct ConversionContext
{
- LoadResult& mOutput;
+ LoadResult& mOutput;
std::string mPath;
- Index mDefaultMaterial;
+ Index mDefaultMaterial;
- std::vector<Index> mMeshIds;
- NodeIndexMapper mNodeIndices;
+ std::vector<Index> mMeshIds;
+ NodeIndexMapper mNodeIndices;
};
SamplerFlags::Type ConvertWrapMode(gt::Wrap::Type w)
{
- switch (w)
+ switch(w)
{
- case gt::Wrap::REPEAT:
- return SamplerFlags::WRAP_REPEAT;
- case gt::Wrap::CLAMP_TO_EDGE:
- return SamplerFlags::WRAP_CLAMP;
- case gt::Wrap::MIRRORED_REPEAT:
- return SamplerFlags::WRAP_MIRROR;
- default:
- throw std::runtime_error("Invalid wrap type.");
+ case gt::Wrap::REPEAT:
+ return SamplerFlags::WRAP_REPEAT;
+ case gt::Wrap::CLAMP_TO_EDGE:
+ return SamplerFlags::WRAP_CLAMP;
+ case gt::Wrap::MIRRORED_REPEAT:
+ return SamplerFlags::WRAP_MIRROR;
+ default:
+ throw std::runtime_error("Invalid wrap type.");
}
}
SamplerFlags::Type ConvertSampler(const gt::Ref<gt::Sampler>& s)
{
- if (s)
+ if(s)
{
- return (s->mMinFilter < gt::Filter::NEAREST_MIPMAP_NEAREST) ? (s->mMinFilter - gt::Filter::NEAREST) :
- ((s->mMinFilter - gt::Filter::NEAREST_MIPMAP_NEAREST) + 2) |
- ((s->mMagFilter - gt::Filter::NEAREST) << SamplerFlags::FILTER_MAG_SHIFT) |
- (ConvertWrapMode(s->mWrapS) << SamplerFlags::WRAP_S_SHIFT) |
- (ConvertWrapMode(s->mWrapT) << SamplerFlags::WRAP_T_SHIFT);
+ return (s->mMinFilter < gt::Filter::NEAREST_MIPMAP_NEAREST) ? (s->mMinFilter - gt::Filter::NEAREST) : ((s->mMinFilter - gt::Filter::NEAREST_MIPMAP_NEAREST) + 2) | ((s->mMagFilter - gt::Filter::NEAREST) << SamplerFlags::FILTER_MAG_SHIFT) | (ConvertWrapMode(s->mWrapS) << SamplerFlags::WRAP_S_SHIFT) | (ConvertWrapMode(s->mWrapT) << SamplerFlags::WRAP_T_SHIFT);
}
else
{
// "What is an auto filtering", I hear you ask. Since there's nothing else to determine mipmapping from - including glTF image
// properties, if not in some extension -, we will simply assume linear filtering.
return SamplerFlags::FILTER_LINEAR | (SamplerFlags::FILTER_LINEAR << SamplerFlags::FILTER_MAG_SHIFT) |
- (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_S_SHIFT) | (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_T_SHIFT);
+ (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_S_SHIFT) | (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_T_SHIFT);
}
}
TextureDefinition ConvertTextureInfo(const gt::TextureInfo& mm)
{
- return TextureDefinition{ std::string(mm.mTexture->mSource->mUri), ConvertSampler(mm.mTexture->mSampler) };
+ return TextureDefinition{std::string(mm.mTexture->mSource->mUri), ConvertSampler(mm.mTexture->mSampler)};
}
void ConvertMaterial(const gt::Material& m, decltype(ResourceBundle::mMaterials)& outMaterials)
MaterialDefinition matDef;
auto& pbr = m.mPbrMetallicRoughness;
- if (m.mAlphaMode != gt::AlphaMode::OPAQUE || pbr.mBaseColorFactor.a < 1.f)
+ if(m.mAlphaMode != gt::AlphaMode::OPAQUE || pbr.mBaseColorFactor.a < 1.f)
{
matDef.mFlags |= MaterialDefinition::TRANSPARENCY;
}
- if (m.mAlphaMode == gt::AlphaMode::MASK)
+ if(m.mAlphaMode == gt::AlphaMode::MASK)
{
matDef.SetAlphaCutoff(std::min(1.f, std::max(0.f, m.mAlphaCutoff)));
}
matDef.mColor = pbr.mBaseColorFactor;
matDef.mTextureStages.reserve(!!pbr.mBaseColorTexture + !!pbr.mMetallicRoughnessTexture + !!m.mNormalTexture);
- if (pbr.mBaseColorTexture)
+ if(pbr.mBaseColorTexture)
{
const auto semantic = MaterialDefinition::ALBEDO;
- matDef.mTextureStages.push_back({ semantic, ConvertTextureInfo(pbr.mBaseColorTexture) });
+ matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mBaseColorTexture)});
// TODO: and there had better be one
matDef.mFlags |= semantic;
}
- matDef.mMetallic = pbr.mMetallicFactor;
+ matDef.mMetallic = pbr.mMetallicFactor;
matDef.mRoughness = pbr.mRoughnessFactor;
- if (pbr.mMetallicRoughnessTexture)
+ if(pbr.mMetallicRoughnessTexture)
{
const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS |
- MaterialDefinition::GLTF_CHANNELS;
- matDef.mTextureStages.push_back({ semantic, ConvertTextureInfo(pbr.mMetallicRoughnessTexture) });
+ MaterialDefinition::GLTF_CHANNELS;
+ matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mMetallicRoughnessTexture)});
// TODO: and there had better be one
matDef.mFlags |= semantic;
}
- if (m.mNormalTexture)
+ if(m.mNormalTexture)
{
const auto semantic = MaterialDefinition::NORMAL;
- matDef.mTextureStages.push_back({ semantic, ConvertTextureInfo(m.mNormalTexture) });
+ matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(m.mNormalTexture)});
// TODO: and there had better be one
matDef.mFlags |= semantic;
}
auto& outMaterials = cctx.mOutput.mResources.mMaterials;
outMaterials.reserve(doc.mMaterials.size());
- for (auto& m : doc.mMaterials)
+ for(auto& m : doc.mMaterials)
{
ConvertMaterial(m, outMaterials);
}
MeshDefinition::Accessor ConvertMeshPrimitiveAccessor(const gt::Accessor& acc)
{
DALI_ASSERT_ALWAYS((acc.mBufferView &&
- (acc.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) ||
- (acc.mSparse && !acc.mBufferView));
+ (acc.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) ||
+ (acc.mSparse && !acc.mBufferView));
DALI_ASSERT_ALWAYS(!acc.mSparse ||
- ((acc.mSparse->mIndices.mBufferView && (acc.mSparse->mIndices.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) &&
- (acc.mSparse->mValues.mBufferView && (acc.mSparse->mValues.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max()))));
-
+ ((acc.mSparse->mIndices.mBufferView && (acc.mSparse->mIndices.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) &&
+ (acc.mSparse->mValues.mBufferView && (acc.mSparse->mValues.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max()))));
MeshDefinition::SparseBlob sparseBlob;
- if (acc.mSparse)
+ if(acc.mSparse)
{
- const gt::Accessor::Sparse& sparse = *acc.mSparse;
+ const gt::Accessor::Sparse& sparse = *acc.mSparse;
const gt::ComponentTypedBufferViewClient& indices = sparse.mIndices;
- const gt::BufferViewClient& values = sparse.mValues;
+ const gt::BufferViewClient& values = sparse.mValues;
MeshDefinition::Blob indicesBlob(
indices.mBufferView->mByteOffset + indices.mByteOffset,
sparse.mCount * indices.GetBytesPerComponent(),
static_cast<uint16_t>(indices.mBufferView->mByteStride),
static_cast<uint16_t>(indices.GetBytesPerComponent()),
- {}, {}
- );
+ {},
+ {});
MeshDefinition::Blob valuesBlob(
values.mBufferView->mByteOffset + values.mByteOffset,
sparse.mCount * acc.GetElementSizeBytes(),
static_cast<uint16_t>(values.mBufferView->mByteStride),
static_cast<uint16_t>(acc.GetElementSizeBytes()),
- {}, {}
- );
+ {},
+ {});
sparseBlob = std::move(MeshDefinition::SparseBlob(std::move(indicesBlob), std::move(valuesBlob), acc.mSparse->mCount));
}
uint32_t bufferViewOffset = 0u;
uint32_t bufferViewStride = 0u;
- if (acc.mBufferView)
+ if(acc.mBufferView)
{
bufferViewOffset = acc.mBufferView->mByteOffset;
bufferViewStride = acc.mBufferView->mByteStride;
return MeshDefinition::Accessor{
std::move(MeshDefinition::Blob{bufferViewOffset + acc.mByteOffset,
- acc.GetBytesLength(),
- static_cast<uint16_t>(bufferViewStride),
- static_cast<uint16_t>(acc.GetElementSizeBytes()),
- acc.mMin,
- acc.mMax}),
- std::move(sparseBlob) };
+ acc.GetBytesLength(),
+ static_cast<uint16_t>(bufferViewStride),
+ static_cast<uint16_t>(acc.GetElementSizeBytes()),
+ acc.mMin,
+ acc.mMax}),
+ std::move(sparseBlob)};
}
void ConvertMeshes(const gt::Document& doc, ConversionContext& cctx)
{
uint32_t meshCount = 0;
cctx.mMeshIds.reserve(doc.mMeshes.size());
- for (auto& m : doc.mMeshes)
+ for(auto& m : doc.mMeshes)
{
cctx.mMeshIds.push_back(meshCount);
meshCount += m.mPrimitives.size();
auto& outMeshes = cctx.mOutput.mResources.mMeshes;
outMeshes.reserve(meshCount);
- for (auto& m : doc.mMeshes)
+ for(auto& m : doc.mMeshes)
{
- for (auto& p : m.mPrimitives)
+ for(auto& p : m.mPrimitives)
{
MeshDefinition meshDef;
- auto& attribs = p.mAttributes;
- meshDef.mUri = attribs.begin()->second->mBufferView->mBuffer->mUri;
+ auto& attribs = p.mAttributes;
+ meshDef.mUri = attribs.begin()->second->mBufferView->mBuffer->mUri;
meshDef.mPrimitiveType = GLTF2_TO_DALI_PRIMITIVES[p.mMode];
auto& accPositions = *attribs.find(gt::Attribute::POSITION)->second;
meshDef.mPositions = ConvertMeshPrimitiveAccessor(accPositions);
const bool needNormalsTangents = accPositions.mType == gt::AccessorType::VEC3;
- for (auto& am : ATTRIBUTE_MAPPINGS)
+ for(auto& am : ATTRIBUTE_MAPPINGS)
{
auto iFind = attribs.find(am.mType);
- if (iFind != attribs.end())
+ if(iFind != attribs.end())
{
DALI_ASSERT_DEBUG(iFind->second->mBufferView->mBuffer->mUri.compare(meshDef.mUri) == 0);
auto& accessor = meshDef.*(am.mAccessor);
- accessor = ConvertMeshPrimitiveAccessor(*iFind->second);
+ accessor = ConvertMeshPrimitiveAccessor(*iFind->second);
// Fixing up -- a few of glTF2 sample models have VEC4 tangents; we need VEC3s.
- if (iFind->first == gt::Attribute::TANGENT && (accessor.mBlob.mElementSizeHint > am.mElementSizeRequired))
+ if(iFind->first == gt::Attribute::TANGENT && (accessor.mBlob.mElementSizeHint > am.mElementSizeRequired))
{
- accessor.mBlob.mStride = std::max(static_cast<uint16_t>(accessor.mBlob.mStride + accessor.mBlob.mElementSizeHint - am.mElementSizeRequired),
- accessor.mBlob.mElementSizeHint);
+ accessor.mBlob.mStride = std::max(static_cast<uint16_t>(accessor.mBlob.mStride + accessor.mBlob.mElementSizeHint - am.mElementSizeRequired),
+ accessor.mBlob.mElementSizeHint);
accessor.mBlob.mElementSizeHint = am.mElementSizeRequired;
}
- if (iFind->first == gt::Attribute::JOINTS_0)
+ if(iFind->first == gt::Attribute::JOINTS_0)
{
meshDef.mFlags |= (iFind->second->mComponentType == gt::Component::UNSIGNED_SHORT) * MeshDefinition::U16_JOINT_IDS;
DALI_ASSERT_DEBUG(MaskMatch(meshDef.mFlags, MeshDefinition::U16_JOINT_IDS) || iFind->second->mComponentType == gt::Component::FLOAT);
}
}
- else if (needNormalsTangents)
+ else if(needNormalsTangents)
{
- switch (am.mType)
+ switch(am.mType)
{
- case gt::Attribute::NORMAL:
- meshDef.RequestNormals();
- break;
+ case gt::Attribute::NORMAL:
+ meshDef.RequestNormals();
+ break;
- case gt::Attribute::TANGENT:
- meshDef.RequestTangents();
- break;
+ case gt::Attribute::TANGENT:
+ meshDef.RequestTangents();
+ break;
- default:
- break;
+ default:
+ break;
}
}
}
- if (p.mIndices)
+ if(p.mIndices)
{
meshDef.mIndices = ConvertMeshPrimitiveAccessor(*p.mIndices);
meshDef.mFlags |= (p.mIndices->mComponentType == gt::Component::UNSIGNED_INT) * MeshDefinition::U32_INDICES;
DALI_ASSERT_DEBUG(MaskMatch(meshDef.mFlags, MeshDefinition::U32_INDICES) || p.mIndices->mComponentType == gt::Component::UNSIGNED_SHORT);
}
- if (!p.mTargets.empty())
+ if(!p.mTargets.empty())
{
meshDef.mBlendShapes.reserve(p.mTargets.size());
meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
- for (const auto& target : p.mTargets)
+ for(const auto& target : p.mTargets)
{
MeshDefinition::BlendShape blendShape;
auto endIt = target.end();
- auto it = target.find(gt::Attribute::POSITION);
- if (it != endIt)
+ auto it = target.find(gt::Attribute::POSITION);
+ if(it != endIt)
{
blendShape.deltas = ConvertMeshPrimitiveAccessor(*it->second);
}
it = target.find(gt::Attribute::NORMAL);
- if (it != endIt)
+ if(it != endIt)
{
blendShape.normals = ConvertMeshPrimitiveAccessor(*it->second);
}
it = target.find(gt::Attribute::TANGENT);
- if (it != endIt)
+ if(it != endIt)
{
blendShape.tangents = ConvertMeshPrimitiveAccessor(*it->second);
}
- if (!m.mWeights.empty())
+ if(!m.mWeights.empty())
{
blendShape.weight = m.mWeights[meshDef.mBlendShapes.size()];
}
}
}
- outMeshes.push_back({ std::move(meshDef), MeshGeometry{} });
+ outMeshes.push_back({std::move(meshDef), MeshGeometry{}});
}
}
}
{
auto modelNode = new ModelNode();
- modelNode->mShaderIdx = 0; // TODO: further thought
+ modelNode->mShaderIdx = 0; // TODO: further thought
auto materialIdx = prim.mMaterial.GetIndex();
- if (INVALID_INDEX == materialIdx)
+ if(INVALID_INDEX == materialIdx)
{
// https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#default-material
- if (INVALID_INDEX == cctx.mDefaultMaterial)
+ if(INVALID_INDEX == cctx.mDefaultMaterial)
{
- auto& outMaterials = cctx.mOutput.mResources.mMaterials;
+ auto& outMaterials = cctx.mOutput.mResources.mMaterials;
cctx.mDefaultMaterial = outMaterials.size();
ConvertMaterial(gt::Material{}, outMaterials);
void ConvertCamera(const gt::Camera& camera, CameraParameters& camParams)
{
camParams.isPerspective = camera.mType.compare("perspective") == 0;
- if (camParams.isPerspective)
+ if(camParams.isPerspective)
{
auto& perspective = camera.mPerspective;
- camParams.yFov = Degree(Radian(perspective.mYFov)).degree;
- camParams.zNear = perspective.mZNear;
- camParams.zFar = perspective.mZFar;
+ camParams.yFov = Degree(Radian(perspective.mYFov)).degree;
+ camParams.zNear = perspective.mZNear;
+ camParams.zFar = perspective.mZFar;
// TODO: yes, we seem to ignore aspectRatio in CameraParameters.
}
else
{
- auto& ortho = camera.mOrthographic;
+ auto& ortho = camera.mOrthographic;
camParams.orthographicSize = Vector4(-ortho.mXMag, ortho.mXMag, ortho.mYMag, -ortho.mYMag) * .5f;
- camParams.zNear = ortho.mZNear;
- camParams.zFar = ortho.mZFar;
+ camParams.zNear = ortho.mZNear;
+ camParams.zFar = ortho.mZFar;
}
}
void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, ConversionContext& cctx)
{
- auto& output = cctx.mOutput;
- auto& scene = output.mScene;
+ auto& output = cctx.mOutput;
+ auto& scene = output.mScene;
auto& resources = output.mResources;
- const auto idx = scene.GetNodeCount();
- auto weakNode = scene.AddNode([&]() {
- std::unique_ptr<NodeDefinition> nodeDef{ new NodeDefinition() };
+ const auto idx = scene.GetNodeCount();
+ auto weakNode = scene.AddNode([&]() {
+ std::unique_ptr<NodeDefinition> nodeDef{new NodeDefinition()};
nodeDef->mParentIdx = parentIdx;
- nodeDef->mName = node.mName;
- if (nodeDef->mName.empty())
+ nodeDef->mName = node.mName;
+ if(nodeDef->mName.empty())
{
// TODO: Production quality generation of unique names.
nodeDef->mName = std::to_string(reinterpret_cast<uintptr_t>(nodeDef.get()));
}
- if (!node.mSkin) // Nodes with skinned meshes are not supposed to have local transforms.
+ if(!node.mSkin) // Nodes with skinned meshes are not supposed to have local transforms.
{
- nodeDef->mPosition = node.mTranslation;
+ nodeDef->mPosition = node.mTranslation;
nodeDef->mOrientation = node.mRotation;
- nodeDef->mScale = node.mScale;
+ nodeDef->mScale = node.mScale;
}
return nodeDef;
}());
- if (!weakNode)
+ if(!weakNode)
{
ExceptionFlinger(ASSERT_LOCATION) << "Node name '" << node.mName << "' is not unique; scene is invalid.";
}
cctx.mNodeIndices.RegisterMapping(gltfIdx, idx);
Index skeletonIdx = node.mSkin ? node.mSkin.GetIndex() : INVALID_INDEX;
- if (node.mMesh && !node.mMesh->mPrimitives.empty())
+ if(node.mMesh && !node.mMesh->mPrimitives.empty())
{
auto& mesh = *node.mMesh;
- auto iPrim = mesh.mPrimitives.begin();
- auto modelNode = MakeModelNode(*iPrim, cctx);
- auto meshIdx = cctx.mMeshIds[node.mMesh.GetIndex()];
+ auto iPrim = mesh.mPrimitives.begin();
+ auto modelNode = MakeModelNode(*iPrim, cctx);
+ auto meshIdx = cctx.mMeshIds[node.mMesh.GetIndex()];
modelNode->mMeshIdx = meshIdx;
weakNode->mRenderable.reset(modelNode);
DALI_ASSERT_DEBUG(resources.mMeshes[meshIdx].first.mSkeletonIdx == INVALID_INDEX ||
- resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx);
+ resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx);
resources.mMeshes[meshIdx].first.mSkeletonIdx = skeletonIdx;
// As does model-exporter, we'll create anonymous child nodes for additional mesh( primitiv)es.
- while (++iPrim != mesh.mPrimitives.end())
+ while(++iPrim != mesh.mPrimitives.end())
{
- std::unique_ptr<NodeDefinition> child{ new NodeDefinition };
+ std::unique_ptr<NodeDefinition> child{new NodeDefinition};
child->mParentIdx = idx;
auto childModel = MakeModelNode(*iPrim, cctx);
scene.AddNode(std::move(child));
DALI_ASSERT_DEBUG(resources.mMeshes[meshIdx].first.mSkeletonIdx == INVALID_INDEX ||
- resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx);
+ resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx);
resources.mMeshes[meshIdx].first.mSkeletonIdx = skeletonIdx;
}
}
- if (node.mCamera)
+ if(node.mCamera)
{
CameraParameters camParams;
ConvertCamera(*node.mCamera, camParams);
output.mCameraParameters.push_back(camParams);
}
- for (auto& n : node.mChildren)
+ for(auto& n : node.mChildren)
{
ConvertNode(*n, n.GetIndex(), idx, cctx);
}
void ConvertSceneNodes(const gt::Scene& scene, ConversionContext& cctx)
{
auto& outScene = cctx.mOutput.mScene;
- Index rootIdx = outScene.GetNodeCount();
- switch (scene.mNodes.size())
+ Index rootIdx = outScene.GetNodeCount();
+ switch(scene.mNodes.size())
{
- case 0:
- break;
+ case 0:
+ break;
- case 1:
- ConvertNode(*scene.mNodes[0], scene.mNodes[0].GetIndex(), INVALID_INDEX, cctx);
- outScene.AddRootNode(rootIdx);
- break;
+ case 1:
+ ConvertNode(*scene.mNodes[0], scene.mNodes[0].GetIndex(), INVALID_INDEX, cctx);
+ outScene.AddRootNode(rootIdx);
+ break;
- default:
+ default:
{
- std::unique_ptr<NodeDefinition> sceneRoot{ new NodeDefinition() };
+ std::unique_ptr<NodeDefinition> sceneRoot{new NodeDefinition()};
sceneRoot->mName = "GLTF_LOADER_SCENE_ROOT_" + std::to_string(outScene.GetRoots().size());
outScene.AddNode(std::move(sceneRoot));
outScene.AddRootNode(rootIdx);
- for (auto& n : scene.mNodes)
+ for(auto& n : scene.mNodes)
{
ConvertNode(*n, n.GetIndex(), rootIdx, cctx);
}
{
ConvertSceneNodes(*doc.mScene, cctx);
- for (uint32_t i = 0, i1 = doc.mScene.GetIndex(); i < i1; ++i)
+ for(uint32_t i = 0, i1 = doc.mScene.GetIndex(); i < i1; ++i)
{
ConvertSceneNodes(doc.mScenes[i], cctx);
}
- for (uint32_t i = doc.mScene.GetIndex() + 1; i < doc.mScenes.size(); ++i)
+ for(uint32_t i = doc.mScene.GetIndex() + 1; i < doc.mScenes.size(); ++i)
{
ConvertSceneNodes(doc.mScenes[i], cctx);
}
}
-template <typename T>
+template<typename T>
void LoadDataFromAccessor(const std::string& path, Vector<T>& dataBuffer, uint32_t offset, uint32_t size)
{
std::ifstream animationBinaryFile(path, std::ifstream::binary);
- if (!animationBinaryFile.is_open())
+ if(!animationBinaryFile.is_open())
{
throw std::runtime_error("Failed to load " + path);
}
animationBinaryFile.close();
}
-template <typename T>
+template<typename T>
float LoadDataFromAccessors(const std::string& path, const gltf2::Accessor& input, const gltf2::Accessor& output, Vector<float>& inputDataBuffer, Vector<T>& outputDataBuffer)
{
inputDataBuffer.Resize(input.mCount);
outputDataBuffer.Resize(output.mCount);
- const uint32_t inputDataBufferSize = input.GetBytesLength();
+ const uint32_t inputDataBufferSize = input.GetBytesLength();
const uint32_t outputDataBufferSize = output.GetBytesLength();
- LoadDataFromAccessor<float>(path + std::string(input.mBufferView->mBuffer->mUri), inputDataBuffer,
- input.mBufferView->mByteOffset + input.mByteOffset, inputDataBufferSize);
- LoadDataFromAccessor<T>(path + std::string(output.mBufferView->mBuffer->mUri), outputDataBuffer,
- output.mBufferView->mByteOffset + output.mByteOffset, outputDataBufferSize);
+ LoadDataFromAccessor<float>(path + std::string(input.mBufferView->mBuffer->mUri), inputDataBuffer, input.mBufferView->mByteOffset + input.mByteOffset, inputDataBufferSize);
+ LoadDataFromAccessor<T>(path + std::string(output.mBufferView->mBuffer->mUri), outputDataBuffer, output.mBufferView->mByteOffset + output.mByteOffset, outputDataBufferSize);
ApplyAccessorMinMax(output, reinterpret_cast<float*>(outputDataBuffer.begin()));
return inputDataBuffer[input.mCount - 1u];
template<typename T>
float LoadKeyFrames(const std::string& path, const gt::Animation::Channel& channel, KeyFrames& keyFrames, gt::Animation::Channel::Target::Type type)
{
- const gltf2::Accessor& input = *channel.mSampler->mInput;
+ const gltf2::Accessor& input = *channel.mSampler->mInput;
const gltf2::Accessor& output = *channel.mSampler->mOutput;
Vector<float> inputDataBuffer;
- Vector<T> outputDataBuffer;
+ Vector<T> outputDataBuffer;
const float duration = LoadDataFromAccessors<T>(path, input, output, inputDataBuffer, outputDataBuffer);
- for (uint32_t i = 0; i < input.mCount; ++i)
+ for(uint32_t i = 0; i < input.mCount; ++i)
{
keyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i]);
}
float LoadBlendShapeKeyFrames(const std::string& path, const gt::Animation::Channel& channel, const std::string& nodeName, uint32_t& propertyIndex, std::vector<SceneLoader::AnimatedProperty>& properties)
{
- const gltf2::Accessor& input = *channel.mSampler->mInput;
+ const gltf2::Accessor& input = *channel.mSampler->mInput;
const gltf2::Accessor& output = *channel.mSampler->mOutput;
Vector<float> inputDataBuffer;
const float duration = LoadDataFromAccessors<float>(path, input, output, inputDataBuffer, outputDataBuffer);
- char weightNameBuffer[32];
- auto prefixSize = snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s[", BLEND_SHAPE_WEIGHTS_UNIFORM.c_str());
- char* const pWeightName = weightNameBuffer + prefixSize;
- const auto remainingSize = sizeof(weightNameBuffer) - prefixSize;
- for (uint32_t weightIndex = 0u, endWeightIndex = channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount; weightIndex < endWeightIndex; ++weightIndex)
+ char weightNameBuffer[32];
+ auto prefixSize = snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s[", BLEND_SHAPE_WEIGHTS_UNIFORM.c_str());
+ char* const pWeightName = weightNameBuffer + prefixSize;
+ const auto remainingSize = sizeof(weightNameBuffer) - prefixSize;
+ for(uint32_t weightIndex = 0u, endWeightIndex = channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount; weightIndex < endWeightIndex; ++weightIndex)
{
AnimatedProperty& animatedProperty = properties[propertyIndex++];
animatedProperty.mPropertyName = std::string(weightNameBuffer);
animatedProperty.mKeyFrames = KeyFrames::New();
- for (uint32_t i = 0; i < input.mCount; ++i)
+ for(uint32_t i = 0; i < input.mCount; ++i)
{
- animatedProperty.mKeyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i*endWeightIndex + weightIndex]);
+ animatedProperty.mKeyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i * endWeightIndex + weightIndex]);
}
- animatedProperty.mTimePeriod = { 0.f, duration };
+ animatedProperty.mTimePeriod = {0.f, duration};
}
return duration;
output.mAnimationDefinitions.reserve(output.mAnimationDefinitions.size() + doc.mAnimations.size());
- for (const auto& animation : doc.mAnimations)
+ for(const auto& animation : doc.mAnimations)
{
AnimationDefinition animationDef;
- if (!animation.mName.empty())
+ if(!animation.mName.empty())
{
animationDef.mName = animation.mName;
}
uint32_t numberOfProperties = 0u;
- for (const auto& channel : animation.mChannels)
+ for(const auto& channel : animation.mChannels)
{
numberOfProperties += channel.mSampler->mOutput->mCount;
}
animationDef.mProperties.resize(numberOfProperties);
Index propertyIndex = 0u;
- for (const auto& channel : animation.mChannels)
+ for(const auto& channel : animation.mChannels)
{
std::string nodeName;
- if (!channel.mTarget.mNode->mName.empty())
+ if(!channel.mTarget.mNode->mName.empty())
{
nodeName = channel.mTarget.mNode->mName;
}
else
{
Index index = cctx.mNodeIndices.GetRuntimeId(channel.mTarget.mNode.GetIndex());
- nodeName = cctx.mOutput.mScene.GetNode(index)->mName;
+ nodeName = cctx.mOutput.mScene.GetNode(index)->mName;
}
float duration = 0.f;
- switch (channel.mTarget.mPath)
+ switch(channel.mTarget.mPath)
{
case gt::Animation::Channel::Target::TRANSLATION:
{
AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
- animatedProperty.mNodeName = nodeName;
+ animatedProperty.mNodeName = nodeName;
animatedProperty.mPropertyName = POSITION_PROPERTY;
animatedProperty.mKeyFrames = KeyFrames::New();
- duration = LoadKeyFrames<Vector3>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
+ duration = LoadKeyFrames<Vector3>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
- animatedProperty.mTimePeriod = { 0.f, duration };
+ animatedProperty.mTimePeriod = {0.f, duration};
break;
}
case gt::Animation::Channel::Target::ROTATION:
{
AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
- animatedProperty.mNodeName = nodeName;
+ animatedProperty.mNodeName = nodeName;
animatedProperty.mPropertyName = ORIENTATION_PROPERTY;
animatedProperty.mKeyFrames = KeyFrames::New();
- duration = LoadKeyFrames<Quaternion>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
+ duration = LoadKeyFrames<Quaternion>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
- animatedProperty.mTimePeriod = { 0.f, duration };
+ animatedProperty.mTimePeriod = {0.f, duration};
break;
}
case gt::Animation::Channel::Target::SCALE:
{
AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
- animatedProperty.mNodeName = nodeName;
+ animatedProperty.mNodeName = nodeName;
animatedProperty.mPropertyName = SCALE_PROPERTY;
animatedProperty.mKeyFrames = KeyFrames::New();
- duration = LoadKeyFrames<Vector3>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
+ duration = LoadKeyFrames<Vector3>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
- animatedProperty.mTimePeriod = { 0.f, duration };
+ animatedProperty.mTimePeriod = {0.f, duration};
break;
}
case gt::Animation::Channel::Target::WEIGHTS:
// otherwise we'll set identity matrices for inverse bind pose.
struct IInverseBindMatrixProvider
{
- virtual ~IInverseBindMatrixProvider() {}
+ virtual ~IInverseBindMatrixProvider()
+ {
+ }
virtual void Provide(Matrix& ibm) = 0;
};
struct InverseBindMatrixAccessor : public IInverseBindMatrixProvider
{
- std::ifstream mStream;
+ std::ifstream mStream;
const uint32_t mElementSizeBytes;
InverseBindMatrixAccessor(const gt::Accessor& accessor, const std::string& path)
auto& resources = cctx.mOutput.mResources;
resources.mSkeletons.reserve(doc.mSkins.size());
- for (auto& s : doc.mSkins)
+ for(auto& s : doc.mSkins)
{
std::unique_ptr<IInverseBindMatrixProvider> ibmProvider;
- if (s.mInverseBindMatrices)
+ if(s.mInverseBindMatrices)
{
ibmProvider.reset(new InverseBindMatrixAccessor(*s.mInverseBindMatrices, cctx.mPath));
}
}
SkeletonDefinition skeleton;
- if (s.mSkeleton.GetIndex() != INVALID_INDEX)
+ if(s.mSkeleton.GetIndex() != INVALID_INDEX)
{
skeleton.mRootNodeIdx = cctx.mNodeIndices.GetRuntimeId(s.mSkeleton.GetIndex());
}
skeleton.mJoints.resize(s.mJoints.size());
auto iJoint = skeleton.mJoints.begin();
- for (auto& j : s.mJoints)
+ for(auto& j : s.mJoints)
{
iJoint->mNodeIdx = cctx.mNodeIndices.GetRuntimeId(j.GetIndex());
void ProduceShaders(ShaderDefinitionFactory& shaderFactory, SceneDefinition& scene)
{
- for (size_t i0 = 0, i1 = scene.GetNodeCount(); i0 != i1; ++i0)
+ for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 != i1; ++i0)
{
auto nodeDef = scene.GetNode(i0);
- if (auto renderable = nodeDef->mRenderable.get())
+ if(auto renderable = nodeDef->mRenderable.get())
{
renderable->mShaderIdx = shaderFactory.ProduceShader(*nodeDef);
}
js::SetObjectReader(SCENE_READER);
}
-} // nonamespace
+} // namespace
void LoadGltfScene(const std::string& url, ShaderDefinitionFactory& shaderFactory, LoadResult& params)
{
bool failed = false;
- auto js = LoadTextFile(url.c_str(), &failed);
- if (failed)
+ auto js = LoadTextFile(url.c_str(), &failed);
+ if(failed)
{
throw std::runtime_error("Failed to load " + url);
}
json::unique_ptr root(json_parse(js.c_str(), js.size()));
- if (!root)
+ if(!root)
{
throw std::runtime_error("Failed to parse " + url);
}
static bool setObjectReaders = true;
- if (setObjectReaders)
+ if(setObjectReaders)
{
// NOTE: only referencing own, anonymous namespace, const objects; the pointers will never need to change.
SetObjectReaders();
gt::Document doc;
- auto& rootObj = js::Cast<json_object_s>(*root);
- auto jsAsset = js::FindObjectChild("asset", rootObj);
- auto jsAssetVersion = js::FindObjectChild("version", js::Cast<json_object_s>(*jsAsset));
- doc.mAsset.mVersion = js::Read::StringView(*jsAssetVersion);
+ auto& rootObj = js::Cast<json_object_s>(*root);
+ auto jsAsset = js::FindObjectChild("asset", rootObj);
+ auto jsAssetVersion = js::FindObjectChild("version", js::Cast<json_object_s>(*jsAsset));
+ doc.mAsset.mVersion = js::Read::StringView(*jsAssetVersion);
gt::SetRefReaderObject(doc);
DOCUMENT_READER.Read(rootObj, doc);
- auto path = url.substr(0, url.rfind('/') + 1);
- ConversionContext cctx{ params, path, INVALID_INDEX };
+ auto path = url.substr(0, url.rfind('/') + 1);
+ ConversionContext cctx{params, path, INVALID_INDEX};
ConvertMaterials(doc, cctx);
ConvertMeshes(doc, cctx);
params.mScene.EnsureUniqueSkinningShaderInstances(params.mResources);
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
*/
- // FILE HEADER
+// FILE HEADER
#include "dali-scene-loader/public-api/ktx-loader.h"
- // EXTERNAL INCLUDES
-#include "dali/public-api/rendering/texture.h"
+// EXTERNAL INCLUDES
#include <fstream>
#include <memory>
+#include "dali/public-api/rendering/texture.h"
namespace Dali
{
-
namespace
{
-
// http://github.khronos.org/KTX-Specification/
-const uint8_t KTX_ID_HEAD[] = { 0xAB, 0x4B, 0x54, 0x58, 0x20 };
-const uint8_t KTX_ID_TAIL[] = { 0xBB, 0x0D, 0x0A, 0x1A, 0x0A };
+const uint8_t KTX_ID_HEAD[] = {0xAB, 0x4B, 0x54, 0x58, 0x20};
+const uint8_t KTX_ID_TAIL[] = {0xBB, 0x0D, 0x0A, 0x1A, 0x0A};
-const uint8_t KTX_VERSION_1_1[] = { 0x31, 0x31 };
-const uint8_t KTX_VERSION_2_0[] = { 0x32, 0x30 };
+const uint8_t KTX_VERSION_1_1[] = {0x31, 0x31};
+const uint8_t KTX_VERSION_2_0[] = {0x32, 0x30};
static_assert(sizeof(KTX_ID_HEAD) + sizeof(KTX_ID_TAIL) == 10);
static_assert(sizeof(KTX_VERSION_1_1) == 2);
{
struct KtxFileHeader
{
- uint8_t identifier[12];
- uint32_t endianness;
- uint32_t glType; //(UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5, etc.)
- uint32_t glTypeSize;
- uint32_t glFormat; //(RGB, RGBA, BGRA, etc.)
- uint32_t glInternalFormat; //For uncompressed textures, specifies the internalformat parameter passed to glTexStorage*D or glTexImage*D
- uint32_t glBaseInternalFormat;
- uint32_t pixelWidth;
- uint32_t pixelHeight;
- uint32_t pixelDepth;
- uint32_t numberOfArrayElements;
- uint32_t numberOfFaces; //Cube map faces are stored in the order: +X, -X, +Y, -Y, +Z, -Z.
- uint32_t numberOfMipmapLevels;
- uint32_t bytesOfKeyValueData;
+ uint8_t identifier[12];
+ uint32_t endianness;
+ uint32_t glType; //(UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5, etc.)
+ uint32_t glTypeSize;
+ uint32_t glFormat; //(RGB, RGBA, BGRA, etc.)
+ uint32_t glInternalFormat; //For uncompressed textures, specifies the internalformat parameter passed to glTexStorage*D or glTexImage*D
+ uint32_t glBaseInternalFormat;
+ uint32_t pixelWidth;
+ uint32_t pixelHeight;
+ uint32_t pixelDepth;
+ uint32_t numberOfArrayElements;
+ uint32_t numberOfFaces; //Cube map faces are stored in the order: +X, -X, +Y, -Y, +Z, -Z.
+ uint32_t numberOfMipmapLevels;
+ uint32_t bytesOfKeyValueData;
bool IsIdentifierValid() const
{
return std::equal(KTX_ID_HEAD, std::end(KTX_ID_HEAD), identifier) &&
- (std::equal(KTX_VERSION_1_1, std::end(KTX_VERSION_1_1), identifier + sizeof(KTX_ID_HEAD)) ||
- std::equal(KTX_VERSION_2_0, std::end(KTX_VERSION_2_0), identifier + sizeof(KTX_ID_HEAD))) &&
- std::equal(KTX_ID_TAIL, std::end(KTX_ID_TAIL), identifier + (sizeof(KTX_ID_HEAD) + sizeof(KTX_VERSION_1_1)));
+ (std::equal(KTX_VERSION_1_1, std::end(KTX_VERSION_1_1), identifier + sizeof(KTX_ID_HEAD)) ||
+ std::equal(KTX_VERSION_2_0, std::end(KTX_VERSION_2_0), identifier + sizeof(KTX_ID_HEAD))) &&
+ std::equal(KTX_ID_TAIL, std::end(KTX_ID_TAIL), identifier + (sizeof(KTX_ID_HEAD) + sizeof(KTX_VERSION_1_1)));
}
};
*/
bool ConvertPixelFormat(const uint32_t ktxPixelFormat, Pixel::Format& format)
{
- switch (ktxPixelFormat)
- {
- case 0x93B0: // GL_COMPRESSED_RGBA_ASTC_4x4
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR;
- break;
- }
- case 0x93B1: // GL_COMPRESSED_RGBA_ASTC_5x4
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_5x4_KHR;
- break;
- }
- case 0x93B2: // GL_COMPRESSED_RGBA_ASTC_5x5
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_5x5_KHR;
- break;
- }
- case 0x93B3: // GL_COMPRESSED_RGBA_ASTC_6x5
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_6x5_KHR;
- break;
- }
- case 0x93B4: // GL_COMPRESSED_RGBA_ASTC_6x6
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_6x6_KHR;
- break;
- }
- case 0x93B5: // GL_COMPRESSED_RGBA_ASTC_8x5
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_8x5_KHR;
- break;
- }
- case 0x93B6: // GL_COMPRESSED_RGBA_ASTC_8x6
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_8x6_KHR;
- break;
- }
- case 0x93B7: // GL_COMPRESSED_RGBA_ASTC_8x8
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_8x8_KHR;
- break;
- }
- case 0x93B8: // GL_COMPRESSED_RGBA_ASTC_10x5
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_10x5_KHR;
- break;
- }
- case 0x93B9: // GL_COMPRESSED_RGBA_ASTC_10x6
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_10x6_KHR;
- break;
- }
- case 0x93BA: // GL_COMPRESSED_RGBA_ASTC_10x8
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_10x8_KHR;
- break;
- }
- case 0x93BB: // GL_COMPRESSED_RGBA_ASTC_10x10
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_10x10_KHR;
- break;
- }
- case 0x93BC: // GL_COMPRESSED_RGBA_ASTC_12x10
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_12x10_KHR;
- break;
- }
- case 0x93BD: // GL_COMPRESSED_RGBA_ASTC_12x12
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_12x12_KHR;
- break;
- }
- case 0x881B: // GL_RGB16F
+ switch(ktxPixelFormat)
{
- format = Pixel::RGB16F;
- break;
- }
- case 0x8815: // GL_RGB32F
- {
- format = Pixel::RGB32F;
- break;
- }
- case 0x8C3A: // GL_R11F_G11F_B10F
- {
- format = Pixel::RGB32F;
- break;
- }
- case 0x8D7C: // GL_RGBA8UI
- {
- format = Pixel::RGBA8888;
- break;
- }
- case 0x8D7D: // GL_RGB8UI
- {
- format = Pixel::RGB888;
- break;
- }
- default:
- {
- return false;
- }
+ case 0x93B0: // GL_COMPRESSED_RGBA_ASTC_4x4
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR;
+ break;
+ }
+ case 0x93B1: // GL_COMPRESSED_RGBA_ASTC_5x4
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_5x4_KHR;
+ break;
+ }
+ case 0x93B2: // GL_COMPRESSED_RGBA_ASTC_5x5
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_5x5_KHR;
+ break;
+ }
+ case 0x93B3: // GL_COMPRESSED_RGBA_ASTC_6x5
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_6x5_KHR;
+ break;
+ }
+ case 0x93B4: // GL_COMPRESSED_RGBA_ASTC_6x6
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_6x6_KHR;
+ break;
+ }
+ case 0x93B5: // GL_COMPRESSED_RGBA_ASTC_8x5
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_8x5_KHR;
+ break;
+ }
+ case 0x93B6: // GL_COMPRESSED_RGBA_ASTC_8x6
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_8x6_KHR;
+ break;
+ }
+ case 0x93B7: // GL_COMPRESSED_RGBA_ASTC_8x8
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_8x8_KHR;
+ break;
+ }
+ case 0x93B8: // GL_COMPRESSED_RGBA_ASTC_10x5
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_10x5_KHR;
+ break;
+ }
+ case 0x93B9: // GL_COMPRESSED_RGBA_ASTC_10x6
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_10x6_KHR;
+ break;
+ }
+ case 0x93BA: // GL_COMPRESSED_RGBA_ASTC_10x8
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_10x8_KHR;
+ break;
+ }
+ case 0x93BB: // GL_COMPRESSED_RGBA_ASTC_10x10
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_10x10_KHR;
+ break;
+ }
+ case 0x93BC: // GL_COMPRESSED_RGBA_ASTC_12x10
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_12x10_KHR;
+ break;
+ }
+ case 0x93BD: // GL_COMPRESSED_RGBA_ASTC_12x12
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_12x12_KHR;
+ break;
+ }
+ case 0x881B: // GL_RGB16F
+ {
+ format = Pixel::RGB16F;
+ break;
+ }
+ case 0x8815: // GL_RGB32F
+ {
+ format = Pixel::RGB32F;
+ break;
+ }
+ case 0x8C3A: // GL_R11F_G11F_B10F
+ {
+ format = Pixel::RGB32F;
+ break;
+ }
+ case 0x8D7C: // GL_RGBA8UI
+ {
+ format = Pixel::RGBA8888;
+ break;
+ }
+ case 0x8D7D: // GL_RGB8UI
+ {
+ format = Pixel::RGB888;
+ break;
+ }
+ default:
+ {
+ return false;
+ }
}
return true;
Texture CubeData::CreateTexture() const
{
- Texture texture = Texture::New(TextureType::TEXTURE_CUBE, data[0][0].GetPixelFormat(),
- data[0][0].GetWidth(), data[0][0].GetHeight());
- for (size_t iSide = 0u, iEndSize = data.size(); iSide < iEndSize; ++iSide)
+ Texture texture = Texture::New(TextureType::TEXTURE_CUBE, data[0][0].GetPixelFormat(), data[0][0].GetWidth(), data[0][0].GetHeight());
+ for(size_t iSide = 0u, iEndSize = data.size(); iSide < iEndSize; ++iSide)
{
auto& side = data[iSide];
- for (size_t iMipLevel = 0u, iEndMipLevel = data[0].size(); iMipLevel < iEndMipLevel; ++iMipLevel)
+ for(size_t iMipLevel = 0u, iEndMipLevel = data[0].size(); iMipLevel < iEndMipLevel; ++iMipLevel)
{
- texture.Upload(side[iMipLevel], CubeMapLayer::POSITIVE_X + iSide, iMipLevel,
- 0u, 0u, side[iMipLevel].GetWidth(), side[iMipLevel].GetHeight());
+ texture.Upload(side[iMipLevel], CubeMapLayer::POSITIVE_X + iSide, iMipLevel, 0u, 0u, side[iMipLevel].GetWidth(), side[iMipLevel].GetHeight());
}
}
bool LoadCubeMapData(const std::string& path, CubeData& cubedata)
{
std::fstream fp(path, std::ios::in | std::ios::binary);
- if (fp.is_open() == false)
+ if(fp.is_open() == false)
{
return false;
}
KtxFileHeader header;
- if (fp.read(reinterpret_cast<char*>(&header), sizeof(KtxFileHeader)).good() == false)
+ if(fp.read(reinterpret_cast<char*>(&header), sizeof(KtxFileHeader)).good() == false)
{
return false;
}
- if (!header.IsIdentifierValid())
+ if(!header.IsIdentifierValid())
{
return false;
}
// Skip the key-values:
- if (fp.seekg(header.bytesOfKeyValueData, fp.cur).good() == false)
+ if(fp.seekg(header.bytesOfKeyValueData, fp.cur).good() == false)
{
return false;
}
- header.numberOfMipmapLevels = std::max(header.numberOfMipmapLevels, 1u);
+ header.numberOfMipmapLevels = std::max(header.numberOfMipmapLevels, 1u);
header.numberOfArrayElements = std::max(header.numberOfArrayElements, 1u);
- header.pixelDepth = std::max(header.pixelDepth, 1u);
- header.pixelHeight = std::max(header.pixelHeight, 1u);
+ header.pixelDepth = std::max(header.pixelDepth, 1u);
+ header.pixelHeight = std::max(header.pixelHeight, 1u);
cubedata.data.resize(header.numberOfFaces);
- for (uint32_t face = 0u; face < header.numberOfFaces; ++face)
+ for(uint32_t face = 0u; face < header.numberOfFaces; ++face)
{
cubedata.data[face].resize(header.numberOfMipmapLevels);
}
ConvertPixelFormat(header.glInternalFormat, daliformat);
- for (uint32_t mipmapLevel = 0u; mipmapLevel < header.numberOfMipmapLevels; ++mipmapLevel)
+ for(uint32_t mipmapLevel = 0u; mipmapLevel < header.numberOfMipmapLevels; ++mipmapLevel)
{
uint32_t byteSize = 0u;
- if (fp.read(reinterpret_cast<char*>(&byteSize), sizeof(byteSize)).good() == false)
+ if(fp.read(reinterpret_cast<char*>(&byteSize), sizeof(byteSize)).good() == false)
{
return false;
}
- if (0u != byteSize % 4u)
+ if(0u != byteSize % 4u)
{
byteSize += 4u - byteSize % 4u;
}
- for (uint32_t arrayElement = 0u; arrayElement < header.numberOfArrayElements; ++arrayElement) //arrayElement must be 0 or 1
+ for(uint32_t arrayElement = 0u; arrayElement < header.numberOfArrayElements; ++arrayElement) //arrayElement must be 0 or 1
{
- for (uint32_t face = 0u; face < header.numberOfFaces; ++face)
+ for(uint32_t face = 0u; face < header.numberOfFaces; ++face)
{
- std::unique_ptr<uint8_t, void(*)(uint8_t*)>img(new uint8_t[byteSize], FreeBuffer);
- if (fp.read(reinterpret_cast<char*>(img.get()), byteSize).good() == false)
+ std::unique_ptr<uint8_t, void (*)(uint8_t*)> img(new uint8_t[byteSize], FreeBuffer);
+ if(fp.read(reinterpret_cast<char*>(img.get()), byteSize).good() == false)
{
return false;
}
return true;
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace
{
-
constexpr SamplerFlags::Type FILTER_MODES_FROM_DALI[]{
SamplerFlags::FILTER_LINEAR | SamplerFlags::FILTER_MIPMAP_NEAREST,
SamplerFlags::FILTER_LINEAR,
SamplerFlags::WRAP_MIRROR,
};
-constexpr FilterMode::Type FILTER_MODES_TO_DALI[]{
+constexpr FilterMode::Type FILTER_MODES_TO_DALI[]{
FilterMode::NEAREST,
FilterMode::LINEAR,
FilterMode::NEAREST_MIPMAP_NEAREST,
constexpr WrapMode::Type WRAP_MODES_TO_DALI[]{
WrapMode::REPEAT,
WrapMode::CLAMP_TO_EDGE,
- WrapMode::MIRRORED_REPEAT
-};
+ WrapMode::MIRRORED_REPEAT};
const SamplerFlags::Type SINGLE_VALUE_SAMPLER = SamplerFlags::Encode(FilterMode::NEAREST, FilterMode::NEAREST, WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE);
-}
+} // namespace
SamplerFlags::Type SamplerFlags::Encode(FilterMode::Type minFilter, FilterMode::Type magFilter, WrapMode::Type wrapS, WrapMode::Type wrapT)
{
return FILTER_MODES_FROM_DALI[minFilter] | ((FILTER_MODES_FROM_DALI[magFilter] & FILTER_MAG_BITS) << FILTER_MAG_SHIFT) |
- (WRAP_MODES_FROM_DALI[wrapS] << WRAP_S_SHIFT) | (WRAP_MODES_FROM_DALI[wrapT] << WRAP_T_SHIFT);
+ (WRAP_MODES_FROM_DALI[wrapS] << WRAP_S_SHIFT) | (WRAP_MODES_FROM_DALI[wrapT] << WRAP_T_SHIFT);
}
FilterMode::Type SamplerFlags::GetMinFilter(Type flags)
TextureDefinition::TextureDefinition(const std::string& imageUri, SamplerFlags::Type samplerFlags)
: mImageUri(imageUri),
mSamplerFlags(samplerFlags)
-{}
+{
+}
MaterialDefinition::RawData
- MaterialDefinition::LoadRaw(const std::string& imagesPath) const
+MaterialDefinition::LoadRaw(const std::string& imagesPath) const
{
RawData raw;
const bool hasTransparency = MaskMatch(mFlags, TRANSPARENCY);
- uint32_t numBuffers = mTextureStages.size() + (hasTransparency ?
- !CheckTextures(ALBEDO) + !CheckTextures(METALLIC | ROUGHNESS) + !CheckTextures(NORMAL) :
- !CheckTextures(ALBEDO | METALLIC) + !CheckTextures(NORMAL | ROUGHNESS));
- if (numBuffers == 0)
+ uint32_t numBuffers = mTextureStages.size() + (hasTransparency ? !CheckTextures(ALBEDO) + !CheckTextures(METALLIC | ROUGHNESS) + !CheckTextures(NORMAL) : !CheckTextures(ALBEDO | METALLIC) + !CheckTextures(NORMAL | ROUGHNESS));
+ if(numBuffers == 0)
{
return raw;
}
raw.mTextures.reserve(numBuffers);
// Load textures
- auto iTexture = mTextureStages.cbegin();
+ auto iTexture = mTextureStages.cbegin();
auto checkStage = [&](uint32_t flags) {
return iTexture != mTextureStages.end() && MaskMatch(iTexture->mSemantic, flags);
};
// Check for compulsory textures: Albedo, Metallic, Roughness, Normal
- if (checkStage(ALBEDO | METALLIC))
+ if(checkStage(ALBEDO | METALLIC))
{
- raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags });
+ raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags});
++iTexture;
- if (checkStage(NORMAL | ROUGHNESS))
+ if(checkStage(NORMAL | ROUGHNESS))
{
- raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags });
+ raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
else // single value normal-roughness
{
const auto bufferSize = 4;
- uint8_t* buffer = new uint8_t[bufferSize]{ 0x7f, 0x7f, 0xff, 0xff }; // normal of (0, 0, 1), roughness of 1
- raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER });
+ uint8_t* buffer = new uint8_t[bufferSize]{0x7f, 0x7f, 0xff, 0xff}; // normal of (0, 0, 1), roughness of 1
+ raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER});
}
}
else
{
- if (checkStage(ALBEDO))
+ if(checkStage(ALBEDO))
{
- raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags });
+ raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
else // single value albedo, albedo-alpha or albedo-metallic
{
uint32_t bufferSize = 4;
- uint8_t* buffer = nullptr;
- auto format = Pixel::Format::RGBA8888;
- if (hasTransparency) // albedo-alpha
+ uint8_t* buffer = nullptr;
+ auto format = Pixel::Format::RGBA8888;
+ if(hasTransparency) // albedo-alpha
{
- buffer = new uint8_t[bufferSize];
+ buffer = new uint8_t[bufferSize];
buffer[3] = static_cast<uint8_t>(mColor.a * 255.f);
}
- else if (!checkStage(METALLIC | ROUGHNESS)) // albedo-metallic
+ else if(!checkStage(METALLIC | ROUGHNESS)) // albedo-metallic
{
- buffer = new uint8_t[bufferSize];
- buffer[3] = 0xff; // metallic of 1.0
+ buffer = new uint8_t[bufferSize];
+ buffer[3] = 0xff; // metallic of 1.0
}
- else // albedo
+ else // albedo
{
bufferSize = 3;
- buffer = new uint8_t[bufferSize];
- format = Pixel::Format::RGB888;
+ buffer = new uint8_t[bufferSize];
+ format = Pixel::Format::RGB888;
}
buffer[0] = static_cast<uint8_t>(mColor.r * 255.f);
buffer[1] = static_cast<uint8_t>(mColor.g * 255.f);
buffer[2] = static_cast<uint8_t>(mColor.b * 255.f);
- raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, format, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER });
+ raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, format, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER});
}
// If we have transparency, or an image based albedo map, we will have to continue with separate metallicRoughness + normal.
const bool createMetallicRoughnessAndNormal = hasTransparency || std::distance(mTextureStages.begin(), iTexture) > 0;
- if (checkStage(METALLIC | ROUGHNESS))
+ if(checkStage(METALLIC | ROUGHNESS))
{
- raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags });
+ raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
- else if (createMetallicRoughnessAndNormal)
+ else if(createMetallicRoughnessAndNormal)
{
// NOTE: we want to set both metallic and roughness to 1.0; dli uses the R & A channels,
// glTF2 uses B & G, so we might as well just set all components to 1.0.
const auto bufferSize = 4;
- uint8_t* buffer = new uint8_t[bufferSize]{ 0xff, 0xff, 0xff, 0xff };
- raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER });
+ uint8_t* buffer = new uint8_t[bufferSize]{0xff, 0xff, 0xff, 0xff};
+ raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER});
}
- if (checkStage(NORMAL))
+ if(checkStage(NORMAL))
{
- raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags });
+ raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
- else if (createMetallicRoughnessAndNormal)
+ else if(createMetallicRoughnessAndNormal)
{
const auto bufferSize = 3;
- uint8_t* buffer = new uint8_t[bufferSize]{ 0x7f, 0x7f, 0xff }; // normal of (0, 0, 1)
- raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER });
+ uint8_t* buffer = new uint8_t[bufferSize]{0x7f, 0x7f, 0xff}; // normal of (0, 0, 1)
+ raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER});
}
else // single-value normal-roughness
{
const auto bufferSize = 4;
- uint8_t* buffer = new uint8_t[bufferSize]{ 0x7f, 0x7f, 0xff, 0xff }; // normal of (0, 0, 1), roughness of 1.0
- raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER });
+ uint8_t* buffer = new uint8_t[bufferSize]{0x7f, 0x7f, 0xff, 0xff}; // normal of (0, 0, 1), roughness of 1.0
+ raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER});
}
}
// Extra textures. TODO: emissive, occlusion etc.
- if (checkStage(SUBSURFACE))
+ if(checkStage(SUBSURFACE))
{
- raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags });
+ raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
auto textureSet = TextureSet::New();
uint32_t n = 0;
- for (auto& tData : raw.mTextures)
+ for(auto& tData : raw.mTextures)
{
- auto& pixels = tData.mPixels;
- auto texture = Texture::New(TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight());
+ auto& pixels = tData.mPixels;
+ auto texture = Texture::New(TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight());
texture.Upload(tData.mPixels, 0, 0, 0, 0, pixels.GetWidth(), pixels.GetHeight());
- if (tData.mSamplerFlags & SamplerFlags::MIPMAP_MASK)
+ if(tData.mSamplerFlags & SamplerFlags::MIPMAP_MASK)
{
texture.GenerateMipmaps();
}
}
// Assign textures to slots -- starting with 2D ones, then cubemaps, if any.
- if (mEnvironmentIdx < environments.size())
+ if(mEnvironmentIdx < environments.size())
{
auto& envTextures = environments[mEnvironmentIdx].second;
- if (envTextures.mDiffuse)
+ if(envTextures.mDiffuse)
{
textureSet.SetTexture(n, envTextures.mDiffuse);
++n;
}
- if (envTextures.mSpecular)
+ if(envTextures.mSpecular)
{
auto specularSampler = Sampler::New();
specularSampler.SetWrapMode(WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE);
}
else
{
- ExceptionFlinger(ASSERT_LOCATION) << "Environment index (" << mEnvironmentIdx << ") out of bounds (" <<
- environments.size() << ").";
+ ExceptionFlinger(ASSERT_LOCATION) << "Environment index (" << mEnvironmentIdx << ") out of bounds (" << environments.size() << ").";
}
return textureSet;
bool MaterialDefinition::CheckTextures(uint32_t flags) const
{
return std::find_if(mTextureStages.begin(), mTextureStages.end(), [flags](const TextureStage& ts) {
- return MaskMatch(ts.mSemantic, flags);
- }) != mTextureStages.end();
+ return MaskMatch(ts.mSemantic, flags);
+ }) != mTextureStages.end();
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
-* Copyright (c) 2020 Samsung Electronics Co., Ltd.
+* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
MatrixStack::MatrixStack()
{
mStack.reserve(16);
void MatrixStack::Push(const Matrix& model)
{
- if (mStack.empty())
+ if(mStack.empty())
{
mStack.push_back(model);
}
else
{
- Matrix m{ false };
+ Matrix m{false};
Matrix::Multiply(m, model, mStack.back());
mStack.push_back(m);
}
mStack.clear();
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "dali-scene-loader/public-api/mesh-definition.h"
// EXTERNAL INCLUDES
-#include "dali/devel-api/adaptor-framework/pixel-buffer.h"
-#include <fstream>
#include <cstring>
+#include <fstream>
+#include "dali/devel-api/adaptor-framework/pixel-buffer.h"
namespace Dali
{
{
namespace
{
-
using Uint16Vector4 = uint16_t[4];
class IndexProvider
IndexProvider(const uint16_t* indices)
: mData(reinterpret_cast<uintptr_t>(indices)),
mFunc(indices ? IncrementPointer : Increment)
- {}
+ {
+ }
uint16_t operator()()
{
static uint16_t IncrementPointer(uintptr_t& data)
{
- auto iPtr = reinterpret_cast<const uint16_t*>(data);
+ auto iPtr = reinterpret_cast<const uint16_t*>(data);
auto result = *iPtr;
- data = reinterpret_cast<uintptr_t>(++iPtr);
+ data = reinterpret_cast<uintptr_t>(++iPtr);
return result;
}
uintptr_t mData;
- uint16_t(*mFunc)(uintptr_t&);
+ uint16_t (*mFunc)(uintptr_t&);
};
-
const std::string QUAD("quad");
///@brief Reads a blob from the given stream @a source into @a target, which must have
/// at least @a descriptor.length bytes.
bool ReadBlob(const MeshDefinition::Blob& descriptor, std::istream& source, uint8_t* target)
{
- if (!source.seekg(descriptor.mOffset, std::istream::beg))
+ if(!source.seekg(descriptor.mOffset, std::istream::beg))
{
return false;
}
- if (descriptor.IsConsecutive())
+ if(descriptor.IsConsecutive())
{
return !!source.read(reinterpret_cast<char*>(target), descriptor.mLength);
}
else
{
DALI_ASSERT_DEBUG(descriptor.mStride > descriptor.mElementSizeHint);
- const uint32_t diff = descriptor.mStride - descriptor.mElementSizeHint;
- uint32_t readSize = 0;
- while (readSize < descriptor.mLength &&
- source.read(reinterpret_cast<char*>(target), descriptor.mElementSizeHint) &&
- source.seekg(diff, std::istream::cur))
+ const uint32_t diff = descriptor.mStride - descriptor.mElementSizeHint;
+ uint32_t readSize = 0;
+ while(readSize < descriptor.mLength &&
+ source.read(reinterpret_cast<char*>(target), descriptor.mElementSizeHint) &&
+ source.seekg(diff, std::istream::cur))
{
readSize += descriptor.mStride;
target += descriptor.mElementSizeHint;
}
}
-template <typename T>
+template<typename T>
void ReadValues(const std::vector<uint8_t>& valuesBuffer, const std::vector<uint8_t>& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint)
{
const T* const indicesPtr = reinterpret_cast<const T* const>(indicesBuffer.data());
- for (uint32_t index = 0u; index < count; ++index)
+ for(uint32_t index = 0u; index < count; ++index)
{
uint32_t valuesIndex = indicesPtr[index] * elementSizeHint;
memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint);
{
bool success = false;
- if (accessor.mBlob.IsDefined())
+ if(accessor.mBlob.IsDefined())
{
success = ReadBlob(accessor.mBlob, source, target);
- if (!success)
+ if(!success)
{
return false;
}
}
- if (accessor.mSparse)
+ if(accessor.mSparse)
{
const MeshDefinition::Blob& indices = accessor.mSparse->mIndices;
- const MeshDefinition::Blob& values = accessor.mSparse->mValues;
+ const MeshDefinition::Blob& values = accessor.mSparse->mValues;
- if (!indices.IsDefined() || !values.IsDefined())
+ if(!indices.IsDefined() || !values.IsDefined())
{
return false;
}
- const auto indicesBufferSize = indices.GetBufferSize();
+ const auto indicesBufferSize = indices.GetBufferSize();
std::vector<uint8_t> indicesBuffer(indicesBufferSize);
success = ReadBlob(indices, source, indicesBuffer.data());
- if (!success)
+ if(!success)
{
return false;
}
- const auto valuesBufferSize = values.GetBufferSize();
+ const auto valuesBufferSize = values.GetBufferSize();
std::vector<uint8_t> valuesBuffer(valuesBufferSize);
success = ReadBlob(values, source, valuesBuffer.data());
- if (!success)
+ if(!success)
{
return false;
}
- switch (indices.mElementSizeHint)
+ switch(indices.mElementSizeHint)
{
- case 1u:
- {
- ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
- break;
- }
- case 2u:
- {
- ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
- break;
- }
- case 4u:
- {
- ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
- break;
- }
- default:
- DALI_ASSERT_DEBUG(!"Unsupported type for an index");
+ case 1u:
+ {
+ ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
+ break;
+ }
+ case 2u:
+ {
+ ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
+ break;
+ }
+ case 4u:
+ {
+ ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
+ break;
+ }
+ default:
+ DALI_ASSERT_DEBUG(!"Unsupported type for an index");
}
}
void GenerateNormals(MeshDefinition::RawData& raw)
{
auto& attribs = raw.mAttribs;
- DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
+ DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
IndexProvider getIndex(raw.mIndices.data());
const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size();
auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
- auto normals = reinterpret_cast<Vector3*>(buffer.data());
+ auto normals = reinterpret_cast<Vector3*>(buffer.data());
- for (uint32_t i = 0; i < numIndices; i += 3)
+ for(uint32_t i = 0; i < numIndices; i += 3)
{
- uint16_t indices[]{ getIndex(), getIndex(), getIndex() };
- Vector3 pos[]{ positions[indices[0]], positions[indices[1]], positions[indices[2]] };
+ uint16_t indices[]{getIndex(), getIndex(), getIndex()};
+ Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
Vector3 a = pos[1] - pos[0];
Vector3 b = pos[2] - pos[0];
}
auto iEnd = normals + attribs[0].mNumElements;
- while (normals != iEnd)
+ while(normals != iEnd)
{
normals->Normalize();
++normals;
}
- attribs.push_back({ "aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer) });
+ attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
}
void GenerateTangentsWithUvs(MeshDefinition::RawData& raw)
{
auto& attribs = raw.mAttribs;
- DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs
+ DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs
IndexProvider getIndex(raw.mIndices.data());
const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size();
auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
- auto* uvs = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
+ auto* uvs = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
- auto tangents = reinterpret_cast<Vector3*>(buffer.data());
+ auto tangents = reinterpret_cast<Vector3*>(buffer.data());
- for (uint32_t i = 0; i < numIndices; i += 3)
+ for(uint32_t i = 0; i < numIndices; i += 3)
{
- uint16_t indices[]{ getIndex(), getIndex(), getIndex() };
- Vector3 pos[]{ positions[indices[0]], positions[indices[1]], positions[indices[2]] };
- Vector2 uv[]{ uvs[indices[0]], uvs[indices[1]], uvs[indices[2]] };
+ uint16_t indices[]{getIndex(), getIndex(), getIndex()};
+ Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
+ Vector2 uv[]{uvs[indices[0]], uvs[indices[1]], uvs[indices[2]]};
float x0 = pos[1].x - pos[0].x;
float y0 = pos[1].y - pos[0].y;
float s1 = uv[2].x - uv[0].x;
float t1 = uv[2].y - uv[0].y;
- float r = 1.f / (s0 * t1 - t0 * s1);
+ float r = 1.f / (s0 * t1 - t0 * s1);
Vector3 tangent((x0 * t1 - t0 * x1) * r, (y0 * t1 - t0 * y1) * r, (z0 * t1 - t0 * z1) * r);
tangents[indices[0]] += tangent;
tangents[indices[1]] += tangent;
}
auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
- auto iEnd = normals + attribs[1].mNumElements;
- while (normals != iEnd)
+ auto iEnd = normals + attribs[1].mNumElements;
+ while(normals != iEnd)
{
*tangents -= *normals * normals->Dot(*tangents);
tangents->Normalize();
++tangents;
++normals;
}
- attribs.push_back({ "aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer) });
+ attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
}
void GenerateTangents(MeshDefinition::RawData& raw)
{
auto& attribs = raw.mAttribs;
- DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals
+ DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals
auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
- auto tangents = reinterpret_cast<Vector3*>(buffer.data());
+ auto tangents = reinterpret_cast<Vector3*>(buffer.data());
auto iEnd = normals + attribs[1].mNumElements;
- while (normals != iEnd)
+ while(normals != iEnd)
{
- Vector3 t[]{ normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS) };
+ Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)};
*tangents = t[t[1].LengthSquared() > t[0].LengthSquared()];
*tangents -= *normals * normals->Dot(*tangents);
++tangents;
++normals;
}
- attribs.push_back({ "aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer) });
+ attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
}
void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight)
// Calculate the dimensions of the texture.
// The total size of the texture is the length of the blend shapes blob.
- textureWidth = 0u;
+ textureWidth = 0u;
textureHeight = 0u;
- if (0u == totalTextureSize)
+ if(0u == totalTextureSize)
{
// nothing to do.
return;
}
- const uint32_t pow2 = static_cast<uint32_t>(ceil(log2(totalTextureSize)));
- const uint32_t powWidth = pow2 >> 1u;
+ const uint32_t pow2 = static_cast<uint32_t>(ceil(log2(totalTextureSize)));
+ const uint32_t powWidth = pow2 >> 1u;
const uint32_t powHeight = pow2 - powWidth;
- textureWidth = 1u << powWidth;
+ textureWidth = 1u << powWidth;
textureHeight = 1u << powHeight;
}
void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, std::ifstream& binFile, const std::vector<MeshDefinition::BlendShape>& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor)
{
uint32_t geometryBufferIndex = 0u;
- float maxDistance = 0.f;
- Vector3* geometryBufferV3 = reinterpret_cast<Vector3*>(geometryBuffer);
- for (const auto& blendShape : blendShapes)
+ float maxDistance = 0.f;
+ Vector3* geometryBufferV3 = reinterpret_cast<Vector3*>(geometryBuffer);
+ for(const auto& blendShape : blendShapes)
{
- if (blendShape.deltas.IsDefined())
+ if(blendShape.deltas.IsDefined())