3 This file is part of the MSP Märklin suite
4 Copyright © 2007-2010 Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
9 #include <msp/strings/formatter.h>
13 #include "trackiter.h"
14 #include "tracktype.h"
21 using namespace Marklin;
23 typedef std::pair<Track *, unsigned> Key;
35 Node(const TrackIter &t):
36 track(t), prev(0), dist(0)
39 Node(const TrackIter &t, Node &r, float d):
40 track(t), prev(&r), dist(prev->dist+d)
43 bool operator<(const Node &other) const
44 { return dist>other.dist; }
51 TrackMatch(Track &t): track(t) { }
53 bool operator()(Track &t) const { return &t==&track; }
58 const set<Track *> &tracks;
60 TrackInSet(const set<Track *> &t): tracks(t) { }
62 bool operator()(Track &t) const { return tracks.count(&t); }
65 template<typename Pred>
66 list<Track *> dijkstra(const TrackIter &from, const Pred &goal)
68 map<Key, Node> track_nodes;
69 priority_queue<Node> nodes;
76 Node lowest = nodes.top();
79 Key key(lowest.track.track(), lowest.track.entry());
80 if(track_nodes.count(key))
83 Node &ref = track_nodes[key] = lowest;
84 if(goal(*lowest.track))
90 unsigned paths = lowest.track->get_type().get_endpoints()[lowest.track.entry()].paths;
91 for(unsigned i=0; paths>>i; ++i)
94 TrackIter next = lowest.track.next(i);
98 if(track_nodes.count(Key(next.track(), next.entry())))
101 nodes.push(Node(next, ref, lowest.track->get_type().get_path_length(i)));
105 list<Track *> result;
106 for(Node *node=final; node; node=node->prev)
107 result.push_front(&*node->track);
112 template<typename Pred>
113 Route *create_route(const TrackIter &from, const Pred &goal)
115 list<Track *> tracks = dijkstra(from, goal);
120 Route *route = new Route(from->get_layout());
121 for(list<Track *>::iterator i=tracks.begin(); i!=tracks.end(); ++i)
122 route->add_track(**i);
124 route->set_name("Pathfinder");
125 route->set_temporary(true);
135 Route::Route(Layout &l):
139 layout.add_route(*this);
140 layout.signal_track_removed.connect(sigc::mem_fun(this, &Route::track_removed));
145 layout.remove_route(*this);
148 void Route::set_name(const string &n)
151 signal_name_changed.emit(name);
154 void Route::set_temporary(bool t)
159 void Route::set_turnout(unsigned addr, unsigned path)
162 throw InvalidParameterValue("Invalid turnout address");
163 map<unsigned, int>::iterator i = turnouts.find(addr);
164 if(i==turnouts.end())
165 throw KeyError("Turnout is not in this route");
166 if(i->second>=0 && path!=static_cast<unsigned>(i->second))
167 throw InvalidState("Setting conflicts with route");
171 void Route::update_turnouts()
174 for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
175 if(unsigned tid = (*i)->get_turnout_id())
179 const vector<TrackType::Endpoint> &endpoints = (*i)->get_type().get_endpoints();
180 const vector<Track *> &links = (*i)->get_links();
182 // Build a combined path mask from linked endpoints
184 for(unsigned j=0; j<endpoints.size(); ++j)
186 if(!tracks.count(links[j]))
189 if(unsigned tid2 = links[j]->get_turnout_id())
191 const TrackType::Endpoint &ep = links[j]->get_type().get_endpoints()[links[j]->get_endpoint_by_link(**i)];
192 int p = get_turnout(tid2);
193 if(p>=0 && !(ep.paths&(1<<p)))
195 // The linked track is a turnout and has a path which is incompatible with this endpoint
196 mask &= ~endpoints[j].paths;
200 mask &= endpoints[j].paths;
203 if(mask && !(mask&(mask-1)))
205 // Exactly one possible choice, set the path accordingly
207 for(; (mask && !(mask&1)); mask>>=1, ++path) ;
208 turnouts[tid] = path;
210 else if(!turnouts.count(tid))
211 // More than one possible choice, and no existing entry - set as undecided
215 // Remove any turnouts that do not exist in the route
216 for(map<unsigned, int>::iterator i=turnouts.begin(); i!=turnouts.end();)
218 if(!found.count(i->first))
225 int Route::get_turnout(unsigned id) const
227 map<unsigned, int>::const_iterator i = turnouts.find(id);
228 if(i!=turnouts.end())
233 unsigned Route::get_path(Track &trk) const
235 if(unsigned tid = trk.get_turnout_id())
237 map<unsigned, int>::const_iterator i = turnouts.find(tid);
238 if(i!=turnouts.end())
241 return trk.get_active_path();
244 void Route::add_track(Track &trk)
246 if(tracks.count(&trk))
251 unsigned valid = check_validity(trk);
253 throw Exception("Not linked to existing tracks");
255 throw Exception("Branching routes not allowed");
257 throw Exception("Route must be smooth");
264 void Route::add_tracks(const set<Track *> &trks)
266 set<Track *> pending;
267 for(set<Track *>::const_iterator i=trks.begin(); i!=trks.end(); ++i)
268 if(!tracks.count(*i))
271 while(!pending.empty())
274 for(set<Track *>::const_iterator i=pending.begin(); i!=pending.end(); ++i)
275 if(tracks.empty() || check_validity(**i)==7)
284 throw Exception("Could not add all tracks to route");
290 void Route::add_track_chain(Track &start, unsigned ep, const TurnoutMap &trnts)
292 TrackIter iter(&start, ep);
295 if(iter->get_type().is_dead_end())
302 if(iter->get_turnout_id())
304 TurnoutMap::const_iterator i = trnts.find(iter->get_turnout_id());
313 iter = iter.next(path);
317 bool Route::has_track(Track &t) const
319 return tracks.count(&t);
322 void Route::save(list<DataFile::Statement> &st) const
324 st.push_back((DataFile::Statement("name"), name));
325 for(map<unsigned, int>::const_iterator i=turnouts.begin(); i!=turnouts.end(); ++i)
326 st.push_back((DataFile::Statement("turnout"), i->first, i->second));
329 unsigned Route::check_validity(Track &trk) const
332 for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
334 int epi=(*i)->get_endpoint_by_link(trk);
337 // Linked to an existing track - good
339 const vector<TrackType::Endpoint> &endpoints = (*i)->get_type().get_endpoints();
340 if(unsigned tid=(*i)->get_turnout_id())
342 int r = get_turnout(tid);
345 // Linking to a turnout with path set is only good if we're continuing that path
346 if(endpoints[epi].paths&(1<<r))
351 // Linked to a turnout with no path set - find out other linked tracks
353 const vector<Track *> &links = (*i)->get_links();
355 for(unsigned k=0; k<endpoints.size(); ++k)
356 if(tracks.count(links[k]))
362 // Only good if at most one other track is linked to the turnout
366 if(epj>=0 && !(endpoints[epi].paths&endpoints[epj].paths))
367 // Impossible path through the turnout - not good
373 // Linked to something linear - good
381 void Route::track_removed(Track &t)
386 Route *Route::find(const TrackIter &from, Track &to)
388 return create_route(from, TrackMatch(to));
391 Route *Route::find(const TrackIter &from, const Route &to)
393 return create_route(from, TrackInSet(to.get_tracks()));
396 Route *Route::find(const TrackIter &from, const set<Track *> &to)
398 return create_route(from, TrackInSet(to));
402 Route::Loader::Loader(Route &r):
403 DataFile::BasicLoader<Route>(r)
405 add("name", &Route::name);
406 add("turnout", &Loader::turnout);
409 void Route::Loader::finish()
411 const set<Track *> <racks = obj.layout.get_tracks();
412 for(set<Track *>::const_iterator i=ltracks.begin(); i!=ltracks.end(); ++i)
414 unsigned tid = (*i)->get_turnout_id();
418 TurnoutMap::iterator j = turnouts.find(tid);
419 if(j==turnouts.end())
422 unsigned path_mask = 1<<j->second;
423 const vector<TrackType::Endpoint> &eps = (*i)->get_type().get_endpoints();
424 for(unsigned k=0; k<eps.size(); ++k)
425 if(eps[k].paths&path_mask)
427 Track *link = (*i)->get_link(k);
428 if(!obj.tracks.count(link))
429 obj.add_track_chain(*link, link->get_endpoint_by_link(**i), turnouts);
430 if(!obj.tracks.count(*i))
431 obj.add_track_chain(**i, k, turnouts);
439 void Route::Loader::turnout(unsigned id, unsigned path)
444 } // namespace Marklin