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)
43 BlockIter fncb = train.get_first_noncritical_block();
46 if(r && train.is_placed())
48 const BlockAllocator &allocator = train.get_block_allocator();
49 TrackIter first = allocator.first().track_iter();
50 TrackIter next = fncb.track_iter();
51 if(!r->has_track(*next))
53 lead = Route::find(next, *r);
56 create_lead_route(lead, lead);
58 else if(!r->has_track(*first))
59 lead = create_lead_route(0, r);
64 routes.push_back(lead);
70 sequence_points.clear();
72 sequence_check_pending = false;
79 const Route *TrainRouter::get_route() const
83 return routes.front();
86 void TrainRouter::route_changed()
88 BlockIter fncb = train.get_first_noncritical_block();
90 reserving_route = routes.begin();
91 bool already_at_end = false;
94 /* Find the route that should be used for the next allocated block. We
95 can't rely on the resync code in block_reserved since we may need to
96 clear the stop marker to continue allocation. */
97 TrackIter track = train.get_block_allocator().first().track_iter();
98 for(; track; track=track.next())
100 if(!advance_to_track(reserving_route, *track))
102 already_at_end = true;
105 if(&track->get_block()==fncb.block())
112 // We are not at the end of the route now, but might have been before.
113 arrival = ON_THE_WAY;
115 train.refresh_blocks_from(*fncb);
119 /* If arrival wasn't set before (perhaps because we weren't on a route),
121 arrival = RESERVED_TO_END;
122 train.stop_at(&*fncb.flip());
123 train.refresh_blocks_from(*fncb);
126 const Route *route = get_route();
127 signal_route_changed.emit(route);
128 signal_event.emit(Message("route-changed", route));
131 void TrainRouter::set_destination(const TrackChain &d)
134 destination_changed = true;
135 metrics_stale = true;
138 bool TrainRouter::is_destination(Track &track) const
141 return destination->has_track(track);
146 void TrainRouter::add_waypoint(const TrackChain &wp)
148 waypoints.push_back(&wp);
149 destination_changed = true;
150 metrics_stale = true;
153 bool TrainRouter::is_waypoint(unsigned index, Track &track) const
155 if(index>=waypoints.size())
156 throw out_of_range("TrainRouter::is_waypoint");
158 return waypoints[index]->has_track(track);
161 const TrainRouteMetric &TrainRouter::get_metric(int index) const
164 throw logic_error("no metrics");
165 else if(metrics_stale)
166 throw logic_error("metrics are stale");
169 return *metrics.front();
170 else if(static_cast<unsigned>(index)>=waypoints.size())
171 throw out_of_range("TrainRouter::get_metric");
173 return *metrics[index+1];
176 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
179 destination_changed = true;
182 void TrainRouter::message(const Message &msg)
184 if(msg.type=="set-route")
186 if(msg.value.check_type<Route *>())
187 set_route(msg.value.value<Route *>());
189 set_route(msg.value.value<const Route *>());
191 else if(msg.type=="clear-route")
193 else if(msg.type=="set-destination")
195 if(msg.value.check_type<TrackChain *>())
196 set_destination(*msg.value.value<TrackChain *>());
198 set_destination(*msg.value.value<const TrackChain *>());
200 else if(msg.type=="add-waypoint")
202 if(msg.value.check_type<TrackChain *>())
203 add_waypoint(*msg.value.value<TrackChain *>());
205 add_waypoint(*msg.value.value<const TrackChain *>());
207 else if(msg.type=="set-departure-delay")
208 set_departure_delay(msg.value.value<Time::TimeDelta>());
211 void TrainRouter::tick(const Time::TimeDelta &dt)
216 if(delay<=Time::zero)
220 if(destination_changed)
223 start_planning(train.get_layout());
224 else if(planner->get_result()!=TrainRoutePlanner::PENDING)
226 destination_changed = false;
227 if(planner->get_result()==TrainRoutePlanner::COMPLETE)
229 const list<Route *> &planned_routes = planner->get_routes_for(train);
231 routes.push_back(create_lead_route(0, planned_routes.front()));
232 routes.insert(routes.end(), planned_routes.begin(), planned_routes.end());
233 sequence_points = planner->get_sequence_for(train);
234 current_sequence = 0;
235 sequence_check_pending = false;
243 if(sequence_check_pending)
245 if(sequence_points.front().is_cleared())
247 sequence_check_pending = false;
250 if(arrival==RESERVED_TO_END && !train.get_speed())
252 signal_arrived.emit(destination);
253 signal_event.emit(Message("arrived", destination));
256 else if(arrival==ARRIVED && !train.get_block_allocator().is_active())
260 void TrainRouter::save(list<DataFile::Statement> &st) const
262 st.push_back((DataFile::Statement("priority"), priority));
266 RouteList::const_iterator i = routes.begin();
267 for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
269 st.push_back((DataFile::Statement("route"), (*i)->get_name()));
273 void TrainRouter::block_reserved(Block &block, Train *t)
283 // Are we waiting for the other train to pass a sequence point?
284 SequencePoint &sp = sequence_points.front();
285 if(sp.preceding_train==t && sp.block==&block)
286 /* The other train's router will advance its sequence on the same
287 signal and may not have handled it yet. */
288 sequence_check_pending = true;
293 // Did we reach our next sequence point?
294 if(!sequence_points.empty())
296 SequencePoint &sp = sequence_points.front();
299 current_sequence = sp.sequence_out;
300 sequence_points.pop_front();
304 TrackIter track = train.get_block_allocator().iter_for(block).track_iter();
306 // Is the block a turnout? If it is, set it to the correct path.
307 if(unsigned taddr = block.get_turnout_address())
309 int path = (*reserving_route)->get_turnout(taddr);
311 track->set_active_path(path);
314 /* If the allocator has released blocks from the front, we may need to
315 resync reserving_route. */
316 if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
318 reserving_route = routes.begin();
319 arrival = ON_THE_WAY;
320 track = t->get_block_allocator().first().track_iter();
321 for(; track; track=track.next())
323 if(!advance_to_track(reserving_route, *track))
324 throw logic_error("internal error (reservation outside of route)");
325 else if(&track->get_block()==&block)
330 /* Keep reserving_route pointing to the route containing the block that is
331 expected to be allocated next. */
332 for(; track; track=track.next((*reserving_route)->get_path(*track)))
334 if(!advance_to_track(reserving_route, *track))
336 // We've reached the end of the route. Stop here.
337 arrival = RESERVED_TO_END;
338 train.stop_at(&block);
341 if(&track->get_block()!=&block)
345 // Do we need to wait for another train to pass?
346 if(!sequence_points.empty())
348 SequencePoint &sp = sequence_points.front();
349 if(sp.block==&track->get_block() && !sp.is_cleared())
350 train.stop_at(&block);
354 void TrainRouter::train_advanced(Block &block)
356 BlockIter b_iter = train.get_block_allocator().iter_for(block);
358 if(!waypoints.empty())
360 // A waypoint is considered reached when the train has advanced through it.
361 const TrackChain &wp = *waypoints.front();
362 TrackIter t_iter = b_iter.track_iter();
363 if(wp.has_track(*t_iter))
365 for(; t_iter; t_iter=t_iter.next())
367 if(!wp.has_track(*t_iter))
369 waypoints.erase(waypoints.begin());
370 signal_waypoint_reached.emit(&wp);
371 signal_event.emit(Message("waypoint-reached", &wp));
374 else if(!block.has_track(*t_iter))
381 void TrainRouter::train_rear_advanced(Block &block)
383 Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
385 // Drop any routes that are now completely behind the train.
386 for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
387 if((*i)->has_track(track))
389 if(i!=routes.begin())
391 routes.erase(routes.begin(), i);
392 const Route *route = get_route();
393 signal_route_changed.emit(route);
394 signal_event.emit(Message("route-changed", route));
400 void TrainRouter::create_metrics()
402 for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
409 metrics.push_back(new TrainRouteMetric(*destination));
410 for(vector<const TrackChain *>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
411 metrics.push_back(new TrainRouteMetric(**i));
413 for(unsigned i=metrics.size(); --i>0; )
414 metrics[i]->chain_to(*metrics[(i+1)%metrics.size()]);
417 Route *TrainRouter::create_lead_route(Route *lead, const Route *target)
421 lead = new Route(train.get_layout());
422 lead->set_name("Lead");
423 lead->set_temporary(true);
426 bool target_reached = false;
427 for(TrackIter i=train.get_block_allocator().first().track_iter(); i; i=i.next())
429 if(i->get_block().get_train()!=&train)
433 if(target->has_track(*i))
434 target_reached = true;
435 else if(target_reached)
444 bool TrainRouter::is_valid_for_track(const Route &route, Track &track) const
446 if(!route.has_track(track))
448 if(track.get_type().is_turnout() && route.get_turnout(track.get_turnout_address())<0)
453 bool TrainRouter::advance_to_track(RouteList::iterator &route, Track &track)
455 if(!is_valid_for_track(**route, track))
458 if(route==routes.end())
460 if(!is_valid_for_track(**route, track))
461 throw logic_error("internal error (routes are not continuous)");
467 void TrainRouter::start_planning(Layout &layout)
469 RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
471 const map<unsigned, Train *> &trains = layout.get_trains();
472 for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
473 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
475 if(router->metrics_stale)
477 router->create_metrics();
478 router->metrics_stale = false;
480 router->planner = planner;
487 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
494 bool TrainRouter::SequencePoint::is_cleared() const
499 TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
500 return router->get_current_sequence()>=sequence_in;
504 TrainRouter::Loader::Loader(TrainRouter &r):
505 DataFile::ObjectLoader<TrainRouter>(r)
507 add("priority", &TrainRouter::priority);
508 add("route", &Loader::route);
511 void TrainRouter::Loader::route(const string &n)
513 obj.set_route(&obj.train.get_layout().get_route(n));