]> git.tdb.fi Git - r2c2.git/blobdiff - source/libr2c2/train.cpp
Fix critical block logic
[r2c2.git] / source / libr2c2 / train.cpp
index f43969d1949b0729eed8ba9132fb1bb37125d23f..b1fbc6a76ebb1bf4ad02f85d981f465fef1a1759 100644 (file)
@@ -1,40 +1,29 @@
 #include <algorithm>
 #include <cmath>
 #include <msp/core/maputils.h>
+#include <msp/core/raii.h>
 #include <msp/strings/format.h>
 #include <msp/time/units.h>
 #include <msp/time/utils.h>
-#include "aicontrol.h"
+#include "beamgate.h"
+#include "block.h"
 #include "catalogue.h"
 #include "driver.h"
 #include "layout.h"
-#include "route.h"
 #include "simplecontroller.h"
 #include "speedquantizer.h"
 #include "timetable.h"
+#include "trackcircuit.h"
 #include "trackiter.h"
 #include "tracktype.h"
 #include "train.h"
+#include "trainrouter.h"
 #include "vehicle.h"
 #include "vehicletype.h"
-#include "zone.h"
 
 using namespace std;
 using namespace Msp;
 
-namespace {
-
-struct SetFlag
-{
-       bool &flag;
-
-       SetFlag(bool &f): flag(f) { flag = true; }
-       ~SetFlag() { flag = false; }
-};
-
-}
-
-
 namespace R2C2 {
 
 Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
@@ -42,22 +31,14 @@ Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
        loco_type(t),
        address(a),
        protocol(p),
-       priority(0),
-       yielding_to(0),
        preceding_train(0),
-       cur_blocks_end(blocks.end()),
-       clear_blocks_end(blocks.end()),
-       pending_block(0),
-       reserving(false),
+       allocator(*this),
        advancing(false),
        controller(new SimpleController),
-       active(false),
        current_speed_step(0),
        speed_changing(false),
        reverse(false),
        functions(0),
-       end_of_route(false),
-       travel_dist(0),
        pure_speed(false),
        speed_quantizer(0),
        accurate_position(false),
@@ -71,24 +52,20 @@ Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
                speed_quantizer = new SpeedQuantizer(speed_steps);
 
        vehicles.push_back(new Vehicle(layout, loco_type));
+       vehicles.back()->set_train(this);
 
        layout.add_train(*this);
 
-       layout.get_driver().add_loco(address, protocol, loco_type);
+       loco_id = layout.get_driver().add_loco(address, protocol, loco_type);
        layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
        layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
 
-       layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
-       layout.signal_block_state_changed.connect(sigc::mem_fun(this, &Train::block_state_changed));
-
        layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
 
-       const set<Track *> &tracks = layout.get_tracks();
-       for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
-               if((*i)->get_turnout_id())
-                       (*i)->signal_path_changed.connect(sigc::hide(sigc::bind(sigc::mem_fun(this, &Train::turnout_path_changed), sigc::ref(**i))));
-
        controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
+
+       allocator.signal_advanced.connect(sigc::mem_fun(this, &Train::advanced));
+       allocator.signal_rear_advanced.connect(signal_rear_advanced);
 }
 
 Train::~Train()
@@ -106,21 +83,13 @@ void Train::set_name(const string &n)
        signal_name_changed.emit(name);
 }
 
-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);
        vehicles.back()->attach_back(*veh);
        vehicles.push_back(veh);
+       veh->set_train(this);
+       signal_vehicle_added.emit(vehicles.size()-1, *veh);
 }
 
 void Train::remove_vehicle(unsigned i)
@@ -129,10 +98,17 @@ void Train::remove_vehicle(unsigned i)
                throw out_of_range("Train::remove_vehicle");
        if(i==0)
                throw logic_error("can't remove locomotive");
-       delete vehicles[i];
+
+       Vehicle *veh = vehicles[i];
        vehicles.erase(vehicles.begin()+i);
+       veh->detach_front();
        if(i<vehicles.size())
+       {
+               veh->detach_back();
                vehicles[i-1]->attach_back(*vehicles[i]);
+       }
+       signal_vehicle_removed.emit(i, *veh);
+       delete veh;
 }
 
 unsigned Train::get_n_vehicles() const
@@ -159,28 +135,11 @@ void Train::set_control(const string &n, float v)
        controller->set_control(n, v);
 }
 
-void Train::set_active(bool a)
-{
-       if(a==active)
-               return;
-       if(!a && controller->get_speed())
-               throw logic_error("moving");
-
-       active = a;
-       if(active)
-       {
-               stop_timeout = Time::TimeStamp();
-               reserve_more();
-       }
-       else
-               stop_timeout = Time::now()+2*Time::sec;
-}
-
 void Train::set_function(unsigned func, bool state)
 {
        if(!loco_type.get_functions().count(func))
                throw invalid_argument("Train::set_function");
-       layout.get_driver().set_loco_function(address, func, state);
+       layout.get_driver().set_loco_function(loco_id, func, state);
 }
 
 float Train::get_control(const string &ctrl) const
@@ -201,6 +160,18 @@ float Train::get_quantized_speed() const
                return controller->get_speed();
 }
 
+float Train::get_maximum_speed() const
+{
+       float ms = 0;
+       for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
+       {
+               float vms = (*i)->get_type().get_maximum_speed();
+               if(ms<=0 || (vms>0 && vms<ms))
+                       ms = vms;
+       }
+       return ms;
+}
+
 bool Train::get_function(unsigned func) const
 {
        return (functions>>func)&1;
@@ -219,230 +190,34 @@ void Train::remove_ai(TrainAI &ai)
                ais.erase(i);
 }
 
