]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/route.cpp
Make use of the unified storage class for other parts of Layout
[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_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 invalid_argument("Route::set_turnout");
158         int &state = get_item(turnouts, addr);
159         if(state>=0 && path!=static_cast<unsigned>(state))
160                 throw logic_error("route conflict");
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_link_slot(**i));
185                                         int p = get_turnout(tid2);
186                                         if(p>=0 && !ep.has_path(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_chain(const TrackIter &start, const TurnoutMap &trnts)
238 {
239         if(!start)
240                 throw invalid_argument("Route::add_track_chain");
241
242         TrackIter iter = start;
243         while(iter)
244         {
245                 if(iter->get_type().is_dead_end())
246                         break;
247
248                 if(has_track(*iter))
249                         break;
250
251                 int path = 0;
252                 if(iter->get_turnout_id())
253                 {
254                         TurnoutMap::const_iterator i = trnts.find(iter->get_turnout_id());
255                         if(i==trnts.end())
256                                 break;
257
258                         path = i->second;
259                 }
260
261                 add_track(*iter);
262
263                 iter = iter.next(path);
264         }
265 }
266
267 void Route::on_track_added(Track &)
268 {
269         update_turnouts();
270 }
271
272 void Route::save(list<DataFile::Statement> &st) const
273 {
274         st.push_back((DataFile::Statement("name"), name));
275         for(map<unsigned, int>::const_iterator i=turnouts.begin(); i!=turnouts.end(); ++i)
276                 st.push_back((DataFile::Statement("turnout"), i->first, i->second));
277 }
278
279 Route *Route::find(const TrackIter &from, Track &to)
280 {
281         return create_route(from, TrackMatch(to));
282 }
283
284 Route *Route::find(const TrackIter &from, const Route &to)
285 {
286         return create_route(from, TrackInSet(to.get_tracks()));
287 }
288
289 Route *Route::find(const TrackIter &from, const Zone &to)
290 {
291         return create_route(from, TrackInSet(to.get_tracks()));
292 }
293
294 Route *Route::find(const TrackIter &from, const set<Track *> &to)
295 {
296         return create_route(from, TrackInSet(to));
297 }
298
299
300 Route::Loader::Loader(Route &r):
301         DataFile::ObjectLoader<Route>(r)
302 {
303         add("name",    &Route::name);
304         add("turnout", &Loader::turnout);
305 }
306
307 void Route::Loader::finish()
308 {
309         const set<Track *> &ltracks = obj.layout.get_all<Track>();
310         for(set<Track *>::const_iterator i=ltracks.begin(); i!=ltracks.end(); ++i)
311         {
312                 unsigned tid = (*i)->get_turnout_id();
313                 if(!tid)
314                         continue;
315
316                 TurnoutMap::iterator j = turnouts.find(tid);
317                 if(j==turnouts.end())
318                         continue;
319
320                 const vector<TrackType::Endpoint> &eps = (*i)->get_type().get_endpoints();
321                 for(unsigned k=0; k<eps.size(); ++k)
322                         if(eps[k].has_path(j->second))
323                         {
324                                 Track *link = (*i)->get_link(k);
325                                 if(!obj.tracks.count(link))
326                                         obj.add_track_chain(TrackIter(link, link->get_link_slot(**i)), turnouts);
327                                 if(!obj.tracks.count(*i))
328                                         obj.add_track_chain(TrackIter(*i, k), turnouts);
329                                 break;
330                         }
331
332                 break;
333         }
334 }
335
336 void Route::Loader::turnout(unsigned id, unsigned path)
337 {
338         turnouts[id] = path;
339 }
340
341 } // namespace R2C2