]> git.tdb.fi Git - r2c2.git/blobdiff - source/libmarklin/train.cpp
Add Block::has_track and Route::has_track methods
[r2c2.git] / source / libmarklin / train.cpp
index c53f30f66e6de0f05cca61da9b24f20486579e13..5bc50d85ff23ee5011535e34e5e6142f6b08fccc 100644 (file)
@@ -14,7 +14,7 @@ Distributed under the GPL
 #include "driver.h"
 #include "layout.h"
 #include "route.h"
-#include "simplephysics.h"
+#include "simplecontroller.h"
 #include "timetable.h"
 #include "tracktype.h"
 #include "train.h"
@@ -24,6 +24,19 @@ Distributed under the GPL
 using namespace std;
 using namespace Msp;
 
+namespace {
+
+struct SetFlag
+{
+       bool &flag;
+
+       SetFlag(bool &f): flag(f) { flag = true; }
+       ~SetFlag() { flag = false; }
+};
+
+}
+
+
 namespace Marklin {
 
 Train::Train(Layout &l, const VehicleType &t, unsigned a):
@@ -31,16 +44,17 @@ Train::Train(Layout &l, const VehicleType &t, unsigned a):
        loco_type(t),
        address(a),
        priority(0),
+       yielding_to(0),
        pending_block(0),
-       control(new AIControl(*this, new SimplePhysics)),
+       reserving(false),
+       advancing(false),
+       controller(new AIControl(*this, new SimpleController)),
        timetable(0),
        active(false),
        current_speed(0),
        speed_changing(false),
        reverse(false),
        functions(0),
-       route(0),
-       next_route(0),
        end_of_route(false),
        status("Unplaced"),
        travel_dist(0),
@@ -66,12 +80,12 @@ Train::Train(Layout &l, const VehicleType &t, unsigned a):
 
        layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
 
-       control->signal_control_changed.connect(signal_control_changed);
+       controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
 }
 
 Train::~Train()
 {
-       delete control;
+       delete controller;
        delete timetable;
        for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
                delete *i;
@@ -90,6 +104,11 @@ void Train::set_priority(int p)
        priority = p;
 }
 