-TrainAI *Train::get_tagged_ai(const string &tag) const
-{
-       for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
-               if((*i)->get_tag()==tag)
-                       return *i;
-
-       return 0;
-}
-
 void Train::ai_message(const TrainAI::Message &msg)
 {
        for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
                (*i)->message(msg);
 }
 
-bool Train::set_route(const Route *r)
-{
-       free_noncritical_blocks();
-
-       Route *lead = 0;
-       if(r && !blocks.empty())
-       {
-               TrackIter first = blocks.front().track_iter();
-               TrackIter next = blocks.back().next().track_iter();
-               if(!r->has_track(*next))
-               {
-                       lead = Route::find(next, *r);
-                       if(!lead)
-                               return false;
-                       create_lead_route(lead, lead);
-                       routes.push_front(lead);
-               }
-               else if(!r->has_track(*first))
-                       lead = create_lead_route(0, r);
-       }
-
-       routes.clear();
-       if(lead)
-               routes.push_back(lead);
-       if(r)
-               routes.push_back(r);
-       end_of_route = false;
-
-       reserve_more();
-
-       signal_route_changed.emit(get_route());
-
-       return true;
-}
-
-bool Train::go_to(Track &to)
-{
-       for(BlockList::const_iterator i=blocks.begin(); i!=cur_blocks_end; ++i)
-               if((*i)->has_track(to))
-               {
-                       signal_arrived.emit();
-                       return set_route(0);
-               }
-
-       free_noncritical_blocks();
-
-       TrackIter next = blocks.back().next().track_iter();
-
-       Route *route = Route::find(next, to);
-       if(!route)
-               return false;
-       create_lead_route(route, route);
-       return set_route(route);
-}
-
-bool Train::go_to(const Zone &to)
-{
-       set<Track *> tracks;
-       for(BlockList::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
-               tracks.insert((*i)->get_tracks().begin(), (*i)->get_tracks().end());
-
-       const Zone::TrackSet &ztracks = to.get_tracks();
-       unsigned union_size = 0;
-       for(Zone::TrackSet::const_iterator i=ztracks.begin(); i!=ztracks.end(); ++i)
-               union_size += tracks.count(*i);
-
-       if(union_size==tracks.size() || union_size==ztracks.size())
-       {
-               signal_arrived.emit();
-               return set_route(0);
-       }
-
-       free_noncritical_blocks();
-
-       TrackIter next = blocks.back().next().track_iter();
-
-       Route *route = Route::find(next, to);
-       if(!route)
-               return false;
-       create_lead_route(route, route);
-       route->add_tracks(ztracks);
-       return set_route(route);
-}
-
-bool Train::divert(Track &from)
-{
-       if(!from.get_turnout_id())
-               throw invalid_argument("Train::divert");
-       if(routes.empty())
-               return false;
-
-       unsigned path = 0;
-       unsigned entry = 0;
-       list<RouteRef>::iterator route = routes.begin();
-
-       // Follow our routes to find out where we're entering the turnout
-       for(TrackLoopIter track = blocks.front().track_iter();;)
-       {
-               if(!advance_route(route, *track))
-                       return false;
-
-               if(&*track==&from)
-               {
-                       Block &block = track->get_block();
-                       if(block.get_train()==this && !free_block(block))
-                               return false;
-
-                       int route_path = route->route->get_turnout(from.get_turnout_id());
-
-                       // Check that more than one path is available
-                       unsigned ep_paths = track.endpoint().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!=route_path)
-                               {
-                                       path = i;
-                                       break;
-                               }
-
-                       entry = track.entry();
-                       break;
-               }
-
-               track = track.next(route->route->get_path(*track));
-
-               if(!track || track.looped())
-                       return false;
-       }
-
-       TrackIter track = TrackIter(&from, entry).next(path);
-       if(!track)
-               return false;
-
-       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());
-       RefPtr<Route> diversion = Route::find(track, tracks);
-       if(!diversion)
-               return false;
-
-       diversion->set_name("Diversion");
-       diversion->add_track(from);
-       diversion->set_turnout(from.get_turnout_id(), path);
-
-       if(!is_valid_diversion(*diversion, TrackIter(&from, entry)))
-               return false;
-
-       // Follow the diversion route until we get back to the original route
-       list<RouteRef>::iterator end = routes.end();
-       while(1)
-       {
-               for(list<RouteRef>::iterator i=route; (end==routes.end() && i!=routes.end()); ++i)
-                       if(i->route->has_track(*track))
-                               end = i;
-
-               if(end!=routes.end())
-                       break;
-               else if(!diversion->has_track(*track))
-                       throw logic_error("bad diversion");
-
-               track = track.next(diversion->get_path(*track));
-       }
-
-       if(route==end)
-               // We are rejoining the same route we diverted from, duplicate it
-               routes.insert(end, *route);
-       else
-       {
-               ++route;
-               routes.erase(route, end);
-       }
-       routes.insert(end, RouteRef(diversion.release(), from.get_turnout_id()));
-
-       return true;
-}
-
-const Route *Train::get_route() const
-{
-       if(routes.empty())
-               return 0;
-       return routes.front().route;
-}
-
-void Train::place(Block &block, unsigned entry)
+bool Train::place(const BlockIter &block)
 {
+       if(!block)
+               throw invalid_argument("Train::place");
        if(controller->get_speed())
                throw logic_error("moving");
 
-       release_blocks();
-
-       set_active(false);
        accurate_position = false;
+       last_entry_block = BlockIter();
 
-       if(!block.reserve(this))
-               return;
-
-       blocks.push_back(BlockIter(&block, entry));
-       if(reverse)
+       if(allocator.start_from(block))
        {
-               TrackIter track = BlockIter(&block, entry).reverse().track_iter();
-               vehicles.front()->place(*track, track.entry(), 0, Vehicle::FRONT_BUFFER);
+               if(reverse)
+                       vehicles.front()->place(block.reverse().track_iter(), VehiclePlacement::FRONT_BUFFER);
+               else
+                       vehicles.back()->place(block.track_iter(), VehiclePlacement::BACK_BUFFER);
+               return true;
        }
        else
        {
-               const Block::Endpoint &bep = block.get_endpoint(entry);
-               vehicles.back()->place(*bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
+               unplace();
+               return false;
        }
 }
 
@@ -451,130 +226,115 @@ void Train::unplace()
        if(controller->get_speed())
                throw logic_error("moving");
 
-       release_blocks();
-
-       set_active(false);
+       allocator.clear();
        accurate_position = false;
+       last_entry_block = BlockIter();
 
        for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
                (*i)->unplace();
 }
 
