Merge branch 'devel/master' into tizen
[platform/core/uifw/dali-toolkit.git] / dali-scene3d / internal / algorithm / path-finder-spfa.cpp
1 /*
2  * Copyright (c) 2023 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 // CLASS HEADER
18 #include <dali-scene3d/internal/algorithm/path-finder-spfa.h>
19
20 // EXTERNAL INCLUDES
21 #include <dali/public-api/common/vector-wrapper.h>
22 #include <limits>
23
24 // INTERNAL INCLUDES
25 #include <dali-scene3d/internal/algorithm/path-finder-waypoint-data.h>
26 #include <dali-scene3d/public-api/algorithm/path-finder-waypoint.h>
27
28 using WayPointList = Dali::Scene3D::Algorithm::WayPointList;
29
30 namespace Dali::Scene3D::Internal::Algorithm
31 {
32 PathFinderAlgorithmSPFA::PathFinderAlgorithmSPFA(Dali::Scene3D::Algorithm::NavigationMesh& navMesh)
33 : mNavigationMesh(&GetImplementation(navMesh))
34 {
35   PrepareData();
36 }
37
38 PathFinderAlgorithmSPFA::~PathFinderAlgorithmSPFA() = default;
39
40 Scene3D::Algorithm::WayPointList PathFinderAlgorithmSPFA::FindPath(const Dali::Vector3& positionFrom, const Dali::Vector3& positionTo)
41 {
42   Dali::Vector3 outPosFrom;
43   uint32_t      polyIndexFrom;
44   auto          result = mNavigationMesh->FindFloor(positionFrom, outPosFrom, polyIndexFrom);
45
46   Scene3D::Algorithm::WayPointList waypoints;
47
48   if(result)
49   {
50     Dali::Vector3 outPosTo;
51     uint32_t      polyIndexTo;
52     result = mNavigationMesh->FindFloor(positionTo, outPosTo, polyIndexTo);
53
54     if(result)
55     {
56       // Get waypoints
57       waypoints = FindPath(polyIndexFrom, polyIndexTo);
58
59       // replace first and last waypoint
60       auto& wpFrom = static_cast<WayPointData&>(waypoints[0]);
61       auto& wpTo   = static_cast<WayPointData&>(waypoints.back());
62
63       Vector2 fromCenter(wpFrom.point3d.x, wpFrom.point3d.y);
64       wpFrom.point3d = outPosFrom;
65       wpFrom.point2d = fromCenter - Vector2(outPosFrom.x, outPosFrom.y);
66
67       Vector2 toCenter(wpTo.point3d.x, wpTo.point3d.y);
68       wpTo.point3d = outPosTo;
69       wpTo.point2d = toCenter - Vector2(outPosTo.x, outPosTo.y);
70       wpTo.point3d = outPosTo;
71     }
72   }
73
74   // Returns waypoints with non-zero size of empty vector in case of failure (no path to be found)
75   return waypoints;
76 }
77
78 Scene3D::Algorithm::WayPointList PathFinderAlgorithmSPFA::FindPath(uint32_t sourcePolyIndex, uint32_t targetPolyIndex)
79 {
80   auto                  nodeCount = uint32_t(mNodes.size());
81   std::vector<float>    dist;
82   std::vector<uint32_t> prev;
83   std::vector<bool>     queued;
84
85   dist.resize(mNodes.size());
86   prev.resize(mNodes.size());
87   queued.resize(mNodes.size());
88
89   std::list<uint32_t> nodeQueue;
90
91   [[maybe_unused]] auto sourcePos = Dali::Vector3(Face(sourcePolyIndex)->center);
92
93   for(auto i = 0u; i < nodeCount; ++i)
94   {
95     dist[i]   = std::numeric_limits<float>::infinity();
96     prev[i]   = Scene3D::Algorithm::NavigationMesh::NULL_FACE; // set prev to null polygon
97     queued[i] = false;
98   }
99
100   // Set distance of source
101   dist[sourcePolyIndex]   = 0.0f;
102   queued[sourcePolyIndex] = true;
103   nodeQueue.push_back(sourcePolyIndex);
104
105   while(!nodeQueue.empty())
106   {
107     // find minimum distance
108     auto minDistIndex = nodeQueue.front();
109     nodeQueue.pop_front();
110     queued[minDistIndex] = false;
111
112     // Skip operator when minDistIndex is target
113     if(minDistIndex == targetPolyIndex)
114     {
115       continue;
116     }
117
118     // check the neighbours
119     for(auto i = 0u; i < 3; ++i)
120     {
121       auto nIndex = mNodes[minDistIndex].faces[i];
122       if(nIndex != Scene3D::Algorithm::NavigationMesh::NULL_FACE)
123       {
124         auto alt = dist[minDistIndex] + mNodes[minDistIndex].weight[i];
125         if(alt < dist[nIndex])
126         {
127           dist[nIndex] = alt;
128           prev[nIndex] = minDistIndex;
129
130           if(!queued[nIndex])
131           {
132             queued[nIndex] = true;
133             if(!nodeQueue.empty() && dist[nIndex] < dist[nodeQueue.front()])
134             {
135               nodeQueue.push_front(nIndex);
136             }
137             else
138             {
139               nodeQueue.push_back(nIndex);
140             }
141           }
142         }
143       }
144     }
145   }
146
147   // Compute distances for each node back to the source
148   auto                u = targetPolyIndex;
149   std::list<uint32_t> q;
150   if(prev[u] != Scene3D::Algorithm::NavigationMesh::NULL_FACE || u == sourcePolyIndex)
151   {
152     while(u != Scene3D::Algorithm::NavigationMesh::NULL_FACE)
153     {
154       q.push_front(u);
155       u = prev[u];
156     }
157   }
158
159   WayPointList waypoints;
160   waypoints.resize(q.size());
161
162   if(q.size() == 0)
163   {
164     // Fail to found path. Return empty list.
165     return waypoints;
166   }
167
168   auto index = 0u;
169   auto prevN = 0u;
170   for(auto n : q)
171   {
172     auto& wp     = static_cast<WayPointData&>(waypoints[index]);
173     wp.face      = mNavigationMesh->GetFace(n);
174     wp.nodeIndex = n;
175
176     wp.edge = nullptr;
177     // set the common edge with previous node
178     if(index > 0)
179     {
180       const auto& node = mNodes[prevN];
181       for(auto i = 0u; i < 3; ++i)
182       {
183         if(node.faces[i] == wp.nodeIndex)
184         {
185           wp.edge = mNavigationMesh->GetEdge(node.edges[i]);
186           break;
187         }
188       }
189     }
190
191     prevN = n;
192     index++;
193   }
194
195   return OptimizeWaypoints(waypoints);
196 }
197
198 void PathFinderAlgorithmSPFA::PrepareData()
199 {
200   // Build the list structure connecting the nodes
201   auto faceCount = mNavigationMesh->GetFaceCount();
202
203   mNodes.resize(faceCount);
204
205   // for each face build the list
206   for(auto i = 0u; i < faceCount; ++i)
207   {
208     auto&       node = mNodes[i];
209     const auto* face = mNavigationMesh->GetFace(i);
210     auto        c0   = Dali::Vector3(face->center);
211
212     // for each edge add neighbouring face and compute distance to set the weight of node
213     for(auto edgeIndex = 0u; edgeIndex < 3; ++edgeIndex)
214     {
215       const auto* edge = mNavigationMesh->GetEdge(face->edge[edgeIndex]);
216       auto        p1   = edge->face[0];
217       auto        p2   = edge->face[1];
218
219       // One of faces is current face so ignore it
220       auto p                = ((p1 != i) ? p1 : p2);
221       node.faces[edgeIndex] = p;
222       if(p != ::Dali::Scene3D::Algorithm::NavigationMesh::NULL_FACE)
223       {
224         node.edges[edgeIndex]  = face->edge[edgeIndex];
225         auto c1                = Dali::Vector3(mNavigationMesh->GetFace(p)->center);
226         node.weight[edgeIndex] = (c1 - c0).Length();
227       }
228     }
229   }
230 }
231
232 [[maybe_unused]] static float ccw(const Dali::Vector2& A, const Dali::Vector2& B, const Dali::Vector2& C)
233 {
234   return (C.y - A.y) * (B.x - A.x) > (B.y - A.y) * (C.x - A.x);
235 }
236
237 [[maybe_unused]] static bool intersect(const Dali::Vector2& A, const Dali::Vector2& B, const Dali::Vector2& C, const Dali::Vector2& D)
238 {
239   return ccw(A, C, D) != ccw(B, C, D) && ccw(A, B, C) != ccw(A, B, D);
240 }
241
242 Scene3D::Algorithm::WayPointList PathFinderAlgorithmSPFA::OptimizeWaypoints(WayPointList& waypoints) const
243 {
244   WayPointList optimizedWaypoints;
245   optimizedWaypoints.emplace_back(waypoints[0]);
246   optimizedWaypoints.reserve(waypoints.size());
247
248   auto startIndex = 1u;
249
250   bool finished = false;
251   for(auto j = 0; !finished; ++j)
252   {
253     auto&       startWaypoint     = optimizedWaypoints.back();
254     const auto& startWaypointData = static_cast<const WayPointData&>(startWaypoint);
255
256     // add new-last waypoint which will be overriden as long as intersection takes place
257     optimizedWaypoints.emplace_back();
258     for(auto wpIndex = startIndex; wpIndex < waypoints.size(); ++wpIndex)
259     {
260       if(wpIndex == waypoints.size() - 1)
261       {
262         optimizedWaypoints.back() = waypoints.back();
263         finished                  = true;
264         continue;
265       }
266       // Points between centres of faces
267
268       const auto& wpData = static_cast<const WayPointData&>(waypoints[wpIndex]);
269
270       auto Pa0 = Dali::Vector2(startWaypointData.face->center[0], startWaypointData.face->center[1]);
271       auto Pa1 = Dali::Vector2(wpData.face->center[0], wpData.face->center[1]);
272
273       bool doesIntersect = true;
274       for(auto i = startIndex; i < wpIndex; ++i)
275       {
276         const auto& wp = static_cast<WayPointData&>(waypoints[i]);
277         // Skip starting waypoint
278         if(wp.face == startWaypointData.face)
279         {
280           continue;
281         }
282         auto Pb0  = mNavigationMesh->GetVertex(wp.edge->vertex[0]);
283         auto Pb1  = mNavigationMesh->GetVertex(wp.edge->vertex[1]);
284         auto vPb0 = Dali::Vector2(Pb0->x, Pb0->y);
285         auto vPb1 = Dali::Vector2(Pb1->x, Pb1->y);
286
287         doesIntersect = intersect(Pa0, Pa1, vPb0, vPb1);
288         if(!doesIntersect)
289         {
290           break;
291         }
292       }
293
294       if(!doesIntersect)
295       {
296         optimizedWaypoints.back() = waypoints[wpIndex - 1];
297         startIndex                = wpIndex - 1;
298         break;
299       }
300     }
301   }
302
303   for(auto& wp : optimizedWaypoints)
304   {
305     auto& wpData   = static_cast<WayPointData&>(wp);
306     wpData.point3d = mNavigationMesh->PointLocalToScene(Dali::Vector3(wpData.face->center));
307     wpData.point2d = Vector2::ZERO;
308   }
309
310   return optimizedWaypoints;
311 }
312 } // namespace Dali::Scene3D::Internal::Algorithm