]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/route.cpp
Don't crash if a train has no router
[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                 const TrackType::Endpoint &ep = lowest.track.endpoint();
87                 for(unsigned i=0; ep.paths>>i; ++i)
88                         if(ep.has_path(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 Route::Route(Layout &l):
132         TrackChain(l),
133         temporary(false)
134 {
135         layout.add(*this);
136 }
137
138 Route::~Route()
139 {
140         layout.remove(*this);
141 }
142
143 void Route::set_temporary(bool t)
144 {
145         temporary = t;
146 }
147
148 void Route::update_turnouts()
149 {
150         set<unsigned> found;
151         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
152                 if((*i)->get_type().is_turnout())
153                 {
154                         found.insert((*i)->get_turnout_address());
155                         update_turnout(**i);
156                 }
157
158         // Remove any turnouts that do not exist in the route
159         for(map<unsigned, int>::iterator i=turnouts.begin(); i!=turnouts.end();)
160         {
161                 if(!found.count(i->first))
162                         turnouts.erase(i++);
163                 else
164                         ++i;
165         }
166 }
167
168 void Route::update_turnout(Track &track)
169 {
170         if(!track.get_type().is_turnout())
171                 return;
172
173         // Build a combined path mask from linked endpoints
174         unsigned nls = track.get_n_link_slots();
175         unsigned mask = track.get_type().get_paths();
176         for(unsigned i=0; i<nls; ++i)
177         {
178                 Track *link = track.get_link(i);
179                 if(!tracks.count(link))
180                         continue;
181
182                 unsigned ep_mask = track.get_type().get_endpoint(i).paths;
183                 if(link->get_type().is_turnout())
184                 {
185                         const TrackType::Endpoint &link_ep = link->get_type().get_endpoint(link->get_link_slot(track));
186                         int p = get_turnout(link->get_turnout_address());
187                         if(p>=0 && !link_ep.has_path(p))
188                                 // The linked track is a turnout and has a path which is incompatible with this endpoint
189                                 ep_mask = ~ep_mask;
190                 }
191
192                 mask &= ep_mask;
193         }
194
195         unsigned taddr = track.get_turnout_address();
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[taddr] = path;
202         }
203         else if(!turnouts.count(taddr))
204                 // More than one possible choice, and no existing entry - set as undecided
205                 turnouts[taddr] = -1;
206 }
207
208 int Route::get_turnout(unsigned id) const
209 {
210         map<unsigned, int>::const_iterator i = turnouts.find(id);
211         if(i!=turnouts.end())
212                 return i->second;
213         return -1;
214 }
215
216 unsigned Route::get_path(Track &trk) const
217 {
218         if(trk.get_type().is_turnout())
219         {
220                 map<unsigned, int>::const_iterator i = turnouts.find(trk.get_turnout_address());
221                 if(i!=turnouts.end() && i->second>=0)
222                         return i->second;
223         }
224         return trk.get_active_path();
225 }
226
227 void Route::add_turnout(Track &track, unsigned path)
228 {
229         TrackSet tracks_to_add;
230         tracks_to_add.insert(&track);
231         unsigned nls = track.get_n_link_slots();
232         for(unsigned i=0; i<nls; ++i)
233                 if(track.get_type().get_endpoint(i).has_path(path))
234                 {
235                         TrackIter iter = TrackIter(&track, i).flip();
236                         for(; (iter && !iter->get_type().is_turnout()); iter=iter.next())
237                                 tracks_to_add.insert(&*iter);
238                 }
239
240         add_tracks(tracks_to_add);
241 }
242
243 void Route::on_track_added(Track &track)
244 {
245         update_turnout(track);
246         unsigned nls = track.get_n_link_slots();
247         for(unsigned i=0; i<nls; ++i)
248                 if(Track *link = track.get_link(i))
249                         if(tracks.count(link))
250                                 update_turnout(*link);
251 }
252
253 void Route::save(list<DataFile::Statement> &st) const
254 {
255         st.push_back((DataFile::Statement("name"), name));
256         for(map<unsigned, int>::const_iterator i=turnouts.begin(); i!=turnouts.end(); ++i)
257                 st.push_back((DataFile::Statement("turnout"), i->first, i->second));
258 }
259
260 DataFile::Statement Route::save_reference() const
261 {
262         return (DataFile::Statement("route"), name);
263 }
264
265 Route *Route::find(const TrackIter &from, Track &to)
266 {
267         return create_route(from, TrackMatch(to));
268 }
269
270 Route *Route::find(const TrackIter &from, const Route &to)
271 {
272         return create_route(from, TrackInSet(to.get_tracks()));
273 }
274
275 Route *Route::find(const TrackIter &from, const Zone &to)
276 {
277         return create_route(from, TrackInSet(to.get_tracks()));
278 }
279
280 Route *Route::find(const TrackIter &from, const set<Track *> &to)
281 {
282         return create_route(from, TrackInSet(to));
283 }
284
285
286 Route::Loader::Loader(Route &r):
287         DataFile::ObjectLoader<Route>(r)
288 {
289         add("name",    &Loader::name);
290         add("turnout", &Loader::turnout);
291 }
292
293 void Route::Loader::finish()
294 {
295         const set<Track *> &ltracks = obj.layout.get_all<Track>();
296         map<Track *, unsigned> turnout_tracks;
297         for(set<Track *>::const_iterator i=ltracks.begin(); i!=ltracks.end(); ++i)
298                 if((*i)->get_type().is_turnout())
299                 {
300                         TurnoutMap::iterator j = turnouts.find((*i)->get_turnout_address());
301                         if(j!=turnouts.end())
302                                 turnout_tracks[*i] = j->second;
303                 }
304
305         for(map<Track *, unsigned>::iterator i=turnout_tracks.begin(); i!=turnout_tracks.end(); )
306         {
307                 if(obj.check_validity(*i->first)==VALID)
308                 {
309                         obj.add_turnout(*i->first, i->second);
310                         turnout_tracks.erase(i);
311                         i = turnout_tracks.begin();
312                 }
313                 else
314                         ++i;
315         }
316 }
317
318 void Route::Loader::name(const string &n)
319 {
320         obj.name = n;
321 }
322
323 void Route::Loader::turnout(unsigned id, unsigned path)
324 {
325         turnouts[id] = path;
326 }
327
328 } // namespace R2C2