+void Train::yield_to(const Train &t)
+{
+       yielding_to = &t;
+}
+
 void Train::add_vehicle(const VehicleType &vt)
 {
        Vehicle *veh = new Vehicle(layout, vt);
@@ -130,14 +149,14 @@ const Vehicle &Train::get_vehicle(unsigned i) const
 
 void Train::set_control(const string &n, float v)
 {
-       control->set_control(n, v);
+       controller->set_control(n, v);
 }
 
 void Train::set_active(bool a)
 {
        if(a==active)
                return;
-       if(!a && control->get_speed())
+       if(!a && controller->get_speed())
                throw InvalidState("Can't deactivate while moving");
 
        active = a;
@@ -163,6 +182,16 @@ void Train::set_function(unsigned func, bool state)
                layout.get_driver().set_loco_function(address+1, func-4, state);
 }
 
+float Train::get_control(const string &ctrl) const
+{
+       return controller->get_control(ctrl).value;
+}
+
+float Train::get_speed() const
+{
+       return controller->get_speed();
+}
+
 bool Train::get_function(unsigned func) const
 {
        return (functions>>func)&1;
@@ -176,66 +205,184 @@ void Train::set_timetable(Timetable *tt)
 
 void Train::set_route(const Route *r)
 {
-       if(!rsv_blocks.empty())
-       {
-               for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
-                       if(i->block->get_sensor_id())
-                       {
-                               release_blocks(rsv_blocks, ++i, rsv_blocks.end());
-                               break;
-                       }
-       }
+       free_noncritical_blocks();
 
-       route = r;
-       next_route = 0;
+       routes.clear();
+       if(r)
+               routes.push_back(r);
        end_of_route = false;
 
-       if(route)
+       if(r && !cur_blocks.empty())
        {
+               BlockRef &first = cur_blocks.front();
                BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
                BlockRef next = last.next();
-               const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
-               if(!route->get_tracks().count(ep.track))
+               const Block::Endpoint &first_ep = first.block->get_endpoints()[first.entry];
+               const Block::Endpoint &next_ep = next.block->get_endpoints()[next.entry];
+               if(!r->has_track(*next_ep.track))
                {
-                       next_route = route;
-                       route = Route::find(*ep.track, ep.track_ep, *next_route);
+                       Route *lead = Route::find(*next_ep.track, next_ep.track_ep, *r);
+                       create_lead_route(lead, lead);
+                       routes.push_front(lead);
                }
+               else if(!r->has_track(*first_ep.track))
+                       routes.push_front(create_lead_route(0, r));
        }
 
        reserve_more();
 
-       signal_route_changed.emit(route);
+       signal_route_changed.emit(get_route());
 }
 
-void Train::go_to(const Track &to)
+void Train::go_to(Track &to)
 {
        for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
-               if(i->block->get_tracks().count(const_cast<Track *>(&to)))
+               if(i->block->has_track(to))
                {
                        signal_arrived.emit();
                        set_route(0);
                        return;
                }
 
-       BlockRef *last = 0;
-       if(rsv_blocks.empty())
-               last = &cur_blocks.back();
+       free_noncritical_blocks();
+
+       BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
+       BlockRef next = last.next();
+       const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
+
+       Route *route = Route::find(*ep.track, ep.track_ep, to);
+       create_lead_route(route, route);
+       set_route(route);
+}
+
+bool Train::divert(Track &from)
+{
+       if(!from.get_turnout_id())
+               throw InvalidParameterValue("Can't divert from a non-turnout");
+       if(routes.empty())
+               return false;
+
+       int path = -1;
+       unsigned from_ep = 0;
+       list<RouteRef>::iterator route = routes.begin();
+       Block *block = cur_blocks.back().block;
+       unsigned entry = cur_blocks.back().entry;
+       set<const Track *> visited;
+
+       // Follow our routes to find out where we're entering the turnout
+       while(1)
+       {
+               Block *link = block->get_link(block->traverse(entry, route->route));
+               entry = link->get_endpoint_by_link(*block);
+               block = link;
+
+               const Block::Endpoint &entry_ep = block->get_endpoints()[entry];
+
+               if(visited.count(entry_ep.track))
+                       return false;
+               visited.insert(entry_ep.track);
+
+               if(!advance_route(route, *entry_ep.track))
+                       return false;
+
+               if(entry_ep.track==&from)
+               {
+                       if(block->get_train()==this && !free_block(*block))
+                               return false;
+
+                       from_ep = entry_ep.track_ep;
+                       path = route->route->get_turnout(from.get_turnout_id());
+                       break;
+               }
+       }
+
+       // Check that more than one path is available
+       unsigned ep_paths = from.get_type().get_endpoints()[from_ep].paths;
+       if(!(ep_paths&(ep_paths-1)))
+               return false;
+
+       // Choose some other path
+       for(int i=0; ep_paths>>i; ++i)
+               if((ep_paths&(1<<i)) && i!=path)
+               {
+                       path = i;
+                       break;
+               }
+
+       Track *track = from.get_link(from.traverse(from_ep, path));
+       if(!track)
+               return false;
+
+       unsigned ep = track->get_endpoint_by_link(from);
+
+       set<Track *> tracks;
+       for(list<RouteRef>::iterator i=routes.begin(); i!=routes.end(); ++i)
+               tracks.insert(i->route->get_tracks().begin(), i->route->get_tracks().end());
+       Route *diversion = 0;
+       try
+       {
+               diversion = Route::find(*track, ep, tracks);
+       }
+       catch(const Msp::Exception &)
+       {
+               return false;
+       }
+
+       diversion->set_name("Diversion");
+       diversion->add_track(from);
+       diversion->set_turnout(from.get_turnout_id(), path);
+
+       if(!is_valid_diversion(*diversion, from, from_ep))
+       {
+               delete diversion;
+               return false;
+       }
+
+       // Follow the diversion route until we get back to the original route
+       list<RouteRef>::iterator end = routes.end();
+       while(1)
+       {
+               path = 0;
+               if(track->get_turnout_id())
+                       path = diversion->get_turnout(track->get_turnout_id());
+               Track *next = track->get_link(track->traverse(ep, path));
+
+               for(list<RouteRef>::iterator i=route; (end==routes.end() && i!=routes.end()); ++i)
+                       if(i->route->has_track(*next))
+                               end = i;
+
+               if(end!=routes.end())
+                       break;
+               else if(!diversion->has_track(*next))
+                       throw Exception("Pathfinder returned a bad route");
+
+               ep = next->get_endpoint_by_link(*track);
+               track = next;
+       }
+
+       if(route==end)
+               // We are rejoining the same route we diverted from, duplicate it
+               routes.insert(end, *route);
        else
        {
-               for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
-                       if(i->block->get_sensor_id())
-                               last = &*i;
+               ++route;
+               routes.erase(route, end);
        }
+       routes.insert(end, RouteRef(diversion, from.get_turnout_id()));
 
-       BlockRef next = last->next();
-       const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
+       return true;
+}
 
-       set_route(Route::find(*ep.track, ep.track_ep, to));
+const Route *Train::get_route() const
+{
+       if(routes.empty())
+               return 0;
+       return routes.front().route;
 }
 
 void Train::place(Block &block, unsigned entry)
 {
-       if(control->get_speed())
+       if(controller->get_speed())
                throw InvalidState("Must be stopped before placing");
 
        release_blocks(rsv_blocks);
@@ -257,17 +404,38 @@ void Train::place(Block &block, unsigned entry)
                const Block::Endpoint &bep = block.get_endpoints()[exit];
                Track *track = bep.track->get_link(bep.track_ep);
                unsigned ep = track->get_endpoint_by_link(*bep.track);
-               vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
+               vehicles.front()->place(*track, ep, 0, Vehicle::FRONT_BUFFER);
        }
        else
        {
                const Block::Endpoint &bep = block.get_endpoints()[entry];
-               vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
+               vehicles.back()->place(*bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
        }
 }
 
+void Train::unplace()
+{
+       if(controller->get_speed())
+               throw InvalidState("Must be stopped before unplacing");
+
+       release_blocks(rsv_blocks);
+       release_blocks(cur_blocks);
+
+       set_active(false);
+       accurate_position = false;
+
+       for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
+               (*i)->unplace();
+
+       set_status("Unplaced");
+}
+
 bool Train::free_block(Block &block)
 {
+       float margin = 10*layout.get_catalogue().get_scale();
+       if(get_reserved_distance_until(&block, false)<controller->get_braking_distance()*1.3+margin)
+               return false;
+
        unsigned nsens = 0;
        for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
        {
@@ -285,64 +453,91 @@ bool Train::free_block(Block &block)
        return false;
 }
 
-int Train::get_entry_to_block(Block &block) const
+void Train::free_noncritical_blocks()
 {
-       for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
-               if(i->block==&block)
-                       return i->entry;
-       for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
-               if(i->block==&block)
-                       return i->entry;
-       return -1;
-}
+       if(cur_blocks.empty() || rsv_blocks.empty())
+               return;
+
+       if(controller->get_speed()==0)
+       {
+               release_blocks(rsv_blocks);
+               return;
+       }
+
+       float margin = 10*layout.get_catalogue().get_scale();
+       float min_dist = controller->get_braking_distance()*1.3+margin;
 
-float Train::get_reserved_distance() const
-{
        Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
-       const VehicleType &vtype = veh.get_type();
 
        Track *track = veh.get_track();
-       if(!track)
-               return 0;
-       unsigned entry = veh.get_entry();
+       list<BlockRef>::iterator block = cur_blocks.begin();
+       bool in_rsv = false;
+       while(block!=rsv_blocks.end() && !block->block->has_track(*track))
+       {
+               ++block;
+               if(block==cur_blocks.end())
+               {
+                       block = rsv_blocks.begin();
+                       in_rsv = true;
+               }
+       }
 
-       float result = -vtype.get_length()/2;
+       unsigned entry = veh.get_entry();
+       float dist = veh.get_offset();
        if(reverse)
-       {
                entry = track->traverse(entry);
-               result += veh.get_offset();
-       }
        else
-               result -= veh.get_offset();
+               dist = track->get_type().get_path_length(track->get_active_path())-dist;
+       dist -= veh.get_type().get_length()/2;
 
-       bool first = true;
-       list<BlockRef>::const_iterator block = cur_blocks.begin();
+       bool nsens = 0;
        while(1)
        {
-               if(!first || !reverse)
-                       result += track->get_type().get_path_length(track->get_active_path());
-               first = false;
-
-               if(track->get_type().get_endpoints().size()<2)
-                       return result;
-
-               unsigned exit = track->traverse(entry);
-               Track *next = track->get_link(exit);
+               Track *next = track->get_link(track->traverse(entry));
+               entry = next->get_endpoint_by_link(*track);
+               track = next;
 
-               while(!block->block->get_tracks().count(next))
+               if(!block->block->has_track(*track))
                {
                        ++block;
                        if(block==cur_blocks.end())
+                       {
                                block = rsv_blocks.begin();
+                               in_rsv = true;
+                       }
                        if(block==rsv_blocks.end())
-                               return result;
+                               return;
+
+                       if(dist>min_dist && nsens>0)
+                       {
+                               release_blocks(rsv_blocks, block, rsv_blocks.end());
+                               return;
+                       }
+
+                       if(in_rsv && block->block->get_sensor_id())
+                               ++nsens;
                }
 
-               entry = next->get_endpoint_by_link(*track);
-               track = next;
+               dist += track->get_type().get_path_length(track->get_active_path());
        }
 }
 
+int Train::get_entry_to_block(Block &block) const
+{
+       for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
+               if(i->block==&block)
+                       return i->entry;
+       for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
+               if(i->block==&block)
+                       return i->entry;
+       return -1;
+}
+
+float Train::get_reserved_distance() const
+{
+       return get_reserved_distance_until(0, false);
+}
+
 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
 {
        if(!active && stop_timeout && t>=stop_timeout)
@@ -356,13 +551,13 @@ void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
 
        if(timetable)
                timetable->tick(t);
-       control->tick(dt);
-       float speed = control->get_speed();
-       unsigned speed_notch = find_speed(abs(speed));
+       controller->tick(dt);
+       float speed = controller->get_speed();
+       unsigned speed_notch = find_speed(speed);
 
-       if(control->get_reverse()!=reverse)
+       if(controller->get_reverse()!=reverse)
        {
-               reverse = control->get_reverse();
+               reverse = controller->get_reverse();
                driver.set_loco_reverse(address, reverse);
 
                release_blocks(rsv_blocks);
@@ -393,11 +588,14 @@ void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
 
                bool ok = false;
                for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
-                       ok = i->block->get_tracks().count(track);
+                       ok = i->block->has_track(*track);
 
                float d = get_real_speed(current_speed)*(dt/Time::sec);
                if(ok)
+               {
+                       SetFlag setf(advancing);
                        vehicle.advance(reverse ? -d : d);
+               }
                else if(accurate_position)
                {
                        overshoot_dist += d;
@@ -408,52 +606,21 @@ void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
                        }
                }
        }
-       else if(end_of_route)
+       else if(end_of_route && rsv_blocks.empty())
+       {
+               set_active(false);
+               signal_arrived.emit();
                set_route(0);
+       }
 
        if(!cur_blocks.empty() && !cur_blocks.front().block->get_sensor_id())
        {
-               Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
-
-               list<BlockRef>::iterator i = cur_blocks.begin();
-               const Block::Endpoint &bep = i->block->get_endpoints()[i->entry];
-
-               Track *track = bep.track;
-               unsigned entry = bep.track_ep;
-
-               bool found = false;
-               float dist = veh.get_offset()-veh.get_type().get_length()/2;
-               while(1)
-               {
-                       if(track==veh.get_track())
-                       {
-                               found = true;
-                               break;
-                       }
-
-                       if(i!=cur_blocks.begin())
-                       {
-                               float path_len = track->get_type().get_path_length(track->get_active_path());
-                               dist += path_len;
-                       }
-
-                       unsigned exit = track->traverse(entry);
-                       Track *next = track->get_link(exit);
-                       entry = next->get_endpoint_by_link(*track);
-                       track = next;
-
-                       if(!i->block->get_tracks().count(track))
-                       {
-                               ++i;
-                               if(i==cur_blocks.end())
-                                       break;
-                       }
-               }
+               float dist = get_reserved_distance_until(cur_blocks.front().block, true);
 
-               if(found && i!=cur_blocks.begin() && dist>10*layout.get_catalogue().get_scale())
+               if(dist>10*layout.get_catalogue().get_scale())
                {
                        cur_blocks.front().block->reserve(0);
-                       cur_blocks.erase(cur_blocks.begin());
+                       cur_blocks.pop_front();
                }
        }
 }
@@ -485,12 +652,12 @@ void Train::save(list<DataFile::Statement> &st) const
                        st.push_back((DataFile::Statement("block"), i->block->get_id()));
        }
 
-       if(route)
+       if(!routes.empty())
        {
-               if(!route->is_temporary())
-                       st.push_back((DataFile::Statement("route"), route->get_name()));
-               else if(next_route && !next_route->is_temporary())
-                       st.push_back((DataFile::Statement("route"), next_route->get_name()));
+               list<RouteRef>::const_iterator i = routes.begin();
+               for(; (i!=routes.end() && i->route->is_temporary()); ++i) ;
+               if(i!=routes.end())
+                       st.push_back((DataFile::Statement("route"), i->route->get_name()));
        }
 
        if(timetable)
@@ -501,6 +668,11 @@ void Train::save(list<DataFile::Statement> &st) const
        }
 }
 
