]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/route.cpp
aabe8807b71cd4b7d92927ca6427edce21f804d1
[r2c2.git] / source / libr2c2 / route.cpp
1 #include <queue>
2 #include <msp/core/maputils.h>
3 #include <msp/strings/format.h>
4 #include <msp/strings/utils.h>
5 #include "layout.h"
6 #include "route.h"
7 #include "track.h"
8 #include "trackiter.h"
9 #include "tracktype.h"
10 #include "zone.h"
11
12 using namespace std;
13 using namespace Msp;
14
15 namespace {
16
17 using namespace R2C2;
18
19 typedef std::pair<Track *, unsigned> Key;
20
21 struct Node
22 {
23         TrackIter track;
24         Node *prev;
25         float dist;
26
27         Node():
28                 prev(0), dist(0)
29         { }
30
31         Node(const TrackIter &t):
32                 track(t), prev(0), dist(0)
33         { }
34
35         Node(const TrackIter &t, Node &r, float d):
36                 track(t), prev(&r), dist(prev->dist+d)
37         { }
38
39         bool operator<(const Node &other) const
40         { return dist>other.dist; }
41 };
42
43 struct TrackMatch
44 {
45         Track &track;
46
47         TrackMatch(Track &t): track(t) { }
48
49         bool operator()(Track &t) const { return &t==&track; }
50 };
51
52 struct TrackInSet
53 {
54         const set<Track *> &tracks;
55
56         TrackInSet(const set<Track *> &t): tracks(t) { }
57
58         bool operator()(Track &t) const { return tracks.count(&t); }
59 };
60
61 template<typename Pred>
62 list<Track *> dijkstra(const TrackIter &from, const Pred &goal)
63 {
64         map<Key, Node> track_nodes;
65         priority_queue<Node> nodes;
66         Node *final = 0;
67
68         nodes.push(from);
69
70         while(!nodes.empty())
71         {
72                 Node lowest = nodes.top();
73                 nodes.pop();
74
75                 Key key(lowest.track.track(), lowest.track.entry());
76                 if(track_nodes.count(key))
77                         continue;
78
79                 Node &ref = track_nodes[key] = lowest;
80                 if(goal(*lowest.track))
81                 {
82                         final = &ref;
83                         break;
84                 }
85
86                 unsigned paths = lowest.track.endpoint().paths;
87                 for(unsigned i=0; paths>>i; ++i)
88                         if(paths&(1<<i))
89                         {
90                                 TrackIter next = lowest.track.next(i);
91                                 if(!next)
92                                         continue;
93
94                                 if(track_nodes.count(Key(next.track(), next.entry())))
95                                         continue;
96
97                                 nodes.push(Node(next, ref, lowest.track->get_type().get_path_length(i)));
98                         }
99         }
100
101         list<Track *> result;
102         for(Node *node=final; node; node=node->prev)
103                 result.push_front(&*node->track);
104
105         return result;
106 }
107
108 template<typename Pred>
109 Route *create_route(const TrackIter &from, const Pred &goal)
110 {
111         list<Track *> tracks = dijkstra(from, goal);
112
113         if(tracks.empty())
114                 return 0;
115
116         Route *route = new Route(from->get_layout());
117         for(list<Track *>::iterator i=tracks.begin(); i!=tracks.end(); ++i)
118                 route->add_track(**i);
119
120         route->set_name("Pathfinder");
121         route->set_temporary(true);
122
123         return route;
124 }
125
126 }
127
128
129 namespace R2C2 {
130
131 string bad_route::get_message(RouteValidityMask valid)
132 {
133         const char *reasons[3];
134         unsigned i = 0;
135         if(!(valid&1))
136                 reasons[i++] = "unlinked";
137         else if(!(valid&2))
138                 reasons[i++] = "branching";
139         else if(!(valid&4))
140                 reasons[i++] = "not smooth";
141         return join(reasons, reasons+i, ", ");
142 }
143
144
145 Route::Route(Layout &l):
146         layout(l),
147         temporary(false)
148 {
149         layout.add_route(*this);
150         layout.signal_track_removed.connect(sigc::mem_fun(this, &Route::track_removed));
151 }
152
153 Route::~Route()
154 {
155         layout.remove_route(*this);
156 }
157
158 void Route::set_name(const string &n)
159 {
160         name = n;
161         signal_name_changed.emit(name);
162 }
163
164 void Route::set_temporary(bool t)
165 {
166         temporary = t;
167 }
168
169 void Route::set_turnout(unsigned addr, unsigned path)
170 {
171         if(!addr)
172                 throw InvalidParameterValue("Invalid turnout address");
173         int &state = get_item(turnouts, addr);
174         if(state>=0 && path!=static_cast<unsigned>(state))
175                 throw InvalidState("Setting conflicts with route");
176         state = path;
177 }
178
179 void Route::update_turnouts()
180 {
181         set<unsigned> found;
182         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
183                 if(unsigned tid = (*i)->get_turnout_id())
184                 {
185                         found.insert(tid);
186
187                         const vector<TrackType::Endpoint> &endpoints = (*i)->get_type().get_endpoints();
188                         const vector<Track *> &links = (*i)->get_links();
189
190                         // Build a combined path mask from linked endpoints
191                         unsigned mask = (*i)->get_type().get_paths();
192                         for(unsigned j=0; j<endpoints.size(); ++j)
193                         {
194                                 if(!tracks.count(links[j]))
195                                         continue;
196
197                                 if(unsigned tid2 = links[j]->get_turnout_id())
198                                 {
199                                         const TrackType::Endpoint &ep = links[j]->get_type().get_endpoint(links[j]->get_endpoint_by_link(**i));
200                                         int p = get_turnout(tid2);
201                                         if(p>=0 && !(ep.paths&(1<<p)))
202                                         {
203                                                 // The linked track is a turnout and has a path which is incompatible with this endpoint
204                                                 mask &= ~endpoints[j].paths;
205                                                 continue;
206                                         }
207                                 }
208                                 mask &= endpoints[j].paths;
209                         }
210
211                         if(mask && !(mask&(mask-1)))
212                         {
213                                 // Exactly one possible choice, set the path accordingly
214                                 unsigned path = 0;
215                                 for(; (mask && !(mask&1)); mask>>=1, ++path) ;
216                                 turnouts[tid] = path;
217                         }
218                         else if(!turnouts.count(tid))
219                                 // More than one possible choice, and no existing entry - set as undecided
220                                 turnouts[tid] = -1;
221                 }
222
223         // Remove any turnouts that do not exist in the route
224         for(map<unsigned, int>::iterator i=turnouts.begin(); i!=turnouts.end();)
225         {
226                 if(!found.count(i->first))
227                         turnouts.erase(i++);
228                 else
229                         ++i;
230         }
231 }
232
233 int Route::get_turnout(unsigned id) const
234 {
235         map<unsigned, int>::const_iterator i = turnouts.find(id);
236         if(i!=turnouts.end())
237                 return i->second;
238         return -1;
239 }
240
241 unsigned Route::get_path(Track &trk) const
242 {
243         if(unsigned tid = trk.get_turnout_id())
244         {
245                 map<unsigned, int>::const_iterator i = turnouts.find(tid);
246                 if(i!=turnouts.end())
247                         return i->second;
248         }
249         return trk.get_active_path();
250 }
251
252 void Route::add_track(Track &trk)
253 {
254         if(tracks.count(&trk))
255                 return;
256
257         if(!tracks.empty())
258         {
259                 RouteValidityMask valid = check_validity(trk);
260                 if(valid!=ROUTE_VALID)
261                         throw bad_route(valid);
262         }
263
264         tracks.insert(&trk);
265         update_turnouts();
266 }
267
268 void Route::add_tracks(const set<Track *> &trks)
269 {
270         set<Track *> pending;
271         for(set<Track *>::const_iterator i=trks.begin(); i!=trks.end(); ++i)
272                 if(!tracks.count(*i))
273                         pending.insert(*i);
274
275         while(!pending.empty())
276         {
277                 RouteValidityMask valid = ROUTE_INVALID;
278                 for(set<Track *>::const_iterator i=pending.begin(); i!=pending.end(); ++i)
279                         if(tracks.empty() || (valid=check_validity(**i))==ROUTE_VALID)
280                         {
281                                 tracks.insert(*i);
282                                 pending.erase(*i);
283                                 break;
284                         }
285
286                 if(valid!=ROUTE_VALID)
287                         throw bad_route(valid);
288         }
289
290         update_turnouts();
291 }
292
293 void Route::add_track_chain(Track &start, unsigned ep, const TurnoutMap &trnts)
294 {
295         TrackIter iter(&start, ep);
296         while(iter)
297         {
298                 if(iter->get_type().is_dead_end())
299                         break;
300
301                 if(has_track(*iter))
302                         break;
303
304                 int path = 0;
305                 if(iter->get_turnout_id())
306                 {
307                         TurnoutMap::const_iterator i = trnts.find(iter->get_turnout_id());
308                         if(i==trnts.end())
309                                 break;
310
311                         path = i->second;
312                 }
313
314                 add_track(*iter);
315
316                 iter = iter.next(path);
317         }
318 }
319
320 bool Route::has_track(Track &t) const
321 {
322         return tracks.count(&t);
323 }
324
325 void Route::save(list<DataFile::Statement> &st) const
326 {
327         st.push_back((DataFile::Statement("name"), name));
328         for(map<unsigned, int>::const_iterator i=turnouts.begin(); i!=turnouts.end(); ++i)
329                 st.push_back((DataFile::Statement("turnout"), i->first, i->second));
330 }
331
332 RouteValidityMask Route::check_validity(Track &trk) const
333 {
334         unsigned result = ROUTE_SMOOTH;
335         const vector<Track *> &links = trk.get_links();
336         for(vector<Track *>::const_iterator i=links.begin(); i!=links.end(); ++i)
337         {
338                 if(!*i)
339                         continue;
340                 if(!tracks.count(*i))
341                         continue;
342
343                 // Linked to an existing track - good
344                 result |= ROUTE_LINKED;
345
346                 if(unsigned tid = (*i)->get_turnout_id())
347                 {
348                         const TrackType::Endpoint &ep = (*i)->get_type().get_endpoint((*i)->get_endpoint_by_link(trk));
349                         int path = get_turnout(tid);
350                         if(path>=0)
351                         {
352                                 // Linking to a turnout with path set is only good if we're continuing that path
353                                 if(ep.paths&(1<<path))
354                                         result |= ROUTE_LINEAR;
355                         }
356                         else
357                         {
358                                 // Linked to a turnout with no path set - check other linked tracks 
359                                 const vector<Track *> &tlinks = (*i)->get_links();
360                                 unsigned count = 0;
361                                 for(unsigned j=0; j<tlinks.size(); ++j)
362                                         if(tracks.count(tlinks[j]))
363                                         {
364                                                 unsigned tid2 = tlinks[j]->get_turnout_id();
365                                                 if(tid2)
366                                                 {
367                                                         const TrackType::Endpoint &ep2 = tlinks[j]->get_type().get_endpoint(tlinks[j]->get_endpoint_by_link(**i));
368                                                         path = get_turnout(tid2);
369                                                         // Ignore a linked turnout with some other path set
370                                                         if(path>=0 && !(ep2.paths&(1<<path)))
371                                                                 continue;
372                                                 }
373
374                                                 ++count;
375
376                                                 const TrackType::Endpoint &ep2 = (*i)->get_type().get_endpoint(j);
377                                                 if(!(ep.paths&ep2.paths))
378                                                         // Impossible path through the turnout - not good
379                                                         result &= ~ROUTE_SMOOTH;
380                                         }
381
382                                 // Only good if at most one other track is linked to the turnout
383                                 if(count<=1)
384                                         result |= ROUTE_LINEAR;
385                         }
386                 }
387                 else
388                         // Linked to something linear - good
389                         result |= ROUTE_LINEAR;
390         }
391
392         return static_cast<RouteValidityMask>(result);
393 }
394
395 void Route::track_removed(Track &t)
396 {
397         tracks.erase(&t);
398 }
399
400 Route *Route::find(const TrackIter &from, Track &to)
401 {
402         return create_route(from, TrackMatch(to));
403 }
404
405 Route *Route::find(const TrackIter &from, const Route &to)
406 {
407         return create_route(from, TrackInSet(to.get_tracks()));
408 }
409
410 Route *Route::find(const TrackIter &from, const Zone &to)
411 {
412         return create_route(from, TrackInSet(to.get_tracks()));
413 }
414
415 Route *Route::find(const TrackIter &from, const set<Track *> &to)
416 {
417         return create_route(from, TrackInSet(to));
418 }
419
420
421 Route::Loader::Loader(Route &r):
422         DataFile::BasicLoader<Route>(r)
423 {
424         add("name",    &Route::name);
425         add("turnout", &Loader::turnout);
426 }
427
428 void Route::Loader::finish()
429 {
430         const set<Track *> &ltracks = obj.layout.get_tracks();
431         for(set<Track *>::const_iterator i=ltracks.begin(); i!=ltracks.end(); ++i)
432         {
433                 unsigned tid = (*i)->get_turnout_id();
434                 if(!tid)
435                         continue;
436
437                 TurnoutMap::iterator j = turnouts.find(tid);
438                 if(j==turnouts.end())
439                         continue;
440
441                 unsigned path_mask = 1<<j->second;
442                 const vector<TrackType::Endpoint> &eps = (*i)->get_type().get_endpoints();
443                 for(unsigned k=0; k<eps.size(); ++k)
444                         if(eps[k].paths&path_mask)
445                         {
446                                 Track *link = (*i)->get_link(k);
447                                 if(!obj.tracks.count(link))
448                                         obj.add_track_chain(*link, link->get_endpoint_by_link(**i), turnouts);
449                                 if(!obj.tracks.count(*i))
450                                         obj.add_track_chain(**i, k, turnouts);
451                                 break;
452                         }
453
454                 break;
455         }
456 }
457
458 void Route::Loader::turnout(unsigned id, unsigned path)
459 {
460         turnouts[id] = path;
461 }
462
463 } // namespace R2C2