Compute min/max value if min/max is not defined.
[platform/core/uifw/dali-toolkit.git] / dali-scene-loader / public-api / scene-definition.cpp
1 /*
2  * Copyright (c) 2021 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 // EXTERNAL
19 #include "dali/devel-api/common/map-wrapper.h"
20 #include "dali/public-api/animation/constraints.h"
21
22 // INTERNAL
23 #include "dali-scene-loader/internal/graphics/builtin-shader-extern-gen.h"
24 #include "dali-scene-loader/public-api/blend-shape-details.h"
25 #include "dali-scene-loader/public-api/scene-definition.h"
26 #include "dali-scene-loader/public-api/skinning-details.h"
27 #include "dali-scene-loader/public-api/utils.h"
28
29 //#define DEBUG_SCENE_DEFINITION
30 //#define DEBUG_JOINTS
31
32 #if defined(DEBUG_SCENE_DEFINITION) || defined(DEBUG_JOINTS)
33 #define DEBUG_ONLY(x) x
34 #else
35 #define DEBUG_ONLY(x)
36 #endif
37
38 #define LOGD(x) DEBUG_ONLY(printf x; printf("\n"); fflush(stdout))
39
40 namespace Dali
41 {
42 namespace SceneLoader
43 {
44 namespace
45 {
46 const std::string JOINT_MATRIX{"jointMatrix"};
47
48 const std::map<Property::Type, Constraint (*)(Actor&, Property::Index)> sConstraintFactory = {
49   {Property::Type::BOOLEAN,
50    [](Actor& a, Property::Index i) {
51      return Constraint::New<bool>(a, i, [](bool& current, const PropertyInputContainer& inputs) {
52        current = inputs[0]->GetBoolean();
53      });
54    }},
55   {Property::Type::INTEGER,
56    [](Actor& a, Property::Index i) {
57      return Constraint::New<int>(a, i, [](int& current, const PropertyInputContainer& inputs) {
58        current = inputs[0]->GetInteger();
59      });
60    }},
61   {Property::Type::FLOAT,
62    [](Actor& a, Property::Index i) {
63      return Constraint::New<float>(a, i, EqualToConstraint());
64    }},
65   {Property::Type::VECTOR2,
66    [](Actor& a, Property::Index i) {
67      return Constraint::New<Vector2>(a, i, EqualToConstraint());
68    }},
69   {Property::Type::VECTOR3,
70    [](Actor& a, Property::Index i) {
71      return Constraint::New<Vector3>(a, i, EqualToConstraint());
72    }},
73   {Property::Type::VECTOR4,
74    [](Actor& a, Property::Index i) {
75      return Constraint::New<Vector4>(a, i, EqualToConstraint());
76    }},
77   {Property::Type::MATRIX,
78    [](Actor& a, Property::Index i) {
79      return Constraint::New<Matrix>(a, i, EqualToConstraint());
80    }},
81   {Property::Type::MATRIX3,
82    [](Actor& a, Property::Index i) {
83      return Constraint::New<Matrix3>(a, i, EqualToConstraint());
84    }},
85   {Property::Type::ROTATION,
86    [](Actor& a, Property::Index i) {
87      return Constraint::New<Quaternion>(a, i, EqualToConstraint());
88    }},
89 };
90
91 struct ResourceReflector : IResourceReflector
92 {
93   Index* iMesh   = nullptr;
94   Index* iShader = nullptr;
95
96   void Reflect(ResourceType::Value type, Index& id)
97   {
98     switch(type)
99     {
100       case ResourceType::Shader:
101         DALI_ASSERT_ALWAYS(!iShader && "Shader index already assigned!");
102         iShader = &id;
103         break;
104
105       case ResourceType::Mesh:
106         DALI_ASSERT_ALWAYS(!iMesh && "Mesh index already assigned!");
107         iMesh = &id;
108         break;
109
110       default: // Other resource types are not relevant to the problem at hand.
111         break;
112     }
113   }
114 };
115
116 #ifdef DEBUG_JOINTS
117
118 Shader sJointDebugShader;
119 int    sNumScenes = 0;
120
121 void EnsureJointDebugShaderCreated()
122 {
123   if(0 == sNumScenes)
124   {
125     sJointDebugShader = Shader::New(SHADER_SCENE_LOADER_JOINT_DEBUG_VERT, SHADER_SCENE_LOADER_JOINT_DEBUG_FRAG);
126   }
127   ++sNumScenes;
128 }
129
130 void AddJointDebugVisual(Actor aJoint)
131 {
132   Property::Map attribs;
133   attribs["aPosition"] = Property::Type::VECTOR3;
134   attribs["aColor"]    = Property::Type::FLOAT;
135
136   PropertyBuffer vbo = PropertyBuffer::New(attribs);
137
138   struct Vertex
139   {
140     Vector3 pos;
141     float   color;
142   } vertices[] = {
143     {Vector3::ZERO, .999f + .999f * 256.f + .999f * 256.f * 256.f},
144     {Vector3::XAXIS, .999f},
145     {Vector3::YAXIS, .999f * 256.f},
146     {Vector3::ZAXIS, .999f * 256.f * 256.f},
147   };
148
149   vbo.SetData(&vertices, std::extent<decltype(vertices)>::value);
150
151   uint16_t indices[] = {0, 1, 0, 2, 0, 3};
152
153   Geometry geo = Geometry::New();
154   geo.AddVertexBuffer(vbo);
155   geo.SetIndexBuffer(indices, std::extent<decltype(indices)>::value);
156   geo.SetType(Geometry::LINES);
157
158   Renderer r = Renderer::New(geo, sJointDebugShader);
159   aJoint.AddRenderer(r);
160
161   aJoint.SetVisible(true);
162 }
163 #endif //DEBUG_JOINTS
164
165 class ActorCreatorVisitor : public NodeDefinition::IConstVisitor
166 {
167 public:
168   ActorCreatorVisitor(NodeDefinition::CreateParams& params)
169   : mCreationContext(params)
170   {
171   }
172
173   void Start(const NodeDefinition& n)
174   {
175     mCreationContext.mXforms.modelStack.Push(n.GetLocalSpace());
176
177     Actor a = n.CreateActor(mCreationContext);
178     if(!mActorStack.empty())
179     {
180       mActorStack.back().Add(a);
181     }
182     else
183     {
184       mRoot = a;
185     }
186     mActorStack.push_back(a);
187   }
188
189   void Finish(const NodeDefinition& n)
190   {
191     mActorStack.pop_back();
192     mCreationContext.mXforms.modelStack.Pop();
193   }
194
195   Actor GetRoot() const
196   {
197     return mRoot;
198   }
199
200 private:
201   NodeDefinition::CreateParams& mCreationContext;
202   std::vector<Actor>            mActorStack;
203   Actor                         mRoot;
204 };
205
206 bool IsAncestor(const SceneDefinition& scene, Index ancestor, Index node, Index rootHint = INVALID_INDEX)
207 {
208   bool isAncestor = false;
209   while(node != rootHint && !isAncestor)
210   {
211     node       = scene.GetNode(node)->mParentIdx;
212     isAncestor = ancestor == node;
213   }
214   return isAncestor;
215 }
216
217 void InsertUniqueSorted(std::vector<Index>& data, Index value)
218 {
219   auto iInsert = std::lower_bound(data.begin(), data.end(), value);
220   if(iInsert == data.end() || *iInsert != value)
221   {
222     data.insert(iInsert, value);
223   }
224 }
225
226 void RemoveFromSorted(std::vector<Index>& data, Index value)
227 {
228   auto iRemove = std::lower_bound(data.begin(), data.end(), value);
229   if(iRemove != data.end() && *iRemove == value)
230   {
231     data.erase(iRemove);
232   }
233 }
234
235 Property::Index ConfigureJointMatrix(Actor actor, Actor ancestor, Property::Index propJointMatrix)
236 {
237   Actor parent = actor.GetParent();
238   if(parent != ancestor)
239   {
240     propJointMatrix = ConfigureJointMatrix(parent, ancestor, propJointMatrix);
241   }
242
243   auto myPropJointMatrix = actor.GetPropertyIndex(JOINT_MATRIX);
244   if(myPropJointMatrix == Property::INVALID_INDEX)
245   {
246     myPropJointMatrix     = actor.RegisterProperty(JOINT_MATRIX, Matrix{false});
247     Constraint constraint = Constraint::New<Matrix>(actor, propJointMatrix, [](Matrix& output, const PropertyInputContainer& inputs) {
248       Matrix jointMatrix{false};
249       jointMatrix.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3());
250
251       Matrix::Multiply(output, jointMatrix, inputs[2]->GetMatrix());
252     });
253     constraint.AddSource(Source{actor, Actor::Property::ORIENTATION});
254     constraint.AddSource(Source{actor, Actor::Property::POSITION});
255     constraint.AddSource(Source{parent, propJointMatrix});
256     constraint.Apply();
257   }
258
259   return myPropJointMatrix;
260 }
261
262 void SortAndDeduplicateSkinningRequests(std::vector<SkinningShaderConfigurationRequest>& requests)
263 {
264   // Sort requests by shaders.
265   std::sort(requests.begin(), requests.end());
266
267   // Remove duplicates.
268   auto   i           = requests.begin();
269   auto   iEnd        = requests.end();
270   Shader s           = i->mShader;
271   Index  skeletonIdx = i->mSkeletonIdx;
272   ++i;
273   do
274   {
275     // Multiple identical shader instances are removed.
276     while(i != iEnd && i->mShader == s)
277     {
278       // Cannot have multiple skeletons input to the same shader.
279       // NOTE: DliModel now makes sure this doesn't happen.
280       DALI_ASSERT_ALWAYS(i->mSkeletonIdx == skeletonIdx &&
281                          "Skinning shader must not be shared between different skeletons.");
282
283       i->mShader = Shader();
284       ++i;
285     }
286
287     if(i == iEnd)
288     {
289       break;
290     }
291     s           = i->mShader;
292     skeletonIdx = i->mSkeletonIdx;
293     ++i;
294   } while(true);
295
296   requests.erase(std::remove_if(requests.begin(), requests.end(), [](const SkinningShaderConfigurationRequest& sscr) {
297                    return !sscr.mShader;
298                  }),
299                  requests.end());
300 }
301
302 void ConfigureBoneMatrix(const Matrix& ibm, Actor joint, Shader& shader, Index& boneIdx)
303 {
304   // Register bone transform on shader.
305   char propertyNameBuffer[32];
306   snprintf(propertyNameBuffer, sizeof(propertyNameBuffer), "%s[%d]", Skinning::BONE_UNIFORM_NAME.c_str(), boneIdx);
307   DALI_ASSERT_DEBUG(shader.GetPropertyIndex(propertyNameBuffer) == Property::INVALID_INDEX);
308   auto propBoneXform = shader.RegisterProperty(propertyNameBuffer, Matrix{false});
309
310   // Constrain bone matrix to joint transform.
311   Constraint constraint = Constraint::New<Matrix>(shader, propBoneXform, [ibm](Matrix& output, const PropertyInputContainer& inputs) {
312     Matrix::Multiply(output, ibm, inputs[0]->GetMatrix());
313   });
314
315   auto propJointMatrix = joint.GetPropertyIndex(JOINT_MATRIX);
316   constraint.AddSource(Source{joint, propJointMatrix});
317   constraint.Apply();
318
319   ++boneIdx;
320 }
321
322 template<class Visitor, class SceneDefinition>
323 void VisitInternal(Index iNode, const Customization::Choices& choices, Visitor& v, SceneDefinition& sd)
324 {
325   auto& node = *sd.GetNode(iNode);
326   v.Start(node);
327
328   if(node.mCustomization)
329   {
330     if(!node.mChildren.empty())
331     {
332       auto  choice = choices.Get(node.mCustomization->mTag);
333       Index i      = std::min(choice != Customization::NONE ? choice : 0, static_cast<Index>(node.mChildren.size() - 1));
334       sd.Visit(node.mChildren[i], choices, v);
335     }
336   }
337   else
338   {
339     for(auto i : node.mChildren)
340     {
341       sd.Visit(i, choices, v);
342     }
343   }
344
345   v.Finish(node);
346 }
347
348 } // namespace
349
350 SceneDefinition::SceneDefinition()
351 {
352   mNodes.reserve(128);
353
354 #ifdef DEBUG_JOINTS
355   EnsureJointDebugShaderCreated();
356 #endif
357 }
358
359 SceneDefinition::SceneDefinition(SceneDefinition&& other)
360 : mNodes(std::move(other.mNodes)),
361   mRootNodeIds(std::move(other.mRootNodeIds))
362 {
363 #ifdef DEBUG_JOINTS
364   EnsureJointDebugShaderCreated();
365 #endif
366 }
367
368 SceneDefinition::~SceneDefinition()
369 {
370 #ifdef DEBUG_JOINTS
371   --sNumScenes;
372   if(sNumScenes == 0)
373   {
374     sJointDebugShader = Shader();
375   }
376 #endif
377 }
378
379 uint32_t SceneLoader::SceneDefinition::AddRootNode(Index iNode)
380 {
381   if(iNode < mNodes.size())
382   {
383     uint32_t result = mRootNodeIds.size();
384     mRootNodeIds.push_back(iNode);
385     return result;
386   }
387   else
388   {
389     ExceptionFlinger(ASSERT_LOCATION) << "Failed to add new root with node " << iNode << " -- index out of bounds.";
390     return -1;
391   }
392 }
393
394 const std::vector<Index>& SceneDefinition::GetRoots() const
395 {
396   return mRootNodeIds;
397 }
398
399 void SceneDefinition::RemoveRootNode(Index iRoot)
400 {
401   if(iRoot < mRootNodeIds.size())
402   {
403     mRootNodeIds.erase(mRootNodeIds.begin() + iRoot);
404   }
405   else
406   {
407     ExceptionFlinger(ASSERT_LOCATION) << "Failed to remove root " << iRoot << " -- index out of bounds.";
408   }
409 }
410
411 uint32_t SceneDefinition::GetNodeCount() const
412 {
413   return mNodes.size();
414 }
415
416 const NodeDefinition* SceneDefinition::GetNode(Index iNode) const
417 {
418   return mNodes[iNode].get();
419 }
420
421 NodeDefinition* SceneDefinition::GetNode(Index iNode)
422 {
423   return mNodes[iNode].get();
424 }
425
426 void SceneDefinition::Visit(Index iNode, const Customization::Choices& choices, NodeDefinition::IVisitor& v)
427 {
428   VisitInternal(iNode, choices, v, *this);
429 }
430
431 void SceneDefinition::Visit(Index iNode, const Customization::Choices& choices, NodeDefinition::IConstVisitor& v) const
432 {
433   VisitInternal(iNode, choices, v, *this);
434 }
435
436 void SceneDefinition::CountResourceRefs(Index iNode, const Customization::Choices& choices, ResourceRefCounts& refCounts) const
437 {
438   struct RefCounter : IResourceReceiver
439   {
440     ResourceRefCounts* refCounts;
441
442     void Register(ResourceType::Value type, Index id)
443     {
444       ++(*refCounts)[type][id];
445     }
446   };
447
448   struct : NodeDefinition::IConstVisitor
449   {
450     RefCounter counter;
451
452     void Start(const NodeDefinition& n)
453     {
454       if(n.mRenderable)
455       {
456         n.mRenderable->RegisterResources(counter);
457       }
458     }
459
460     void Finish(const NodeDefinition& n)
461     {
462     }
463
464   } refCounterVisitor;
465   refCounterVisitor.counter.refCounts = &refCounts;
466
467   Visit(iNode, choices, refCounterVisitor);
468 }
469
470 Actor SceneDefinition::CreateNodes(Index iNode, const Customization::Choices& choices, NodeDefinition::CreateParams& params) const
471 {
472   ActorCreatorVisitor actorCreatorVisitor(params);
473
474   Visit(iNode, choices, actorCreatorVisitor);
475
476   return actorCreatorVisitor.GetRoot();
477 }
478
479 void SceneDefinition::GetCustomizationOptions(const Customization::Choices& choices,
480                                               Customization::Map&           outCustomizationOptions,
481                                               Customization::Choices*       outMissingChoices) const
482 {
483   struct : NodeDefinition::IConstVisitor
484   {
485     const Customization::Choices* choices;        // choices that we know about.
486     Customization::Map*           options;        // tags are registered here. NO OWNERSHIP.
487     Customization::Choices*       missingChoices; // tags will be registered with the default 0. NO OWNERSHIP.
488
489     void Start(const NodeDefinition& n)
490     {
491       if(n.mCustomization)
492       {
493         const std::string& tag = n.mCustomization->mTag;
494         if(missingChoices != nullptr && choices->Get(tag) == Customization::NONE)
495         {
496           missingChoices->Set(tag, 0);
497         }
498
499         auto customization = options->Get(tag);
500         if(!customization)
501         {
502           customization = options->Set(tag, {});
503         }
504         customization->nodes.push_back(n.mName);
505         customization->numOptions = std::max(customization->numOptions,
506                                              static_cast<uint32_t>(n.mChildren.size()));
507       }
508     }
509
510     void Finish(const NodeDefinition& n)
511     {
512     }
513
514   } customizationRegistrationVisitor;
515   customizationRegistrationVisitor.choices        = &choices;
516   customizationRegistrationVisitor.options        = &outCustomizationOptions;
517   customizationRegistrationVisitor.missingChoices = outMissingChoices;
518
519   for(auto i : mRootNodeIds)
520   {
521     Visit(i, choices, customizationRegistrationVisitor);
522   }
523 }
524
525 NodeDefinition* SceneDefinition::AddNode(std::unique_ptr<NodeDefinition>&& nodeDef)
526 {
527   if(FindNode(nodeDef->mName))
528   {
529     return nullptr;
530   }
531
532   // add next index (to which we're about to push) as a child to the designated parent, if any.
533   if(nodeDef->mParentIdx != INVALID_INDEX)
534   {
535     mNodes[nodeDef->mParentIdx]->mChildren.push_back(mNodes.size());
536   }
537
538   mNodes.push_back(std::move(nodeDef));
539
540   return mNodes.back().get();
541 }
542
543 bool SceneDefinition::ReparentNode(const std::string& name, const std::string& newParentName, Index siblingOrder)
544 {
545   LOGD(("reparenting %s to %s @ %d", name.c_str(), newParentName.c_str(), siblingOrder));
546
547   std::unique_ptr<NodeDefinition>* nodePtr      = nullptr;
548   std::unique_ptr<NodeDefinition>* newParentPtr = nullptr;
549   if(!FindNode(name, &nodePtr) || !FindNode(newParentName, &newParentPtr))
550   {
551     return false;
552   }
553
554   auto& node  = *nodePtr;
555   auto  iNode = std::distance(mNodes.data(), nodePtr);
556
557   DEBUG_ONLY(auto dumpNode = [](NodeDefinition const& n) {
558     std::ostringstream stream;
559     stream << n.mName << " (" << n.mParentIdx << "):";
560     for(auto i : n.mChildren)
561     {
562       stream << i << ", ";
563     }
564     LOGD(("%s", stream.str().c_str()));
565   };)
566
567   // Remove node from children of previous parent (if any).
568   if(node->mParentIdx != INVALID_INDEX)
569   {
570     LOGD(("old parent:"));
571     DEBUG_ONLY(dumpNode(*mNodes[node->mParentIdx]);)
572
573     auto& children = mNodes[node->mParentIdx]->mChildren;
574     children.erase(std::remove(children.begin(), children.end(), iNode), children.end());
575
576     DEBUG_ONLY(dumpNode(*mNodes[node->mParentIdx]);)
577   }
578
579   // Register node to new parent.
580   LOGD(("new parent:"));
581   DEBUG_ONLY(dumpNode(**newParentPtr);)
582   auto& children = (*newParentPtr)->mChildren;
583   if(siblingOrder > children.size())
584   {
585     siblingOrder = children.size();
586   }
587   children.insert(children.begin() + siblingOrder, 1, iNode);
588   DEBUG_ONLY(dumpNode(**newParentPtr);)
589
590   // Update parent index.
591   LOGD(("node:"));
592   DEBUG_ONLY(dumpNode(*node);)
593   auto iParent     = std::distance(mNodes.data(), newParentPtr);
594   node->mParentIdx = iParent;
595   DEBUG_ONLY(dumpNode(*node);)
596   return true;
597 }
598
599 bool SceneDefinition::RemoveNode(const std::string& name)
600 {
601   std::unique_ptr<NodeDefinition>* node = nullptr;
602   if(!FindNode(name, &node))
603   {
604     return false;
605   }
606
607   // Reset node def pointers recursively.
608   auto&                                                 thisNodes = mNodes;
609   unsigned int                                          numReset  = 0;
610   std::function<void(std::unique_ptr<NodeDefinition>&)> resetFn =
611     [&thisNodes, &resetFn, &numReset](std::unique_ptr<NodeDefinition>& nd) {
612       LOGD(("resetting %d", &nd - thisNodes.data()));
613       for(auto i : nd->mChildren)
614       {
615         resetFn(thisNodes[i]);
616       }
617       nd.reset();
618       ++numReset;
619     };
620
621   resetFn(*node);
622
623   // Gather indices of dead nodes into a vector which we sort on insertion.
624   std::vector<Index> offsets;
625   offsets.reserve(numReset);
626   for(auto& n : mNodes)
627   {
628     if(!n)
629     {
630       offsets.push_back(std::distance(mNodes.data(), &n));
631     }
632   }
633
634   // Erase dead nodes as they don't have to be processed anymore.
635   mNodes.erase(std::remove(mNodes.begin(), mNodes.end(), decltype(mNodes)::value_type()), mNodes.end());
636
637   // Offset all indices (parent and child) by the index they'd sort into in offsets.
638   enum
639   {
640     INDEX_FOR_REMOVAL = INVALID_INDEX
641   };
642   auto offsetter = [&offsets](Index& i) {
643     auto iFind = std::lower_bound(offsets.begin(), offsets.end(), i);
644     if(iFind != offsets.end() && *iFind == i)
645     {
646       LOGD(("marking %d for removal.", i));
647       i = INDEX_FOR_REMOVAL;
648       return false;
649     }
650     else
651     {
652       auto distance = std::distance(offsets.begin(), iFind);
653       if(distance > 0)
654       {
655         LOGD(("offsetting %d by %d.", i, distance));
656         i -= distance;
657       }
658       return true;
659     }
660   };
661
662   for(auto& nd : mNodes)
663   {
664     bool parentOffsetResult = offsetter(nd->mParentIdx);
665     DALI_ASSERT_ALWAYS(parentOffsetResult); // since nodes were recursively removed, we should not be finding invalid parents at this point.
666
667     auto& children = nd->mChildren;
668     for(auto i0 = children.begin(), i1 = children.end(); i0 != i1; ++i0)
669     {
670       offsetter(*i0);
671     }
672
673     children.erase(std::remove(children.begin(), children.end(), INDEX_FOR_REMOVAL), children.end());
674   }
675
676   return true;
677 }
678
679 void SceneDefinition::GetNodeModelStack(Index index, MatrixStack& model) const
680 {
681   auto&                    thisNodes  = mNodes;
682   std::function<void(int)> buildStack = [&model, &thisNodes, &buildStack](int i) {
683     auto node = thisNodes[i].get();
684     if(node->mParentIdx != INVALID_INDEX)
685     {
686       buildStack(node->mParentIdx);
687     }
688     model.Push(node->GetLocalSpace());
689   };
690   buildStack(index);
691 }
692
693 NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex)
694 {
695   auto iBegin = mNodes.begin();
696   auto iEnd   = mNodes.end();
697   auto iFind  = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr<NodeDefinition>& nd) {
698     return nd->mName == name;
699   });
700
701   auto result = iFind != iEnd ? iFind->get() : nullptr;
702   if(result && outIndex)
703   {
704     *outIndex = std::distance(iBegin, iFind);
705   }
706   return result;
707 }
708
709 const NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex) const
710 {
711   auto iBegin = mNodes.begin();
712   auto iEnd   = mNodes.end();
713   auto iFind  = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr<NodeDefinition>& nd) {
714     return nd->mName == name;
715   });
716
717   auto result = iFind != iEnd ? iFind->get() : nullptr;
718   if(result && outIndex)
719   {
720     *outIndex = std::distance(iBegin, iFind);
721   }
722   return result;
723 }
724
725 Index SceneDefinition::FindNodeIndex(const NodeDefinition& node) const
726 {
727   auto iBegin = mNodes.begin();
728   auto iEnd   = mNodes.end();
729   auto iFind  = std::find_if(iBegin, iEnd, [&node](const std::unique_ptr<NodeDefinition>& n) {
730     return n.get() == &node;
731   });
732   return iFind != iEnd ? std::distance(iBegin, iFind) : INVALID_INDEX;
733 }
734
735 void SceneDefinition::FindNodes(NodePredicate predicate, NodeConsumer consumer, unsigned int limit)
736 {
737   unsigned int n = 0;
738   for(auto& defp : mNodes)
739   {
740     if(predicate(*defp))
741     {
742       consumer(*defp);
743       ++n;
744       if(n == limit)
745       {
746         break;
747       }
748     }
749   }
750 }
751
752 void SceneDefinition::FindNodes(NodePredicate predicate, ConstNodeConsumer consumer, unsigned int limit) const
753 {
754   unsigned int n = 0;
755   for(auto& defp : mNodes)
756   {
757     if(predicate(*defp))
758     {
759       consumer(*defp);
760       ++n;
761       if(n == limit)
762       {
763         break;
764       }
765     }
766   }
767 }
768
769 void SceneDefinition::ApplyConstraints(Actor&                           root,
770                                        std::vector<ConstraintRequest>&& constrainables,
771                                        StringCallback                   onError) const
772 {
773   for(auto& cr : constrainables)
774   {
775     auto&           nodeDef    = mNodes[cr.mConstraint->mSourceIdx];
776     auto            sourceName = nodeDef->mName.c_str();
777     Property::Index iTarget    = cr.mTarget.GetPropertyIndex(cr.mConstraint->mProperty);
778     if(iTarget != Property::INVALID_INDEX)
779     {
780       auto propertyType = cr.mTarget.GetPropertyType(iTarget);
781       auto iFind        = sConstraintFactory.find(propertyType);
782       if(iFind == sConstraintFactory.end())
783       {
784         onError(FormatString("node '%s': Property '%s' has unsupported type '%s'; ignored.",
785                              sourceName,
786                              cr.mConstraint->mProperty.c_str(),
787                              PropertyTypes::GetName(propertyType)));
788         continue;
789       }
790
791       Constraint constraint = iFind->second(cr.mTarget, iTarget);
792
793       Actor source = root.FindChildByName(nodeDef->mName);
794       if(!source)
795       {
796         auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get<std::string>();
797         onError(FormatString("node '%s': Failed to locate constraint source %s@%s; ignored.",
798                              sourceName,
799                              cr.mConstraint->mProperty.c_str(),
800                              targetName.c_str()));
801         continue;
802       }
803       else if(source == cr.mTarget)
804       {
805         onError(FormatString("node '%s': Cyclic constraint definition for property '%s'; ignored.",
806                              sourceName,
807                              cr.mConstraint->mProperty.c_str()));
808         continue;
809       }
810
811       Property::Index iSource = source.GetPropertyIndex(cr.mConstraint->mProperty);
812       constraint.AddSource(Source{source, iSource});
813       constraint.Apply();
814     }
815     else
816     {
817       auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get<std::string>();
818       onError(FormatString("node '%s': Failed to create constraint for property %s@%s; ignored.",
819                            sourceName,
820                            cr.mConstraint->mProperty.c_str(),
821                            targetName.c_str()));
822     }
823   }
824 }
825
826 void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefinition::Vector& skeletons, Actor root) const
827 {
828   // 1, For each skeleton, for each joint, walk upwards until we reach mNodes[iRoot]. If we do, record +1
829   // to the refcount of each node we have visited, in our temporary registry. Those with refcount 1
830   // are the leaves, while the most descendant node with the highest refcount is the root of the skeleton.
831   std::map<Index, std::vector<Index>> rootsJoints;
832   std::vector<Index>                  path;
833   path.reserve(16);
834   for(auto& s : skeletons)
835   {
836     std::map<uint32_t, uint32_t> jointRefs;
837     for(auto& j : s.mJoints)
838     {
839       auto nodeIdx = j.mNodeIdx;
840       do // Traverse upwards and record each node we have visited until we reach the scene root.
841       {
842         path.push_back(nodeIdx);
843         if(nodeIdx == iRoot)
844         {
845           break;
846         }
847         auto node = GetNode(nodeIdx);
848         nodeIdx   = node->mParentIdx;
849       } while(nodeIdx != INVALID_INDEX);
850
851       if(nodeIdx == iRoot) // If the joint is in the correct scene, increment the reference count for all visited nodes.
852       {
853         for(auto i : path)
854         {
855           ++jointRefs[i];
856         }
857       }
858
859       path.clear();
860     }
861
862     // Only record the skeleton if we have encountered the root of the current scene.
863     if(jointRefs.empty())
864     {
865       continue;
866     }
867
868     Index    root   = s.mRootNodeIdx;
869     uint32_t maxRef = 0;
870     auto     iFind  = jointRefs.find(root);
871     if(iFind != jointRefs.end())
872     {
873       maxRef = iFind->second;
874     }
875
876     std::vector<Index> joints;
877     for(auto& j : jointRefs) // NOTE: jointRefs are sorted, so joints will also be.
878     {
879       // The most descendant node with the highest ref count is the root of the skeleton.
880       if(j.second > maxRef || (j.second == maxRef && IsAncestor(*this, root, j.first, iRoot)))
881       {
882         maxRef = j.second;
883
884         RemoveFromSorted(joints, root);
885         root = j.first;
886       }
887       else if(j.second == 1) // This one's a leaf.
888       {
889         InsertUniqueSorted(joints, j.first);
890       }
891     }
892
893     // Merge skeletons that share the same root.
894     auto& finalJoints = rootsJoints[root];
895     for(auto j : joints)
896     {
897       if(std::find_if(finalJoints.begin(), finalJoints.end(), [this, j, root](Index jj) {
898            return IsAncestor(*this, j, jj, root);
899          }) != finalJoints.end())
900       {
901         continue; // if the joint is found to be an ancestor of another joint already registered, move on.
902       }
903
904       auto i = j;
905       while(i != root) // See if the current joint is a better leaf, i.e. descended from another leaf - which we'll then remove.
906       {
907         auto node = GetNode(i);
908         i         = node->mParentIdx;
909
910         RemoveFromSorted(finalJoints, i);
911       }
912
913       InsertUniqueSorted(finalJoints, j);
914     }
915   }
916
917   // 2, Merge records where one root joint is descendant of another. Handle leaf node changes - remove previous
918   // leaf nodes that now have descendants, and add new ones.
919   auto iRoots    = rootsJoints.begin();
920   auto iRootsEnd = rootsJoints.end();
921   while(iRoots != iRootsEnd)
922   {
923     auto i      = iRoots->first;
924     bool merged = false;
925     while(i != iRoot) // Starting with the root joint of the skeleton, traverse upwards.
926     {
927       auto node = GetNode(i);
928       i         = node->mParentIdx;
929
930       auto iFind = rootsJoints.find(i);
931       if(iFind != rootsJoints.end()) // Check if we've reached the root of another skeleton.
932       {
933         // Now find out which leaf of iFind is an ancestor, if any.
934         auto iFindLeaf = std::find_if(iFind->second.begin(), iFind->second.end(), [this, iRoots, iFind](Index j) {
935           return IsAncestor(*this, j, iRoots->first, iFind->first);
936         });
937         if(iFindLeaf != iFind->second.end())
938         {
939           iFind->second.erase(iFindLeaf); // Will no longer be a leaf -- remove it.
940         }
941
942         // Merge iRoots with iFind
943         auto& targetJoints = iFind->second;
944         if(iRoots->second.empty()) // The root is a leaf.
945         {
946           InsertUniqueSorted(targetJoints, iRoots->first);
947         }
948         else
949           for(auto j : iRoots->second)
950           {
951             InsertUniqueSorted(targetJoints, j);
952           }
953
954         merged = true;
955         break; // Traverse no more
956       }
957     }
958
959     iRoots = merged ? rootsJoints.erase(iRoots) : std::next(iRoots);
960   }
961
962   // 3, For each root, register joint matrices and constraints
963   for(auto r : rootsJoints)
964   {
965     auto node      = GetNode(r.first);
966     auto rootJoint = root.FindChildByName(node->mName);
967     DALI_ASSERT_ALWAYS(!!rootJoint);
968
969     DALI_ASSERT_DEBUG(rootJoint.GetPropertyIndex(JOINT_MATRIX) == Property::INVALID_INDEX);
970     auto       propJointMatrix = rootJoint.RegisterProperty(JOINT_MATRIX, Matrix{false});
971     Constraint constraint      = Constraint::New<Matrix>(rootJoint, propJointMatrix, [](Matrix& output, const PropertyInputContainer& inputs) {
972       output.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3());
973     });
974     constraint.AddSource(Source(rootJoint, Actor::Property::ORIENTATION));
975     constraint.AddSource(Source(rootJoint, Actor::Property::POSITION));
976     constraint.Apply();
977
978     for(auto j : r.second)
979     {
980       node       = GetNode(j);
981       auto joint = rootJoint.FindChildByName(node->mName);
982       ConfigureJointMatrix(joint, rootJoint, propJointMatrix);
983     }
984   }
985 }
986
987 void SceneDefinition::EnsureUniqueSkinningShaderInstances(ResourceBundle& resources) const
988 {
989   std::map<Index, std::map<Index, std::vector<Index*>>> skinningShaderUsers;
990   for(auto& node : mNodes)
991   {
992     if(node->mRenderable)
993     {
994       ResourceReflector reflector;
995       node->mRenderable->ReflectResources(reflector);
996
997       if(reflector.iMesh)
998       {
999         const auto& mesh = resources.mMeshes[*reflector.iMesh].first;
1000         if(mesh.IsSkinned())
1001         {
1002           skinningShaderUsers[*reflector.iShader][mesh.mSkeletonIdx].push_back(reflector.iShader);
1003         }
1004       }
1005     }
1006   }
1007
1008   // For each shader, and each skeleton using the same shader as the first skeleton,
1009   // update the shader references (from nodes with skinned meshes) with a new copy of
1010   // the shader definition from the node using the first skeleton.
1011   for(auto& users : skinningShaderUsers)
1012   {
1013     auto& skeletons    = users.second;
1014     auto  iterSkeleton = skeletons.begin();
1015     // skipping the first skeleton.
1016     ++iterSkeleton;
1017
1018     resources.mShaders.reserve(resources.mShaders.size() + std::distance(iterSkeleton, skeletons.end()));
1019     const ShaderDefinition& shaderDef = resources.mShaders[users.first].first;
1020
1021     while(iterSkeleton != skeletons.end())
1022     {
1023       Index iShader = resources.mShaders.size();
1024       resources.mShaders.push_back({shaderDef, Shader()});
1025
1026       for(auto& i : iterSkeleton->second)
1027       {
1028         *i = iShader;
1029       }
1030       ++iterSkeleton;
1031     }
1032   }
1033 }
1034
1035 void SceneDefinition::ConfigureSkinningShaders(const ResourceBundle&                             resources,
1036                                                Actor                                             rootActor,
1037                                                std::vector<SkinningShaderConfigurationRequest>&& requests) const
1038 {
1039   if(requests.empty())
1040   {
1041     return;
1042   }
1043
1044   SortAndDeduplicateSkinningRequests(requests);
1045
1046   for(auto& i : requests)
1047   {
1048     auto& skeleton = resources.mSkeletons[i.mSkeletonIdx];
1049     if(skeleton.mJoints.empty())
1050     {
1051       LOGD(("Skeleton %d has no joints.", i.mSkeletonIdx));
1052       continue;
1053     }
1054
1055     Index boneIdx = 0;
1056     for(auto& j : skeleton.mJoints)
1057     {
1058       auto  node  = GetNode(j.mNodeIdx);
1059       Actor actor = rootActor.FindChildByName(node->mName);
1060       ConfigureBoneMatrix(j.mInverseBindMatrix, actor, i.mShader, boneIdx);
1061     }
1062   }
1063 }
1064
1065 bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle&                               resources,
1066                                                  Actor                                               rootActor,
1067                                                  std::vector<BlendshapeShaderConfigurationRequest>&& requests,
1068                                                  StringCallback                                      onError) const
1069 {
1070   if(requests.empty())
1071   {
1072     return true;
1073   }
1074
1075   // Sort requests by shaders.
1076   std::sort(requests.begin(), requests.end());
1077
1078   // Remove duplicates.
1079   auto   i    = requests.begin();
1080   auto   iEnd = requests.end();
1081   Shader s    = i->mShader;
1082   ++i;
1083   do
1084   {
1085     // Multiple identical shader instances are removed.
1086     while(i != iEnd && i->mShader == s)
1087     {
1088       i->mShader = Shader();
1089       ++i;
1090     }
1091
1092     if(i == iEnd)
1093     {
1094       break;
1095     }
1096     s = i->mShader;
1097     ++i;
1098   } while(true);
1099
1100   // Configure the rest.
1101   bool ok = true;
1102
1103   for(auto& i : requests)
1104   {
1105     Index iNode;
1106     if(FindNode(i.mNodeName, &iNode))
1107     {
1108       const auto& node = GetNode(iNode);
1109
1110       const auto& mesh = resources.mMeshes[i.mMeshIdx];
1111
1112       if(mesh.first.HasBlendShapes())
1113       {
1114         Actor actor = rootActor.FindChildByName(node->mName);
1115
1116         // Sets the property to be animated.
1117         BlendShapes::ConfigureProperties(mesh, i.mShader, actor);
1118       }
1119     }
1120   }
1121
1122   return ok;
1123 }
1124
1125 void SceneDefinition::EnsureUniqueBlendShapeShaderInstances(ResourceBundle& resources) const
1126 {
1127   std::map<Index, std::map<std::string, std::vector<Index*>>> blendShapeShaderUsers;
1128   for(auto& node : mNodes)
1129   {
1130     if(node->mRenderable)
1131     {
1132       ResourceReflector reflector;
1133       node->mRenderable->ReflectResources(reflector);
1134
1135       if(reflector.iMesh)
1136       {
1137         const auto& mesh = resources.mMeshes[*reflector.iMesh].first;
1138         if(mesh.HasBlendShapes())
1139         {
1140           blendShapeShaderUsers[*reflector.iShader][node->mName].push_back(reflector.iShader);
1141         }
1142       }
1143     }
1144   }
1145
1146   for(auto& users : blendShapeShaderUsers)
1147   {
1148     resources.mShaders.reserve(resources.mShaders.size() + users.second.size() - 1u);
1149     const ShaderDefinition& shaderDef = resources.mShaders[users.first].first;
1150
1151     auto nodesIt    = users.second.begin();
1152     auto nodesEndIt = users.second.end();
1153     // skipping the first node.
1154     ++nodesIt;
1155     while(nodesIt != nodesEndIt)
1156     {
1157       Index iShader = resources.mShaders.size();
1158       resources.mShaders.push_back({shaderDef, Shader()});
1159
1160       auto& nodes = *nodesIt;
1161       for(auto& shader : nodes.second)
1162       {
1163         *shader = iShader;
1164       }
1165       ++nodesIt;
1166     }
1167   }
1168 }
1169
1170 SceneDefinition& SceneDefinition::operator=(SceneDefinition&& other)
1171 {
1172   SceneDefinition temp(std::move(other));
1173   std::swap(mNodes, temp.mNodes);
1174   std::swap(mRootNodeIds, temp.mRootNodeIds);
1175   return *this;
1176 }
1177
1178 bool SceneDefinition::FindNode(const std::string& name, std::unique_ptr<NodeDefinition>** result)
1179 {
1180   // We're searching from the end assuming a higher probability of operations targeting
1181   // recently added nodes. (conf.: root, which is immovable, cannot be removed, and was
1182   // the first to be added, is index 0.)
1183   auto iFind = std::find_if(mNodes.rbegin(), mNodes.rend(), [&name](const std::unique_ptr<NodeDefinition>& nd) {
1184                  return nd->mName == name;
1185                }).base();
1186
1187   const bool success = iFind != mNodes.begin();
1188   if(success && result)
1189   {
1190     --iFind;
1191     *result = &*iFind;
1192   }
1193
1194   return success;
1195 }
1196
1197 } // namespace SceneLoader
1198 } // namespace Dali