+void Train::control_changed(const Controller::Control &ctrl)
+{
+       signal_control_changed.emit(ctrl.name, ctrl.value);
+}
+
 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
 {
        if(addr==address)
@@ -571,17 +743,17 @@ void Train::sensor_event(unsigned addr, bool state)
                                j->block->traverse(j->entry, &block_len);
                                travel_dist += block_len;
 
-                               if(j->block->get_sensor_id()==addr)
+                               if(j->block->get_sensor_id()==addr && !advancing)
                                {
                                        const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
                                        if(reverse)
                                        {
                                                Track *track = bep.track->get_link(bep.track_ep);
                                                unsigned ep = track->get_endpoint_by_link(*bep.track);
-                                               vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
+                                               vehicles.back()->place(*track, ep, 0, Vehicle::BACK_AXLE);
                                        }
                                        else
-                                               vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
+                                               vehicles.front()->place(*bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
                                }
                        }
                        last_entry_time = Time::now();
@@ -590,16 +762,15 @@ void Train::sensor_event(unsigned addr, bool state)
                        overshoot_dist = 0;
 
                        // Check if we've reached the next route
-                       if(next_route)
+                       if(routes.size()>1)
                        {
-                               const set<const Track *> &rtracks = next_route->get_tracks();
+                               const set<Track *> &rtracks = (++routes.begin())->route->get_tracks();
                                for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
                                        if(rtracks.count(j->block->get_endpoints()[j->entry].track))
                                        {
-                                               route = next_route;
-                                               next_route = 0;
+                                               routes.pop_front();
                                                // XXX Exceptions?
-                                               signal_route_changed.emit(route);
+                                               signal_route_changed.emit(routes.front().route);
                                                break;
                                        }
                        }
@@ -609,20 +780,21 @@ void Train::sensor_event(unsigned addr, bool state)
 
                        // Try to get more blocks if we're moving
                        if(active)
-                       {
-                               unsigned nsens = reserve_more();
-                               if(!nsens && end_of_route)
-                                       signal_arrived.emit();
-                       }
+                               reserve_more();
                }
                else if(result==3)
                        layout.emergency("Sensor for "+name+" triggered out of order");
        }
        else
        {
+               const Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
+
                // Find the first sensor in our current blocks that's still active
                list<BlockRef>::iterator end = cur_blocks.begin();
                for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
+               {
+                       if(i->block->has_track(*veh.get_track()))
+                               break;
                        if(i->block->get_sensor_id())
                        {
                                if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
@@ -633,8 +805,9 @@ void Train::sensor_event(unsigned addr, bool state)
                                        ++end;
                                }
                        }
+               }
                
