5 #include "trackchain.h"
6 #include "trainroutemetric.h"
7 #include "trainrouteplanner.h"
8 #include "trainrouter.h"
15 TrainRouter::TrainRouter(Train &t):
20 destination_changed(false),
23 sequence_check_pending(false)
25 train.get_layout().signal_block_reserved.connect(sigc::mem_fun(this, &TrainRouter::block_reserved));
26 train.signal_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_advanced));
27 train.signal_rear_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_rear_advanced));
30 TrainRouter::~TrainRouter()
32 for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
36 void TrainRouter::set_priority(int p)
41 bool TrainRouter::set_route(const Route *r)
52 sequence_points.clear();
54 sequence_check_pending = false;
61 const Route *TrainRouter::get_route() const
65 return routes.front();
68 void TrainRouter::route_changed()
70 BlockIter fncb = train.get_first_noncritical_block();
72 reserving_route = routes.begin();
73 bool already_at_end = false;
76 /* Find the route that should be used for the next allocated block. We
77 can't rely on the resync code in block_reserved since we may need to
78 clear the stop marker to continue allocation. */
79 TrackIter track = train.get_block_allocator().first().track_iter();
80 list<SequencePoint>::iterator seq_begin = sequence_points.begin();
81 for(; track; track=track.next())
83 if(!advance_to_track(reserving_route, track))
85 already_at_end = true;
88 if(&track->get_block()==fncb.block())
91 if(seq_begin!=sequence_points.end() && seq_begin->block==&track->get_block())
93 current_sequence = seq_begin->sequence_out;
98 sequence_points.erase(sequence_points.begin(), seq_begin);
103 // We are not at the end of the route now, but might have been before.
104 arrival = ON_THE_WAY;
105 train.refresh_blocks_from(*fncb);
111 /* If arrival wasn't set before (perhaps because we weren't on a route),
113 arrival = RESERVED_TO_END;
114 train.stop_at(&*fncb.flip());
115 train.refresh_blocks_from(*fncb);
118 const Route *route = get_route();
119 signal_route_changed.emit(route);
120 signal_event.emit(Message("route-changed", route));
123 void TrainRouter::set_destination(const TrackChain &d)
126 destination_changed = true;
127 metrics_stale = true;
130 void TrainRouter::add_waypoint(const TrackChain &wp)
132 waypoints.push_back(&wp);
133 destination_changed = true;
134 metrics_stale = true;
137 const TrackChain &TrainRouter::get_waypoint(unsigned index) const
139 if(index>=waypoints.size())
140 throw out_of_range("TrainRouter::is_waypoint");
142 return *waypoints[index];
145 const TrainRouteMetric &TrainRouter::get_metric(int index) const
148 throw logic_error("no metrics");
149 else if(metrics_stale)
150 throw logic_error("metrics are stale");
153 return *metrics.front();
154 else if(static_cast<unsigned>(index)>=waypoints.size())
155 throw out_of_range("TrainRouter::get_metric");
157 return *metrics[index+1];
160 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
163 destination_changed = true;
166 void TrainRouter::set_trip_duration(const Time::TimeDelta &d)
171 void TrainRouter::message(const Message &msg)
173 if(msg.type=="set-route")
175 if(msg.value.check_type<Route *>())
176 set_route(msg.value.value<Route *>());
178 set_route(msg.value.value<const Route *>());
180 else if(msg.type=="clear-route")
182 else if(msg.type=="set-destination")
184 if(msg.value.check_type<TrackChain *>())
185 set_destination(*msg.value.value<TrackChain *>());
187 set_destination(*msg.value.value<const TrackChain *>());
189 else if(msg.type=="add-waypoint")
191 if(msg.value.check_type<TrackChain *>())
192 add_waypoint(*msg.value.value<TrackChain *>());
194 add_waypoint(*msg.value.value<const TrackChain *>());
196 else if(msg.type=="set-departure-delay")
197 set_departure_delay(msg.value.value<Time::TimeDelta>());
198 else if(msg.type=="set-trip-duration")
199 set_trip_duration(msg.value.value<Time::TimeDelta>());
202 void TrainRouter::tick(const Time::TimeDelta &dt)
209 duration = max(duration+delay, Time::zero);
214 duration = max(duration-dt, Time::zero);
216 if(destination_changed && !planner)
217 start_planning(train.get_layout());
219 if(planner && planner->check()!=TrainRoutePlanner::PENDING)
221 destination_changed = false;
222 if(planner->get_result()==TrainRoutePlanner::COMPLETE)
224 const list<Route *> &planned_routes = planner->get_routes_for(train);
227 routes.insert(routes.end(), planned_routes.begin(), planned_routes.end());
230 sequence_points = planner->get_sequence_for(train);
231 current_sequence = 0;
232 sequence_check_pending = false;
239 if(sequence_check_pending)
241 if(sequence_points.front().is_cleared())
243 sequence_check_pending = false;
246 if(arrival==RESERVED_TO_END && !train.get_speed())
248 signal_arrived.emit(destination);
249 signal_event.emit(Message("arrived", destination));
252 else if(arrival==ARRIVED && !train.get_block_allocator().is_active())
256 void TrainRouter::save(list<DataFile::Statement> &st) const
258 st.push_back((DataFile::Statement("priority"), priority));
262 RouteList::const_iterator i = routes.begin();
263 for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
265 st.push_back((DataFile::Statement("route"), (*i)->get_name()));
269 void TrainRouter::block_reserved(Block &block, Train *t)
279 // Are we waiting for the other train to pass a sequence point?
280 SequencePoint &sp = sequence_points.front();
281 if(sp.preceding_train==t && sp.block==&block)
282 /* The other train's router will advance its sequence on the same
283 signal and may not have handled it yet. */
284 sequence_check_pending = true;
289 // Did we reach our next sequence point?
290 if(!sequence_points.empty())
292 SequencePoint &sp = sequence_points.front();
295 current_sequence = sp.sequence_out;
296 sequence_points.pop_front();
300 TrackIter track = train.get_block_allocator().iter_for(block).track_iter();
302 // Is the block a turnout? If it is, set it to the correct path.
303 if(unsigned taddr = block.get_turnout_address())
305 int path = (*reserving_route)->get_turnout(taddr);
307 track->set_active_path(path);
310 /* If the allocator has released blocks from the front, we may need to
311 resync reserving_route. */
312 if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
314 reserving_route = routes.begin();
315 arrival = ON_THE_WAY;
316 track = t->get_block_allocator().first().track_iter();
317 for(; track; track=track.next())
319 if(!advance_to_track(reserving_route, track))
320 throw logic_error("internal error (reservation outside of route)");
321 else if(&track->get_block()==&block)
326 /* Keep reserving_route pointing to the route containing the block that is
327 expected to be allocated next. */
328 for(; track; track=track.next((*reserving_route)->get_path(*track)))
330 if(!advance_to_track(reserving_route, track))
332 // We've reached the end of the route. Stop here.
333 arrival = RESERVED_TO_END;
334 train.stop_at(&block);
337 if(&track->get_block()!=&block)
341 // Do we need to wait for another train to pass?
342 if(!sequence_points.empty())
344 SequencePoint &sp = sequence_points.front();
345 if(sp.block==&track->get_block() && !sp.is_cleared())
346 train.stop_at(&block);
350 void TrainRouter::train_advanced(Block &block)
352 BlockIter b_iter = train.get_block_allocator().iter_for(block);
354 if(!waypoints.empty())
356 // A waypoint is considered reached when the train has advanced through it.
357 const TrackChain &wp = *waypoints.front();
358 TrackIter t_iter = b_iter.track_iter();
359 if(wp.has_track(*t_iter))
361 for(; t_iter; t_iter=t_iter.next())
363 if(!wp.has_track(*t_iter))
365 waypoints.erase(waypoints.begin());
366 metrics_stale = true;
367 signal_waypoint_reached.emit(&wp);
368 signal_event.emit(Message("waypoint-reached", &wp));
371 else if(!block.has_track(*t_iter))
378 void TrainRouter::train_rear_advanced(Block &block)
380 Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
382 // Drop any routes that are now completely behind the train.
383 for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
384 if((*i)->has_track(track))
386 if(i!=routes.begin())
388 routes.erase(routes.begin(), i);
389 const Route *route = get_route();
390 signal_route_changed.emit(route);
391 signal_event.emit(Message("route-changed", route));
397 void TrainRouter::create_metrics()
399 for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
403 metrics_stale = false;
408 metrics.push_back(new TrainRouteMetric(*destination));
409 for(vector<const TrackChain *>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
410 metrics.push_back(new TrainRouteMetric(**i));
412 for(unsigned i=metrics.size(); --i>0; )
413 metrics[i]->chain_to(*metrics[(i+1)%metrics.size()]);
416 bool TrainRouter::create_lead_route()
418 if(routes.empty() || !train.is_placed())
421 BlockIter fncb = train.get_first_noncritical_block();
422 TrackIter next_track = fncb.track_iter();
425 for(TrackIter i=next_track.flip(); (i && i->get_block().get_train()==&train); i=i.next())
427 if(routes.front()->has_track(*i))
431 if(count==routes.front()->get_tracks().size())
432 next_track = i.flip();
437 if(!routes.front()->has_track(*next_track) && !routes.front()->has_track(*next_track.flip()))
439 Route *pf = Route::find(next_track, *routes.front());
443 routes.push_front(pf);
447 for(TrackIter i=next_track.flip(); (i && i->get_block().get_train()==&train); i=i.next())
449 if(!lead && !routes.front()->has_track(*i))
451 lead = new Route(train.get_layout());
452 lead->set_name("Lead");
453 lead->set_temporary(true);
454 routes.push_front(lead);
456 TrackIter j = i.flip();
458 lead->add_track(*j.next());
468 bool TrainRouter::is_valid_for_track(const Route &route, const TrackIter &track) const
470 if(!route.has_track(*track))
472 if(track->get_type().is_turnout() && route.get_turnout(track->get_turnout_address())<0 && route.has_track(*track.flip()))
477 bool TrainRouter::advance_to_track(RouteList::iterator &route, const TrackIter &track)
479 if(!is_valid_for_track(**route, track))
482 if(route==routes.end())
484 if(!is_valid_for_track(**route, track))
485 throw logic_error("internal error (routes are not continuous)");
491 void TrainRouter::start_planning(Layout &layout)
493 vector<TrainRouter *> routers;
494 const map<unsigned, Train *> &trains = layout.get_trains();
495 routers.reserve(trains.size());
496 for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
497 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
498 routers.push_back(router);
500 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
501 if((*i)->metrics_stale)
502 (*i)->create_metrics();
504 RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
505 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
506 (*i)->planner = planner;
508 planner->plan_async();
512 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
519 bool TrainRouter::SequencePoint::is_cleared() const
524 TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
525 return router->get_current_sequence()>=sequence_in;
529 TrainRouter::Loader::Loader(TrainRouter &r):
530 DataFile::ObjectLoader<TrainRouter>(r)
532 add("priority", &TrainRouter::priority);
533 add("route", &Loader::route);
536 void TrainRouter::Loader::route(const string &n)
538 obj.set_route(&obj.train.get_layout().get_route(n));