6 #include "trackchain.h"
7 #include "trainroutemetric.h"
8 #include "trainrouteplanner.h"
9 #include "trainrouter.h"
16 TrainRouter::TrainRouter(Train &t):
20 waypoints_changed(false),
24 train.get_layout().signal_block_reserved.connect(sigc::mem_fun(this, &TrainRouter::block_reserved));
25 train.signal_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_advanced));
26 train.signal_rear_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_rear_advanced));
29 TrainRouter::~TrainRouter()
31 for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
35 void TrainRouter::set_priority(int p)
40 bool TrainRouter::set_route(const Route *r)
50 sequence_points.clear();
57 const Route *TrainRouter::get_route() const
61 return routes.front();
64 void TrainRouter::use_planned_route()
66 if(!planner || planner->get_result()!=TrainRoutePlanner::COMPLETE)
71 const list<Route *> &planned_routes = planner->get_routes_for(train);
74 routes.insert(routes.end(), planned_routes.begin(), planned_routes.end());
77 sequence_points = planner->get_sequence_for(train);
83 void TrainRouter::route_changed()
85 BlockIter fncb = train.get_last_critical_block().next();
88 reserving_route = routes.begin();
91 /* Find the route that should be used for the next allocated block. We
92 can't rely on the resync code in block_reserved since we may need to
93 clear the stop marker to continue allocation. */
94 const BlockAllocator &allocator = train.get_block_allocator();
95 TrackIter track = allocator.first().track_iter();
96 list<SequencePoint>::iterator seq_begin = sequence_points.begin();
97 for(; track; track=track.next())
99 if(!advance_to_track(reserving_route, track))
101 state = (allocator.is_block_current(track->get_block()) ? ADVANCED_TO_END : RESERVED_TO_END);
104 if(&track->get_block()==fncb.block())
107 if(seq_begin!=sequence_points.end() && seq_begin->block==&track->get_block())
109 // Assume any sequence points within critical blocks to be cleared
110 current_sequence = seq_begin->sequence_out;
115 sequence_points.erase(sequence_points.begin(), seq_begin);
117 if(!sequence_points.empty())
119 const SequencePoint &sp = sequence_points.front();
120 if(sp.block==fncb.block() && !sp.is_cleared())
121 state = SEQUENCE_CHECK_PENDING;
125 /* Refresh from the first non-critical block to pick up any changes in the
126 route. Set stop marker first in case a stopping state was set within the
128 if(state!=ON_THE_WAY)
129 train.stop_at(&*fncb.flip());
130 train.refresh_blocks_from(*fncb);
131 // If we don't need to stop, clear a possible previous stop marker.
132 if(state==ON_THE_WAY)
135 const Route *route = get_route();
136 signal_route_changed.emit(route);
137 signal_event.emit(Message("route-changed", route));
140 void TrainRouter::set_destination(const TrackChain &d)
142 if(waypoints.empty())
143 waypoints.push_back(Waypoint(d));
145 waypoints.back() = Waypoint(d);
146 waypoints_changed = true;
147 metrics_stale = true;
150 void TrainRouter::add_waypoint(const TrackChain &chain, TrackChain::Direction dir)
152 waypoints.push_back(Waypoint(chain, dir));
153 waypoints_changed = true;
154 metrics_stale = true;
157 const TrainRouter::Waypoint &TrainRouter::get_waypoint(unsigned index) const
159 if(index>=waypoints.size())
160 throw out_of_range("TrainRouter::is_waypoint");
162 return waypoints[index];
165 const TrainRouteMetric &TrainRouter::get_metric(int index) const
167 if(waypoints.empty())
168 throw logic_error("no metrics");
169 else if(metrics_stale)
170 throw logic_error("metrics are stale");
173 return *metrics.back();
174 else if(static_cast<unsigned>(index)>=waypoints.size())
175 throw out_of_range("TrainRouter::get_metric");
177 return *metrics[index];
180 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
183 waypoints_changed = true;
186 void TrainRouter::set_trip_duration(const Time::TimeDelta &d)
191 void TrainRouter::message(const Message &msg)
193 if(msg.type=="set-route")
195 if(msg.value.check_type<Route *>())
196 set_route(msg.value.value<Route *>());
198 set_route(msg.value.value<const Route *>());
200 else if(msg.type=="clear-route")
202 else if(msg.type=="set-destination")
204 if(msg.value.check_type<TrackChain *>())
205 set_destination(*msg.value.value<TrackChain *>());
207 set_destination(*msg.value.value<const TrackChain *>());
209 else if(msg.type=="add-waypoint")
211 if(msg.value.check_type<Waypoint>())
213 Waypoint wp = msg.value.value<Waypoint>();
214 add_waypoint(*wp.chain, wp.direction);
216 else if(msg.value.check_type<TrackChain *>())
217 add_waypoint(*msg.value.value<TrackChain *>());
219 add_waypoint(*msg.value.value<const TrackChain *>());
221 else if(msg.type=="set-departure-delay")
222 set_departure_delay(msg.value.value<Time::TimeDelta>());
223 else if(msg.type=="set-trip-duration")
224 set_trip_duration(msg.value.value<Time::TimeDelta>());
227 void TrainRouter::tick(const Time::TimeDelta &dt)
229 if(waypoints_changed && !planner)
230 start_planning(train.get_layout());
232 if(planner && planner->check()!=TrainRoutePlanner::PENDING)
233 apply_plan(train.get_layout(), *planner);
235 Layout &layout = train.get_layout();
236 if(!layout.get_driver().is_halted() && !layout.get_clock().is_stopped())
243 duration = max(duration+delay, Time::zero);
248 duration = max(duration-dt, Time::zero);
251 if(state==SEQUENCE_CHECK_PENDING)
253 if(sequence_points.front().is_cleared())
259 state = WAITING_FOR_SEQUENCE;
262 if(state==ADVANCED_TO_END && !train.get_speed())
264 signal_arrived.emit(waypoints.back().chain);
265 signal_event.emit(Message("arrived", waypoints.back().chain));
268 else if(state==ARRIVED && !train.get_block_allocator().is_active())
272 void TrainRouter::save(list<DataFile::Statement> &st) const
274 st.push_back((DataFile::Statement("priority"), priority));
278 RouteList::const_iterator i = routes.begin();
279 for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
281 st.push_back((DataFile::Statement("route"), (*i)->get_name()));
285 void TrainRouter::block_reserved(Block &block, Train *t)
295 // Are we waiting for the other train to pass a sequence point?
296 if(state==WAITING_FOR_SEQUENCE)
298 SequencePoint &sp = sequence_points.front();
299 if(sp.preceding_train==t && sp.block==&block)
300 /* The other train's router will advance its sequence on the same
301 signal and may not have handled it yet. */
302 state = SEQUENCE_CHECK_PENDING;
308 // Did we reach our next sequence point?
309 if(!sequence_points.empty())
311 SequencePoint &sp = sequence_points.front();
314 current_sequence = sp.sequence_out;
315 sequence_points.pop_front();
319 TrackIter track = train.get_block_allocator().iter_for(block).track_iter();
321 // Is the block a turnout? If it is, set it to the correct path.
322 if(unsigned taddr = block.get_turnout_address())
324 int path = (*reserving_route)->get_turnout(taddr);
326 track->set_active_path(path);
329 /* If the allocator has released blocks from the front, we may need to
330 resync reserving_route. */
331 if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
333 reserving_route = routes.begin();
335 track = t->get_block_allocator().first().track_iter();
336 for(; track; track=track.next())
338 if(!advance_to_track(reserving_route, track))
339 throw logic_error("internal error (reservation outside of route)");
340 else if(&track->get_block()==&block)
345 /* Keep reserving_route pointing to the route containing the block that is
346 expected to be allocated next. */
347 for(; track; track=track.next((*reserving_route)->get_path(*track)))
349 if(!advance_to_track(reserving_route, track))
351 // We've reached the end of the route. Stop here.
352 state = RESERVED_TO_END;
353 train.stop_at(&block);
356 if(&track->get_block()!=&block)
360 // Do we need to wait for another train to pass?
361 if(!sequence_points.empty())
363 SequencePoint &sp = sequence_points.front();
364 if(sp.block==&track->get_block() && !sp.is_cleared())
366 state = SEQUENCE_CHECK_PENDING;
367 train.stop_at(&block);
372 void TrainRouter::train_advanced(Block &block)
374 if(!waypoints.empty())
376 // A waypoint is considered reached when the train has advanced through it.
377 BlockIter b_iter = train.get_block_allocator().iter_for(block);
378 const Waypoint &wp = waypoints.front();
379 TrackIter t_iter = b_iter.track_iter();
380 if(wp.chain->has_track(*t_iter))
384 TrackIter next = t_iter.next();
388 if(!wp.chain->has_track(*next))
390 if(wp.direction!=TrackChain::UNSPECIFIED)
391 if(t_iter!=wp.chain->iter_for(*t_iter, wp.direction))
394 if(waypoints.size()==1)
396 if(state==RESERVED_TO_END)
397 state = ADVANCED_TO_END;
401 const TrackChain *chain = wp.chain;
402 waypoints.erase(waypoints.begin());
403 metrics_stale = true;
404 signal_waypoint_reached.emit(chain);
405 signal_event.emit(Message("waypoint-reached", chain));
409 else if(!block.has_track(*next))
418 void TrainRouter::train_rear_advanced(Block &block)
420 Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
422 // Drop any routes that are now completely behind the train.
423 for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
424 if((*i)->has_track(track))
426 if(i!=routes.begin())
428 routes.erase(routes.begin(), i);
429 const Route *route = get_route();
430 signal_route_changed.emit(route);
431 signal_event.emit(Message("route-changed", route));
437 void TrainRouter::create_metrics()
439 for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
443 metrics_stale = false;
445 if(waypoints.empty())
448 for(vector<Waypoint>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
449 metrics.push_back(new TrainRouteMetric(*i->chain, i->direction));
451 for(unsigned i=metrics.size()-1; i-->0; )
452 metrics[i]->chain_to(*metrics[i+1]);
455 bool TrainRouter::create_lead_route()
457 if(routes.empty() || !train.is_placed())
460 BlockIter lcb = train.get_last_critical_block();
461 TrackIter last_track_rev = lcb.reverse().track_iter();
464 for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
466 if(routes.front()->has_track(*i))
470 if(count==routes.front()->get_tracks().size())
476 TrackIter next_track = last_track_rev.flip();
477 if(!routes.front()->has_track(*last_track_rev) && !routes.front()->has_track(*next_track))
479 Route *pf = Route::find(next_track, *routes.front());
483 routes.push_front(pf);
487 for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
489 if(!lead && !routes.front()->has_track(*i))
491 lead = new Route(train.get_layout());
492 lead->set_name("Lead");
493 lead->set_temporary(true);
494 routes.push_front(lead);
496 TrackIter j = i.flip();
498 lead->add_track(*j.next());
508 bool TrainRouter::advance_to_track(RouteList::iterator &route, const TrackIter &track)
510 Track &prev_track = *track.flip();
511 unsigned taddr = (track->get_type().is_turnout() ? track->get_turnout_address() : 0);
512 for(unsigned i=0; route!=routes.end(); ++i)
514 bool in_route = (*route)->has_track(*track);
515 bool prev_in_route = (*route)->has_track(prev_track);
516 bool known_path = (!taddr || (*route)->get_turnout(taddr)>=0);
518 if(in_route && (known_path || !prev_in_route))
520 else if(i==0 || prev_in_route)
523 throw logic_error("internal error (routes are not continuous)");
529 void TrainRouter::get_routers(Layout &layout, vector<TrainRouter *> &routers, TrainRoutePlanner *planner)
531 const map<unsigned, Train *> &trains = layout.get_trains();
532 routers.reserve(trains.size());
533 for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
534 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
535 if(!planner || router->planner.get()==planner)
536 routers.push_back(router);
539 void TrainRouter::start_planning(Layout &layout)
541 vector<TrainRouter *> routers;
542 get_routers(layout, routers);
544 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
545 if((*i)->metrics_stale)
546 (*i)->create_metrics();
548 RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
549 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
551 (*i)->waypoints_changed = false;
552 (*i)->planner = planner;
555 planner->plan_async();
558 void TrainRouter::apply_plan(Layout &layout, TrainRoutePlanner &planner)
560 if(planner.get_result()==TrainRoutePlanner::FAILED)
561 layout.emergency(0, "Route planning failed");
563 vector<TrainRouter *> routers;
564 get_routers(layout, routers, &planner);
566 /* Clear sequence counters first to avoid inconsistent state while applying
568 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
569 (*i)->current_sequence = 0;
571 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
573 (*i)->use_planned_route();
579 TrainRouter::Waypoint::Waypoint(const TrackChain &c, TrackChain::Direction d):
585 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
592 bool TrainRouter::SequencePoint::is_cleared() const
597 TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
598 return router->get_current_sequence()>=sequence_in;
602 TrainRouter::Loader::Loader(TrainRouter &r):
603 DataFile::ObjectLoader<TrainRouter>(r)
605 add("priority", &TrainRouter::priority);
606 add("route", &Loader::route);
609 void TrainRouter::Loader::route(const string &n)
611 obj.set_route(&obj.train.get_layout().get_route(n));