-               if(end!=cur_blocks.begin())
+               if(end!=cur_blocks.begin() && end!=cur_blocks.end())
                        // Free blocks up to the last inactive sensor
                        release_blocks(cur_blocks, cur_blocks.begin(), end);
        }
@@ -642,12 +815,17 @@ void Train::sensor_event(unsigned addr, bool state)
 
 void Train::turnout_event(unsigned addr, bool)
 {
-       if(pending_block)
+       if(pending_block && (!pending_block->get_train() || pending_block->get_train()==this))
        {
                unsigned pending_addr = pending_block->get_turnout_id();
                bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
                if(addr==pending_addr || (double_addr && addr==pending_addr+1))
-                       reserve_more();
+               {
+                       if(reserving)
+                               pending_block = 0;
+                       else
+                               reserve_more();
+               }
        }
 }
 
@@ -659,7 +837,7 @@ void Train::halt_event(bool h)
 
 void Train::block_reserved(const Block &block, const Train *train)
 {
-       if(&block==pending_block && !train)
+       if(&block==pending_block && !train && !reserving)
                reserve_more();
 }
 
@@ -668,46 +846,61 @@ unsigned Train::reserve_more()
        if(!active)
                return 0;
 
-       BlockRef *last = 0;
+       BlockRef *start = 0;
        if(!rsv_blocks.empty())