-bool Train::free_block(Block &block)
+void Train::stop_at(Block *block)
 {
-       if(get_reserved_distance_until(&block, false)<controller->get_braking_distance()*1.3)
-               return false;
+       allocator.stop_at(block);
+}
 
-       unsigned nsens = 0;
-       for(BlockList::iterator i=cur_blocks_end; i!=blocks.end(); ++i)
-       {
-               if(i->block()==&block)
-               {
-                       if(nsens<1)
-                               return false;
-                       release_blocks(i, blocks.end());
-                       return true;
-               }
-               else if((*i)->get_sensor_id())
-                       ++nsens;
-       }
+bool Train::is_block_critical(const Block &block) const
+{
+       if(allocator.is_block_current(block))
+               return true;
 
-       return false;
+       BlockIter i = check_critical_blocks(&block);
+       return i.block()==&block;
 }
 
-void Train::free_noncritical_blocks()
+BlockIter Train::get_last_critical_block() const
 {
-       if(blocks.empty())
-               return;
+       return check_critical_blocks(0);
+}
+
+BlockIter Train::check_critical_blocks(const Block *check) const
+{
+       if(allocator.empty())
+               return BlockIter();
+
+       BlockIter i = allocator.last_current();
 
        if(controller->get_speed()==0)
-       {
-               release_blocks(cur_blocks_end, blocks.end());
-               return;
-       }
+               return i;
+
+       BlockIter last = allocator.last();
+       if(i.block()==last.block())
+               return i;
 
        float margin = 10*layout.get_catalogue().get_scale();
        float min_dist = controller->get_braking_distance()*1.3+margin;
 
-       Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
-
-       TrackIter track(veh.get_track(), veh.get_entry());
-       BlockList::iterator block = blocks.begin();
-       bool in_rsv = false;
-       while(block!=blocks.end() && !(*block)->has_track(*track))
+       float dist = 0;
+       bool sensor_seen = false;
+       i = i.next();
+       while(i.block()!=last.block() && i.block()!=check)
        {
-               ++block;
-               if(block==cur_blocks_end)
-                       in_rsv = true;
-       }
-
-       float dist = veh.get_offset();
-       if(reverse)
-               track.reverse();
-       else
-               dist = track->get_type().get_path_length(track->get_active_path())-dist;
-       dist -= veh.get_type().get_length()/2;
+               dist += i->get_path_length(i.entry());
 
-       bool nsens = 0;
-       while(1)
-       {
-               track = track.next();
+               if(i->get_sensor_address())
+                       sensor_seen = true;
 
-               if(!(*block)->has_track(*track))
-               {
-                       ++block;
-                       if(block==cur_blocks_end)
-                               in_rsv = true;
-                       if(block==blocks.end())
-                               return;
-
-                       if(dist>min_dist && nsens>0)
-                       {
-                               release_blocks(block, blocks.end());
-                               return;
-                       }
+               if(dist>min_dist && sensor_seen)
+                       break;
 
-                       if(in_rsv && (*block)->get_sensor_id())
-                               ++nsens;
-               }
+               BlockIter j = i.next();
+               if(j->get_train()!=this)
+                       break;
 
-               dist += track->get_type().get_path_length(track->get_active_path());
+               i = j;
        }
+
+       return i;
 }
 
