-
Notifications
You must be signed in to change notification settings - Fork 16
/
pathfinding.hpp
250 lines (200 loc) · 7.13 KB
/
pathfinding.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
#pragma once
#include <vector>
#include <numeric>
#include <algorithm>
#include <functional>
class Pathfinder
{
public:
using NodeId = uint32_t;
using Cost = float;
//The pathfinder is a general algorithm that can be used for mutliple purpose
//So it use adaptor
class PathfinderAdaptor
{
public:
friend Pathfinder;
virtual size_t getNodeCount() const = 0;
virtual Cost distance(const NodeId n1, const NodeId n2) const = 0;
virtual bool lineOfSight(const NodeId n1, const NodeId n2) const = 0;
virtual std::vector<std::pair<NodeId, Cost>> getNodeNeighbors(const NodeId id) const = 0;
};
static constexpr const float EPSILON = 0.00001f;
static constexpr Cost INFINITE_COST = std::numeric_limits<Cost>::max();
enum ListType {NO_LIST, OPEN_LIST, CLOSED_LIST};
struct Node
{
std::vector<std::pair<NodeId, Cost>> neighbors;
uint32_t searchIndex = 0; //The last search at which it has bean generated, bassicacly used to decide if the node need to be reseted before we use it
NodeId parent; // Parent of the node.
Cost g; // Initialized to infinity when generated.
Cost h; // Initialized to the heuristic distance to the goal when generated.
ListType list; // Initially NO_LIST, can be changed to OPEN_LIST or CLOSED_LIST.
};
struct HeapElement
{
NodeId id;
Cost g; // Used for tie-breaking
Cost f; // Main key
//inverted so that the smaller is at the end of the vector
bool operator<(const HeapElement& rhs) const
{
if(abs(f - rhs.f) < EPSILON)
// return g > rhs.g;
return g < rhs.g;
// return f < rhs.f;
return f > rhs.f;
}
};
Pathfinder(PathfinderAdaptor& adaptor, Cost weight = 1.0f) : adaptor(adaptor), weight(weight)
{
generateNodes();
}
template<typename DataType>
std::vector<DataType> search(const DataType& start, const DataType& end, std::function<DataType(const NodeId)> idToData, std::function<NodeId(const DataType&)> dataToId)
{
const auto path = search(dataToId(start), dataToId(end));
std::vector<DataType> finalPath;
finalPath.reserve(path.size());
for(const auto id : path)
finalPath.push_back(idToData(id));
return finalPath;
}
std::vector<NodeId> search(const NodeId startId, const NodeId endId)
{
openList.clear();
currentSearch++;
generateState(startId, endId);
generateState(endId, endId);
nodes[startId].g = 0;
nodes[startId].parent = startId;
addToOpen(startId);
while(!openList.empty() && nodes[endId].g > getMin().f + EPSILON)
{
NodeId currId = getMin().id;
popMin();
// Lazy Theta* assumes that there is always line-of-sight from the parent of an expanded state to a successor state.
// When expanding a state, check if this is true.
if(!adaptor.lineOfSight(nodes[currId].parent, currId))
{
// Since the previous parent is invalid, set g-value to infinity.
nodes[currId].g = INFINITE_COST;
// Go over potential parents and update its parent to the parent that yields the lowest g-value for s.
for(const auto neighbordInfo : nodes[currId].neighbors)
{
auto newParent = neighbordInfo.first;
generateState(newParent, endId);
if(nodes[newParent].list == CLOSED_LIST)
{
Cost newG = nodes[newParent].g + neighbordInfo.second;
if(newG < nodes[currId].g)
{
nodes[currId].g = newG;
nodes[currId].parent = newParent;
}
}
}
}
for(const auto neighborInfo : nodes[currId].neighbors)
{
auto neighborId = neighborInfo.first;
generateState(neighborId, endId);
NodeId newParent = nodes[currId].parent;
if(nodes[neighborId].list != CLOSED_LIST)
{
Cost newG = nodes[newParent].g + adaptor.distance(newParent, neighborId);
if(newG + EPSILON < nodes[neighborId].g)
{
nodes[neighborId].g = newG;
nodes[neighborId].parent = newParent;
addToOpen(neighborId);
}
}
}
}
std::vector<NodeId> path;
if(nodes[endId].g < INFINITE_COST)
{
// ValidateParent(endId, endId);
NodeId curr = endId;
while(curr != startId)
{
path.push_back(curr);
curr = nodes[curr].parent;
}
path.push_back(curr);
std::reverse(path.begin(), path.end());
}
return path;
}
void generateNodes()
{
nodes.clear();
nodes.resize(adaptor.getNodeCount());
NodeId current = 0;
for(auto& node : nodes)
node.neighbors = adaptor.getNodeNeighbors(current++);
}
private:
std::vector<Node> nodes;
std::vector<HeapElement> openList;
PathfinderAdaptor& adaptor;
const Cost weight;
uint32_t currentSearch = 0;
void generateState(NodeId s, NodeId goal)
{
if(nodes[s].searchIndex != currentSearch)
{
nodes[s].searchIndex = currentSearch;
nodes[s].h = adaptor.distance(s, goal) * weight;
nodes[s].g = INFINITE_COST;
nodes[s].list = NO_LIST;
}
}
void addToOpen(NodeId id)
{
// If it is already in the open list, remove it and do a sorted insert
if (nodes[id].list == OPEN_LIST)
{
auto index = std::find_if(openList.begin(), openList.end(), [&](const auto& heap){return heap.id == id;});
auto id = index->id;
openList.erase(index);
insert_sorted(openList, {id, nodes[id].g, nodes[id].g + nodes[id].h});
}
// Otherwise, add it to the open list
else
{
nodes[id].list = OPEN_LIST;
insert_sorted(openList, {id, nodes[id].g, nodes[id].g + nodes[id].h});
}
}
const HeapElement getMin() const
{
return openList.back();
}
void popMin()
{
nodes[openList.back().id].list = CLOSED_LIST;
openList.pop_back();
}
template< typename T >
typename std::vector<T>::iterator
insert_sorted( std::vector<T> & vec, T const& item )
{
return vec.insert
(
std::upper_bound( vec.begin(), vec.end(), item ),
item
);
}
template< typename T, typename Pred >
typename std::vector<T>::iterator
insert_sorted( std::vector<T> & vec, T const& item, Pred pred )
{
return vec.insert
(
std::upper_bound( vec.begin(), vec.end(), item, pred ),
item
);
}
};