+void TrainRouter::get_routers(Layout &layout, vector<TrainRouter *> &routers, TrainRoutePlanner *planner)
+{
+ const map<unsigned, Train *> &trains = layout.get_trains();
+ routers.reserve(trains.size());
+ for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
+ if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
+ if(!planner || router->planner.get()==planner)
+ routers.push_back(router);
+}
+
+void TrainRouter::start_planning(Layout &layout)
+{
+ vector<TrainRouter *> routers;
+ get_routers(layout, routers);
+
+ for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
+ if((*i)->metrics_stale)
+ (*i)->create_metrics();
+
+ RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
+ for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
+ {
+ (*i)->waypoints_changed = false;
+ (*i)->planner = planner;
+ }
+
+ planner->plan_async();
+}
+
+void TrainRouter::apply_plan(Layout &layout, TrainRoutePlanner &planner)
+{
+ if(planner.get_result()==TrainRoutePlanner::FAILED)
+ layout.emergency(0, "Route planning failed");
+
+ vector<TrainRouter *> routers;
+ get_routers(layout, routers, &planner);
+
+ /* Clear sequence counters first to avoid inconsistent state while applying
+ the plan. */
+ for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
+ (*i)->current_sequence = 0;
+
+ for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
+ {
+ (*i)->use_planned_route();
+ (*i)->planner = 0;
+ }
+}
+
+
+TrainRouter::Waypoint::Waypoint(const TrackChain &c, TrackChain::Direction d):
+ chain(&c),
+ direction(d)
+{ }
+
+
+TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
+ block(&b),
+ preceding_train(0),
+ sequence_in(0),
+ sequence_out(o)
+{ }
+
+bool TrainRouter::SequencePoint::is_cleared() const