-int Train::get_entry_to_block(Block &block) const
+void Train::refresh_blocks_from(Block &block)
 {
-       for(BlockList::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
-               if(i->block()==&block)
-                       return i->entry();
-       return -1;
+       if(is_block_critical(block))
+               allocator.rewind_to(*get_last_critical_block().next());
+       else
+               allocator.rewind_to(block);
 }
 
 float Train::get_reserved_distance() const
 {
-       if(blocks.empty())
+       if(allocator.empty())
                return 0;
 
        float margin = 0;
-       TrackIter next = blocks.back().next().track_iter();
+       TrackIter next = allocator.last().next().track_iter();
        if(next && next->get_type().is_turnout())
                margin = 15*layout.get_catalogue().get_scale();
 
-       return max(get_reserved_distance_until(0, false)-margin, 0.0f);
+       return max(get_reserved_distance_until(0)-margin, 0.0f);
 }
 
-void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
+void Train::tick(const Time::TimeDelta &dt)
 {
-       if(!active && stop_timeout && t>=stop_timeout)
+       if(stop_timeout)
        {
-               release_blocks(cur_blocks_end, blocks.end());
-               stop_timeout = Time::TimeStamp();
+               stop_timeout = max(stop_timeout-dt, Time::zero);
+               if(stop_timeout<=Time::zero)
+                       allocator.set_active(false);
        }
 
+       travel_time += dt;
+
        Driver &driver = layout.get_driver();
 
+       bool intent_to_move = false;
        for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
-               (*i)->tick(t, dt);
+       {
+               (*i)->tick(dt);
+               if((*i)->has_intent_to_move())
+                       intent_to_move = true;
+       }
+
        controller->tick(dt);
        float speed = controller->get_speed();
        bool moving = speed>0;
@@ -585,12 +345,10 @@ void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
                bool r = reverse;
                if(loco_type.get_swap_direction())
                        r = !r;
-               driver.set_loco_reverse(address, r);
+               driver.set_loco_reverse(loco_id, r);
 
-               release_blocks(cur_blocks_end, blocks.end());
-               reverse_blocks(blocks);
-
-               reserve_more();
+               allocator.reverse();
+               last_entry_block = BlockIter();
        }
 
        if(speed_quantizer)
@@ -599,7 +357,7 @@ void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
                if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
                {
                        speed_changing = true;
-                       driver.set_loco_speed(address, speed_step);
+                       driver.set_loco_speed(loco_id, speed_step);
 
                        pure_speed = false;
                }
@@ -609,18 +367,14 @@ void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
 
        if(moving)
        {
-               if(!active)
-                       set_active(true);
+               if(!allocator.is_active())
+                       allocator.set_active(true);
 
                Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
-               Track *track = vehicle.get_track();
-
-               bool ok = false;
-               for(BlockList::const_iterator i=blocks.begin(); (!ok && i!=cur_blocks_end); ++i)
-                       ok = (*i)->has_track(*track);
 
                float d = speed*(dt/Time::sec);
-               if(ok)
+               Block &block = vehicle.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE)->get_block();
+               if(allocator.is_block_current(block))
                {
                        SetFlag setf(advancing);
                        vehicle.advance(reverse ? -d : d);
@@ -630,39 +384,25 @@ void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
                        overshoot_dist += d;
                        if(overshoot_dist>40*layout.get_catalogue().get_scale())
                        {
-                               layout.emergency(name+" has not arrived at sensor");
+                               layout.emergency(&block, name+" has not arrived at sensor");
                                accurate_position = false;
                        }
                }
        }
-       else if(end_of_route && cur_blocks_end==blocks.end())
-       {
-               set_active(false);
-               signal_arrived.emit();
-               set_route(0);
-       }
-
-       if(!blocks.empty() && !blocks.front()->get_sensor_id())
-       {
-               float dist = get_reserved_distance_until(&*blocks.front(), true);
-
-               if(dist>10*layout.get_catalogue().get_scale())
-               {
-                       blocks.front()->reserve(0);
-                       blocks.pop_front();
-               }
-       }
+       else if(intent_to_move && !allocator.is_active())
+               allocator.set_active(true);
+       else if(allocator.is_active() && !intent_to_move && !stop_timeout)
+               stop_timeout = 2*Time::sec;
 }
 
 void Train::save(list<DataFile::Statement> &st) const
 {
        st.push_back((DataFile::Statement("name"), name));
 
-       st.push_back((DataFile::Statement("priority"), priority));
-
+       const Catalogue &cat = layout.get_catalogue();
        for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
                if(i!=vehicles.begin())
-                       st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
+                       st.push_back((DataFile::Statement("vehicle"), cat.get_name(&(*i)->get_type())));
 
        if(speed_quantizer)
        {
@@ -671,35 +411,28 @@ void Train::save(list<DataFile::Statement> &st) const
                st.push_back(ss);
        }
 
-       if(!blocks.empty() && cur_blocks_end!=blocks.begin())
-       {
-               BlockList blks(blocks.begin(), BlockList::const_iterator(cur_blocks_end));
-               if(reverse)
-                       reverse_blocks(blks);
-
-               BlockIter prev = blks.front().flip();
-               st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
-
-               for(BlockList::const_iterator i=blks.begin(); i!=blks.end(); ++i)
-                       st.push_back((DataFile::Statement("block"), (*i)->get_id()));
-       }
-
-       if(!routes.empty())
        {
-               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()));
+               DataFile::Statement ss("blocks");
+               allocator.save(ss.sub);
+               st.push_back(ss);
        }
 
        // XXX Need more generic way of saving AI state
        for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
-               if(Timetable *timetable = dynamic_cast<Timetable *>(*i))
+       {
+               if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
+               {
+                       DataFile::Statement ss("router");
+                       router->save(ss.sub);
+                       st.push_back(ss);
+               }
+               else if(Timetable *timetable = dynamic_cast<Timetable *>(*i))
                {
                        DataFile::Statement ss("timetable");
                        timetable->save(ss.sub);
                        st.push_back(ss);
                }
+       }
 }
 
 void Train::control_changed(const Controller::Control &ctrl)
@@ -707,24 +440,24 @@ 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 rev)
+void Train::loco_speed_event(unsigned id, unsigned speed, bool rev)
 {
-       if(addr==address)
+       if(id==loco_id)
        {
                current_speed_step = speed;
                bool r = reverse;
                if(loco_type.get_swap_direction())
                        r = !r;
                if(rev!=r)
-                       layout.get_driver().set_loco_reverse(address, r);
+                       layout.get_driver().set_loco_reverse(loco_id, r);
                speed_changing = false;
                pure_speed = false;
        }
 }
 