-               last = &rsv_blocks.back();
+               start = &rsv_blocks.back();
        else if(!cur_blocks.empty())
-               last = &cur_blocks.back();
-       if(!last)
+               start = &cur_blocks.back();
+       if(!start)
                return 0;
 
        pending_block = 0;
 
-       // See how many sensor blocks we already have
+       // See how many sensor blocks and how much track we already have
        unsigned nsens = 0;
+       float dist = 0;
        for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
+       {
                if(i->block->get_sensor_id())
                        ++nsens;
+               if(nsens>0)
+               {
+                       float length = 0;
+                       i->block->traverse(i->entry, &length);
+                       dist += length;
+               }
+       }
        
        if(end_of_route)
                return nsens;
 
-       const Route *cur_route = 0;
-       if(route)
-       {
-               const set<Track *> &tracks = last->block->get_tracks();
-               for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
-               {
-                       if(route->get_tracks().count(*i))
-                               cur_route = route;
-                       else if(next_route && next_route->get_tracks().count(*i))
-                               cur_route = next_route;
-               }
-       }
+       list<RouteRef>::iterator cur_route = routes.begin();
+       advance_route(cur_route, *start->block->get_endpoints()[start->entry].track);
 
-       bool got_more = false;
-       BlockRef *good = last;
+       float approach_margin = 50*layout.get_catalogue().get_scale();
+       float min_dist = controller->get_braking_distance()*1.3+approach_margin*2;
+
+       BlockRef *last = start;
+       BlockRef *good = start;
+       Track *divert_track = 0;
+       bool try_divert = false;
        unsigned good_sens = nsens;
