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