-void Train::loco_func_event(unsigned addr, unsigned func, bool state)
+void Train::loco_func_event(unsigned id, unsigned func, bool state)
 {
-       if(addr==address)
+       if(id==loco_id)
        {
                if(state)
                        functions |= 1<<func;
@@ -735,625 +468,151 @@ void Train::loco_func_event(unsigned addr, unsigned func, bool state)
        }
 }
 
-void Train::block_state_changed(Block &block, Block::State state)
+void Train::advanced(Block &block, Sensor *sensor)
 {
-       if(state==Block::MAYBE_ACTIVE)
-       {
-               // Find the first sensor block from our reserved blocks that isn't this sensor
-               BlockList::iterator end;
-               unsigned result = 0;
-               for(end=cur_blocks_end; end!=blocks.end(); ++end)
-                       if((*end)->get_sensor_id())
-                       {
-                               if(&**end!=&block)
-                               {
-                                       if(result==0)
-                                               result = 2;
-                                       else if(result==1)
-                                               break;
-                               }
-                               else if(result==0)
-                                       result = 1;
-                               else if(result==2)
-                                       result = 3;
-                       }
+       if(!sensor || sensor==block.get_sensor())
+               signal_advanced.emit(block);
+
+       if(!sensor)
+               return;
 
-               if(result==1)
+       if(sensor==block.get_sensor())
+       {
+               if(last_entry_block && pure_speed && speed_quantizer)
                {
-                       // Compute speed and update related state
-                       float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
+                       float travel_distance = 0;
 
-                       if(pure_speed && speed_quantizer && current_speed_step>0 && travel_time_secs>=2)
-                               speed_quantizer->learn(current_speed_step, travel_dist/travel_time_secs, travel_time_secs);
+                       for(BlockIter i=last_entry_block; &*i!=&block; i=i.next())
+                               travel_distance += i->get_path_length(i.entry());
 
-                       travel_dist = 0;
-                       for(BlockList::iterator j=cur_blocks_end; j!=end; ++j)
+                       if(travel_distance>0)
                        {
-                               travel_dist += (*j)->get_path_length(j->entry());
+                               float travel_time_secs = travel_time/Time::sec;
 
-                               if(&**j==&block && !advancing)
-                               {
-                                       TrackIter track = j->track_iter();
-                                       if(reverse)
-                                       {
-                                               track = track.flip();
-                                               vehicles.back()->place(*track, track.entry(), 0, Vehicle::BACK_AXLE);
-                                       }
-                                       else
-                                               vehicles.front()->place(*track, track.entry(), 0, Vehicle::FRONT_AXLE);
-                               }
+                               if(travel_time_secs>=2)
+                                       speed_quantizer->learn(current_speed_step, travel_distance/travel_time_secs, travel_time_secs);
                        }
-                       last_entry_time = Time::now();
+               }
+
+               last_entry_block = allocator.iter_for(block);
+               travel_time = Time::zero;
+               if(!layout.get_driver().is_halted())
+               {
                        pure_speed = true;
                        accurate_position = true;
-                       overshoot_dist = 0;
-
-                       // Check if we've reached the next route
-                       if(routes.size()>1)
-                       {
-                               const Route &route = *(++routes.begin())->route;
-                               for(BlockList::iterator j=cur_blocks_end; j!=end; ++j)
-                                       if(route.has_track(*j->track_iter()))
-                                       {
-                                               routes.pop_front();
-                                               // XXX Exceptions?
-                                               signal_route_changed.emit(routes.front().route);
-                                               break;
-                                       }
-                       }
-
-                       // Move blocks up to the next sensor to our current blocks
-                       for(BlockList::iterator j=cur_blocks_end; j!=end; ++j)
-                               signal_advanced.emit(**j);
-                       cur_blocks_end = end;
-
-                       // Try to get more blocks if we're moving
-                       if(active)
-                               reserve_more();
                }
-               else if(result==3)
-                       layout.emergency("Sensor for "+name+" triggered out of order");
-       }
-       else if(state==Block::INACTIVE)
-       {
-               const Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
+               overshoot_dist = 0;
 
-               // Find the first sensor in our current blocks that's still active
-               BlockList::iterator end = blocks.begin();
-               for(BlockList::iterator i=blocks.begin(); i!=cur_blocks_end; ++i)
+               if(!advancing && vehicles.front()->is_placed())
                {
-                       if((*i)->has_track(*veh.get_track()))
-                               break;
-                       if((*i)->get_sensor_id())
+                       TrackIter track = last_entry_block.track_iter();
+                       if(reverse)
                        {
-                               if(layout.get_driver().get_sensor((*i)->get_sensor_id()))
-                                       break;
-                               else
-                               {
-                                       end = i;
-                                       ++end;
-                               }
+                               track = track.flip();
+                               vehicles.back()->place(track, VehiclePlacement::BACK_AXLE);
                        }
+                       else
+                               vehicles.front()->place(track, VehiclePlacement::FRONT_AXLE);
                }
-               
-               if(end!=blocks.begin() && end!=cur_blocks_end)
-                       // Free blocks up to the last inactive sensor
-                       release_blocks(blocks.begin(), end);
        }
-}
-
-void Train::turnout_path_changed(Track &track)
-{
-       for(list<BlockIter>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
-               if((*i)->get_turnout_id()==track.get_turnout_id() && !reserving)
-                       check_turnout_paths(false);
-}
-
-void Train::halt_event(bool h)
-{
-       if(h)
-               accurate_position = false;
-}
-
-void Train::block_reserved(const Block &block, const Train *train)
-{
-       if(&block==pending_block && !train && !reserving)
-               reserve_more();
-}
-
-void Train::reserve_more()
-{
-       if(!active || blocks.empty() || end_of_route)
-               return;
-
-       BlockIter start = blocks.back();
-
-       pending_block = 0;
-       preceding_train = 0;
-
-       // See how many sensor blocks and how much track we already have
-       unsigned nsens = 0;
-       float dist = 0;
-       for(BlockList::const_iterator i=cur_blocks_end; i!=blocks.end(); ++i)
-       {
-               if((*i)->get_sensor_id())
-                       ++nsens;
-               if(nsens>0)
-                       dist += (*i)->get_path_length(i->entry());
-       }
-
-       list<RouteRef>::iterator cur_route = routes.begin();
-       advance_route(cur_route, *start.track_iter());
-
-       float approach_margin = 50*layout.get_catalogue().get_scale();
-       float min_dist = controller->get_braking_distance()*1.3+approach_margin*2;
-
-       BlockIter block = start;
-       list<BlockIter>::iterator good_end = blocks.end();
-       Track *divert_track = 0;
-       bool try_divert = false;
-       Train *blocking_train = 0;
-       BlockList contested_blocks;
-
-       SetFlag setf(reserving);
-
-       while(1)
+       else if(BeamGate *gate = dynamic_cast<BeamGate *>(sensor))
        {
-               BlockIter last = block;
-               block = block.next(cur_route!=routes.end() ? cur_route->route : 0);
-               if(!block || block->get_endpoints().size()<2)
-               {
-                       if(!blocking_train)
-                       {
-                               good_end = blocks.end();
-                               end_of_route = true;
-                       }
-                       break;
-               }
-
-               TrackIter track = block.track_iter();
-
-               if(cur_route!=routes.end())
-               {
-                       if(!advance_route(cur_route, *track))
-                       {
-                               // Keep the blocks if we arrived at the end of the route
-                               if(!blocking_train)
-                               {
-                                       good_end = blocks.end();
-                                       end_of_route = true;
-                               }
-                               break;
-                       }
-               }
-
-               if(block->get_turnout_id() && !last->get_turnout_id())
+               if(!advancing && vehicles.front()->is_placed())
                {
-                       /* We can keep the blocks if we arrive at a turnout from a non-turnout
-                       block.  Having a turnout block as our last reserved block is not good
-                       as it would limit our diversion possibilities for little benefit. */
-                       good_end = blocks.end();
-                       if(nsens>=3 && dist>=min_dist)
-                               break;
-               }
-
-               if(blocking_train)
-               {
-                       if(block->get_train()!=blocking_train)
-                       {
-                               if(blocking_train->free_block(*contested_blocks.back()))
-                               {
-                                       // Roll back and start actually reserving the blocks
-                                       block = blocks.back();
-                                       cur_route = routes.begin();
-                                       advance_route(cur_route, *block.track_iter().track());
-                                       if(blocking_train->get_priority()==priority)
-                                               blocking_train->yield_to(*this);
-                                       blocking_train = 0;
-                                       continue;
-                               }
-                               else
+                       TrackIter track = allocator.iter_for(block).track_iter();
+                       for(; (track && &track->get_block()==&block); track=track.next())
+                               if(track.track()==gate->get_track())
                                {
-                                       yield_to(*blocking_train);
-                                       pending_block = contested_blocks.front().block();
-                                       try_divert = divert_track;
+                                       if(reverse)
+                                               track = track.reverse();
+                                       float offset = gate->get_offset_from_endpoint(track.entry());
+                                       if(reverse)
+                                               vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
+                                       else
+                                               vehicles.front()->place(TrackOffsetIter(track, offset), VehiclePlacement::FRONT_BUFFER);
                                        break;
                                }
-                       }
-                       else
-                       {
-                               contested_blocks.push_back(block);
-                               continue;
-                       }
                }
-
-               bool reserved = block->reserve(this);
-               if(!reserved)
-               {
-                       /* 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 = block->get_train();
-                       int other_entry = other_train->get_entry_to_block(*block);
-                       if(other_entry<0)
-                               throw logic_error("block reservation inconsistency");
-
-                       unsigned exit = block.reverse().entry();
-                       unsigned other_exit = BlockIter(block.block(), other_entry).reverse().entry();
-                       bool entry_conflict = (block.entry()==other_exit);
-                       bool exit_conflict = (exit==static_cast<unsigned>(other_entry));
-                       if(!entry_conflict && !last->get_turnout_id())
-                       {
-                               /* The other train is not coming to the blocks we're holding, so we
-                               can keep them. */
-                               good_end = blocks.end();
-
-                               if(static_cast<unsigned>(other_entry)==block.entry())
-                                       preceding_train = other_train;
-                       }
-
-                       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(*block))
-                                       reserved = block->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(block);
-                               continue;
-                       }
-                       else if(divert_track && (entry_conflict || exit_conflict || !other_train->is_active()))
-                               // We are blocked, but there's a diversion possibility
-                               try_divert = true;
-
-                       if(!reserved)
-                       {
-                               pending_block = &*block;
-                               break;
-                       }
-               }
-
-               if(block->get_turnout_id())
-               {
-                       const TrackType::Endpoint &track_ep = track.endpoint();
-                       bool multiple_paths = (track_ep.paths&(track_ep.paths-1));
-
-                       if(multiple_paths && cur_route!=routes.end() && cur_route->diversion!=block->get_turnout_id())
-                               /* There's multiple paths to be taken and we are on a route - take
-                               note of the diversion possibility */
-                               divert_track = &*track;
-               }
-
-               if(!contested_blocks.empty() && contested_blocks.front()==block)
-                       contested_blocks.pop_front();
-
-               blocks.push_back(block);
-
-               if(cur_blocks_end==blocks.end())
-                       --cur_blocks_end;
-               if(clear_blocks_end==blocks.end())
-                       --clear_blocks_end;
-               if(good_end==blocks.end())
-                       --good_end;
-
-               if(block->get_sensor_id())
-                       ++nsens;
-               if(nsens>0)
-                       dist += block->get_path_length(block.entry());
        }