-       while(good_sens<3)
+       float good_dist = dist;
+       Train *blocking_train = 0;
+       std::list<BlockRef> contested_blocks;
+
+       SetFlag setf(reserving);
+
+       while(good_sens<3 || good_dist<min_dist || !contested_blocks.empty())
        {
                // Traverse to the next block
-               unsigned exit = last->block->traverse(last->entry);
-               Block *link = last->block->get_link(exit);
+               float length = 0;
+               Block *link = 0;
+               {
+                       const Route *route = (cur_route!=routes.end() ? cur_route->route : 0);
+                       unsigned exit = last->block->traverse(last->entry, route, &length);
+                       link = last->block->get_link(exit);
+               }
                if(!link)
                        break;
 
@@ -717,48 +910,114 @@ unsigned Train::reserve_more()
 
                const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
 
-               if(cur_route)
+               if(cur_route!=routes.end())
                {
-                       if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
-                               cur_route = next_route;
-                       else if(!cur_route->get_tracks().count(entry_ep.track))
+                       if(!advance_route(cur_route, *entry_ep.track))
                        {
                                // Keep the blocks if we arrived at the end of the route
-                               good = last;
-                               good_sens = nsens;
-                               end_of_route = true;
+                               if(!blocking_train)
+                               {
+                                       good = last;
+                                       good_sens = nsens;
+                                       good_dist = dist;
+                                       end_of_route = true;
+                               }
                                break;
                        }
                }
-               else if(route && route->get_tracks().count(entry_ep.track))
-                       cur_route = route;
+               else if(!routes.empty() && routes.front().route->has_track(*entry_ep.track))
+                       cur_route = routes.begin();
 
                if(link->get_endpoints().size()<2)
                {
-                       good = last;
-                       good_sens = nsens;
+                       if(!blocking_train)
+                       {
+                               good = last;
+                               good_sens = nsens;
+                               good_dist = dist;
+                       }
                        break;
                }
 
+               if(blocking_train)
+               {
+                       if(link->get_train()!=blocking_train)
+                       {
+                               if(blocking_train->free_block(*contested_blocks.back().block))
+                               {
+                                       // Roll back and start actually reserving the blocks
+                                       last = &rsv_blocks.back();
+                                       cur_route = routes.begin();
+                                       advance_route(cur_route, *last->block->get_endpoints()[last->entry].track);
+                                       if(blocking_train->get_priority()==priority)
+                                               blocking_train->yield_to(*this);
+                                       blocking_train = 0;
+                                       continue;
+                               }
+                               else
+                               {
+                                       yield_to(*blocking_train);
+                                       pending_block = contested_blocks.front().block;
+                                       try_divert = divert_track;
+                                       break;
+                               }
+                       }
+                       else
+                       {
+                               contested_blocks.push_back(BlockRef(link, entry));
+                               last = &contested_blocks.back();
+                               continue;
+                       }
+               }
+
                bool reserved = link->reserve(this);
                if(!reserved)
                {
-                       // Ask a lesser priority train to free the block for us
-                       if(link->get_train()->get_priority()<priority)
-                               if(link->get_train()->free_block(*link))
+                       /* We've found another train.  If it wants to exit the block from the
+                       same endpoint we're trying to enter from or the other way around,
+                       treat it as coming towards us.  Otherwise treat it as going in the
+                       same direction. */
+                       Train *other_train = link->get_train();
+                       int other_entry = other_train->get_entry_to_block(*link);
+                       if(other_entry<0)
+                               throw LogicError("Block reservation inconsistency");
+
+                       bool entry_conflict = (static_cast<unsigned>(entry)==link->traverse(other_entry));
+                       bool exit_conflict = (link->traverse(entry)==static_cast<unsigned>(other_entry));
+                       if(!entry_conflict && !last->block->get_turnout_id())
+                       {
+                               /* The other train is not coming to the blocks we're holding, so we
+                               can keep them. */
+                               good = last;
+                               good_sens = nsens;
+                               good_dist = dist;
+                       }
+
+                       int other_prio = other_train->get_priority();
+
+                       if(!entry_conflict && !exit_conflict && other_prio<priority)
+                       {
+                               /* Ask a lesser priority train going to the same direction to free
+                               the block for us */
+                               if(other_train->free_block(*link))
                                        reserved = link->reserve(this);
+                       }
+                       else if(other_train!=yielding_to && (other_prio<priority || (other_prio==priority && entry_conflict)))
+                       {
+                               /* A lesser priority train is coming at us, we must ask it to free
+                               enough blocks to get clear of it to avoid a potential deadlock */
+                               blocking_train = other_train;
+                               contested_blocks.clear();
+                               contested_blocks.push_back(BlockRef(link, entry));
+                               last = &contested_blocks.back();
+                               continue;
+                       }
+                       else if(divert_track && (entry_conflict || exit_conflict))
+                               // We are blocked, but there's a diversion possibility
+                               try_divert = true;
 
                        if(!reserved)
                        {
-                               // If we found another train and it's not headed straight for us, we can keep the blocks we got
-                               int other_entry = link->get_train()->get_entry_to_block(*link);
-                               if(other_entry<0)
-                                       throw LogicError("Block reservation inconsistency");
-                               if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
-                               {
-                                       good = last;
-                                       good_sens = nsens;
-                               }
                                pending_block = link;
                                break;
                        }
@@ -767,61 +1026,156 @@ unsigned Train::reserve_more()
                if(link->get_turnout_id())
                {
                        const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
+                       bool multiple_paths = (track_ep.paths&(track_ep.paths-1));
 
-                       // Keep the blocks reserved so far, as either us or the other train can diverge
-                       good = last;
-                       good_sens = nsens;
+                       if(multiple_paths || !last->block->get_turnout_id())
+                       {
+                               /* We can keep the blocks reserved so far if we are facing the
+                               points or if there was no turnout immediately before this one.
+                               With multiple successive turnouts (as is common in crossovers) it's
+                               best to hold at one we can divert from. */
+                               good = last;
+                               good_sens = nsens;
+                               good_dist = dist;
+                       }
 
                        // Figure out what path we'd like to take on the turnout
                        int path = -1;
-                       if(cur_route)
-                               path = cur_route->get_turnout(link->get_turnout_id());
+                       for(list<RouteRef>::iterator i=cur_route; (path<0 && i!=routes.end()); ++i)
+                               path = i->route->get_turnout(link->get_turnout_id());
                        if(path<0)
                                path = entry_ep.track->get_active_path();
-                       if(!((track_ep.paths>>path)&1))
+                       if(!(track_ep.paths&(1<<path)))
                        {
                                for(unsigned i=0; track_ep.paths>>i; ++i)
-                                       if((track_ep.paths>>i)&1)
+                                       if(track_ep.paths&(1<<i))
                                                path = i;
                        }
 
                        if(path!=static_cast<int>(entry_ep.track->get_active_path()))
                        {
                                // The turnout is set to wrong path - switch and wait for it
-                               link->reserve(0);
                                pending_block = link;
                                entry_ep.track->set_active_path(path);
-                               break;
+                               if(pending_block)
+                               {
+                                       link->reserve(0);
+                                       break;
+                               }
                        }
+
+                       if(multiple_paths && cur_route!=routes.end() && cur_route->diversion!=link->get_turnout_id())
+                               /* There's multiple paths to be taken and we are on a route - take
+                               note of the diversion possibility */
+                               divert_track = entry_ep.track;
                }
 
+               if(!contested_blocks.empty() && contested_blocks.front().block==link)
+                       contested_blocks.pop_front();
+
                rsv_blocks.push_back(BlockRef(link, entry));
                last = &rsv_blocks.back();
                if(last->block->get_sensor_id())
-               {
                        ++nsens;
-                       got_more = true;
-               }
+               if(nsens>0)
+                       dist += length;
        }
 
        // Unreserve blocks that were not good
-       while(!rsv_blocks.empty() && last!=good)
+       while(!rsv_blocks.empty() && &rsv_blocks.back()!=good)
        {
-               last->block->reserve(0);
-               rsv_blocks.erase(--rsv_blocks.end());
-               if(!rsv_blocks.empty())
-                       last = &rsv_blocks.back();
+               rsv_blocks.back().block->reserve(0);
+               rsv_blocks.pop_back();
        }
 
+       if(!rsv_blocks.empty() && &rsv_blocks.back()!=start)
+               // We got some new blocks, so no longer need to yield
+               yielding_to = 0;
+
        // Make any sensorless blocks at the beginning immediately current
        list<BlockRef>::iterator i;
        for(i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !i->block->get_sensor_id()); ++i) ;
        if(i!=rsv_blocks.begin())
                cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
 
