+#include "driver.h"
#include "layout.h"
#include "route.h"
#include "trackiter.h"
TrainRouter::TrainRouter(Train &t):
TrainAI(t),
priority(0),
- arrival(ON_THE_WAY),
- destination(0),
- destination_changed(false),
+ state(ON_THE_WAY),
+ waypoints_changed(false),
metrics_stale(false),
- current_sequence(0),
- sequence_check_pending(false)
+ current_sequence(0)
{
train.get_layout().signal_block_reserved.connect(sigc::mem_fun(this, &TrainRouter::block_reserved));
train.signal_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_advanced));
bool TrainRouter::set_route(const Route *r)
{
- BlockIter fncb = train.get_first_noncritical_block();
-
- Route *lead = 0;
- if(r && train.is_placed())
- {
- const BlockAllocator &allocator = train.get_block_allocator();
- TrackIter first = allocator.first().track_iter();
- TrackIter next = fncb.track_iter();
- if(!r->has_track(*next))
- {
- lead = Route::find(next, *r);
- if(!lead)
- return false;
- create_lead_route(lead, lead);
- }
- else if(!r->has_track(*first))
- lead = create_lead_route(0, r);
- }
-
routes.clear();
- if(lead)
- routes.push_back(lead);
- // TODO Check if eclipsed by lead route
if(r)
+ {
routes.push_back(r);
+ create_lead_route();
+ }
- destination = 0;
waypoints.clear();
sequence_points.clear();
- current_sequence = 0;
- sequence_check_pending = false;
route_changed();
return routes.front();
}
+void TrainRouter::use_planned_route()
+{
+ if(!planner || planner->get_result()!=TrainRoutePlanner::COMPLETE)
+ return;
+ if(waypoints.empty())
+ return;
+
+ const list<Route *> &planned_routes = planner->get_routes_for(train);
+
+ routes.clear();
+ routes.insert(routes.end(), planned_routes.begin(), planned_routes.end());
+ create_lead_route();
+
+ sequence_points = planner->get_sequence_for(train);
+ current_sequence = 0;
+
+ route_changed();
+}
+
void TrainRouter::route_changed()
{
- BlockIter fncb = train.get_first_noncritical_block();
+ BlockIter fncb = train.get_last_critical_block().next();
+ state = ON_THE_WAY;
reserving_route = routes.begin();
- bool already_at_end = false;
if(!routes.empty())
{
/* Find the route that should be used for the next allocated block. We
can't rely on the resync code in block_reserved since we may need to
clear the stop marker to continue allocation. */
- TrackIter track = train.get_block_allocator().first().track_iter();
+ const BlockAllocator &allocator = train.get_block_allocator();
+ TrackIter track = allocator.first().track_iter();
+ list<SequencePoint>::iterator seq_begin = sequence_points.begin();
for(; track; track=track.next())
{
- if(!advance_to_track(reserving_route, *track))
+ if(!advance_to_track(reserving_route, track))
{
- already_at_end = true;
+ state = (allocator.is_block_current(track->get_block()) ? ADVANCED_TO_END : RESERVED_TO_END);
break;
}
if(&track->get_block()==fncb.block())
break;
+
+ if(seq_begin!=sequence_points.end() && seq_begin->block==&track->get_block())
+ {
+ // Assume any sequence points within critical blocks to be cleared
+ current_sequence = seq_begin->sequence_out;
+ ++seq_begin;
+ }
}
- }
- if(!already_at_end)
- {
- // We are not at the end of the route now, but might have been before.
- arrival = ON_THE_WAY;
- train.refresh_blocks_from(*fncb);
- if(!arrival)
- train.stop_at(0);
+ sequence_points.erase(sequence_points.begin(), seq_begin);
+
+ if(!sequence_points.empty())
+ {
+ const SequencePoint &sp = sequence_points.front();
+ if(sp.block==fncb.block() && !sp.is_cleared())
+ state = SEQUENCE_CHECK_PENDING;
+ }
}
- else if(!arrival)
- {
- /* If arrival wasn't set before (perhaps because we weren't on a route),
- set it now. */
- arrival = RESERVED_TO_END;
+
+ /* Refresh from the first non-critical block to pick up any changes in the
+ route. Set stop marker first in case a stopping state was set within the
+ critical blocks. */
+ if(state!=ON_THE_WAY)
train.stop_at(&*fncb.flip());
- train.refresh_blocks_from(*fncb);
- }
+ train.refresh_blocks_from(*fncb);
+ // If we don't need to stop, clear a possible previous stop marker.
+ if(state==ON_THE_WAY)
+ train.stop_at(0);
const Route *route = get_route();
signal_route_changed.emit(route);
void TrainRouter::set_destination(const TrackChain &d)
{
- destination = &d;
- destination_changed = true;
+ if(waypoints.empty())
+ waypoints.push_back(Waypoint(d));
+ else
+ waypoints.back() = Waypoint(d);
+ waypoints_changed = true;
metrics_stale = true;
}
-void TrainRouter::add_waypoint(const TrackChain &wp)
+void TrainRouter::add_waypoint(const TrackChain &chain, TrackChain::Direction dir)
{
- waypoints.push_back(&wp);
- destination_changed = true;
+ waypoints.push_back(Waypoint(chain, dir));
+ waypoints_changed = true;
metrics_stale = true;
}
-const TrackChain &TrainRouter::get_waypoint(unsigned index) const
+const TrainRouter::Waypoint &TrainRouter::get_waypoint(unsigned index) const
{
if(index>=waypoints.size())
throw out_of_range("TrainRouter::is_waypoint");
- return *waypoints[index];
+ return waypoints[index];
}
const TrainRouteMetric &TrainRouter::get_metric(int index) const
{
- if(!destination)
+ if(waypoints.empty())
throw logic_error("no metrics");
else if(metrics_stale)
throw logic_error("metrics are stale");
if(index<0)
- return *metrics.front();
+ return *metrics.back();
else if(static_cast<unsigned>(index)>=waypoints.size())
throw out_of_range("TrainRouter::get_metric");
else
- return *metrics[index+1];
+ return *metrics[index];
}
void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
{
delay = d;
- destination_changed = true;
+ waypoints_changed = true;
}
void TrainRouter::set_trip_duration(const Time::TimeDelta &d)
}
else if(msg.type=="add-waypoint")
{
- if(msg.value.check_type<TrackChain *>())
+ if(msg.value.check_type<Waypoint>())
+ {
+ Waypoint wp = msg.value.value<Waypoint>();
+ add_waypoint(*wp.chain, wp.direction);
+ }
+ else if(msg.value.check_type<TrackChain *>())
add_waypoint(*msg.value.value<TrackChain *>());
else
add_waypoint(*msg.value.value<const TrackChain *>());
void TrainRouter::tick(const Time::TimeDelta &dt)
{
- if(delay)
- {
- delay -= dt;
- if(delay<Time::zero)
- {
- duration = max(duration+delay, Time::zero);
- delay = Time::zero;
- }
- }
- else if(duration)
- duration = max(duration-dt, Time::zero);
-
- if(destination_changed && !planner)
+ if(waypoints_changed && !planner)
start_planning(train.get_layout());
if(planner && planner->check()!=TrainRoutePlanner::PENDING)
+ apply_plan(train.get_layout(), *planner);
+
+ Layout &layout = train.get_layout();
+ if(!layout.get_driver().is_halted() && !layout.get_clock().is_stopped())
{
- destination_changed = false;
- if(planner->get_result()==TrainRoutePlanner::COMPLETE)
+ if(delay)
{
- const list<Route *> &planned_routes = planner->get_routes_for(train);
-
- routes.clear();
- Route *lead = create_lead_route(0, planned_routes.front());
- routes.push_back(lead);
-
- list<Route *>::const_iterator begin = planned_routes.begin();
- for(; begin!=planned_routes.end(); ++begin)
+ delay -= dt;
+ if(delay<Time::zero)
{
- const Route::TrackSet &tracks = (*begin)->get_tracks();
- bool eclipsed = true;
- for(Route::TrackSet::const_iterator i=tracks.begin(); (eclipsed && i!=tracks.end()); ++i)
- eclipsed = lead->has_track(**i);
- if(!eclipsed)
- break;
+ duration = max(duration+delay, Time::zero);
+ delay = Time::zero;
+ train.ai_message(Message("set-target-speed", train.get_maximum_speed()));
+ signal_departed.emit();
+ signal_event.emit(Message("departed"));
}
- routes.insert(routes.end(), begin, planned_routes.end());
-
- sequence_points = planner->get_sequence_for(train);
- current_sequence = 0;
- sequence_check_pending = false;
-
- route_changed();
}
- planner = 0;
+ else if(duration)
+ duration = max(duration-dt, Time::zero);
}
- if(sequence_check_pending)
+ if(state==SEQUENCE_CHECK_PENDING)
{
if(sequence_points.front().is_cleared())
+ {
+ state = ON_THE_WAY;
train.stop_at(0);
- sequence_check_pending = false;
+ }
+ else
+ state = WAITING_FOR_SEQUENCE;
}
- if(arrival==RESERVED_TO_END && !train.get_speed())
+ if(state==ADVANCED_TO_END && !train.get_speed())
{
- signal_arrived.emit(destination);
- signal_event.emit(Message("arrived", destination));
- arrival = ARRIVED;
+ signal_arrived.emit(waypoints.back().chain);
+ signal_event.emit(Message("arrived", waypoints.back().chain));
+ state = ARRIVED;
}
- else if(arrival==ARRIVED && !train.get_block_allocator().is_active())
+ else if(state==ARRIVED && !train.get_block_allocator().is_active())
set_route(0);
}
return;
// Are we waiting for the other train to pass a sequence point?
- SequencePoint &sp = sequence_points.front();
- if(sp.preceding_train==t && sp.block==&block)
- /* The other train's router will advance its sequence on the same
- signal and may not have handled it yet. */
- sequence_check_pending = true;
+ if(state==WAITING_FOR_SEQUENCE)
+ {
+ SequencePoint &sp = sequence_points.front();
+ if(sp.preceding_train==t && sp.block==&block)
+ /* The other train's router will advance its sequence on the same
+ signal and may not have handled it yet. */
+ state = SEQUENCE_CHECK_PENDING;
+ }
return;
}
if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
{
reserving_route = routes.begin();
- arrival = ON_THE_WAY;
+ state = ON_THE_WAY;
track = t->get_block_allocator().first().track_iter();
for(; track; track=track.next())
{
- if(!advance_to_track(reserving_route, *track))
+ if(!advance_to_track(reserving_route, track))
throw logic_error("internal error (reservation outside of route)");
else if(&track->get_block()==&block)
break;
expected to be allocated next. */
for(; track; track=track.next((*reserving_route)->get_path(*track)))
{
- if(!advance_to_track(reserving_route, *track))
+ if(!advance_to_track(reserving_route, track))
{
// We've reached the end of the route. Stop here.
- arrival = RESERVED_TO_END;
+ state = RESERVED_TO_END;
train.stop_at(&block);
return;
}
{
SequencePoint &sp = sequence_points.front();
if(sp.block==&track->get_block() && !sp.is_cleared())
+ {
+ state = SEQUENCE_CHECK_PENDING;
train.stop_at(&block);
+ }
}
}
void TrainRouter::train_advanced(Block &block)
{
- BlockIter b_iter = train.get_block_allocator().iter_for(block);
-
if(!waypoints.empty())
{
// A waypoint is considered reached when the train has advanced through it.
- const TrackChain &wp = *waypoints.front();
+ BlockIter b_iter = train.get_block_allocator().iter_for(block);
+ const Waypoint &wp = waypoints.front();
TrackIter t_iter = b_iter.track_iter();
- if(wp.has_track(*t_iter))
+ if(wp.chain->has_track(*t_iter))
{
- for(; t_iter; t_iter=t_iter.next())
+ while(1)
{
- if(!wp.has_track(*t_iter))
+ TrackIter next = t_iter.next();
+ if(!next)
+ break;
+
+ if(!wp.chain->has_track(*next))
{
- waypoints.erase(waypoints.begin());
- signal_waypoint_reached.emit(&wp);
- signal_event.emit(Message("waypoint-reached", &wp));
+ if(wp.direction!=TrackChain::UNSPECIFIED)
+ if(t_iter!=wp.chain->iter_for(*t_iter, wp.direction))
+ break;
+
+ if(waypoints.size()==1)
+ {
+ if(state==RESERVED_TO_END)
+ state = ADVANCED_TO_END;
+ }
+ else
+ {
+ const TrackChain *chain = wp.chain;
+ waypoints.erase(waypoints.begin());
+ metrics_stale = true;
+ signal_waypoint_reached.emit(chain);
+ signal_event.emit(Message("waypoint-reached", chain));
+ }
break;
}
- else if(!block.has_track(*t_iter))
+ else if(!block.has_track(*next))
break;
+
+ t_iter = next;
}
}
}
delete *i;
metrics.clear();
- if(!destination)
- return;
+ metrics_stale = false;
- metrics.push_back(new TrainRouteMetric(*destination));
- for(vector<const TrackChain *>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
- metrics.push_back(new TrainRouteMetric(**i));
+ if(waypoints.empty())
+ return;
- for(unsigned i=metrics.size(); --i>0; )
- metrics[i]->chain_to(*metrics[(i+1)%metrics.size()]);
+ for(vector<Waypoint>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
+ metrics.push_back(new TrainRouteMetric(*i->chain, i->direction));
- metrics_stale = false;
+ for(unsigned i=metrics.size()-1; i-->0; )
+ metrics[i]->chain_to(*metrics[i+1]);
}
-Route *TrainRouter::create_lead_route(Route *lead, const Route *target)
+bool TrainRouter::create_lead_route()
{
- if(!lead)
+ if(routes.empty() || !train.is_placed())
+ return false;
+
+ BlockIter lcb = train.get_last_critical_block();
+ TrackIter last_track_rev = lcb.reverse().track_iter();
+
+ unsigned count = 0;
+ for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
+ {
+ if(routes.front()->has_track(*i))
+ ++count;
+ else if(count>0)
+ {
+ if(count==routes.front()->get_tracks().size())
+ last_track_rev = i;
+ break;
+ }
+ }
+
+ TrackIter next_track = last_track_rev.flip();
+ if(!routes.front()->has_track(*last_track_rev) && !routes.front()->has_track(*next_track))
{
- lead = new Route(train.get_layout());
- lead->set_name("Lead");
- lead->set_temporary(true);
+ Route *pf = Route::find(next_track, *routes.front());
+ if(!pf)
+ return false;
+
+ routes.push_front(pf);
}
- unsigned target_tracks = 0;
- for(TrackIter i=train.get_block_allocator().first().track_iter(); (target_tracks<2 && i); i=i.next())
+ Route *lead = 0;
+ for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
{
- if(i->get_block().get_train()!=&train)
- break;
- if(target)
+ if(!lead && !routes.front()->has_track(*i))
{
- if(target->has_track(*i))
- ++target_tracks;
- else if(target_tracks>0)
- break;
+ lead = new Route(train.get_layout());
+ lead->set_name("Lead");
+ lead->set_temporary(true);
+ routes.push_front(lead);
+
+ TrackIter j = i.flip();
+ lead->add_track(*j);
+ lead->add_track(*j.next());
}
- lead->add_track(*i);
- }
- return lead;
-}
+ if(lead)
+ lead->add_track(*i);
+ }
-bool TrainRouter::is_valid_for_track(const Route &route, Track &track) const
-{
- if(!route.has_track(track))
- return false;
- if(track.get_type().is_turnout() && route.get_turnout(track.get_turnout_address())<0)
- return false;
return true;
}
-bool TrainRouter::advance_to_track(RouteList::iterator &route, Track &track)
+bool TrainRouter::advance_to_track(RouteList::iterator &route, const TrackIter &track)
{
- if(!is_valid_for_track(**route, track))
+ Track &prev_track = *track.flip();
+ unsigned taddr = (track->get_type().is_turnout() ? track->get_turnout_address() : 0);
+ for(unsigned i=0; route!=routes.end(); ++i)
{
- ++route;
- if(route==routes.end())
- return false;
- if(!is_valid_for_track(**route, track))
+ bool in_route = (*route)->has_track(*track);
+ bool prev_in_route = (*route)->has_track(prev_track);
+ bool known_path = (!taddr || (*route)->get_turnout(taddr)>=0);
+
+ if(in_route && (known_path || !prev_in_route))
+ return true;
+ else if(i==0 || prev_in_route)
+ ++route;
+ else
throw logic_error("internal error (routes are not continuous)");
}
- return true;
+ return false;
}
-void TrainRouter::start_planning(Layout &layout)
+void TrainRouter::get_routers(Layout &layout, vector<TrainRouter *> &routers, TrainRoutePlanner *planner)
{
- vector<TrainRouter *> routers;
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>())
- routers.push_back(router);
+ 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)
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),