]> git.tdb.fi Git - r2c2.git/blobdiff - source/libmarklin/route.cpp
Fix pathfinder to not block itself in some situations
[r2c2.git] / source / libmarklin / route.cpp
index 98943985db147044acc4fa9b4aee06e9f2fde8d3..ace8d0b950812c56a22e23a0ba381f4d389b9f7b 100644 (file)
@@ -1,7 +1,347 @@
+/* $Id$
+
+This file is part of the MSP Märklin suite
+Copyright © 2007-2010  Mikkosoft Productions, Mikko Rasa
+Distributed under the GPL
+*/
+
+#include <queue>
+#include <msp/strings/formatter.h>
+#include "layout.h"
 #include "route.h"
+#include "track.h"
+#include "tracktype.h"
+
+using namespace std;
+using namespace Msp;
+
+namespace {
+
+using namespace Marklin;
+
+typedef std::pair<const Track *, unsigned> Key;
+
+struct Node
+{
+       const Track *track;
+       unsigned ep;
+       Node *prev;
+       float dist;
+
+       Node():
+               track(0), ep(0), prev(0), dist(0)
+       { }
+
+       Node(const Track &t, unsigned e):
+               track(&t), ep(e), prev(0), dist(0)
+       { }
+
+       Node(const Track &t, unsigned e, Node &r, float d):
+               track(&t), ep(e), prev(&r), dist(prev->dist+d)
+       { }
+
+       bool operator<(const Node &other) const
+       { return dist>other.dist; }
+};
+
+struct TrackMatch
+{
+       const Track &track;
+
+       TrackMatch(const Track &t): track(t) { }
+
+       bool operator()(const Track &t) const { return &t==&track; }
+};
+
+struct TrackInRoute
+{
+       const Route &route;
+
+       TrackInRoute(const Route &r): route(r) { }
+
+       bool operator()(const Track &t) const { return route.get_tracks().count(&t); }
+};
+
+template<typename Pred>
+list<const Track *> dijkstra(const Track &from, unsigned ep, const Pred &goal)
+{
+       map<Key, Node> track_nodes;
+       priority_queue<Node> nodes;
+       Node *final = 0;
+
+       nodes.push(Node(from, ep));
+
+       while(!nodes.empty())
+       {
+               Node lowest = nodes.top();
+               nodes.pop();
+
+               Key key(lowest.track, lowest.ep);
+               if(track_nodes.count(key))
+                       continue;
+
+               Node &ref = track_nodes[key] = lowest;
+               if(goal(*lowest.track))
+               {
+                       final = &ref;
+                       break;
+               }
+
+               const TrackType &type = lowest.track->get_type();
+               const vector<Endpoint> &eps = type.get_endpoints();
+               const vector<Track *> &links = lowest.track->get_links();
+               for(unsigned i=0; i<eps.size(); ++i)
+               {
+                       if(i==lowest.ep || !links[i])
+                               continue;
+
+                       unsigned link_ep = links[i]->get_endpoint_by_link(*lowest.track);
+                       if(track_nodes.count(Key(links[i], link_ep)))
+                               continue;
+
+                       unsigned mask = eps[i].paths&eps[lowest.ep].paths;
+                       if(!mask)
+                               continue;
+
+                       unsigned path=0;
+                       for(; !(mask&1); ++path, mask>>=1) ;
+                       nodes.push(Node(*links[i], links[i]->get_endpoint_by_link(*lowest.track), ref, type.get_path_length(path)));
+               }
+       }
+
+       if(!final)
+               throw InvalidParameterValue("Could not find a route");
+
+       list<const Track *> result;
+       for(Node *node=final; node; node=node->prev)
+               result.push_front(node->track);
+
+       return result;
+}
+
+unsigned count = 0;
+
+template<typename Pred>
+Route *create_route(const Track &from, unsigned ep, const Pred &goal)
+{
+       list<const Track *> tracks = dijkstra(from, ep, goal);
+
+       Route *route = new Route(from.get_layout(), format("-%d-", ++count));
+       for(list<const Track *>::iterator i=tracks.begin(); i!=tracks.end(); ++i)
+               route->add_track(**i);
+
+       return route;
+}
+
+}
+
 
 namespace Marklin {
 
+Route::Route(Layout &l, const string &n):
+       layout(l),
+       name(n)
+{
+       layout.add_route(*this);
+       layout.signal_track_removed.connect(sigc::mem_fun(this, &Route::track_removed));
+}
+
+Route::~Route()
+{
+       layout.remove_route(*this);
+}
+
+int Route::get_turnout(unsigned id) const
+{
+       map<unsigned, int>::const_iterator i = turnouts.find(id);
+       if(i!=turnouts.end())
+               return i->second;
+       return -1;
+}
+
+void Route::add_track(const Track &trk)
+{
+       if(tracks.count(&trk))
+               return;
+
+       if(!tracks.empty())
+       {
+               unsigned valid = check_validity(trk);
+               if(!(valid&1))
+                       throw Exception("Not linked to existing tracks");
+               else if(!(valid&2))
+                       throw Exception("Branching routes not allowed");
+               else if(!(valid&4))
+                       throw Exception("Route must be smooth");
+       }
+
+       tracks.insert(&trk);
+       update_turnouts();
+}
+
+void Route::add_tracks(const set<const Track *> &trks)
+{
+       set<const Track *> pending;
+       for(set<const Track *>::const_iterator i=trks.begin(); i!=trks.end(); ++i)
+               if(!tracks.count(*i))
+                       pending.insert(*i);
+
+       while(!pending.empty())
+       {
+               bool found = false;
+               for(set<const Track *>::const_iterator i=pending.begin(); i!=pending.end(); ++i)
+                       if(tracks.empty() || check_validity(**i)==7)
+                       {
+                               tracks.insert(*i);
+                               pending.erase(*i);
+                               found = true;
+                               break;
+                       }
+
+               if(!found)
+                       throw Exception("Could not add all tracks to route");
+       }
+
+       update_turnouts();
+}
+
+void Route::save(list<DataFile::Statement> &st) const
+{
+       for(map<unsigned, int>::const_iterator i=turnouts.begin(); i!=turnouts.end(); ++i)
+               st.push_back((DataFile::Statement("turnout"), i->first, i->second));
+}
+
+void Route::update_turnouts()
+{
+       set<unsigned> found;
+       for(set<const Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
+               if(unsigned tid=(*i)->get_turnout_id())
+               {
+                       found.insert(tid);
+
+                       const vector<Endpoint> &endpoints = (*i)->get_type().get_endpoints();
+                       const vector<Track *> &links = (*i)->get_links();
+
+                       // Build a combined path mask from linked endpoints
+                       unsigned mask = 15;
+                       for(unsigned j=0; j<endpoints.size(); ++j)
+                       {
+                               if(!tracks.count(links[j]))
+                                       continue;
+
+                               if(unsigned tid2=links[j]->get_turnout_id())
+                               {
+                                       const Endpoint &ep = links[j]->get_type().get_endpoints()[links[j]->get_endpoint_by_link(**i)];
+                                       int p = get_turnout(tid2);
+                                       if(p>=0 && !(ep.paths&(1<<p)))
+                                       {
+                                               // The linked track is a turnout and has a path which is incompatible with this endpoint
+                                               mask &= ~endpoints[j].paths;
+                                               continue;
+                                       }
+                               }
+                               mask &= endpoints[j].paths;
+                       }
+
+                       if(mask && !(mask&(mask-1)))
+                       {
+                               // Exactly one possible choice, set the path accordingly
+                               unsigned path = 0;
+                               for(; (mask && !(mask&1)); mask>>=1, ++path) ;
+                               turnouts[tid] = path;
+                       }
+                       else if(!turnouts.count(tid))
+                               // More than one possible choice, and no existing entry - set as undecided
+                               turnouts[tid] = -1;
+               }
+
+       // Remove any turnouts that do not exist in the route
+       for(map<unsigned, int>::iterator i=turnouts.begin(); i!=turnouts.end();)
+       {
+               if(!found.count(i->first))
+                       turnouts.erase(i++);
+               else
+                       ++i;
+       }
+}
+
+unsigned Route::check_validity(const Track &trk) const
+{
+       unsigned result = 4;
+       for(set<const Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
+       {
+               int epi=(*i)->get_endpoint_by_link(trk);
+               if(epi>=0)
+               {
+                       // Linked to an existing track - good
+                       result |= 1;
+                       const vector<Endpoint> &endpoints = (*i)->get_type().get_endpoints();
+                       if(unsigned tid=(*i)->get_turnout_id())
+                       {
+                               int r = get_turnout(tid);
+                               if(r>=0)
+                               {
+                                       // Linking to a turnout with path set is only good if we're continuing that path
+                                       if(endpoints[epi].paths&(1<<r))
+                                               result |= 2;
+                               }
+                               else
+                               {
+                                       // Linked to a turnout with no path set - find out other linked tracks 
+                                       unsigned count = 0;
+                                       const vector<Track *> &links = (*i)->get_links();
+                                       int epj = -1;
+                                       for(unsigned k=0; k<endpoints.size(); ++k)
+                                               if(tracks.count(links[k]))
+                                               {
+                                                       ++count;
+                                                       epj = k;
+                                               }
+
+                                       // Only good if at most one other track is linked to the turnout
+                                       if(count<=1)
+                                       {
+                                               result |= 2;
+                                               if(epj>=0 && !(endpoints[epi].paths&endpoints[epj].paths))
+                                                       // Impossible path through the turnout - not good
+                                                       result &= 3;
+                                       }
+                               }
+                       }
+                       else
+                               // Linked to something linear - good
+                               result |= 2;
+               }
+       }
+
+       return result;
+}
+
+void Route::track_removed(Track &t)
+{
+       tracks.erase(&t);
+}
+
+Route *Route::find(const Track &from, unsigned ep, const Track &to)
+{
+       return create_route(from, ep, TrackMatch(to));
+}
+
+Route *Route::find(const Track &from, unsigned ep, const Route &to)
+{
+       return create_route(from, ep, TrackInRoute(to));
+}
+
+
+Route::Loader::Loader(Route &r):
+       DataFile::BasicLoader<Route>(r)
+{
+       add("turnout", &Loader::turnout);
+}
 
+void Route::Loader::turnout(unsigned id, unsigned path)
+{
+       obj.turnouts[id] = path;
+}
 
 } // namespace Marklin