DALi Version 2.2.11
[platform/core/uifw/dali-toolkit.git] / dali-scene3d / public-api / loader / dli-loader.cpp
1 /*
2  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include "dali-scene3d/public-api/loader/dli-loader.h"
20
21 // EXTERNAL INCLUDES
22 #include <algorithm>
23 #include <cmath>
24 #include <fstream>
25 #include <limits>
26 #include <memory>
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"
31
32 // INTERNAL INCLUDES
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"
45
46 #define DLI_0_1_COMPATIBILITY
47
48 namespace Dali
49 {
50 using namespace Toolkit;
51
52 namespace Scene3D
53 {
54 namespace Loader
55 {
56 namespace rs = RendererState;
57
58 namespace
59 {
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");
73
74 const char* const SHADOW_MAP_SIZE   = "shadowMapSize";
75 const char* const ORTHOGRAPHIC_SIZE = "orthographicSize";
76 const char* const PIXEL_UNITS       = "px";
77
78 const char SLASH = '/';
79
80 void ReadModelTransform(const TreeNode* node, Quaternion& orientation, Vector3& translation, Vector3& scale)
81 {
82   float num[16u] = {.0f};
83
84   if(ReadVector(node->GetChild("matrix"), num, 16u))
85   {
86     Matrix mat(num);
87     mat.GetTransformComponents(translation, orientation, scale);
88   }
89   else
90   {
91     if(ReadVector(node->GetChild("angle"), num, 3u))
92     {
93       orientation = Quaternion(Radian(Degree(num[0u])), Radian(Degree(num[1u])), Radian(Degree(num[2u])));
94     }
95
96     if(ReadVector(node->GetChild("position"), num, 3u))
97     {
98       translation = Vector3(num);
99     }
100   }
101 }
102
103 bool ReadAttribBlob(const TreeNode* node, MeshDefinition::Blob& buffer)
104 {
105   return ReadBlob(node, buffer.mOffset, buffer.mLength);
106 }
107
108 bool ReadAttribAccessor(const TreeNode* node, MeshDefinition::Accessor& accessor)
109 {
110   return ReadBlob(node, accessor.mBlob.mOffset, accessor.mBlob.mLength);
111 }
112
113 bool ReadColorCode(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode)
114 {
115   if(!node || !convertColorCode)
116   {
117     return false;
118   }
119
120   color = convertColorCode(node->GetString());
121
122   return true;
123 }
124
125 bool ReadColorCodeOrColor(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode)
126 {
127   return ReadColorCode(node->GetChild("colorCode"), color, convertColorCode) ||
128          ReadColor(node->GetChild("color"), color);
129 }
130
131 RendererState::Type ReadRendererState(const TreeNode& tnRendererState)
132 {
133   if(tnRendererState.GetType() == TreeNode::INTEGER)
134   {
135     return static_cast<RendererState::Type>(tnRendererState.GetInteger());
136   }
137   else if(tnRendererState.GetType() == TreeNode::STRING)
138   {
139     return RendererState::Parse(tnRendererState.GetString());
140   }
141   else
142   {
143     return -1;
144   }
145 }
146
147 ///@brief Reads arc properties.
148 void ReadArcField(const TreeNode* eArc, ArcRenderable& arc)
149 {
150   ReadBool(eArc->GetChild("antiAliasing"), arc.mAntiAliasing);
151   ReadInt(eArc->GetChild("arcCaps"), arc.mArcCaps);
152   ReadFloat(eArc->GetChild("radius"), arc.mRadius);
153
154   arc.mStartAngleDegrees = .0f;
155   ReadFloat(eArc->GetChild("startAngle"), arc.mStartAngleDegrees);
156
157   arc.mEndAngleDegrees = .0f;
158   ReadFloat(eArc->GetChild("endAngle"), arc.mEndAngleDegrees);
159 }
160
161 const TreeNode* GetNthChild(const TreeNode* node, uint32_t index)
162 {
163   uint32_t i = 0;
164   for(TreeNode::ConstIterator it = (*node).CBegin(); it != (*node).CEnd(); ++it, ++i)
165   {
166     if(i == index)
167     {
168       return &((*it).second);
169     }
170   }
171   return NULL;
172 }
173
174 const TreeNode* RequireChild(const TreeNode* node, const std::string& childName)
175 {
176   auto child = node->GetChild(childName);
177   if(!child)
178   {
179     ExceptionFlinger flinger(ASSERT_LOCATION);
180     flinger << "Failed to find child node '" << childName << "'";
181     if(auto nodeName = node->GetName())
182     {
183       flinger << " on '" << nodeName << "'";
184     }
185     flinger << ".";
186   }
187   return child;
188 }
189
190 void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array);
191
192 void ParseProperties(const Toolkit::TreeNode& node, Property::Map& map)
193 {
194   DALI_ASSERT_DEBUG(node.GetType() == TreeNode::OBJECT);
195   for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
196   {
197     auto kv = *i0;
198     switch(kv.second.GetType())
199     {
200       case TreeNode::ARRAY:
201       {
202         Property::Array array;
203         ParseProperties(kv.second, array);
204         map.Insert(kv.first, array);
205         break;
206       }
207
208       case TreeNode::OBJECT:
209       {
210         Property::Map innerMap;
211         ParseProperties(kv.second, innerMap);
212         map.Insert(kv.first, innerMap);
213         break;
214       }
215
216       case TreeNode::STRING:
217       {
218         map.Insert(kv.first, kv.second.GetString());
219         break;
220       }
221
222       case TreeNode::INTEGER:
223       {
224         map.Insert(kv.first, kv.second.GetInteger());
225         break;
226       }
227
228       case TreeNode::BOOLEAN:
229       {
230         map.Insert(kv.first, kv.second.GetBoolean());
231         break;
232       }
233
234       case TreeNode::FLOAT:
235       {
236         map.Insert(kv.first, kv.second.GetFloat());
237         break;
238       }
239
240       case TreeNode::IS_NULL:
241       {
242         break;
243       }
244     }
245   }
246 }
247
248 void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array)
249 {
250   DALI_ASSERT_DEBUG(node.GetType() == TreeNode::ARRAY);
251   for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
252   {
253     auto kv = *i0;
254     switch(kv.second.GetType())
255     {
256       case TreeNode::ARRAY:
257       {
258         Property::Array innerArray;
259         ParseProperties(kv.second, innerArray);
260         array.PushBack(innerArray);
261         break;
262       }
263
264       case TreeNode::OBJECT:
265       {
266         Property::Map map;
267         ParseProperties(kv.second, map);
268         array.PushBack(map);
269         break;
270       }
271
272       case TreeNode::STRING:
273       {
274         array.PushBack(kv.second.GetString());
275         break;
276       }
277
278       case TreeNode::INTEGER:
279       {
280         array.PushBack(kv.second.GetInteger());
281         break;
282       }
283
284       case TreeNode::BOOLEAN:
285       {
286         array.PushBack(kv.second.GetBoolean());
287         break;
288       }
289
290       case TreeNode::FLOAT:
291       {
292         array.PushBack(kv.second.GetFloat());
293         break;
294       }
295
296       case TreeNode::IS_NULL:
297       {
298         break;
299       }
300     }
301   }
302 }
303
304 } // namespace
305
306 struct DliLoader::Impl
307 {
308   StringCallback      mOnError = DefaultErrorCallback;
309   Toolkit::JsonParser mParser;
310
311   void ParseScene(LoadParams& params);
312
313 private:
314   std::map<Index, Matrix> mInverseBindMatrices;
315
316   /**
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.
324    */
325   struct IIndexMapper
326   {
327     /**
328      * @brief Attempts to create a mapping from a node's @a dli index to its @a scene
329      *  index.
330      * @return Whether the operation was successful.
331      */
332     virtual bool Map(Index iDli, Index iScene) = 0;
333
334     /**
335      * @return The scene index for the node's @a dli index.
336      */
337     virtual Index Resolve(Index iDli) = 0;
338   };
339
340   /**
341    * @brief Traverses the DOM tree created by LoadDocument() in an attempt to create
342    *  an intermediate representation of resources and nodes.
343    */
344   void ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params);
345
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);
349
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);
352
353   void ParseAnimations(const Toolkit::TreeNode* animations, LoadParams& params);
354   void ParseAnimationGroups(const Toolkit::TreeNode* animationGroups, LoadParams& params);
355
356   void ParseShaders(const Toolkit::TreeNode* shaders, ResourceBundle& resources);
357   void ParseMeshes(const Toolkit::TreeNode* meshes, ResourceBundle& resources);
358
359   void GetCameraParameters(std::vector<CameraParameters>& cameras) const;
360   void GetLightParameters(std::vector<LightParameters>& lights) const;
361 };
362
363 DliLoader::DliLoader()
364 : mImpl{new Impl}
365 {
366 }
367
368 DliLoader::~DliLoader() = default;
369
370 void DliLoader::SetErrorCallback(StringCallback onError)
371 {
372   mImpl->mOnError = onError;
373 }
374
375 bool DliLoader::LoadScene(const std::string& uri, LoadParams& params)
376 {
377   std::string daliBuffer = LoadTextFile(uri.c_str());
378
379   auto& parser = mImpl->mParser;
380   parser       = JsonParser::New();
381   if(!parser.Parse(daliBuffer))
382   {
383     return false;
384   }
385
386   mImpl->ParseScene(params);
387   return true;
388 }
389
390 std::string DliLoader::GetParseError() const
391 {
392   std::stringstream stream;
393
394   auto& parser = mImpl->mParser;
395   if(parser.ParseError())
396   {
397     stream << "position: " << parser.GetErrorPosition() << ", line: " << parser.GetErrorLineNumber() << ", column: " << parser.GetErrorColumn() << ", description: " << parser.GetErrorDescription() << ".";
398   }
399
400   return stream.str();
401 }
402
403 void DliLoader::Impl::ParseScene(LoadParams& params)
404 {
405   auto& input  = params.input;
406   auto& output = params.output;
407
408   // get index of root node.
409   auto docRoot = mParser.GetRoot();
410   if(docRoot)
411   {
412     // Process resources first - these are shared
413     if(auto environments = docRoot->GetChild("environment"))
414     {
415       ParseEnvironments(environments, output.mResources); // NOTE: must precede parsing of materials
416     }
417
418     if(auto meshes = docRoot->GetChild("meshes"))
419     {
420       ParseMeshes(meshes, output.mResources);
421     }
422
423     if(auto shaders = docRoot->GetChild("shaders"))
424     {
425       ParseShaders(shaders, output.mResources);
426     }
427
428     if(auto materials = docRoot->GetChild("materials"))
429     {
430       ParseMaterials(materials, input.mConvertColorCode, output.mResources);
431     }
432
433     for(auto& c : input.mPreNodeCategoryProcessors)
434     {
435       if(auto node = docRoot->GetChild(c.first))
436       {
437         Property::Array array;
438         ParseProperties(*node, array);
439         c.second(std::move(array), mOnError);
440       }
441     }
442
443     // Process scenes
444     Index iScene = 0; // default scene
445     ReadIndex(docRoot->GetChild("scene"), iScene);
446
447     auto tnScenes = RequireChild(docRoot, "scenes");
448     auto tnNodes  = RequireChild(docRoot, "nodes");
449     ParseSceneInternal(iScene, tnScenes, tnNodes, params);
450
451     ParseSkeletons(docRoot->GetChild("skeletons"), output.mScene, output.mResources);
452
453     output.mScene.EnsureUniqueSkinningShaderInstances(output.mResources);
454     output.mScene.EnsureUniqueBlendShapeShaderInstances(output.mResources);
455
456     // Ger cameras and lights
457     GetCameraParameters(output.mCameraParameters);
458     GetLightParameters(output.mLightParameters);
459
460     // Post-node processors and animations last
461     for(auto& c : input.mPostNodeCategoryProcessors)
462     {
463       if(auto node = docRoot->GetChild(c.first))
464       {
465         Property::Array array;
466         ParseProperties(*node, array);
467         c.second(std::move(array), mOnError);
468       }
469     }
470
471     if(auto animations = docRoot->GetChild("animations"))
472     {
473       ParseAnimations(animations, params);
474     }
475
476     if(!output.mAnimationDefinitions.empty())
477     {
478       if(auto animationGroups = docRoot->GetChild("animationGroups"))
479       {
480         ParseAnimationGroups(animationGroups, params);
481       }
482     }
483   }
484 }
485
486 void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params)
487 {
488   auto getSceneRootIdx = [tnScenes, tnNodes](Index iScene) {
489     auto tn = GetNthChild(tnScenes, iScene); // now a "scene" object
490     if(!tn)
491     {
492       ExceptionFlinger(ASSERT_LOCATION) << iScene << " is out of bounds access into " << SCENES << ".";
493     }
494
495     tn = RequireChild(tn, NODES); // now a "nodes" array
496     if(tn->GetType() != TreeNode::ARRAY)
497     {
498       ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid type; array required.";
499     }
500
501     if(tn->Size() < 1)
502     {
503       ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " must define a node id.";
504     }
505
506     tn = GetNthChild(tn, 0); // now the first element of the array
507     Index iRootNode;
508     if(!ReadIndex(tn, iRootNode))
509     {
510       ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid value for root node index: '" << iRootNode << "'.";
511     }
512
513     if(iRootNode >= tnNodes->Size())
514     {
515       ExceptionFlinger(ASSERT_LOCATION) << "Root node index << " << iRootNode << " of scene " << iScene << " is out of bounds.";
516     }
517
518     tn = GetNthChild(tnNodes, iRootNode); // now a "node" object
519     if(tn->GetType() != TreeNode::OBJECT)
520     {
521       ExceptionFlinger(ASSERT_LOCATION) << "Root node of scene " << iScene << " is of invalid JSON type; object required";
522     }
523
524     return iRootNode;
525   };
526
527   Index iRootNode = getSceneRootIdx(iScene);
528   ParseNodes(tnNodes, iRootNode, params);
529
530   auto& scene = params.output.mScene;
531   scene.AddRootNode(0);
532
533   for(Index i = 0; i < iScene; ++i)
534   {
535     Index       iRootNode = getSceneRootIdx(i);
536     const Index iRoot     = scene.GetNodeCount();
537     ParseNodes(tnNodes, iRootNode, params);
538     scene.AddRootNode(iRoot);
539   }
540
541   auto numScenes = tnScenes->Size();
542   for(Index i = iScene + 1; i < numScenes; ++i)
543   {
544     Index       iRootNode = getSceneRootIdx(i);
545     const Index iRoot     = scene.GetNodeCount();
546     ParseNodes(tnNodes, iRootNode, params);
547     scene.AddRootNode(iRoot);
548   }
549 }
550
551 void DliLoader::Impl::ParseSkeletons(const TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources)
552 {
553   if(skeletons)
554   {
555     auto iStart = skeletons->CBegin();
556     for(auto i0 = iStart, i1 = skeletons->CEnd(); i0 != i1; ++i0)
557     {
558       auto&       node = (*i0).second;
559       std::string skeletonRootName;
560       if(ReadString(node.GetChild(NODE), skeletonRootName))
561       {
562         SkeletonDefinition skeleton;
563         if(!scene.FindNode(skeletonRootName, &skeleton.mRootNodeIdx))
564         {
565           ExceptionFlinger(ASSERT_LOCATION) << FormatString("Skeleton %d: node '%s' not defined.", resources.mSkeletons.size(), skeletonRootName.c_str());
566         }
567
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();
574
575           for(auto i : node->mChildren)
576           {
577             visitFn(i);
578           }
579         };
580         visitFn(skeleton.mRootNodeIdx);
581
582         if(jointCount > Skinning::MAX_JOINTS)
583         {
584           mOnError(FormatString("Skeleton %d: joint count exceeds supported limit.", resources.mSkeletons.size()));
585           jointCount = Skinning::MAX_JOINTS;
586         }
587
588         skeleton.mJoints.reserve(jointCount);
589
590         visitFn = [&](Index id) {
591           auto iFind = ibms.find(id);
592           if(iFind != ibms.end() && skeleton.mJoints.size() < Skinning::MAX_JOINTS)
593           {
594             skeleton.mJoints.push_back({id, iFind->second});
595           }
596
597           auto node = scene.GetNode(id);
598           for(auto i : node->mChildren)
599           {
600             visitFn(i);
601           }
602         };
603         visitFn(skeleton.mRootNodeIdx);
604
605         resources.mSkeletons.push_back(std::move(skeleton));
606       }
607       else
608       {
609         ExceptionFlinger(ASSERT_LOCATION) << "skeleton " << std::distance(iStart, i0) << ": Missing required attribute '" << NODE << "'.";
610       }
611     }
612   }
613 }
614
615 void DliLoader::Impl::ParseEnvironments(const TreeNode* environments, ResourceBundle& resources)
616 {
617   Matrix cubeOrientation(Matrix::IDENTITY);
618
619   for(auto i0 = environments->CBegin(), i1 = environments->CEnd(); i0 != i1; ++i0)
620   {
621     auto& node = (*i0).second;
622
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))
631     {
632       envDef.mCubeOrientation = Quaternion(cubeOrientation);
633     }
634
635     resources.mEnvironmentMaps.emplace_back(std::move(envDef), EnvironmentDefinition::Textures());
636   }
637
638   // NOTE: guarantees environmentMaps to have an empty environment.
639   if(resources.mEnvironmentMaps.empty())
640   {
641     resources.mEnvironmentMaps.emplace_back(EnvironmentDefinition(), EnvironmentDefinition::Textures());
642   }
643 }
644
645 void DliLoader::Impl::ParseShaders(const TreeNode* shaders, ResourceBundle& resources)
646 {
647   uint32_t iShader = 0;
648   for(auto i0 = shaders->CBegin(), i1 = shaders->CEnd(); i0 != i1; ++i0, ++iShader)
649   {
650     auto&            node = (*i0).second;
651     ShaderDefinition shaderDef;
652     ReadStringVector(node.GetChild("defines"), shaderDef.mDefines);
653
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.
658
659     ReadStringVector(node.GetChild(HINTS), shaderDef.mHints);
660
661     if(ReadString(node.GetChild("vertex"), shaderDef.mVertexShaderPath) &&
662        ReadString(node.GetChild("fragment"), shaderDef.mFragmentShaderPath))
663     {
664       ToUnixFileSeparators(shaderDef.mVertexShaderPath);
665       ToUnixFileSeparators(shaderDef.mFragmentShaderPath);
666
667       for(TreeNode::ConstIterator j0 = node.CBegin(), j1 = node.CEnd(); j0 != j1; ++j0)
668       {
669         const TreeNode::KeyNodePair& keyValue = *j0;
670         const std::string&           key      = keyValue.first;
671         const TreeNode&              value    = keyValue.second;
672
673         Property::Value uniformValue;
674         if(key.compare("vertex") == 0 || key.compare("fragment") == 0 || key.compare("defines") == 0 || key.compare(HINTS) == 0)
675         {
676           continue;
677         }
678         else if(key.compare("rendererState") == 0)
679         {
680           shaderDef.mRendererState = ReadRendererState(keyValue.second);
681         }
682         else if(value.GetType() == TreeNode::INTEGER || value.GetType() == TreeNode::FLOAT)
683         {
684           float f = 0.f;
685           ReadFloat(&value, f);
686           uniformValue = f;
687         }
688         else if(value.GetType() == TreeNode::BOOLEAN)
689         {
690           DALI_LOG_WARNING("\"bool\" uniforms are handled as floats in shader");
691           bool value = false;
692           if(ReadBool(&keyValue.second, value))
693           {
694             uniformValue = value ? 1.0f : 0.0f;
695           }
696         }
697         else
698           switch(auto size = GetNumericalArraySize(&value))
699           {
700             case 16:
701             {
702               Matrix m;
703               ReadVector(&value, m.AsFloat(), size);
704               uniformValue = m;
705               break;
706             }
707
708             case 9:
709             {
710               Matrix3 m;
711               ReadVector(&value, m.AsFloat(), size);
712               uniformValue = m;
713               break;
714             }
715
716             case 4:
717             {
718               Vector4 v;
719               ReadVector(&value, v.AsFloat(), size);
720               uniformValue = v;
721               break;
722             }
723
724             case 3:
725             {
726               Vector3 v;
727               ReadVector(&value, v.AsFloat(), size);
728               uniformValue = v;
729               break;
730             }
731
732             case 2:
733             {
734               Vector2 v;
735               ReadVector(&value, v.AsFloat(), size);
736               uniformValue = v;
737               break;
738             }
739
740             default:
741               mOnError(FormatString(
742                 "shader %u: Ignoring uniform '%s': failed to infer type from %zu elements.",
743                 iShader,
744                 key.c_str(),
745                 size));
746               break;
747           }
748
749         if(Property::NONE != uniformValue.GetType())
750         {
751           shaderDef.mUniforms.Insert(key, uniformValue);
752         }
753       }
754
755       resources.mShaders.emplace_back(std::move(shaderDef), Shader());
756     }
757     else
758     {
759       ExceptionFlinger(ASSERT_LOCATION) << "shader " << iShader << ": Missing vertex / fragment shader definition.";
760     }
761   }
762 }
763
764 void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resources)
765 {
766   for(auto i0 = meshes->CBegin(), i1 = meshes->CEnd(); i0 != i1; ++i0)
767   {
768     auto& node = (*i0).second;
769
770     MeshDefinition meshDef;
771     if(!ReadString(node.GetChild(URI), meshDef.mUri))
772     {
773       ExceptionFlinger(ASSERT_LOCATION) << "mesh " << resources.mMeshes.size() << ": Missing required attribute '" << URI << "'.";
774     }
775
776     ToUnixFileSeparators(meshDef.mUri);
777
778     std::string primitive;
779     if(ReadString(node.GetChild("primitive"), primitive))
780     {
781       if(primitive == "LINES")
782       {
783         meshDef.mPrimitiveType = Geometry::LINES;
784       }
785       else if(primitive == "POINTS")
786       {
787         meshDef.mPrimitiveType = Geometry::POINTS;
788       }
789       else if(primitive != "TRIANGLES")
790       {
791         mOnError(FormatString(
792           "mesh %d: Using TRIANGLES instead of unsupported primitive type '%s'.",
793           resources.mMeshes.size(),
794           primitive.c_str()));
795       }
796     }
797
798     int attributes;
799     if(ReadInt(node.GetChild("attributes"), attributes))
800     {
801       if(MaskMatch(attributes, MeshDefinition::INDICES) &&
802          !ReadAttribAccessor(node.GetChild("indices"), meshDef.mIndices))
803       {
804         ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
805                                                           resources.mMeshes.size(),
806                                                           "indices");
807       }
808
809       if(MaskMatch(attributes, MeshDefinition::POSITIONS) &&
810          !ReadAttribAccessor(node.GetChild("positions"), meshDef.mPositions))
811       {
812         ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
813                                                           resources.mMeshes.size(),
814                                                           "positions");
815       }
816
817       if(MaskMatch(attributes, MeshDefinition::NORMALS) &&
818          !ReadAttribAccessor(node.GetChild("normals"), meshDef.mNormals))
819       {
820         mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "normals"));
821       }
822
823       if(MaskMatch(attributes, MeshDefinition::TEX_COORDS) &&
824          !ReadAttribAccessor(node.GetChild("textures"), meshDef.mTexCoords))
825       {
826         mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "textures"));
827       }
828
829       if(MaskMatch(attributes, MeshDefinition::TANGENTS) &&
830          !ReadAttribAccessor(node.GetChild("tangents"), meshDef.mTangents))
831       {
832         mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "tangents"));
833       }
834
835       // NOTE: we're no longer reading bitangents as these are calculated in the shaders.
836       if(ReadIndex(node.GetChild("skeleton"), meshDef.mSkeletonIdx))
837       {
838         if(!MaskMatch(attributes, MeshDefinition::JOINTS_0) &&
839            !MaskMatch(attributes, MeshDefinition::WEIGHTS_0))
840         {
841           mOnError(FormatString("mesh %d: Expected joints0 / weights0 attribute(s) missing.",
842                                 resources.mMeshes.size()));
843         }
844         else if(!ReadAttribAccessor(node.GetChild("joints0"), meshDef.mJoints0) ||
845                 !ReadAttribAccessor(node.GetChild("weights0"), meshDef.mWeights0))
846         {
847           mOnError(FormatString("mesh %d: Failed to read skinning information.",
848                                 resources.mMeshes.size()));
849         }
850       }
851
852       if(auto blendshapeHeader = node.GetChild(BLEND_SHAPE_HEADER))
853       {
854         std::string blendShapeVersion;
855         ReadString(blendshapeHeader->GetChild(VERSION), blendShapeVersion);
856
857         if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_1_0))
858         {
859           meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_1_0;
860         }
861         else if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_2_0))
862         {
863           meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
864         }
865
866         switch(meshDef.mBlendShapeVersion)
867         {
868           case BlendShapes::Version::VERSION_1_0:
869           case BlendShapes::Version::VERSION_2_0: // FALL THROUGH
870           {
871             ReadAttribBlob(blendshapeHeader, meshDef.mBlendShapeHeader);
872             break;
873           }
874           default:
875           {
876             // nothing to do
877             break;
878           }
879         }
880       }
881
882       if(auto blendShapes = node.GetChild(BLEND_SHAPES))
883       {
884         meshDef.mBlendShapes.resize(blendShapes->Size());
885
886         auto index = 0u;
887         for(auto it = blendShapes->CBegin(), endIt = blendShapes->CEnd(); it != endIt; ++it, ++index)
888         {
889           // Each blend shape is stored as the difference with the original mesh.
890
891           auto& blendShapeNode = (*it).second;
892
893           auto& blendShape = meshDef.mBlendShapes[index];
894           ReadString(blendShapeNode.GetChild("name"), blendShape.name);
895           if(auto position = blendShapeNode.GetChild("positions"))
896           {
897             ReadAttribAccessor(position, blendShape.deltas);
898           }
899           if(auto normals = blendShapeNode.GetChild("normals"))
900           {
901             ReadAttribAccessor(normals, blendShape.normals);
902           }
903           if(auto tangents = blendShapeNode.GetChild("tangents"))
904           {
905             ReadAttribAccessor(tangents, blendShape.tangents);
906           }
907           ReadFloat(blendShapeNode.GetChild("weight"), blendShape.weight);
908         }
909       }
910
911       bool flipV;
912       if(ReadBool(node.GetChild("flipV"), flipV))
913       {
914         meshDef.mFlags |= flipV * MeshDefinition::FLIP_UVS_VERTICAL;
915       }
916
917       resources.mMeshes.emplace_back(std::move(meshDef), MeshGeometry());
918     }
919   }
920 }
921
922 void DliLoader::Impl::ParseMaterials(const TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources)
923 {
924   for(auto i0 = materials->CBegin(), i1 = materials->CEnd(); i0 != i1; ++i0)
925   {
926     auto& node = (*i0).second;
927
928     MaterialDefinition materialDef;
929     if(auto eEnvironment = node.GetChild("environment"))
930     {
931       ReadIndex(eEnvironment, materialDef.mEnvironmentIdx);
932       if(static_cast<unsigned int>(materialDef.mEnvironmentIdx) >= resources.mEnvironmentMaps.size())
933       {
934         ExceptionFlinger(ASSERT_LOCATION) << "material " << resources.mMaterials.size() << ": Environment index " << materialDef.mEnvironmentIdx << " out of bounds (" << resources.mEnvironmentMaps.size() << ").";
935       }
936     }
937
938     // TODO : need to consider AGIF
939     std::vector<std::string> texturePaths;
940     std::string              texturePath;
941     if(ReadString(node.GetChild("albedoMap"), texturePath))
942     {
943       ToUnixFileSeparators(texturePath);
944       const auto semantic = MaterialDefinition::ALBEDO;
945       materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
946       materialDef.mFlags |= semantic | MaterialDefinition::TRANSPARENCY; // NOTE: only in dli does single / separate ALBEDO texture mean TRANSPARENCY.
947     }
948     if(ReadString(node.GetChild("albedoMetallicMap"), texturePath))
949     {
950       ToUnixFileSeparators(texturePath);
951
952       if(MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO))
953       {
954         mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "albedo"));
955       }
956
957       const auto semantic = MaterialDefinition::ALBEDO | MaterialDefinition::METALLIC;
958       materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
959       materialDef.mFlags |= semantic;
960     }
961
962     if(ReadString(node.GetChild("metallicRoughnessMap"), texturePath))
963     {
964       ToUnixFileSeparators(texturePath);
965
966       if(MaskMatch(materialDef.mFlags, MaterialDefinition::METALLIC))
967       {
968         mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "metallic"));
969       }
970
971       const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS;
972       materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
973       materialDef.mFlags |= semantic |
974                             // We have a metallic-roughhness map and the first texture did not have albedo semantics - we're in the transparency workflow.
975                             (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
976     }
977
978     if(ReadString(node.GetChild("normalMap"), texturePath))
979     {
980       ToUnixFileSeparators(texturePath);
981
982       const auto semantic = MaterialDefinition::NORMAL;
983       materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
984       materialDef.mFlags |= semantic |
985                             // We have a standalone normal map and the first texture did not have albedo semantics - we're in the transparency workflow.
986                             (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
987     }
988
989     if(ReadString(node.GetChild("normalRoughnessMap"), texturePath))
990     {
991       ToUnixFileSeparators(texturePath);
992
993       if(MaskMatch(materialDef.mFlags, MaterialDefinition::NORMAL))
994       {
995         mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "normal"));
996       }
997
998       if(MaskMatch(materialDef.mFlags, MaterialDefinition::ROUGHNESS))
999       {
1000         mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "roughness"));
1001       }
1002
1003       if(MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY))
1004       {
1005         mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "transparency"));
1006       }
1007
1008       const auto semantic = MaterialDefinition::NORMAL | MaterialDefinition::ROUGHNESS;
1009       materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1010       materialDef.mFlags |= semantic;
1011     }
1012
1013     if(ReadString(node.GetChild("subsurfaceMap"), texturePath))
1014     {
1015       ToUnixFileSeparators(texturePath);
1016
1017       const auto semantic = MaterialDefinition::SUBSURFACE;
1018       materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1019       materialDef.mFlags |= semantic;
1020     }
1021
1022     if(ReadString(node.GetChild("occlusionMap"), texturePath))
1023     {
1024       ToUnixFileSeparators(texturePath);
1025       const auto semantic = MaterialDefinition::OCCLUSION;
1026       materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
1027       materialDef.mFlags |= semantic;
1028     }
1029
1030     if(ReadColorCodeOrColor(&node, materialDef.mColor, convertColorCode) &&
1031        materialDef.mColor.a < 1.0f)
1032     {
1033       materialDef.mFlags |= MaterialDefinition::TRANSPARENCY;
1034     }
1035
1036     ReadFloat(node.GetChild("metallic"), materialDef.mMetallic);
1037     ReadFloat(node.GetChild("roughness"), materialDef.mRoughness);
1038
1039     bool mipmaps;
1040     if(ReadBool(node.GetChild("mipmap"), mipmaps) && mipmaps)
1041     {
1042       for(auto& ts : materialDef.mTextureStages)
1043       {
1044         ts.mTexture.mSamplerFlags |= SamplerFlags::FILTER_MIPMAP_LINEAR;
1045       }
1046     }
1047
1048     resources.mMaterials.emplace_back(std::move(materialDef), TextureSet());
1049   }
1050 }
1051
1052 void DliLoader::Impl::ParseNodes(const TreeNode* const nodes, Index index, LoadParams& params)
1053 {
1054   std::vector<Index> parents;
1055   parents.reserve(8);
1056
1057   struct IndexMapper : IIndexMapper
1058   {
1059     IndexMapper(size_t numNodes)
1060     {
1061       mIndices.reserve(numNodes);
1062     }
1063
1064     virtual bool Map(Index iDli, Index iScene) override
1065     {
1066       Entry idx{iDli, iScene};
1067       auto  iInsert = std::lower_bound(mIndices.begin(), mIndices.end(), idx);
1068       if(iInsert == mIndices.end() || iInsert->iDli != iDli)
1069       {
1070         mIndices.insert(iInsert, idx);
1071       }
1072       else if(iInsert->iScene != iScene)
1073       {
1074         return false;
1075       }
1076       return true;
1077     }
1078
1079     virtual unsigned int Resolve(Index iDli) override
1080     {
1081       auto iFind = std::lower_bound(mIndices.begin(), mIndices.end(), iDli, [](const Entry& idx, Index iDli) { return idx.iDli < iDli; });
1082       DALI_ASSERT_ALWAYS(iFind != mIndices.end());
1083       return iFind->iScene;
1084     }
1085
1086   private:
1087     struct Entry
1088     {
1089       unsigned int iDli;
1090       unsigned int iScene;
1091
1092       bool operator<(const Entry& other) const
1093       {
1094         return iDli < other.iDli;
1095       }
1096     };
1097     std::vector<Entry> mIndices;
1098   } mapper(nodes->Size());
1099   ParseNodesInternal(nodes, index, parents, params, mapper);
1100
1101   auto& scene = params.output.mScene;
1102   for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 < i1; ++i0)
1103   {
1104     for(auto& c : scene.GetNode(i0)->mConstraints)
1105     {
1106       c.mSourceIdx = mapper.Resolve(c.mSourceIdx);
1107     }
1108   }
1109 }
1110
1111 void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index index, std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& mapper)
1112 {
1113   // Properties that may be resolved from a JSON value with ReadInt() -- or default to 0.
1114   struct IndexProperty
1115   {
1116     ResourceType::Value type;
1117     const TreeNode*     source;
1118     Index&              target;
1119   };
1120   std::vector<IndexProperty> resourceIds;
1121   resourceIds.reserve(4);
1122
1123   if(auto node = GetNthChild(nodes, index))
1124   {
1125     NodeDefinition nodeDef;
1126     nodeDef.mParentIdx = inOutParentStack.empty() ? INVALID_INDEX : inOutParentStack.back();
1127
1128     // name
1129     ReadString(node->GetChild(NAME), nodeDef.mName);
1130
1131     // transform
1132     ReadModelTransform(node, nodeDef.mOrientation, nodeDef.mPosition, nodeDef.mScale);
1133
1134     // Reads the size of the node.
1135     //
1136     // * It can be given as 'size' or 'bounds'.
1137     // * The sdk saves the 'size' as a vector2 in some cases.
1138     // * To avoid size related issues the following code attemps
1139     //   to read the 'size/bounds' as a vector3 first, if it's
1140     //   not successful then reads it as a vector2.
1141     ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 3) ||
1142       ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 2) ||
1143       ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 3) ||
1144       ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 2);
1145
1146     // visibility
1147     ReadBool(node->GetChild("visible"), nodeDef.mIsVisible);
1148
1149     // type classification
1150     if(auto eCustomization = node->GetChild("customization")) // customization
1151     {
1152       std::string tag;
1153       if(ReadString(eCustomization->GetChild("tag"), tag))
1154       {
1155         nodeDef.mCustomization.reset(new NodeDefinition::CustomizationDefinition{tag});
1156       }
1157     }
1158     else // something renderable maybe
1159     {
1160       std::unique_ptr<NodeDefinition::Renderable> renderable;
1161       ModelRenderable*                            modelRenderable = nullptr; // no ownership, aliasing renderable for the right type.
1162
1163       const TreeNode* eRenderable = nullptr;
1164       if((eRenderable = node->GetChild("model")))
1165       {
1166         // check for mesh before allocating - this can't be missing.
1167         auto eMesh = eRenderable->GetChild("mesh");
1168         if(!eMesh)
1169         {
1170           ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
1171         }
1172
1173         modelRenderable = new ModelRenderable();
1174         renderable.reset(modelRenderable);
1175
1176         resourceIds.push_back({ResourceType::Mesh, eMesh, modelRenderable->mMeshIdx});
1177       }
1178       else if((eRenderable = node->GetChild("arc")))
1179       {
1180         // check for mesh before allocating - this can't be missing.
1181         auto eMesh = eRenderable->GetChild("mesh");
1182         if(!eMesh)
1183         {
1184           ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
1185         }
1186
1187         auto arcRenderable = new ArcRenderable;
1188         renderable.reset(arcRenderable);
1189         modelRenderable = arcRenderable;
1190
1191         resourceIds.push_back({ResourceType::Mesh, eMesh, arcRenderable->mMeshIdx});
1192
1193         ReadArcField(eRenderable, *arcRenderable);
1194       }
1195
1196       if(renderable && eRenderable != nullptr) // process common properties of all renderables + register payload
1197       {
1198         // shader
1199         renderable->mShaderIdx = 0;
1200         auto eShader           = eRenderable->GetChild("shader");
1201         if(eShader)
1202         {
1203           resourceIds.push_back({ResourceType::Shader, eShader, renderable->mShaderIdx});
1204         }
1205
1206         // color
1207         if(modelRenderable)
1208         {
1209           modelRenderable->mMaterialIdx = 0; // must offer default of 0
1210           auto eMaterial                = eRenderable->GetChild("material");
1211           if(eMaterial)
1212           {
1213             resourceIds.push_back({ResourceType::Material, eMaterial, modelRenderable->mMaterialIdx});
1214           }
1215
1216           if(!ReadColorCodeOrColor(eRenderable, modelRenderable->mColor, params.input.mConvertColorCode))
1217           {
1218             ReadColorCodeOrColor(node, modelRenderable->mColor, params.input.mConvertColorCode);
1219           }
1220         }
1221
1222         nodeDef.mRenderables.push_back(std::move(renderable));
1223       }
1224     }
1225
1226     // Resolve ints - default to 0 if undefined
1227     auto& output = params.output;
1228     for(auto& idRes : resourceIds)
1229     {
1230       Index iCheck = 0;
1231       switch(idRes.type)
1232       {
1233         case ResourceType::Shader:
1234           iCheck = output.mResources.mShaders.size();
1235           break;
1236
1237         case ResourceType::Mesh:
1238           iCheck = output.mResources.mMeshes.size();
1239           break;
1240
1241         case ResourceType::Material:
1242           iCheck = output.mResources.mMaterials.size();
1243           break;
1244
1245         default:
1246           ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid resource type: " << idRes.type << " (Programmer error)";
1247       }
1248
1249       if(!idRes.source)
1250       {
1251         idRes.target = 0;
1252       }
1253       else if(idRes.source->GetType() != TreeNode::INTEGER)
1254       {
1255         ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid " << GetResourceTypeName(idRes.type) << " index type.";
1256       }
1257       else
1258       {
1259         idRes.target = idRes.source->GetInteger();
1260       }
1261
1262       if(idRes.target >= iCheck)
1263       {
1264         ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": " << GetResourceTypeName(idRes.type) << " index " << idRes.target << " out of bounds (" << iCheck << ").";
1265       }
1266     }
1267     resourceIds.clear();
1268
1269     // Extra properties
1270     if(auto eExtras = node->GetChild("extras"))
1271     {
1272       auto& extras = nodeDef.mExtras;
1273       extras.reserve(eExtras->Size());
1274
1275       for(auto i0 = eExtras->CBegin(), i1 = eExtras->CEnd(); i0 != i1; ++i0)
1276       {
1277         NodeDefinition::Extra e;
1278
1279         auto eExtra = *i0;
1280         e.mKey      = eExtra.first;
1281         if(e.mKey.empty())
1282         {
1283           mOnError(FormatString("node %d: empty string is invalid for name of extra %d; ignored.",
1284                                 index,
1285                                 extras.size()));
1286           continue;
1287         }
1288
1289         e.mValue = ReadPropertyValue(eExtra.second);
1290         if(e.mValue.GetType() == Property::Type::NONE)
1291         {
1292           mOnError(FormatString("node %d: failed to interpret value of extra '%s' : %s; ignored.",
1293                                 index,
1294                                 e.mKey.c_str(),
1295                                 eExtra.second.GetString()));
1296         }
1297         else
1298         {
1299           auto iInsert = std::lower_bound(extras.begin(), extras.end(), e);
1300           if(iInsert != extras.end() && iInsert->mKey == e.mKey)
1301           {
1302             mOnError(FormatString("node %d: extra '%s' already defined; overriding with %s.",
1303                                   index,
1304                                   e.mKey.c_str(),
1305                                   eExtra.second.GetString()));
1306             *iInsert = std::move(e);
1307           }
1308           else
1309           {
1310             extras.insert(iInsert, e);
1311           }
1312         }
1313       }
1314     }
1315
1316     // Constraints
1317     if(auto eConstraints = node->GetChild("constraints"))
1318     {
1319       auto& constraints = nodeDef.mConstraints;
1320       constraints.reserve(eConstraints->Size());
1321
1322       ConstraintDefinition cDef;
1323       for(auto i0 = eConstraints->CBegin(), i1 = eConstraints->CEnd(); i0 != i1; ++i0)
1324       {
1325         auto eConstraint = *i0;
1326         if(!ReadIndex(&eConstraint.second, cDef.mSourceIdx))
1327         {
1328           mOnError(FormatString("node %d: node ID %s for constraint %d is invalid; ignored.",
1329                                 index,
1330                                 eConstraint.second.GetString(),
1331                                 constraints.size()));
1332         }
1333         else
1334         {
1335           cDef.mProperty = eConstraint.first;
1336
1337           auto iInsert = std::lower_bound(constraints.begin(), constraints.end(), cDef);
1338           if(iInsert != constraints.end() && *iInsert == cDef)
1339           {
1340             mOnError(FormatString("node %d: constraint %s@%d already defined; ignoring.",
1341                                   index,
1342                                   cDef.mProperty.c_str(),
1343                                   cDef.mSourceIdx));
1344           }
1345           else
1346           {
1347             constraints.insert(iInsert, cDef);
1348           }
1349         }
1350       }
1351     }
1352
1353     // Determine index for mapping
1354     const unsigned int myIndex = output.mScene.GetNodeCount();
1355     if(!mapper.Map(index, myIndex))
1356     {
1357       mOnError(FormatString("node %d: error mapping dli index %d: node has multiple parents. Ignoring subtree.", index, myIndex));
1358       return;
1359     }
1360
1361     // if the node is a bone in a skeletal animation, it will have the inverse bind pose matrix.
1362     Matrix invBindMatrix{false};
1363     if(ReadVector(node->GetChild("inverseBindPoseMatrix"), invBindMatrix.AsFloat(), 16u)) // TODO: more robust error checking?
1364     {
1365       mInverseBindMatrices[myIndex] = invBindMatrix;
1366     }
1367
1368     // Register nodeDef
1369     auto rawDef = output.mScene.AddNode(std::make_unique<NodeDefinition>(std::move(nodeDef)));
1370     if(rawDef) // NOTE: no ownership. Guaranteed to stay in scope.
1371     {
1372       // ...And only then parse children.
1373       if(auto children = node->GetChild("children"))
1374       {
1375         inOutParentStack.push_back(myIndex);
1376
1377         rawDef->mChildren.reserve(children->Size());
1378
1379         uint32_t iChild = 0;
1380         for(auto j0 = children->CBegin(), j1 = children->CEnd(); j0 != j1; ++j0, ++iChild)
1381         {
1382           auto& child = (*j0).second;
1383           if(child.GetType() == TreeNode::INTEGER)
1384           {
1385             ParseNodesInternal(nodes, child.GetInteger(), inOutParentStack, params, mapper); // child object is created in scene definition.
1386           }
1387           else
1388           {
1389             ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ", child " << iChild << ": invalid index type.";
1390           }
1391         }
1392
1393         inOutParentStack.pop_back();
1394       }
1395       else if(rawDef->mCustomization)
1396       {
1397         mOnError(FormatString("node %d: not an actual customization without children.", index));
1398       }
1399
1400       if(auto proc = params.input.mNodePropertyProcessor) // optional processing
1401       {
1402         // WARNING: constraint IDs are not resolved at this point.
1403         Property::Map nodeData;
1404         ParseProperties(*node, nodeData);
1405         proc(*rawDef, std::move(nodeData), mOnError);
1406       }
1407     }
1408     else
1409     {
1410       ExceptionFlinger(ASSERT_LOCATION) << "Node " << index << ": name already used.";
1411     }
1412   }
1413 }
1414
1415 void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& params)
1416 {
1417   auto& definitions = params.output.mAnimationDefinitions;
1418   definitions.reserve(definitions.size() + tnAnimations->Size());
1419
1420   for(TreeNode::ConstIterator iAnim = tnAnimations->CBegin(), iAnimEnd = tnAnimations->CEnd();
1421       iAnim != iAnimEnd;
1422       ++iAnim)
1423   {
1424     const TreeNode&     tnAnim = (*iAnim).second;
1425     AnimationDefinition animDef;
1426     ReadString(tnAnim.GetChild(NAME), animDef.mName);
1427
1428     auto       iFind     = std::lower_bound(definitions.begin(), definitions.end(), animDef, [](const AnimationDefinition& ad0, const AnimationDefinition& ad1) { return ad0.mName < ad1.mName; });
1429     const bool overwrite = iFind != definitions.end() && iFind->mName == animDef.mName;
1430     if(overwrite)
1431     {
1432       mOnError(FormatString("Pre-existing animation with name '%s' is being overwritten.", animDef.mName.c_str()));
1433     }
1434
1435     // Duration -- We need something that animated properties' delay / duration can
1436     // be expressed as a multiple of; 0 won't work. This is small enough (i.e. shorter
1437     // than our frame delay) to not be restrictive WRT replaying. If anything needs
1438     // to occur more frequently, then Animations are likely not your solution anyway.
1439     animDef.mDuration = AnimationDefinition::MIN_DURATION_SECONDS;
1440     if(!ReadFloat(tnAnim.GetChild("duration"), animDef.mDuration))
1441     {
1442       mOnError(FormatString("Animation '%s' fails to define '%s', defaulting to %f.",
1443                             animDef.mName.c_str(),
1444                             "duration",
1445                             animDef.mDuration));
1446     }
1447
1448     // Get loop count - # of playbacks. Default is once. 0 means repeat indefinitely.
1449     animDef.mLoopCount = 1;
1450     if(ReadInt(tnAnim.GetChild("loopCount"), animDef.mLoopCount) &&
1451        animDef.mLoopCount < 0)
1452     {
1453       animDef.mLoopCount = 0;
1454     }
1455
1456     std::string endAction;
1457     if(ReadString(tnAnim.GetChild("endAction"), endAction))
1458     {
1459       if("BAKE" == endAction)
1460       {
1461         animDef.mEndAction = Animation::BAKE;
1462       }
1463       else if("DISCARD" == endAction)
1464       {
1465         animDef.mEndAction = Animation::DISCARD;
1466       }
1467       else if("BAKE_FINAL" == endAction)
1468       {
1469         animDef.mEndAction = Animation::BAKE_FINAL;
1470       }
1471     }
1472
1473     if(ReadString(tnAnim.GetChild("disconnectAction"), endAction))
1474     {
1475       if("BAKE" == endAction)
1476       {
1477         animDef.mDisconnectAction = Animation::BAKE;
1478       }
1479       else if("DISCARD" == endAction)
1480       {
1481         animDef.mDisconnectAction = Animation::DISCARD;
1482       }
1483       else if("BAKE_FINAL" == endAction)
1484       {
1485         animDef.mDisconnectAction = Animation::BAKE_FINAL;
1486       }
1487     }
1488
1489     if(const TreeNode* tnProperties = tnAnim.GetChild("properties"))
1490     {
1491       animDef.mProperties.reserve(tnProperties->Size());
1492       for(TreeNode::ConstIterator iProperty = tnProperties->CBegin(), iPropertyEnd = tnProperties->CEnd();
1493           iProperty != iPropertyEnd;
1494           ++iProperty)
1495       {
1496         const TreeNode& tnProperty = (*iProperty).second;
1497
1498         AnimatedProperty animProp;
1499         if(!ReadString(tnProperty.GetChild("node"), animProp.mNodeName))
1500         {
1501           mOnError(FormatString("Animation '%s': Failed to read the 'node' tag.", animDef.mName.c_str()));
1502           continue;
1503         }
1504
1505         if(!ReadString(tnProperty.GetChild("property"), animProp.mPropertyName))
1506         {
1507           mOnError(FormatString("Animation '%s': Failed to read the 'property' tag", animDef.mName.c_str()));
1508           continue;
1509         }
1510
1511         // these are the defaults
1512         animProp.mTimePeriod.delaySeconds    = 0.f;
1513         animProp.mTimePeriod.durationSeconds = animDef.mDuration;
1514         if(!ReadTimePeriod(tnProperty.GetChild("timePeriod"), animProp.mTimePeriod))
1515         {
1516           mOnError(FormatString("Animation '%s': timePeriod missing in Property #%d: defaulting to %f.",
1517                                 animDef.mName.c_str(),
1518                                 animDef.mProperties.size(),
1519                                 animProp.mTimePeriod.durationSeconds));
1520         }
1521
1522         std::string alphaFunctionValue;
1523         if(ReadString(tnProperty.GetChild("alphaFunction"), alphaFunctionValue))
1524         {
1525           animProp.mAlphaFunction = GetAlphaFunction(alphaFunctionValue);
1526         }
1527
1528         if(const TreeNode* tnKeyFramesBin = tnProperty.GetChild("keyFramesBin"))
1529         {
1530           DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
1531
1532           std::ifstream binAniFile;
1533           std::string   animationFilename;
1534           if(ReadString(tnKeyFramesBin->GetChild(URL), animationFilename))
1535           {
1536             std::string animationFullPath = params.input.mAnimationsPath + animationFilename;
1537             binAniFile.open(animationFullPath, std::ios::binary);
1538             if(binAniFile.fail())
1539             {
1540               ExceptionFlinger(ASSERT_LOCATION) << "Failed to open animation data '" << animationFullPath << "'";
1541             }
1542           }
1543
1544           int byteOffset = 0;
1545           ReadInt(tnKeyFramesBin->GetChild("byteOffset"), byteOffset);
1546           DALI_ASSERT_ALWAYS(byteOffset >= 0);
1547
1548           binAniFile.seekg(byteOffset, std::ios::beg);
1549
1550           int numKeys = 0;
1551           ReadInt(tnKeyFramesBin->GetChild("numKeys"), numKeys);
1552           DALI_ASSERT_ALWAYS(numKeys >= 0);
1553
1554           animProp.mKeyFrames = KeyFrames::New();
1555
1556           // In binary animation file only is saved the position, rotation, scale and blend shape weight keys.
1557           // so, if it is vector3 we assume is position or scale keys, if it is vector4 we assume is rotation,
1558           //  otherwise are blend shape weight keys.
1559           //  TODO support for binary header with size information
1560           Property::Type propType = Property::FLOAT; // assume blend shape weights
1561           if(animProp.mPropertyName == "orientation")
1562           {
1563             propType = Property::VECTOR4;
1564           }
1565           else if((animProp.mPropertyName == "position") || (animProp.mPropertyName == "scale"))
1566           {
1567             propType = Property::VECTOR3;
1568           }
1569
1570           // alphafunction is reserved for future implementation
1571           //  NOTE: right now we're just using AlphaFunction::LINEAR.
1572           unsigned char dummyAlphaFunction;
1573
1574           float           progress;
1575           Property::Value propValue;
1576           for(int key = 0; key < numKeys; key++)
1577           {
1578             binAniFile.read(reinterpret_cast<char*>(&progress), sizeof(float));
1579             if(propType == Property::VECTOR3)
1580             {
1581               Vector3 value;
1582               binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 3);
1583               propValue = Property::Value(value);
1584             }
1585             else if(propType == Property::VECTOR4)
1586             {
1587               Vector4 value;
1588               binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 4);
1589               propValue = Property::Value(Quaternion(value));
1590             }
1591             else
1592             {
1593               float value;
1594               binAniFile.read(reinterpret_cast<char*>(&value), sizeof(float));
1595               propValue = Property::Value(value);
1596             }
1597
1598             binAniFile.read(reinterpret_cast<char*>(&dummyAlphaFunction), sizeof(unsigned char));
1599
1600             animProp.mKeyFrames.Add(progress, propValue, AlphaFunction::LINEAR);
1601           }
1602         }
1603         else if(const TreeNode* tnKeyFrames = tnProperty.GetChild("keyFrames"))
1604         {
1605           DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
1606           animProp.mKeyFrames = KeyFrames::New();
1607
1608           float progress = 0.0f;
1609           for(auto i0 = tnKeyFrames->CBegin(), i1 = tnKeyFrames->CEnd(); i1 != i0; ++i0)
1610           {
1611             const TreeNode::KeyNodePair& kfKeyChild = *i0;
1612             bool                         readResult = ReadFloat(kfKeyChild.second.GetChild("progress"), progress);
1613             DALI_ASSERT_ALWAYS(readResult && "Key frame entry must have 'progress'");
1614
1615             const TreeNode* tnValue = kfKeyChild.second.GetChild("value");
1616             DALI_ASSERT_ALWAYS(tnValue && "Key frame entry must have 'value'");
1617
1618             // For the "orientation" property, convert from Vector4 -> Rotation value
1619             // This work-around is preferable to a null-pointer exception in the DALi update thread
1620             Property::Value propValue(ReadPropertyValue(*tnValue));
1621             if(propValue.GetType() == Property::VECTOR4 &&
1622                animProp.mPropertyName == "orientation")
1623             {
1624               Vector4 v;
1625               propValue.Get(v);
1626               propValue = Property::Value(Quaternion(v.w, v.x, v.y, v.z));
1627             }
1628
1629             AlphaFunction kfAlphaFunction(AlphaFunction::DEFAULT);
1630             std::string   alphaFuncStr;
1631             if(ReadString(kfKeyChild.second.GetChild("alphaFunction"), alphaFuncStr))
1632             {
1633               kfAlphaFunction = GetAlphaFunction(alphaFuncStr);
1634             }
1635
1636             animProp.mKeyFrames.Add(progress, propValue, kfAlphaFunction);
1637           }
1638         }
1639         else
1640         {
1641           const TreeNode* tnValue = tnProperty.GetChild("value");
1642           if(tnValue)
1643           {
1644             animProp.mValue.reset(new AnimatedProperty::Value{ReadPropertyValue(*tnValue)});
1645             ReadBool(tnProperty.GetChild("relative"), animProp.mValue->mIsRelative);
1646           }
1647           else
1648           {
1649             mOnError(FormatString("Property '%s' fails to define target value.",
1650                                   animProp.mPropertyName.c_str()));
1651           }
1652         }
1653
1654         animDef.mProperties.push_back(std::move(animProp));
1655       }
1656     }
1657
1658     if(overwrite)
1659     {
1660       *iFind = std::move(animDef);
1661     }
1662     else
1663     {
1664       iFind = definitions.insert(iFind, std::move(animDef));
1665     }
1666
1667     if(auto proc = params.input.mAnimationPropertyProcessor) // optional processing
1668     {
1669       Property::Map map;
1670       ParseProperties(tnAnim, map);
1671       proc(animDef, std::move(map), mOnError);
1672     }
1673   }
1674 }
1675
1676 void DliLoader::Impl::ParseAnimationGroups(const Toolkit::TreeNode* tnAnimationGroups, LoadParams& params)
1677 {
1678   auto& animGroups = params.output.mAnimationGroupDefinitions;
1679
1680   int numGroups = 0;
1681   for(auto iGroups = tnAnimationGroups->CBegin(), iGroupsEnd = tnAnimationGroups->CEnd();
1682       iGroups != iGroupsEnd;
1683       ++iGroups, ++numGroups)
1684   {
1685     const auto& tnGroup = *iGroups;
1686     auto        tnName  = tnGroup.second.GetChild(NAME);
1687     std::string groupName;
1688     if(!tnName || !ReadString(tnName, groupName))
1689     {
1690       mOnError(FormatString("Failed to get the name for the Animation group %d; ignoring.", numGroups));
1691       continue;
1692     }
1693
1694     auto iFind = std::lower_bound(animGroups.begin(), animGroups.end(), groupName, [](const AnimationGroupDefinition& group, const std::string& name) { return group.mName < name; });
1695     if(iFind != animGroups.end() && iFind->mName == groupName)
1696     {
1697       mOnError(FormatString("Animation group with name '%s' already exists; new entries will be merged.", groupName.c_str()));
1698     }
1699     else
1700     {
1701       iFind = animGroups.insert(iFind, AnimationGroupDefinition{});
1702     }
1703
1704     iFind->mName = groupName;
1705
1706     auto tnAnims = tnGroup.second.GetChild("animations");
1707     if(tnAnims && tnAnims->Size() > 0)
1708     {
1709       auto& anims = iFind->mAnimations;
1710       anims.reserve(anims.size() + tnAnims->Size());
1711       for(auto iAnims = tnAnims->CBegin(), iAnimsEnd = tnAnims->CEnd(); iAnims != iAnimsEnd; ++iAnims)
1712       {
1713         anims.push_back((*iAnims).second.GetString());
1714       }
1715     }
1716   }
1717 }
1718
1719 void DliLoader::Impl::GetCameraParameters(std::vector<CameraParameters>& cameras) const
1720 {
1721   if(mParser.GetRoot())
1722   {
1723     if(const TreeNode* jsonCameras = mParser.GetRoot()->GetChild("cameras"))
1724     {
1725       float dummyFloatArray[4];
1726
1727       cameras.resize(jsonCameras->Size());
1728       auto iCamera = cameras.begin();
1729       for(auto i0 = jsonCameras->CBegin(), i1 = jsonCameras->CEnd(); i0 != i1; ++i0)
1730       {
1731         auto& jsonCamera = (*i0).second;
1732
1733         ReadFloat(jsonCamera.GetChild("fov"), iCamera->yFov);
1734         ReadFloat(jsonCamera.GetChild("near"), iCamera->zNear);
1735         ReadFloat(jsonCamera.GetChild("far"), iCamera->zFar);
1736         if(ReadVector(jsonCamera.GetChild("orthographic"), dummyFloatArray, 4u))
1737         {
1738           iCamera->isPerspective = false;
1739
1740           iCamera->orthographicSize = dummyFloatArray[2] * 0.5f;
1741           iCamera->aspectRatio      = dummyFloatArray[1] / dummyFloatArray[2];
1742         }
1743
1744         if(auto jsonMatrix = jsonCamera.GetChild("matrix"))
1745         {
1746           ReadVector(jsonMatrix, iCamera->matrix.AsFloat(), 16u);
1747         }
1748
1749         ++iCamera;
1750       }
1751     }
1752   }
1753 }
1754
1755 void DliLoader::Impl::GetLightParameters(std::vector<LightParameters>& lights) const
1756 {
1757   if(mParser.GetRoot())
1758   {
1759     if(const TreeNode* jsonLights = mParser.GetRoot()->GetChild("lights"))
1760     {
1761       lights.resize(jsonLights->Size());
1762       auto iLight = lights.begin();
1763       for(auto i0 = jsonLights->CBegin(), i1 = jsonLights->CEnd(); i0 != i1; ++i0)
1764       {
1765         auto& jsonLight = (*i0).second;
1766         if(!ReadVector(jsonLight.GetChild("matrix"), iLight->transform.AsFloat(), 16))
1767         {
1768           mOnError(
1769             FormatString("Failed to parse light %d - \"matrix\" child with 16 floats expected.\n",
1770                          std::distance(jsonLights->CBegin(), i0)));
1771           continue;
1772         }
1773
1774         int shadowMapSize = 0;
1775         if(ReadInt(jsonLight.GetChild(SHADOW_MAP_SIZE), shadowMapSize) && shadowMapSize < 0)
1776         {
1777           mOnError(
1778             FormatString("Failed to parse light %d - %s has an invalid value.",
1779                          std::distance(jsonLights->CBegin(), i0),
1780                          SHADOW_MAP_SIZE));
1781           continue;
1782         }
1783         iLight->shadowMapSize = shadowMapSize;
1784
1785         float orthoSize = 0.f;
1786         if(ReadFloat(jsonLight.GetChild(ORTHOGRAPHIC_SIZE), orthoSize) &&
1787            (orthoSize < .0f || std::isnan(orthoSize) || std::isinf(orthoSize)))
1788         {
1789           mOnError(
1790             FormatString("Failed to parse light %d - %s has an invalid value.",
1791                          std::distance(jsonLights->CBegin(), i0),
1792                          ORTHOGRAPHIC_SIZE));
1793           continue;
1794         }
1795         iLight->orthographicSize = orthoSize;
1796
1797         if((iLight->shadowMapSize > 0) != (iLight->orthographicSize > .0f))
1798         {
1799           mOnError(FormatString(
1800             "Light %d: Both shadow map size and orthographic size must be set for shadows to work.",
1801             std::distance(jsonLights->CBegin(), i0)));
1802         }
1803
1804         if(!ReadVector(jsonLight.GetChild("color"), iLight->color.AsFloat(), 3)) // color is optional
1805         {
1806           iLight->color = Vector3::ONE; // default to white
1807         }
1808
1809         if(!ReadFloat(jsonLight.GetChild("intensity"), iLight->intensity)) // intensity is optional
1810         {
1811           iLight->intensity = 1.0f; // default to 1.0
1812         }
1813
1814         if(!ReadFloat(jsonLight.GetChild("shadowIntensity"), iLight->shadowIntensity)) // intensity is optional
1815         {
1816           iLight->shadowIntensity = 1.0f; // default to 1.0
1817         }
1818
1819         ++iLight;
1820       }
1821     }
1822   }
1823 }
1824
1825 } // namespace Loader
1826 } // namespace Scene3D
1827 } // namespace Dali