2 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include "dali-scene3d/public-api/loader/dli-loader.h"
27 #include "dali-toolkit/devel-api/builder/json-parser.h"
28 #include "dali/devel-api/common/map-wrapper.h"
29 #include "dali/integration-api/debug.h"
30 #include "dali/public-api/object/property-array.h"
33 #include "dali-scene3d/internal/loader/json-util.h"
34 #include "dali-scene3d/public-api/loader/alpha-function-helper.h"
35 #include "dali-scene3d/public-api/loader/animation-definition.h"
36 #include "dali-scene3d/public-api/loader/blend-shape-details.h"
37 #include "dali-scene3d/public-api/loader/camera-parameters.h"
38 #include "dali-scene3d/public-api/loader/ktx-loader.h"
39 #include "dali-scene3d/public-api/loader/light-parameters.h"
40 #include "dali-scene3d/public-api/loader/load-result.h"
41 #include "dali-scene3d/public-api/loader/parse-renderer-state.h"
42 #include "dali-scene3d/public-api/loader/scene-definition.h"
43 #include "dali-scene3d/public-api/loader/skinning-details.h"
44 #include "dali-scene3d/public-api/loader/utils.h"
46 #define DLI_0_1_COMPATIBILITY
50 using namespace Toolkit;
56 namespace rs = RendererState;
60 const std::string NODES = "nodes";
61 const std::string SCENES = "scenes";
62 const std::string NODE = "node";
63 const std::string URI = "uri";
64 const std::string URL = "url";
65 const std::string CUSTOMIZATION = "customization";
66 const std::string HINTS = "hints";
67 const std::string NAME("name");
68 const std::string BLEND_SHAPE_HEADER("blendShapeHeader");
69 const std::string BLEND_SHAPES("blendShapes");
70 const std::string BLEND_SHAPE_VERSION_1_0("1.0");
71 const std::string BLEND_SHAPE_VERSION_2_0("2.0");
72 const std::string VERSION("version");
74 const char* const SHADOW_MAP_SIZE = "shadowMapSize";
75 const char* const ORTHOGRAPHIC_SIZE = "orthographicSize";
76 const char* const PIXEL_UNITS = "px";
78 const char SLASH = '/';
80 void ReadModelTransform(const TreeNode* node, Quaternion& orientation, Vector3& translation, Vector3& scale)
82 float num[16u] = {.0f};
84 if(ReadVector(node->GetChild("matrix"), num, 16u))
87 mat.GetTransformComponents(translation, orientation, scale);
91 if(ReadVector(node->GetChild("angle"), num, 3u))
93 orientation = Quaternion(Radian(Degree(num[0u])), Radian(Degree(num[1u])), Radian(Degree(num[2u])));
96 if(ReadVector(node->GetChild("position"), num, 3u))
98 translation = Vector3(num);
103 bool ReadAttribBlob(const TreeNode* node, MeshDefinition::Blob& buffer)
105 return ReadBlob(node, buffer.mOffset, buffer.mLength);
108 bool ReadAttribAccessor(const TreeNode* node, MeshDefinition::Accessor& accessor)
110 return ReadBlob(node, accessor.mBlob.mOffset, accessor.mBlob.mLength);
113 bool ReadColorCode(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode)
115 if(!node || !convertColorCode)
120 color = convertColorCode(node->GetString());
125 bool ReadColorCodeOrColor(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode)
127 return ReadColorCode(node->GetChild("colorCode"), color, convertColorCode) ||
128 ReadColor(node->GetChild("color"), color);
131 RendererState::Type ReadRendererState(const TreeNode& tnRendererState)
133 if(tnRendererState.GetType() == TreeNode::INTEGER)
135 return static_cast<RendererState::Type>(tnRendererState.GetInteger());
137 else if(tnRendererState.GetType() == TreeNode::STRING)
139 return RendererState::Parse(tnRendererState.GetString());
147 ///@brief Reads arc properties.
148 void ReadArcField(const TreeNode* eArc, ArcNode& arc)
150 ReadBool(eArc->GetChild("antiAliasing"), arc.mAntiAliasing);
151 ReadInt(eArc->GetChild("arcCaps"), arc.mArcCaps);
152 ReadFloat(eArc->GetChild("radius"), arc.mRadius);
154 arc.mStartAngleDegrees = .0f;
155 ReadFloat(eArc->GetChild("startAngle"), arc.mStartAngleDegrees);
157 arc.mEndAngleDegrees = .0f;
158 ReadFloat(eArc->GetChild("endAngle"), arc.mEndAngleDegrees);
161 const TreeNode* GetNthChild(const TreeNode* node, uint32_t index)
164 for(TreeNode::ConstIterator it = (*node).CBegin(); it != (*node).CEnd(); ++it, ++i)
168 return &((*it).second);
174 const TreeNode* RequireChild(const TreeNode* node, const std::string& childName)
176 auto child = node->GetChild(childName);
179 ExceptionFlinger flinger(ASSERT_LOCATION);
180 flinger << "Failed to find child node '" << childName << "'";
181 if(auto nodeName = node->GetName())
183 flinger << " on '" << nodeName << "'";
190 void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array);
192 void ParseProperties(const Toolkit::TreeNode& node, Property::Map& map)
194 DALI_ASSERT_DEBUG(node.GetType() == TreeNode::OBJECT);
195 for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
198 switch(kv.second.GetType())
200 case TreeNode::ARRAY:
202 Property::Array array;
203 ParseProperties(kv.second, array);
204 map.Insert(kv.first, array);
208 case TreeNode::OBJECT:
210 Property::Map innerMap;
211 ParseProperties(kv.second, innerMap);
212 map.Insert(kv.first, innerMap);
216 case TreeNode::STRING:
218 map.Insert(kv.first, kv.second.GetString());
222 case TreeNode::INTEGER:
224 map.Insert(kv.first, kv.second.GetInteger());
228 case TreeNode::BOOLEAN:
230 map.Insert(kv.first, kv.second.GetBoolean());
234 case TreeNode::FLOAT:
236 map.Insert(kv.first, kv.second.GetFloat());
240 case TreeNode::IS_NULL:
248 void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array)
250 DALI_ASSERT_DEBUG(node.GetType() == TreeNode::ARRAY);
251 for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
254 switch(kv.second.GetType())
256 case TreeNode::ARRAY:
258 Property::Array innerArray;
259 ParseProperties(kv.second, innerArray);
260 array.PushBack(innerArray);
264 case TreeNode::OBJECT:
267 ParseProperties(kv.second, map);
272 case TreeNode::STRING:
274 array.PushBack(kv.second.GetString());
278 case TreeNode::INTEGER:
280 array.PushBack(kv.second.GetInteger());
284 case TreeNode::BOOLEAN:
286 array.PushBack(kv.second.GetBoolean());
290 case TreeNode::FLOAT:
292 array.PushBack(kv.second.GetFloat());
296 case TreeNode::IS_NULL:
306 struct DliLoader::Impl
308 StringCallback mOnError = DefaultErrorCallback;
309 Toolkit::JsonParser mParser;
311 void ParseScene(LoadParams& params);
314 std::map<Index, Matrix> mInverseBindMatrices;
317 * @brief Due to .dli nodes being processed in depth-first traversal with orphans being
318 * ignored, features that rely on node indices (which is more compact and closer to
319 * glTF) require a mapping from .dli node indices to those in the resulting SceneDefinition.
320 * The index mapper is responsible for maintaing this mapping, and resolving node IDs
321 * once the processing of the nodes has finished.
322 * @note The resolution requires the whole scene graph to finish parsing, therefore any
323 * node extensions relying on node IDs will see the dli ID in their processor.
328 * @brief Attempts to create a mapping from a node's @a dli index to its @a scene
330 * @return Whether the operation was successful.
332 virtual bool Map(Index iDli, Index iScene) = 0;
335 * @return The scene index for the node's @a dli index.
337 virtual Index Resolve(Index iDli) = 0;
341 * @brief Traverses the DOM tree created by LoadDocument() in an attempt to create
342 * an intermediate representation of resources and nodes.
344 void ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params);
346 void ParseSkeletons(const Toolkit::TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources);
347 void ParseEnvironments(const Toolkit::TreeNode* environments, ResourceBundle& resources);
348 void ParseMaterials(const Toolkit::TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources);
350 void ParseNodes(const Toolkit::TreeNode* nodes, Index index, LoadParams& params);
351 void ParseNodesInternal(const Toolkit::TreeNode* nodes, Index index, std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& indexMapper);
353 void ParseAnimations(const Toolkit::TreeNode* animations, LoadParams& params);
354 void ParseAnimationGroups(const Toolkit::TreeNode* animationGroups, LoadParams& params);
356 void ParseShaders(const Toolkit::TreeNode* shaders, ResourceBundle& resources);
357 void ParseMeshes(const Toolkit::TreeNode* meshes, ResourceBundle& resources);
359 void GetCameraParameters(std::vector<CameraParameters>& cameras) const;
360 void GetLightParameters(std::vector<LightParameters>& lights) const;
363 DliLoader::DliLoader()
368 DliLoader::~DliLoader() = default;
370 void DliLoader::SetErrorCallback(StringCallback onError)
372 mImpl->mOnError = onError;
375 bool DliLoader::LoadScene(const std::string& uri, LoadParams& params)
377 std::string daliBuffer = LoadTextFile(uri.c_str());
379 auto& parser = mImpl->mParser;
380 parser = JsonParser::New();
381 if(!parser.Parse(daliBuffer))
386 mImpl->ParseScene(params);
390 std::string DliLoader::GetParseError() const
392 std::stringstream stream;
394 auto& parser = mImpl->mParser;
395 if(parser.ParseError())
397 stream << "position: " << parser.GetErrorPosition() << ", line: " << parser.GetErrorLineNumber() << ", column: " << parser.GetErrorColumn() << ", description: " << parser.GetErrorDescription() << ".";
403 void DliLoader::Impl::ParseScene(LoadParams& params)
405 auto& input = params.input;
406 auto& output = params.output;
408 // get index of root node.
409 auto docRoot = mParser.GetRoot();
412 // Process resources first - these are shared
413 if(auto environments = docRoot->GetChild("environment"))
415 ParseEnvironments(environments, output.mResources); // NOTE: must precede parsing of materials
418 if(auto meshes = docRoot->GetChild("meshes"))
420 ParseMeshes(meshes, output.mResources);
423 if(auto shaders = docRoot->GetChild("shaders"))
425 ParseShaders(shaders, output.mResources);
428 if(auto materials = docRoot->GetChild("materials"))
430 ParseMaterials(materials, input.mConvertColorCode, output.mResources);
433 for(auto& c : input.mPreNodeCategoryProcessors)
435 if(auto node = docRoot->GetChild(c.first))
437 Property::Array array;
438 ParseProperties(*node, array);
439 c.second(std::move(array), mOnError);
444 Index iScene = 0; // default scene
445 ReadIndex(docRoot->GetChild("scene"), iScene);
447 auto tnScenes = RequireChild(docRoot, "scenes");
448 auto tnNodes = RequireChild(docRoot, "nodes");
449 ParseSceneInternal(iScene, tnScenes, tnNodes, params);
451 ParseSkeletons(docRoot->GetChild("skeletons"), output.mScene, output.mResources);
453 output.mScene.EnsureUniqueSkinningShaderInstances(output.mResources);
454 output.mScene.EnsureUniqueBlendShapeShaderInstances(output.mResources);
456 // Ger cameras and lights
457 GetCameraParameters(output.mCameraParameters);
458 GetLightParameters(output.mLightParameters);
460 // Post-node processors and animations last
461 for(auto& c : input.mPostNodeCategoryProcessors)
463 if(auto node = docRoot->GetChild(c.first))
465 Property::Array array;
466 ParseProperties(*node, array);
467 c.second(std::move(array), mOnError);
471 if(auto animations = docRoot->GetChild("animations"))
473 ParseAnimations(animations, params);
476 if(!output.mAnimationDefinitions.empty())
478 if(auto animationGroups = docRoot->GetChild("animationGroups"))
480 ParseAnimationGroups(animationGroups, params);
486 void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params)
488 auto getSceneRootIdx = [tnScenes, tnNodes](Index iScene) {
489 auto tn = GetNthChild(tnScenes, iScene); // now a "scene" object
492 ExceptionFlinger(ASSERT_LOCATION) << iScene << " is out of bounds access into " << SCENES << ".";
495 tn = RequireChild(tn, NODES); // now a "nodes" array
496 if(tn->GetType() != TreeNode::ARRAY)
498 ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid type; array required.";
503 ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " must define a node id.";
506 tn = GetNthChild(tn, 0); // now the first element of the array
508 if(!ReadIndex(tn, iRootNode))
510 ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid value for root node index: '" << iRootNode << "'.";
513 if(iRootNode >= tnNodes->Size())
515 ExceptionFlinger(ASSERT_LOCATION) << "Root node index << " << iRootNode << " of scene " << iScene << " is out of bounds.";
518 tn = GetNthChild(tnNodes, iRootNode); // now a "node" object
519 if(tn->GetType() != TreeNode::OBJECT)
521 ExceptionFlinger(ASSERT_LOCATION) << "Root node of scene " << iScene << " is of invalid JSON type; object required";
527 Index iRootNode = getSceneRootIdx(iScene);
528 ParseNodes(tnNodes, iRootNode, params);
530 auto& scene = params.output.mScene;
531 scene.AddRootNode(0);
533 for(Index i = 0; i < iScene; ++i)
535 Index iRootNode = getSceneRootIdx(i);
536 const Index iRoot = scene.GetNodeCount();
537 ParseNodes(tnNodes, iRootNode, params);
538 scene.AddRootNode(iRoot);
541 auto numScenes = tnScenes->Size();
542 for(Index i = iScene + 1; i < numScenes; ++i)
544 Index iRootNode = getSceneRootIdx(i);
545 const Index iRoot = scene.GetNodeCount();
546 ParseNodes(tnNodes, iRootNode, params);
547 scene.AddRootNode(iRoot);
551 void DliLoader::Impl::ParseSkeletons(const TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources)
555 auto iStart = skeletons->CBegin();
556 for(auto i0 = iStart, i1 = skeletons->CEnd(); i0 != i1; ++i0)
558 auto& node = (*i0).second;
559 std::string skeletonRootName;
560 if(ReadString(node.GetChild(NODE), skeletonRootName))
562 SkeletonDefinition skeleton;
563 if(!scene.FindNode(skeletonRootName, &skeleton.mRootNodeIdx))
565 ExceptionFlinger(ASSERT_LOCATION) << FormatString("Skeleton %d: node '%s' not defined.", resources.mSkeletons.size(), skeletonRootName.c_str());
568 uint32_t jointCount = 0;
569 std::function<void(Index)> visitFn;
570 auto& ibms = mInverseBindMatrices;
571 visitFn = [&](Index id) {
572 auto node = scene.GetNode(id);
573 jointCount += ibms.find(id) != ibms.end();
575 for(auto i : node->mChildren)
580 visitFn(skeleton.mRootNodeIdx);
582 if(jointCount > Skinning::MAX_JOINTS)
584 mOnError(FormatString("Skeleton %d: joint count exceeds supported limit.", resources.mSkeletons.size()));
585 jointCount = Skinning::MAX_JOINTS;
588 skeleton.mJoints.reserve(jointCount);
590 visitFn = [&](Index id) {
591 auto iFind = ibms.find(id);
592 if(iFind != ibms.end() && skeleton.mJoints.size() < Skinning::MAX_JOINTS)
594 skeleton.mJoints.push_back({id, iFind->second});
597 auto node = scene.GetNode(id);
598 for(auto i : node->mChildren)
603 visitFn(skeleton.mRootNodeIdx);
605 resources.mSkeletons.push_back(std::move(skeleton));
609 ExceptionFlinger(ASSERT_LOCATION) << "skeleton " << std::distance(iStart, i0) << ": Missing required attribute '" << NODE << "'.";
615 void DliLoader::Impl::ParseEnvironments(const TreeNode* environments, ResourceBundle& resources)
617 Matrix cubeOrientation(Matrix::IDENTITY);
619 for(auto i0 = environments->CBegin(), i1 = environments->CEnd(); i0 != i1; ++i0)
621 auto& node = (*i0).second;
623 EnvironmentDefinition envDef;
624 ReadString(node.GetChild("cubeSpecular"), envDef.mSpecularMapPath);
625 ReadString(node.GetChild("cubeDiffuse"), envDef.mDiffuseMapPath);
626 ToUnixFileSeparators(envDef.mSpecularMapPath);
627 ToUnixFileSeparators(envDef.mDiffuseMapPath);
628 envDef.mIblIntensity = 1.0f;
629 ReadFloat(node.GetChild("iblIntensity"), envDef.mIblIntensity);
630 if(ReadVector(node.GetChild("cubeInitialOrientation"), cubeOrientation.AsFloat(), 16u))
632 envDef.mCubeOrientation = Quaternion(cubeOrientation);
635 resources.mEnvironmentMaps.emplace_back(std::move(envDef), EnvironmentDefinition::Textures());
638 // NOTE: guarantees environmentMaps to have an empty environment.
639 if(resources.mEnvironmentMaps.empty())
641 resources.mEnvironmentMaps.emplace_back(EnvironmentDefinition(), EnvironmentDefinition::Textures());
645 void DliLoader::Impl::ParseShaders(const TreeNode* shaders, ResourceBundle& resources)
647 uint32_t iShader = 0;
648 for(auto i0 = shaders->CBegin(), i1 = shaders->CEnd(); i0 != i1; ++i0, ++iShader)
650 auto& node = (*i0).second;
651 ShaderDefinition shaderDef;
652 ReadStringVector(node.GetChild("defines"), shaderDef.mDefines);
654 // Read shader hints. Possible values are:
655 // Don't define for No hints.
656 // "OUTPUT_IS_TRANSPARENT" Might generate transparent alpha from opaque inputs.
657 // "MODIFIES_GEOMETRY" Might change position of vertices, this option disables any culling optimizations.
659 ReadStringVector(node.GetChild(HINTS), shaderDef.mHints);
661 if(ReadString(node.GetChild("vertex"), shaderDef.mVertexShaderPath) &&
662 ReadString(node.GetChild("fragment"), shaderDef.mFragmentShaderPath))
664 ToUnixFileSeparators(shaderDef.mVertexShaderPath);
665 ToUnixFileSeparators(shaderDef.mFragmentShaderPath);
667 for(TreeNode::ConstIterator j0 = node.CBegin(), j1 = node.CEnd(); j0 != j1; ++j0)
669 const TreeNode::KeyNodePair& keyValue = *j0;
670 const std::string& key = keyValue.first;
671 const TreeNode& value = keyValue.second;
673 Property::Value uniformValue;
674 if(key.compare("vertex") == 0 || key.compare("fragment") == 0 || key.compare("defines") == 0 || key.compare(HINTS) == 0)
678 else if(key.compare("rendererState") == 0)
680 shaderDef.mRendererState = ReadRendererState(keyValue.second);
682 else if(value.GetType() == TreeNode::INTEGER || value.GetType() == TreeNode::FLOAT)
685 ReadFloat(&value, f);
688 else if(value.GetType() == TreeNode::BOOLEAN)
690 DALI_LOG_WARNING("\"bool\" uniforms are handled as floats in shader");
692 if(ReadBool(&keyValue.second, value))
694 uniformValue = value ? 1.0f : 0.0f;
698 switch(auto size = GetNumericalArraySize(&value))
703 ReadVector(&value, m.AsFloat(), size);
711 ReadVector(&value, m.AsFloat(), size);
719 ReadVector(&value, v.AsFloat(), size);
727 ReadVector(&value, v.AsFloat(), size);
735 ReadVector(&value, v.AsFloat(), size);
741 mOnError(FormatString(
742 "shader %d: Ignoring uniform '%s': failed to infer type from %d elements.",
748 if(Property::NONE != uniformValue.GetType())
750 shaderDef.mUniforms.Insert(key, uniformValue);
754 resources.mShaders.emplace_back(std::move(shaderDef), Shader());
758 ExceptionFlinger(ASSERT_LOCATION) << "shader " << iShader << ": Missing vertex / fragment shader definition.";
763 void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resources)
765 for(auto i0 = meshes->CBegin(), i1 = meshes->CEnd(); i0 != i1; ++i0)
767 auto& node = (*i0).second;
769 MeshDefinition meshDef;
770 if(!ReadString(node.GetChild(URI), meshDef.mUri))
772 ExceptionFlinger(ASSERT_LOCATION) << "mesh " << resources.mMeshes.size() << ": Missing required attribute '" << URI << "'.";
775 ToUnixFileSeparators(meshDef.mUri);
777 std::string primitive;
778 if(ReadString(node.GetChild("primitive"), primitive))
780 if(primitive == "LINES")
782 meshDef.mPrimitiveType = Geometry::LINES;
784 else if(primitive == "POINTS")
786 meshDef.mPrimitiveType = Geometry::POINTS;
788 else if(primitive != "TRIANGLES")
790 mOnError(FormatString(
791 "mesh %d: Using TRIANGLES instead of unsupported primitive type '%s'.",
792 resources.mMeshes.size(),
798 if(ReadInt(node.GetChild("attributes"), attributes))
800 if(MaskMatch(attributes, MeshDefinition::INDICES) &&
801 !ReadAttribAccessor(node.GetChild("indices"), meshDef.mIndices))
803 ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
804 resources.mMeshes.size(),
808 if(MaskMatch(attributes, MeshDefinition::POSITIONS) &&
809 !ReadAttribAccessor(node.GetChild("positions"), meshDef.mPositions))
811 ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
812 resources.mMeshes.size(),
816 if(MaskMatch(attributes, MeshDefinition::NORMALS) &&
817 !ReadAttribAccessor(node.GetChild("normals"), meshDef.mNormals))
819 mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "normals"));
822 if(MaskMatch(attributes, MeshDefinition::TEX_COORDS) &&
823 !ReadAttribAccessor(node.GetChild("textures"), meshDef.mTexCoords))
825 mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "textures"));
828 if(MaskMatch(attributes, MeshDefinition::TANGENTS) &&
829 !ReadAttribAccessor(node.GetChild("tangents"), meshDef.mTangents))
831 mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "tangents"));
834 // NOTE: we're no longer reading bitangents as these are calculated in the shaders.
835 if(ReadIndex(node.GetChild("skeleton"), meshDef.mSkeletonIdx))
837 if(!MaskMatch(attributes, MeshDefinition::JOINTS_0) &&
838 !MaskMatch(attributes, MeshDefinition::WEIGHTS_0))
840 mOnError(FormatString("mesh %d: Expected joints0 / weights0 attribute(s) missing.",
841 resources.mMeshes.size()));
843 else if(!ReadAttribAccessor(node.GetChild("joints0"), meshDef.mJoints0) ||
844 !ReadAttribAccessor(node.GetChild("weights0"), meshDef.mWeights0))
846 mOnError(FormatString("mesh %d: Failed to read skinning information.",
847 resources.mMeshes.size()));
851 if(auto blendshapeHeader = node.GetChild(BLEND_SHAPE_HEADER))
853 std::string blendShapeVersion;
854 ReadString(blendshapeHeader->GetChild(VERSION), blendShapeVersion);
856 if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_1_0))
858 meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_1_0;
860 else if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_2_0))
862 meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
865 switch(meshDef.mBlendShapeVersion)
867 case BlendShapes::Version::VERSION_1_0:
868 case BlendShapes::Version::VERSION_2_0: // FALL THROUGH
870 ReadAttribBlob(blendshapeHeader, meshDef.mBlendShapeHeader);
881 if(auto blendShapes = node.GetChild(BLEND_SHAPES))
883 meshDef.mBlendShapes.resize(blendShapes->Size());
886 for(auto it = blendShapes->CBegin(), endIt = blendShapes->CEnd(); it != endIt; ++it, ++index)
888 // Each blend shape is stored as the difference with the original mesh.
890 auto& blendShapeNode = (*it).second;
892 auto& blendShape = meshDef.mBlendShapes[index];
893 ReadString(blendShapeNode.GetChild("name"), blendShape.name);
894 if(auto position = blendShapeNode.GetChild("positions"))
896 ReadAttribAccessor(position, blendShape.deltas);
898 if(auto normals = blendShapeNode.GetChild("normals"))
900 ReadAttribAccessor(normals, blendShape.normals);
902 if(auto tangents = blendShapeNode.GetChild("tangents"))
904 ReadAttribAccessor(tangents, blendShape.tangents);
906 ReadFloat(blendShapeNode.GetChild("weight"), blendShape.weight);
911 if(ReadBool(node.GetChild("flipV"), flipV))
913 meshDef.mFlags |= flipV * MeshDefinition::FLIP_UVS_VERTICAL;
916 resources.mMeshes.emplace_back(std::move(meshDef), MeshGeometry());
921 void DliLoader::Impl::ParseMaterials(const TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources)
923 for(auto i0 = materials->CBegin(), i1 = materials->CEnd(); i0 != i1; ++i0)
925 auto& node = (*i0).second;
927 MaterialDefinition materialDef;
928 if(auto eEnvironment = node.GetChild("environment"))
930 ReadIndex(eEnvironment, materialDef.mEnvironmentIdx);
931 if(static_cast<unsigned int>(materialDef.mEnvironmentIdx) >= resources.mEnvironmentMaps.size())
933 ExceptionFlinger(ASSERT_LOCATION) << "material " << resources.mMaterials.size() << ": Environment index " << materialDef.mEnvironmentIdx << " out of bounds (" << resources.mEnvironmentMaps.size() << ").";
937 //TODO : need to consider AGIF
938 std::vector<std::string> texturePaths;
939 std::string texturePath;
940 if(ReadString(node.GetChild("albedoMap"), texturePath))
942 ToUnixFileSeparators(texturePath);
943 const auto semantic = MaterialDefinition::ALBEDO;
944 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
945 materialDef.mFlags |= semantic | MaterialDefinition::TRANSPARENCY; // NOTE: only in dli does single / separate ALBEDO texture mean TRANSPARENCY.
947 if(ReadString(node.GetChild("albedoMetallicMap"), texturePath))
949 ToUnixFileSeparators(texturePath);
951 if(MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO))
953 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "albedo"));
956 const auto semantic = MaterialDefinition::ALBEDO | MaterialDefinition::METALLIC;
957 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
958 materialDef.mFlags |= semantic;
961 if(ReadString(node.GetChild("metallicRoughnessMap"), texturePath))
963 ToUnixFileSeparators(texturePath);
965 if(MaskMatch(materialDef.mFlags, MaterialDefinition::METALLIC))
967 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "metallic"));
970 const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS;
971 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
972 materialDef.mFlags |= semantic |
973 // We have a metallic-roughhness map and the first texture did not have albedo semantics - we're in the transparency workflow.
974 (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
977 if(ReadString(node.GetChild("normalMap"), texturePath))
979 ToUnixFileSeparators(texturePath);
981 const auto semantic = MaterialDefinition::NORMAL;
982 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
983 materialDef.mFlags |= semantic |
984 // We have a standalone normal map and the first texture did not have albedo semantics - we're in the transparency workflow.
985 (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
988 if(ReadString(node.GetChild("normalRoughnessMap"), texturePath))
990 ToUnixFileSeparators(texturePath);
992 if(MaskMatch(materialDef.mFlags, MaterialDefinition::NORMAL))
994 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "normal"));
997 if(MaskMatch(materialDef.mFlags, MaterialDefinition::ROUGHNESS))
999 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "roughness"));
1002 if(MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY))
1004 mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "transparency"));
1007 const auto semantic = MaterialDefinition::NORMAL | MaterialDefinition::ROUGHNESS;
1008 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1009 materialDef.mFlags |= semantic;
1012 if(ReadString(node.GetChild("subsurfaceMap"), texturePath))
1014 ToUnixFileSeparators(texturePath);
1016 const auto semantic = MaterialDefinition::SUBSURFACE;
1017 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1018 materialDef.mFlags |= semantic;
1021 if(ReadString(node.GetChild("occlusionMap"), texturePath))
1023 ToUnixFileSeparators(texturePath);
1024 const auto semantic = MaterialDefinition::OCCLUSION;
1025 materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1026 materialDef.mFlags |= semantic;
1029 if(ReadColorCodeOrColor(&node, materialDef.mColor, convertColorCode) &&
1030 materialDef.mColor.a < 1.0f)
1032 materialDef.mFlags |= MaterialDefinition::TRANSPARENCY;
1035 ReadFloat(node.GetChild("metallic"), materialDef.mMetallic);
1036 ReadFloat(node.GetChild("roughness"), materialDef.mRoughness);
1039 if(ReadBool(node.GetChild("mipmap"), mipmaps) && mipmaps)
1041 for(auto& ts : materialDef.mTextureStages)
1043 ts.mTexture.mSamplerFlags |= SamplerFlags::FILTER_MIPMAP_LINEAR;
1047 resources.mMaterials.emplace_back(std::move(materialDef), TextureSet());
1051 void DliLoader::Impl::ParseNodes(const TreeNode* const nodes, Index index, LoadParams& params)
1053 std::vector<Index> parents;
1056 struct IndexMapper : IIndexMapper
1058 IndexMapper(size_t numNodes)
1060 mIndices.reserve(numNodes);
1063 virtual bool Map(Index iDli, Index iScene) override
1065 Entry idx{iDli, iScene};
1066 auto iInsert = std::lower_bound(mIndices.begin(), mIndices.end(), idx);
1067 if(iInsert == mIndices.end() || iInsert->iDli != iDli)
1069 mIndices.insert(iInsert, idx);
1071 else if(iInsert->iScene != iScene)
1078 virtual unsigned int Resolve(Index iDli) override
1080 auto iFind = std::lower_bound(mIndices.begin(), mIndices.end(), iDli, [](const Entry& idx, Index iDli) {
1081 return idx.iDli < iDli;
1083 DALI_ASSERT_ALWAYS(iFind != mIndices.end());
1084 return iFind->iScene;
1091 unsigned int iScene;
1093 bool operator<(const Entry& other) const
1095 return iDli < other.iDli;
1098 std::vector<Entry> mIndices;
1099 } mapper(nodes->Size());
1100 ParseNodesInternal(nodes, index, parents, params, mapper);
1102 auto& scene = params.output.mScene;
1103 for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 < i1; ++i0)
1105 for(auto& c : scene.GetNode(i0)->mConstraints)
1107 c.mSourceIdx = mapper.Resolve(c.mSourceIdx);
1112 void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index index, std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& mapper)
1114 // Properties that may be resolved from a JSON value with ReadInt() -- or default to 0.
1115 struct IndexProperty
1117 ResourceType::Value type;
1118 const TreeNode* source;
1121 std::vector<IndexProperty> resourceIds;
1122 resourceIds.reserve(4);
1124 if(auto node = GetNthChild(nodes, index))
1126 NodeDefinition nodeDef;
1127 nodeDef.mParentIdx = inOutParentStack.empty() ? INVALID_INDEX : inOutParentStack.back();
1130 ReadString(node->GetChild(NAME), nodeDef.mName);
1133 ReadModelTransform(node, nodeDef.mOrientation, nodeDef.mPosition, nodeDef.mScale);
1135 // Reads the size of the node.
1137 // * It can be given as 'size' or 'bounds'.
1138 // * The sdk saves the 'size' as a vector2 in some cases.
1139 // * To avoid size related issues the following code attemps
1140 // to read the 'size/bounds' as a vector3 first, if it's
1141 // not successful then reads it as a vector2.
1142 ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 3) ||
1143 ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 2) ||
1144 ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 3) ||
1145 ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 2);
1148 ReadBool(node->GetChild("visible"), nodeDef.mIsVisible);
1150 // type classification
1151 if(auto eCustomization = node->GetChild("customization")) // customization
1154 if(ReadString(eCustomization->GetChild("tag"), tag))
1156 nodeDef.mCustomization.reset(new NodeDefinition::CustomizationDefinition{tag});
1159 else // something renderable maybe
1161 std::unique_ptr<NodeDefinition::Renderable> renderable;
1162 ModelNode* modelNode = nullptr; // no ownership, aliasing renderable for the right type.
1164 const TreeNode* eRenderable = nullptr;
1165 if((eRenderable = node->GetChild("model")))
1167 // check for mesh before allocating - this can't be missing.
1168 auto eMesh = eRenderable->GetChild("mesh");
1171 ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
1174 modelNode = new ModelNode();
1175 renderable.reset(modelNode);
1177 resourceIds.push_back({ResourceType::Mesh, eMesh, modelNode->mMeshIdx});
1179 else if((eRenderable = node->GetChild("arc")))
1181 // check for mesh before allocating - this can't be missing.
1182 auto eMesh = eRenderable->GetChild("mesh");
1185 ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
1188 auto arcNode = new ArcNode;
1189 renderable.reset(arcNode);
1190 modelNode = arcNode;
1192 resourceIds.push_back({ResourceType::Mesh, eMesh, arcNode->mMeshIdx});
1194 ReadArcField(eRenderable, *arcNode);
1197 if(renderable && eRenderable != nullptr) // process common properties of all renderables + register payload
1200 renderable->mShaderIdx = 0;
1201 auto eShader = eRenderable->GetChild("shader");
1204 resourceIds.push_back({ResourceType::Shader, eShader, renderable->mShaderIdx});
1210 modelNode->mMaterialIdx = 0; // must offer default of 0
1211 auto eMaterial = eRenderable->GetChild("material");
1214 resourceIds.push_back({ResourceType::Material, eMaterial, modelNode->mMaterialIdx});
1217 if(!ReadColorCodeOrColor(eRenderable, modelNode->mColor, params.input.mConvertColorCode))
1219 ReadColorCodeOrColor(node, modelNode->mColor, params.input.mConvertColorCode);
1223 nodeDef.mRenderable = std::move(renderable);
1227 // Resolve ints - default to 0 if undefined
1228 auto& output = params.output;
1229 for(auto& idRes : resourceIds)
1234 case ResourceType::Shader:
1235 iCheck = output.mResources.mShaders.size();
1238 case ResourceType::Mesh:
1239 iCheck = output.mResources.mMeshes.size();
1242 case ResourceType::Material:
1243 iCheck = output.mResources.mMaterials.size();
1247 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid resource type: " << idRes.type << " (Programmer error)";
1254 else if(idRes.source->GetType() != TreeNode::INTEGER)
1256 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid " << GetResourceTypeName(idRes.type) << " index type.";
1260 idRes.target = idRes.source->GetInteger();
1263 if(idRes.target >= iCheck)
1265 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": " << GetResourceTypeName(idRes.type) << " index " << idRes.target << " out of bounds (" << iCheck << ").";
1268 resourceIds.clear();
1271 if(auto eExtras = node->GetChild("extras"))
1273 auto& extras = nodeDef.mExtras;
1274 extras.reserve(eExtras->Size());
1276 for(auto i0 = eExtras->CBegin(), i1 = eExtras->CEnd(); i0 != i1; ++i0)
1278 NodeDefinition::Extra e;
1281 e.mKey = eExtra.first;
1284 mOnError(FormatString("node %d: empty string is invalid for name of extra %d; ignored.",
1290 e.mValue = ReadPropertyValue(eExtra.second);
1291 if(e.mValue.GetType() == Property::Type::NONE)
1293 mOnError(FormatString("node %d: failed to interpret value of extra '%s' : %s; ignored.",
1296 eExtra.second.GetString()));
1300 auto iInsert = std::lower_bound(extras.begin(), extras.end(), e);
1301 if(iInsert != extras.end() && iInsert->mKey == e.mKey)
1303 mOnError(FormatString("node %d: extra '%s' already defined; overriding with %s.",
1306 eExtra.second.GetString()));
1307 *iInsert = std::move(e);
1311 extras.insert(iInsert, e);
1318 if(auto eConstraints = node->GetChild("constraints"))
1320 auto& constraints = nodeDef.mConstraints;
1321 constraints.reserve(eConstraints->Size());
1323 ConstraintDefinition cDef;
1324 for(auto i0 = eConstraints->CBegin(), i1 = eConstraints->CEnd(); i0 != i1; ++i0)
1326 auto eConstraint = *i0;
1327 if(!ReadIndex(&eConstraint.second, cDef.mSourceIdx))
1329 mOnError(FormatString("node %d: node ID %s for constraint %d is invalid; ignored.",
1331 eConstraint.second.GetString(),
1332 constraints.size()));
1336 cDef.mProperty = eConstraint.first;
1338 auto iInsert = std::lower_bound(constraints.begin(), constraints.end(), cDef);
1339 if(iInsert != constraints.end() && *iInsert == cDef)
1341 mOnError(FormatString("node %d: constraint %s@%d already defined; ignoring.",
1343 cDef.mProperty.c_str(),
1348 constraints.insert(iInsert, cDef);
1354 // Determine index for mapping
1355 const unsigned int myIndex = output.mScene.GetNodeCount();
1356 if(!mapper.Map(index, myIndex))
1358 mOnError(FormatString("node %d: error mapping dli index %d: node has multiple parents. Ignoring subtree."));
1362 // if the node is a bone in a skeletal animation, it will have the inverse bind pose matrix.
1363 Matrix invBindMatrix{false};
1364 if(ReadVector(node->GetChild("inverseBindPoseMatrix"), invBindMatrix.AsFloat(), 16u)) // TODO: more robust error checking?
1366 mInverseBindMatrices[myIndex] = invBindMatrix;
1370 auto rawDef = output.mScene.AddNode(std::make_unique<NodeDefinition>(std::move(nodeDef)));
1371 if(rawDef) // NOTE: no ownership. Guaranteed to stay in scope.
1373 // ...And only then parse children.
1374 if(auto children = node->GetChild("children"))
1376 inOutParentStack.push_back(myIndex);
1378 rawDef->mChildren.reserve(children->Size());
1380 uint32_t iChild = 0;
1381 for(auto j0 = children->CBegin(), j1 = children->CEnd(); j0 != j1; ++j0, ++iChild)
1383 auto& child = (*j0).second;
1384 if(child.GetType() == TreeNode::INTEGER)
1386 ParseNodesInternal(nodes, child.GetInteger(), inOutParentStack, params, mapper); // child object is created in scene definition.
1390 ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ", child " << iChild << ": invalid index type.";
1394 inOutParentStack.pop_back();
1396 else if(rawDef->mCustomization)
1398 mOnError(FormatString("node %d: not an actual customization without children.", index));
1401 if(auto proc = params.input.mNodePropertyProcessor) // optional processing
1403 // WARNING: constraint IDs are not resolved at this point.
1404 Property::Map nodeData;
1405 ParseProperties(*node, nodeData);
1406 proc(*rawDef, std::move(nodeData), mOnError);
1411 ExceptionFlinger(ASSERT_LOCATION) << "Node " << index << ": name already used.";
1416 void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& params)
1418 auto& definitions = params.output.mAnimationDefinitions;
1419 definitions.reserve(definitions.size() + tnAnimations->Size());
1421 for(TreeNode::ConstIterator iAnim = tnAnimations->CBegin(), iAnimEnd = tnAnimations->CEnd();
1425 const TreeNode& tnAnim = (*iAnim).second;
1426 AnimationDefinition animDef;
1427 ReadString(tnAnim.GetChild(NAME), animDef.mName);
1429 auto iFind = std::lower_bound(definitions.begin(), definitions.end(), animDef, [](const AnimationDefinition& ad0, const AnimationDefinition& ad1) {
1430 return ad0.mName < ad1.mName;
1432 const bool overwrite = iFind != definitions.end() && iFind->mName == animDef.mName;
1435 mOnError(FormatString("Pre-existing animation with name '%s' is being overwritten.", animDef.mName.c_str()));
1438 // Duration -- We need something that animated properties' delay / duration can
1439 // be expressed as a multiple of; 0 won't work. This is small enough (i.e. shorter
1440 // than our frame delay) to not be restrictive WRT replaying. If anything needs
1441 // to occur more frequently, then Animations are likely not your solution anyway.
1442 animDef.mDuration = AnimationDefinition::MIN_DURATION_SECONDS;
1443 if(!ReadFloat(tnAnim.GetChild("duration"), animDef.mDuration))
1445 mOnError(FormatString("Animation '%s' fails to define '%s', defaulting to %f.",
1446 animDef.mName.c_str(),
1448 animDef.mDuration));
1451 // Get loop count - # of playbacks. Default is once. 0 means repeat indefinitely.
1452 animDef.mLoopCount = 1;
1453 if(ReadInt(tnAnim.GetChild("loopCount"), animDef.mLoopCount) &&
1454 animDef.mLoopCount < 0)
1456 animDef.mLoopCount = 0;
1459 std::string endAction;
1460 if(ReadString(tnAnim.GetChild("endAction"), endAction))
1462 if("BAKE" == endAction)
1464 animDef.mEndAction = Animation::BAKE;
1466 else if("DISCARD" == endAction)
1468 animDef.mEndAction = Animation::DISCARD;
1470 else if("BAKE_FINAL" == endAction)
1472 animDef.mEndAction = Animation::BAKE_FINAL;
1476 if(ReadString(tnAnim.GetChild("disconnectAction"), endAction))
1478 if("BAKE" == endAction)
1480 animDef.mDisconnectAction = Animation::BAKE;
1482 else if("DISCARD" == endAction)
1484 animDef.mDisconnectAction = Animation::DISCARD;
1486 else if("BAKE_FINAL" == endAction)
1488 animDef.mDisconnectAction = Animation::BAKE_FINAL;
1492 if(const TreeNode* tnProperties = tnAnim.GetChild("properties"))
1494 animDef.mProperties.reserve(tnProperties->Size());
1495 for(TreeNode::ConstIterator iProperty = tnProperties->CBegin(), iPropertyEnd = tnProperties->CEnd();
1496 iProperty != iPropertyEnd;
1499 const TreeNode& tnProperty = (*iProperty).second;
1501 AnimatedProperty animProp;
1502 if(!ReadString(tnProperty.GetChild("node"), animProp.mNodeName))
1504 mOnError(FormatString("Animation '%s': Failed to read the 'node' tag.", animDef.mName.c_str()));
1508 if(!ReadString(tnProperty.GetChild("property"), animProp.mPropertyName))
1510 mOnError(FormatString("Animation '%s': Failed to read the 'property' tag", animDef.mName.c_str()));
1514 // these are the defaults
1515 animProp.mTimePeriod.delaySeconds = 0.f;
1516 animProp.mTimePeriod.durationSeconds = animDef.mDuration;
1517 if(!ReadTimePeriod(tnProperty.GetChild("timePeriod"), animProp.mTimePeriod))
1519 mOnError(FormatString("Animation '%s': timePeriod missing in Property #%d: defaulting to %f.",
1520 animDef.mName.c_str(),
1521 animDef.mProperties.size(),
1522 animProp.mTimePeriod.durationSeconds));
1525 std::string alphaFunctionValue;
1526 if(ReadString(tnProperty.GetChild("alphaFunction"), alphaFunctionValue))
1528 animProp.mAlphaFunction = GetAlphaFunction(alphaFunctionValue);
1531 if(const TreeNode* tnKeyFramesBin = tnProperty.GetChild("keyFramesBin"))
1533 DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
1535 std::ifstream binAniFile;
1536 std::string animationFilename;
1537 if(ReadString(tnKeyFramesBin->GetChild(URL), animationFilename))
1539 std::string animationFullPath = params.input.mAnimationsPath + animationFilename;
1540 binAniFile.open(animationFullPath, std::ios::binary);
1541 if(binAniFile.fail())
1543 ExceptionFlinger(ASSERT_LOCATION) << "Failed to open animation data '" << animationFullPath << "'";
1548 ReadInt(tnKeyFramesBin->GetChild("byteOffset"), byteOffset);
1549 DALI_ASSERT_ALWAYS(byteOffset >= 0);
1551 binAniFile.seekg(byteOffset, std::ios::beg);
1554 ReadInt(tnKeyFramesBin->GetChild("numKeys"), numKeys);
1555 DALI_ASSERT_ALWAYS(numKeys >= 0);
1557 animProp.mKeyFrames = KeyFrames::New();
1559 //In binary animation file only is saved the position, rotation, scale and blend shape weight keys.
1560 //so, if it is vector3 we assume is position or scale keys, if it is vector4 we assume is rotation,
1561 // otherwise are blend shape weight keys.
1562 // TODO support for binary header with size information
1563 Property::Type propType = Property::FLOAT; // assume blend shape weights
1564 if(animProp.mPropertyName == "orientation")
1566 propType = Property::VECTOR4;
1568 else if((animProp.mPropertyName == "position") || (animProp.mPropertyName == "scale"))
1570 propType = Property::VECTOR3;
1573 //alphafunction is reserved for future implementation
1574 // NOTE: right now we're just using AlphaFunction::LINEAR.
1575 unsigned char dummyAlphaFunction;
1578 Property::Value propValue;
1579 for(int key = 0; key < numKeys; key++)
1581 binAniFile.read(reinterpret_cast<char*>(&progress), sizeof(float));
1582 if(propType == Property::VECTOR3)
1585 binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 3);
1586 propValue = Property::Value(value);
1588 else if(propType == Property::VECTOR4)
1591 binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 4);
1592 propValue = Property::Value(Quaternion(value));
1597 binAniFile.read(reinterpret_cast<char*>(&value), sizeof(float));
1598 propValue = Property::Value(value);
1601 binAniFile.read(reinterpret_cast<char*>(&dummyAlphaFunction), sizeof(unsigned char));
1603 animProp.mKeyFrames.Add(progress, propValue, AlphaFunction::LINEAR);
1606 else if(const TreeNode* tnKeyFrames = tnProperty.GetChild("keyFrames"))
1608 DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
1609 animProp.mKeyFrames = KeyFrames::New();
1611 float progress = 0.0f;
1612 for(auto i0 = tnKeyFrames->CBegin(), i1 = tnKeyFrames->CEnd(); i1 != i0; ++i0)
1614 const TreeNode::KeyNodePair& kfKeyChild = *i0;
1615 bool readResult = ReadFloat(kfKeyChild.second.GetChild("progress"), progress);
1616 DALI_ASSERT_ALWAYS(readResult && "Key frame entry must have 'progress'");
1618 const TreeNode* tnValue = kfKeyChild.second.GetChild("value");
1619 DALI_ASSERT_ALWAYS(tnValue && "Key frame entry must have 'value'");
1621 // For the "orientation" property, convert from Vector4 -> Rotation value
1622 // This work-around is preferable to a null-pointer exception in the DALi update thread
1623 Property::Value propValue(ReadPropertyValue(*tnValue));
1624 if(propValue.GetType() == Property::VECTOR4 &&
1625 animProp.mPropertyName == "orientation")
1629 propValue = Property::Value(Quaternion(v.w, v.x, v.y, v.z));
1632 AlphaFunction kfAlphaFunction(AlphaFunction::DEFAULT);
1633 std::string alphaFuncStr;
1634 if(ReadString(kfKeyChild.second.GetChild("alphaFunction"), alphaFuncStr))
1636 kfAlphaFunction = GetAlphaFunction(alphaFuncStr);
1639 animProp.mKeyFrames.Add(progress, propValue, kfAlphaFunction);
1644 const TreeNode* tnValue = tnProperty.GetChild("value");
1647 animProp.mValue.reset(new AnimatedProperty::Value{ReadPropertyValue(*tnValue)});
1648 ReadBool(tnProperty.GetChild("relative"), animProp.mValue->mIsRelative);
1652 mOnError(FormatString("Property '%s' fails to define target value.",
1653 animProp.mPropertyName.c_str()));
1657 animDef.mProperties.push_back(std::move(animProp));
1663 *iFind = std::move(animDef);
1667 iFind = definitions.insert(iFind, std::move(animDef));
1670 if(auto proc = params.input.mAnimationPropertyProcessor) // optional processing
1673 ParseProperties(tnAnim, map);
1674 proc(animDef, std::move(map), mOnError);
1679 void DliLoader::Impl::ParseAnimationGroups(const Toolkit::TreeNode* tnAnimationGroups, LoadParams& params)
1681 auto& animGroups = params.output.mAnimationGroupDefinitions;
1684 for(auto iGroups = tnAnimationGroups->CBegin(), iGroupsEnd = tnAnimationGroups->CEnd();
1685 iGroups != iGroupsEnd;
1686 ++iGroups, ++numGroups)
1688 const auto& tnGroup = *iGroups;
1689 auto tnName = tnGroup.second.GetChild(NAME);
1690 std::string groupName;
1691 if(!tnName || !ReadString(tnName, groupName))
1693 mOnError(FormatString("Failed to get the name for the Animation group %d; ignoring.", numGroups));
1697 auto iFind = std::lower_bound(animGroups.begin(), animGroups.end(), groupName, [](const AnimationGroupDefinition& group, const std::string& name) {
1698 return group.mName < name;
1700 if(iFind != animGroups.end() && iFind->mName == groupName)
1702 mOnError(FormatString("Animation group with name '%s' already exists; new entries will be merged.", groupName.c_str()));
1706 iFind = animGroups.insert(iFind, AnimationGroupDefinition{});
1709 iFind->mName = groupName;
1711 auto tnAnims = tnGroup.second.GetChild("animations");
1712 if(tnAnims && tnAnims->Size() > 0)
1714 auto& anims = iFind->mAnimations;
1715 anims.reserve(anims.size() + tnAnims->Size());
1716 for(auto iAnims = tnAnims->CBegin(), iAnimsEnd = tnAnims->CEnd(); iAnims != iAnimsEnd; ++iAnims)
1718 anims.push_back((*iAnims).second.GetString());
1724 void DliLoader::Impl::GetCameraParameters(std::vector<CameraParameters>& cameras) const
1726 if(mParser.GetRoot())
1728 if(const TreeNode* jsonCameras = mParser.GetRoot()->GetChild("cameras"))
1730 float dummyFloatArray[4];
1732 cameras.resize(jsonCameras->Size());
1733 auto iCamera = cameras.begin();
1734 for(auto i0 = jsonCameras->CBegin(), i1 = jsonCameras->CEnd(); i0 != i1; ++i0)
1736 auto& jsonCamera = (*i0).second;
1738 ReadFloat(jsonCamera.GetChild("fov"), iCamera->yFov);
1739 ReadFloat(jsonCamera.GetChild("near"), iCamera->zNear);
1740 ReadFloat(jsonCamera.GetChild("far"), iCamera->zFar);
1741 if(ReadVector(jsonCamera.GetChild("orthographic"), dummyFloatArray, 4u))
1743 iCamera->isPerspective = false;
1745 iCamera->orthographicSize = dummyFloatArray[2] * 0.5f;
1746 iCamera->aspectRatio = dummyFloatArray[1] / dummyFloatArray[2];
1749 if(auto jsonMatrix = jsonCamera.GetChild("matrix"))
1751 ReadVector(jsonMatrix, iCamera->matrix.AsFloat(), 16u);
1760 void DliLoader::Impl::GetLightParameters(std::vector<LightParameters>& lights) const
1762 if(mParser.GetRoot())
1764 if(const TreeNode* jsonLights = mParser.GetRoot()->GetChild("lights"))
1766 lights.resize(jsonLights->Size());
1767 auto iLight = lights.begin();
1768 for(auto i0 = jsonLights->CBegin(), i1 = jsonLights->CEnd(); i0 != i1; ++i0)
1770 auto& jsonLight = (*i0).second;
1771 if(!ReadVector(jsonLight.GetChild("matrix"), iLight->transform.AsFloat(), 16))
1774 FormatString("Failed to parse light %d - \"matrix\" child with 16 floats expected.\n",
1775 std::distance(jsonLights->CBegin(), i0)));
1779 int shadowMapSize = 0;
1780 if(ReadInt(jsonLight.GetChild(SHADOW_MAP_SIZE), shadowMapSize) && shadowMapSize < 0)
1783 FormatString("Failed to parse light %d - %s has an invalid value.",
1784 std::distance(jsonLights->CBegin(), i0),
1788 iLight->shadowMapSize = shadowMapSize;
1790 float orthoSize = 0.f;
1791 if(ReadFloat(jsonLight.GetChild(ORTHOGRAPHIC_SIZE), orthoSize) &&
1792 (orthoSize < .0f || std::isnan(orthoSize) || std::isinf(orthoSize)))
1795 FormatString("Failed to parse light %d - %s has an invalid value.",
1796 std::distance(jsonLights->CBegin(), i0),
1797 ORTHOGRAPHIC_SIZE));
1800 iLight->orthographicSize = orthoSize;
1802 if((iLight->shadowMapSize > 0) != (iLight->orthographicSize > .0f))
1804 mOnError(FormatString(
1805 "Light %d: Both shadow map size and orthographic size must be set for shadows to work.",
1806 std::distance(jsonLights->CBegin(), i0)));
1809 if(!ReadVector(jsonLight.GetChild("color"), iLight->color.AsFloat(), 3)) // color is optional
1811 iLight->color = Vector3::ONE; // default to white
1814 if(!ReadFloat(jsonLight.GetChild("intensity"), iLight->intensity)) // intensity is optional
1816 iLight->intensity = 1.0f; // default to 1.0
1819 if(!ReadFloat(jsonLight.GetChild("shadowIntensity"), iLight->shadowIntensity)) // intensity is optional
1821 iLight->shadowIntensity = 1.0f; // default to 1.0
1830 } // namespace Loader
1831 } // namespace Scene3D