-
-       // Unreserve blocks that were not good
-       release_blocks(good_end, blocks.end());
-
-       if(blocks.back()!=start)
-               // We got some new blocks, so no longer need to yield
-               yielding_to = 0;
-
-       check_turnout_paths(true);
-
-       // Make any sensorless blocks at the beginning immediately current
-       while(cur_blocks_end!=clear_blocks_end && !(*cur_blocks_end)->get_sensor_id())
-               ++cur_blocks_end;
-
-       if(try_divert && divert(*divert_track))
-               reserve_more();
 }
 
-void Train::check_turnout_paths(bool set)
+void Train::halt_event(bool h)
 {
-       if(clear_blocks_end==blocks.end())
-               return;
-
-       for(list<BlockIter>::iterator i=clear_blocks_end; i!=blocks.end(); ++i)
-       {
-               if((*i)->get_turnout_id())
-               {
-                       TrackIter track = i->track_iter();
-                       const TrackType::Endpoint &track_ep = track.endpoint();
-
-                       unsigned path = 0;
-                       list<BlockIter>::iterator j = i;
-                       if(++j!=blocks.end())
-                       {
-                               TrackIter rev = j->track_iter().flip();
-                               unsigned mask = rev.endpoint().paths&track_ep.paths;
-                               for(path=0; mask>1; mask>>=1, ++path) ;
-                       }
-                       else
-                               return;
-
-                       if(path!=track->get_active_path())
-                       {
-                               if(set)
-                                       track->set_active_path(path);
-
-                               /* Check again, in case the driver was able to service the request
-                               instantly */
-                               if(!set || path!=track->get_active_path())
-                                       continue;
-                       }
-               }
-
-               if(i==clear_blocks_end)
-                       ++clear_blocks_end;
-       }
+       if(h)
+               accurate_position = false;
 }
 
