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