+       if(try_divert && divert(*divert_track))
+               return reserve_more();
+
        return good_sens;
 }
 
+float Train::get_reserved_distance_until(const Block *until_block, bool back) const
+{
+       if(cur_blocks.empty())
+               return 0;
+
+       Vehicle &veh = *(reverse!=back ? vehicles.back() : vehicles.front());
+       const VehicleType &vtype = veh.get_type();
+
+       Track *track = veh.get_track();
+       if(!track)
+               return 0;
+
+       list<BlockRef>::const_iterator block = cur_blocks.begin();
+       while(block!=rsv_blocks.end() && !block->block->has_track(*track))
+       {
+               ++block;
+               if(block==cur_blocks.end())
+               {
+                       if(back)
+                               return 0;
+                       block = rsv_blocks.begin();
+               }
+       }
+       if(block==rsv_blocks.end() || block->block==until_block)
+               return 0;
+
+       unsigned entry = veh.get_entry();
+
+       float result = veh.get_offset();
+       if(reverse!=back)
+               entry = track->traverse(entry);
+       else
+               result = track->get_type().get_path_length(track->get_active_path())-result;
+       result -= vtype.get_length()/2;
+
+       while(1)
+       {
+               if(track->get_type().get_endpoints().size()<2)
+                       break;
+
+               Track *next = track->get_link(track->traverse(entry));
+
+               if(!block->block->has_track(*next))
+               {
+                       if(back)
+                       {
+                               if(block==cur_blocks.begin())
+                                       break;
+                               --block;
+                       }
+                       else
+                       {
+                               ++block;
+                               if(block==cur_blocks.end())
+                                       block = rsv_blocks.begin();
+                               if(block==rsv_blocks.end())
+                                       break;
+                       }
+
+                       if(block->block==until_block)
+                               break;
+               }
+
+               entry = next->get_endpoint_by_link(*track);
+               track = next;
+
+               result += track->get_type().get_path_length(track->get_active_path());
+       }
+
+       return result;
+}
+
 float Train::get_real_speed(unsigned i) const
 {
        if(real_speed[i].weight)
@@ -859,9 +1213,11 @@ unsigned Train::find_speed(float real) const
 
        unsigned low = 0;
        unsigned high = 0;
+       unsigned last = 0;
        for(unsigned i=0; (!high && i<=14); ++i)
                if(real_speed[i].weight)
                {
+                       last = i;
                        if(real_speed[i].speed<real)
                                low = i;
                        else
@@ -876,7 +1232,7 @@ unsigned Train::find_speed(float real) const
                        else
                                return 0;
                }
-               return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
+               return min(min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U), last+3);
        }
 
        float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
