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