-float Train::get_reserved_distance_until(const Block *until_block, bool back) const
+float Train::get_reserved_distance_until(const Block *until_block) const
 {
-       if(blocks.empty())
+       if(allocator.empty())
                return 0;
 
-       Vehicle &veh = *(reverse!=back ? vehicles.back() : vehicles.front());
-       const VehicleType &vtype = veh.get_type();
+       Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
 
-       TrackIter track(veh.get_track(), veh.get_entry());
+       TrackOffsetIter track = veh.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE);
        if(!track)  // XXX Probably unnecessary
                return 0;
 
-       BlockList::const_iterator block = blocks.begin();
-       while(block!=clear_blocks_end && !(*block)->has_track(*track))
-               ++block;
-       if(block==clear_blocks_end || &**block==until_block)
+       if(&track->get_block()==until_block)
                return 0;
 
-       float result = veh.get_offset();
-       if(reverse!=back)
+       // Account for the vehicle's offset on its current track
+       float result = track.offset();
+       if(reverse)
                track = track.reverse();
        else
-               result = track->get_type().get_path_length(track->get_active_path())-result;
-       result -= vtype.get_length()/2;
+               result = track->get_path_length()-result;
+       result -= veh.get_type().get_length()/2;
 
-       while(1)
-       {
-               track = track.next();
-               if(!track)
-                       break;
+       BlockIter block = track.block_iter();
 
-               if(!(*block)->has_track(*track))
-               {
-                       if(back)
-                       {
-                               if(block==blocks.begin())
-                                       break;
-                               --block;
-                       }
-                       else
-                       {
-                               ++block;
-                               if(block==clear_blocks_end)
-                                       break;
-                       }
-
-                       if(&**block==until_block)
-                               break;
-               }
-
-               result += track->get_type().get_path_length(track->get_active_path());
-       }
+       // Count remaining distance in the vehicle's current block
+       for(track=track.next(); &track->get_block()==&*block; track=track.next())
+               result += track->get_path_length();
 
-       return result;
-}
-
-void Train::release_blocks()
-{
-       release_blocks(blocks.begin(), blocks.end());
-}
+       const BlockIter &last = allocator.last();
+       if(&*block==&*last)
+               return result;
 