@@ -918,6 +1274,100 @@ void Train::reverse_blocks(list<BlockRef> &blocks) const
                i->entry = i->block->traverse(i->entry);
 }
 
+bool Train::advance_route(list<RouteRef>::iterator &iter, Track &track)
+{
+       while(iter!=routes.end() && !iter->route->has_track(track))
+               ++iter;
+       if(iter==routes.end())
+               return false;
+
+       list<RouteRef>::iterator next = iter;
+       ++next;
+       if(next!=routes.end() && next->diversion && next->route->has_track(track))
+               iter = next;
+
+       return true;
+}
+
+Route *Train::create_lead_route(Route *lead, const Route *target)
+{
+       if(!lead)
+       {
+               lead = new Route(layout);
+               lead->set_name("Lead");
+               lead->set_temporary(true);
+       }
+
+       set<Track *> tracks;
+       for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=rsv_blocks.end(); )
+       {
+               const set<Track *> &btracks = i->block->get_tracks();
+               for(set<Track *>::const_iterator j=btracks.begin(); j!=btracks.end(); ++j)
+                       if(!target || !target->has_track(**j))
+                               tracks.insert(*j);
+
+               if(++i==cur_blocks.end())
+                       i = rsv_blocks.begin();
+       }
+
+       lead->add_tracks(tracks);
+
+       return lead;
+}
+
+bool Train::is_valid_diversion(const Route &diversion, Track &from, unsigned from_ep)
+{
+       float diversion_len = 0;
+       Track *track = &from;
+       unsigned ep = from_ep;
+       while(diversion.has_track(*track))
+       {
+               unsigned path = 0;
+               if(track->get_turnout_id())
+                       path = diversion.get_turnout(track->get_turnout_id());
+               diversion_len += track->get_type().get_path_length(path);
+
+               Track *next = track->get_link(track->traverse(ep, path));
+               ep = next->get_endpoint_by_link(*track);
+               track = next;
+
+               if(track==&from)
+                       return false;
+       }
+
+       list<RouteRef>::iterator route = routes.begin();
+       if(!advance_route(route, from))
+               return false;
+
+       set<Track *> visited;
+       float route_len = 0;
+       track = &from;
+       ep = from_ep;
+       while(1)
+       {
+               unsigned path = 0;
+               if(track->get_turnout_id())
+                       path = route->route->get_turnout(track->get_turnout_id());
+               route_len += track->get_type().get_path_length(path);
+
+               if(track!=&from && diversion.has_track(*track))
+                       break;
+
+               if(visited.count(track))
+                       return false;
+               visited.insert(track);
+
+               Track *next = track->get_link(track->traverse(ep, path));
+               ep = next->get_endpoint_by_link(*track);
+               track = next;
+
+               if(!advance_route(route, *track))
+                       return false;
+       }
+
+       return diversion_len<route_len*1.2;
+}
+
 
 Train::BlockRef::BlockRef(Block *b, unsigned e):
        block(b),
@@ -938,6 +1388,12 @@ Train::BlockRef Train::BlockRef::next() const
 }
 
 
+Train::RouteRef::RouteRef(const Route *r, unsigned d):
+       route(r),
+       diversion(d)
+{ }
+
+
 Train::RealSpeed::RealSpeed():
        speed(0),
        weight(0)
@@ -971,7 +1427,8 @@ void Train::Loader::finish()
        {
                const BlockRef &blkref = obj.cur_blocks.front();
                const Block::Endpoint &bep = blkref.block->get_endpoints()[blkref.entry];
-               obj.vehicles.back()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
+               float offset = 2*obj.layout.get_catalogue().get_scale();
+               obj.vehicles.back()->place(*bep.track, bep.track_ep, offset, Vehicle::BACK_BUFFER);
 
                obj.set_status("Stopped");
        }