5 #include "trackchain.h"
6 #include "trainroutemetric.h"
7 #include "trainrouteplanner.h"
8 #include "trainrouter.h"
15 TrainRouter::TrainRouter(Train &t):
19 waypoints_changed(false),
22 sequence_check_pending(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();
52 sequence_check_pending = false;
59 const Route *TrainRouter::get_route() const
63 return routes.front();
66 void TrainRouter::use_planned_route()
68 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);
79 sequence_check_pending = false;
84 void TrainRouter::route_changed()
86 BlockIter fncb = train.get_first_noncritical_block();
89 reserving_route = routes.begin();
92 /* Find the route that should be used for the next allocated block. We
93 can't rely on the resync code in block_reserved since we may need to
94 clear the stop marker to continue allocation. */
95 TrackIter track = train.get_block_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 arrival = 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())
122 arrival = WAITING_FOR_SEQUENCE;
123 sequence_check_pending = true;
128 /* Refresh from the first non-critical block to pick up any changes in the
129 route. Set stop marker first in case an arrival condition was met within the
132 train.stop_at(&*fncb.flip());
133 train.refresh_blocks_from(*fncb);
134 // If no arrival condition was found, clear a possible previous stop marker.
138 const Route *route = get_route();
139 signal_route_changed.emit(route);
140 signal_event.emit(Message("route-changed", route));
143 void TrainRouter::set_destination(const TrackChain &d)
145 if(waypoints.empty())
146 waypoints.push_back(&d);
148 waypoints.back() = &d;
149 waypoints_changed = true;
150 metrics_stale = true;
153 void TrainRouter::add_waypoint(const TrackChain &wp)
155 waypoints.push_back(&wp);
156 waypoints_changed = true;
157 metrics_stale = true;
160 const TrackChain &TrainRouter::get_waypoint(unsigned index) const
162 if(index>=waypoints.size())
163 throw out_of_range("TrainRouter::is_waypoint");
165 return *waypoints[index];
168 const TrainRouteMetric &TrainRouter::get_metric(int index) const
170 if(waypoints.empty())
171 throw logic_error("no metrics");
172 else if(metrics_stale)
173 throw logic_error("metrics are stale");
176 return *metrics.back();
177 else if(static_cast<unsigned>(index)>=waypoints.size())
178 throw out_of_range("TrainRouter::get_metric");
180 return *metrics[index];
183 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
186 waypoints_changed = true;
189 void TrainRouter::set_trip_duration(const Time::TimeDelta &d)
194 void TrainRouter::message(const Message &msg)
196 if(msg.type=="set-route")
198 if(msg.value.check_type<Route *>())
199 set_route(msg.value.value<Route *>());
201 set_route(msg.value.value<const Route *>());
203 else if(msg.type=="clear-route")
205 else if(msg.type=="set-destination")
207 if(msg.value.check_type<TrackChain *>())
208 set_destination(*msg.value.value<TrackChain *>());
210 set_destination(*msg.value.value<const TrackChain *>());
212 else if(msg.type=="add-waypoint")
214 if(msg.value.check_type<TrackChain *>())
215 add_waypoint(*msg.value.value<TrackChain *>());
217 add_waypoint(*msg.value.value<const TrackChain *>());
219 else if(msg.type=="set-departure-delay")
220 set_departure_delay(msg.value.value<Time::TimeDelta>());
221 else if(msg.type=="set-trip-duration")
222 set_trip_duration(msg.value.value<Time::TimeDelta>());
225 void TrainRouter::tick(const Time::TimeDelta &dt)
232 duration = max(duration+delay, Time::zero);
237 duration = max(duration-dt, Time::zero);
239 if(waypoints_changed && !planner)
240 start_planning(train.get_layout());
242 if(planner && planner->check()!=TrainRoutePlanner::PENDING)
243 apply_plan(train.get_layout(), *planner);
245 if(sequence_check_pending)
247 if(sequence_points.front().is_cleared())
249 arrival = ON_THE_WAY;
252 sequence_check_pending = false;
255 if(arrival==RESERVED_TO_END && !train.get_speed())
257 signal_arrived.emit(waypoints.back());
258 signal_event.emit(Message("arrived", waypoints.back()));
261 else if(arrival==ARRIVED && !train.get_block_allocator().is_active())
265 void TrainRouter::save(list<DataFile::Statement> &st) const
267 st.push_back((DataFile::Statement("priority"), priority));
271 RouteList::const_iterator i = routes.begin();
272 for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
274 st.push_back((DataFile::Statement("route"), (*i)->get_name()));
278 void TrainRouter::block_reserved(Block &block, Train *t)
288 // Are we waiting for the other train to pass a sequence point?
289 SequencePoint &sp = sequence_points.front();
290 if(sp.preceding_train==t && sp.block==&block)
291 /* The other train's router will advance its sequence on the same
292 signal and may not have handled it yet. */
293 sequence_check_pending = true;
298 // Did we reach our next sequence point?
299 if(!sequence_points.empty())
301 SequencePoint &sp = sequence_points.front();
304 current_sequence = sp.sequence_out;
305 sequence_points.pop_front();
309 TrackIter track = train.get_block_allocator().iter_for(block).track_iter();
311 // Is the block a turnout? If it is, set it to the correct path.
312 if(unsigned taddr = block.get_turnout_address())
314 int path = (*reserving_route)->get_turnout(taddr);
316 track->set_active_path(path);
319 /* If the allocator has released blocks from the front, we may need to
320 resync reserving_route. */
321 if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
323 reserving_route = routes.begin();
324 arrival = ON_THE_WAY;
325 track = t->get_block_allocator().first().track_iter();
326 for(; track; track=track.next())
328 if(!advance_to_track(reserving_route, track))
329 throw logic_error("internal error (reservation outside of route)");
330 else if(&track->get_block()==&block)
335 /* Keep reserving_route pointing to the route containing the block that is
336 expected to be allocated next. */
337 for(; track; track=track.next((*reserving_route)->get_path(*track)))
339 if(!advance_to_track(reserving_route, track))
341 // We've reached the end of the route. Stop here.
342 arrival = RESERVED_TO_END;
343 train.stop_at(&block);
346 if(&track->get_block()!=&block)
350 // Do we need to wait for another train to pass?
351 if(!sequence_points.empty())
353 SequencePoint &sp = sequence_points.front();
354 if(sp.block==&track->get_block() && !sp.is_cleared())
356 arrival = WAITING_FOR_SEQUENCE;
357 train.stop_at(&block);
362 void TrainRouter::train_advanced(Block &block)
364 BlockIter b_iter = train.get_block_allocator().iter_for(block);
366 if(waypoints.size()>1)
368 // A waypoint is considered reached when the train has advanced through it.
369 const TrackChain &wp = *waypoints.front();
370 TrackIter t_iter = b_iter.track_iter();
371 if(wp.has_track(*t_iter))
373 for(; t_iter; t_iter=t_iter.next())
375 if(!wp.has_track(*t_iter))
377 waypoints.erase(waypoints.begin());
378 metrics_stale = true;
379 signal_waypoint_reached.emit(&wp);
380 signal_event.emit(Message("waypoint-reached", &wp));
383 else if(!block.has_track(*t_iter))
390 void TrainRouter::train_rear_advanced(Block &block)
392 Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
394 // Drop any routes that are now completely behind the train.
395 for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
396 if((*i)->has_track(track))
398 if(i!=routes.begin())
400 routes.erase(routes.begin(), i);
401 const Route *route = get_route();
402 signal_route_changed.emit(route);
403 signal_event.emit(Message("route-changed", route));
409 void TrainRouter::create_metrics()
411 for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
415 metrics_stale = false;
417 if(waypoints.empty())
420 for(vector<const TrackChain *>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
421 metrics.push_back(new TrainRouteMetric(**i));
423 for(unsigned i=metrics.size()-1; i-->0; )
424 metrics[i]->chain_to(*metrics[i+1]);
427 bool TrainRouter::create_lead_route()
429 if(routes.empty() || !train.is_placed())
432 BlockIter fncb = train.get_first_noncritical_block();
433 TrackIter next_track = fncb.track_iter();
436 for(TrackIter i=next_track.flip(); (i && i->get_block().get_train()==&train); i=i.next())
438 if(routes.front()->has_track(*i))
442 if(count==routes.front()->get_tracks().size())
443 next_track = i.flip();
448 if(!routes.front()->has_track(*next_track) && !routes.front()->has_track(*next_track.flip()))
450 Route *pf = Route::find(next_track, *routes.front());
454 routes.push_front(pf);
458 for(TrackIter i=next_track.flip(); (i && i->get_block().get_train()==&train); i=i.next())
460 if(!lead && !routes.front()->has_track(*i))
462 lead = new Route(train.get_layout());
463 lead->set_name("Lead");
464 lead->set_temporary(true);
465 routes.push_front(lead);
467 TrackIter j = i.flip();
469 lead->add_track(*j.next());
479 bool TrainRouter::is_valid_for_track(const Route &route, const TrackIter &track) const
481 if(!route.has_track(*track))
483 if(track->get_type().is_turnout() && route.get_turnout(track->get_turnout_address())<0 && route.has_track(*track.flip()))
488 bool TrainRouter::advance_to_track(RouteList::iterator &route, const TrackIter &track)
490 if(!is_valid_for_track(**route, track))
493 if(route==routes.end())
495 if(!is_valid_for_track(**route, track))
496 throw logic_error("internal error (routes are not continuous)");
502 void TrainRouter::get_routers(Layout &layout, vector<TrainRouter *> &routers)
504 const map<unsigned, Train *> &trains = layout.get_trains();
505 routers.reserve(trains.size());
506 for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
507 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
508 routers.push_back(router);
511 void TrainRouter::start_planning(Layout &layout)
513 vector<TrainRouter *> routers;
514 get_routers(layout, routers);
516 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
517 if((*i)->metrics_stale)
518 (*i)->create_metrics();
520 RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
521 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
523 (*i)->waypoints_changed = false;
524 (*i)->planner = planner;
527 planner->plan_async();
530 void TrainRouter::apply_plan(Layout &layout, TrainRoutePlanner &planner)
532 vector<TrainRouter *> routers;
533 get_routers(layout, routers);
535 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
536 if((*i)->planner.get()==&planner)
538 (*i)->use_planned_route();
544 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
551 bool TrainRouter::SequencePoint::is_cleared() const
556 TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
557 return router->get_current_sequence()>=sequence_in;
561 TrainRouter::Loader::Loader(TrainRouter &r):
562 DataFile::ObjectLoader<TrainRouter>(r)
564 add("priority", &TrainRouter::priority);
565 add("route", &Loader::route);
568 void TrainRouter::Loader::route(const string &n)
570 obj.set_route(&obj.train.get_layout().get_route(n));