-void Train::release_blocks(BlockList::iterator begin, BlockList::iterator end)
-{
-       while(begin!=end)
+       // Count any remaining blocks
+       for(block=block.next(); (&*block!=until_block && block->get_train()==this); block=block.next())
        {
-               if(begin==cur_blocks_end)
-                       cur_blocks_end = end;
-               if(begin==clear_blocks_end)
-                       clear_blocks_end = end;
+               result += block->get_path_length(block.entry());
 
-               Block &block = **begin;
-               blocks.erase(begin++);
-               block.reserve(0);
-
-               if(begin==blocks.end())
-                       end_of_route = false;
-       }
-}
-
-void Train::reverse_blocks(BlockList &blks) const
-{
-       blks.reverse();
-       for(BlockList::iterator i=blks.begin(); i!=blks.end(); ++i)
-               *i = i->reverse();
-}
-
-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(BlockList::iterator i=blocks.begin(); i!=blocks.end(); ++i)
-       {
-               const set<Track *> &btracks = (*i)->get_tracks();
-               for(set<Track *>::const_iterator j=btracks.begin(); j!=btracks.end(); ++j)
-                       if(!target || !target->has_track(**j))
-                               tracks.insert(*j);
-       }
-
-       lead->add_tracks(tracks);
-
-       return lead;
-}
-
-bool Train::is_valid_diversion(const Route &diversion, const TrackIter &from)
-{
-       float diversion_len = 0;
-       TrackLoopIter track1 = from;
-       while(diversion.has_track(*track1))
-       {
-               unsigned path = diversion.get_path(*track1);
-               diversion_len += track1->get_type().get_path_length(path);
-
-               track1 = track1.next(path);
-
-               if(!track1 || track1.looped())
-                       return false;
-       }
-
-       list<RouteRef>::iterator route = routes.begin();
-       if(!advance_route(route, *from))
-               return false;
-
-       float route_len = 0;
-       TrackLoopIter track2 = from;
-       while(1)
-       {
-               unsigned path = route->route->get_path(*track2);
-               route_len += track2->get_type().get_path_length(path);
-
-               bool ok = (track2!=from && diversion.has_track(*track2));
-
-               track2 = track2.next(path);
-               if(!track2)
-                       return false;
-
-               if(ok)
+               if(&*block==&*last)
                        break;
-
-               if(track2.looped())
-                       return false;
-
-               if(!advance_route(route, *track2))
-                       return false;
        }
 
-       // Must end up at the same place through both routes
-       if(track2!=track1)
-               return false;
-
-       return diversion_len<route_len*1.2;
+       return result;
 }
 
 
-Train::RouteRef::RouteRef(const Route *r, unsigned d):
-       route(r),
-       diversion(d)
-{ }
-
-
 Train::Loader::Loader(Train &t):
        DataFile::ObjectLoader<Train>(t),
        prev_block(0),
        blocks_valid(true)
 {
-       add("block",       &Loader::block);
-       add("block_hint",  &Loader::block_hint);
+       add("blocks",      &Loader::blocks);
        add("name",        &Loader::name);
-       add("priority",    &Train::priority);
        add("quantized_speed",  &Loader::quantized_speed);
-       add("route",       &Loader::route);
+       add("router",      &Loader::router);
        add("timetable",   &Loader::timetable);
        add("vehicle",     &Loader::vehicle);
 }
 
 void Train::Loader::finish()
 {
-       if(!obj.blocks.empty())
+       if(!obj.allocator.empty())
        {
-               TrackIter track = obj.blocks.front().track_iter();
+               TrackIter track = obj.allocator.first().track_iter();
                float offset = 2*obj.layout.get_catalogue().get_scale();
-               obj.vehicles.back()->place(*track, track.entry(), offset, Vehicle::BACK_BUFFER);
-       }
-}
-
-void Train::Loader::block(unsigned id)
-{
-       if(!blocks_valid)
-               return;
-
-       Block *blk;
-       try
-       {
-               blk = &obj.layout.get_block(id);
-       }
-       catch(const key_error &)
-       {
-               blocks_valid = false;
-               return;
+               obj.vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
        }
-
-       int entry = -1;
-       if(prev_block)
-               entry = blk->get_endpoint_by_link(*prev_block);
-       if(entry<0)
-               entry = 0;
-
-       blk->reserve(&obj);
-       obj.blocks.push_back(BlockIter(blk, entry));
-
-       if(blk->get_sensor_id())
-               obj.layout.get_driver().set_sensor(blk->get_sensor_id(), true);
-
-       prev_block = blk;
 }
 
-void Train::Loader::block_hint(unsigned id)
+void Train::Loader::blocks()
 {
-       try
-       {
-               prev_block = &obj.layout.get_block(id);
-       }
-       catch(const key_error &)
-       {
-               blocks_valid = false;
-       }
+       load_sub(obj.allocator);
 }
 
 void Train::Loader::name(const string &n)
@@ -1367,23 +626,25 @@ void Train::Loader::quantized_speed()
                load_sub(*obj.speed_quantizer);
 }
 
-void Train::Loader::route(const string &n)
+void Train::Loader::router()
 {
-       obj.set_route(&obj.layout.get_route(n));
+       TrainRouter *rtr = new TrainRouter(obj);
+       load_sub(*rtr);
 }
 
 void Train::Loader::timetable()
 {
        Timetable *ttbl = new Timetable(obj);
-       load_sub(*ttbl);
+       load_sub(*ttbl, obj.layout);
 }
 
-void Train::Loader::vehicle(ArticleNumber art_nr)
+void Train::Loader::vehicle(const string &n)
 {
-       const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(art_nr);
+       const VehicleType &vtype = obj.layout.get_catalogue().get<VehicleType>(n);
        Vehicle *veh = new Vehicle(obj.layout, vtype);
        obj.vehicles.back()->attach_back(*veh);
        obj.vehicles.push_back(veh);
+       veh->set_train(&obj);
 }
 
 } // namespace R2C2