1 #include <msp/core/maputils.h>
2 #include <msp/time/utils.h>
7 #include "trainroutemetric.h"
8 #include "trainrouteplanner.h"
9 #include "trainrouter.h"
17 TrainRoutePlanner::TrainRoutePlanner(Layout &layout):
19 path_switch_bias(15*Time::sec),
20 timeout(10*Time::sec),
24 const map<unsigned, Train *> &trains = layout.get_trains();
25 for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
27 TrainRoutingInfo info(*i->second);
28 if(!info.waypoints.empty())
29 routed_trains.push_back(info);
33 TrainRoutePlanner::~TrainRoutePlanner()
42 void TrainRoutePlanner::set_timeout(const Time::TimeDelta &t)
47 TrainRoutePlanner::Result TrainRoutePlanner::plan()
57 void TrainRoutePlanner::plan_async()
60 throw logic_error("already planning");
63 thread = new PlanningThread(*this);
66 TrainRoutePlanner::Result TrainRoutePlanner::check()
68 if(result==PENDING && goal)
82 const list<Route *> &TrainRoutePlanner::get_routes_for(const Train &train) const
84 return get_train_info(train).routes;
87 const list<TrainRouter::SequencePoint> &TrainRoutePlanner::get_sequence_for(const Train &train) const
89 return get_train_info(train).sequence;
92 const TrainRoutePlanner::TrainRoutingInfo &TrainRoutePlanner::get_train_info(const Train &train) const
94 for(vector<TrainRoutingInfo>::const_iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
98 throw key_error(train.get_name());
101 const TrainRoutePlanner::RoutingStep &TrainRoutePlanner::get_step()
103 steps.splice(steps.end(), queue, queue.begin());
107 void TrainRoutePlanner::prepare_plan()
114 queue.push_back(RoutingStep());
115 RoutingStep &start = queue.back();
116 for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
117 start.trains.push_back(TrainRoutingState(*i));
118 start.update_estimate();
121 void TrainRoutePlanner::create_plan()
123 Time::TimeStamp timeout_stamp = Time::now()+timeout;
125 while(!queue.empty())
127 const RoutingStep &step = get_step();
138 if(Time::now()>timeout_stamp)
147 void TrainRoutePlanner::add_steps(const RoutingStep &step)
149 list<RoutingStep> new_steps;
150 step.create_successors(new_steps);
151 if(new_steps.empty())
155 if(!queue.empty() && new_steps.front().cost_estimate<queue.front().cost_estimate+path_switch_bias)
156 new_steps.front().preferred = true;
157 queue.merge(new_steps);
160 void TrainRoutePlanner::finalize_plan()
162 for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
166 for(unsigned j=0; j<2; ++j)
167 i->track_history[j] = 0;
170 map<Track *, TrainRouter::SequencePoint *> sequenced_tracks;
171 unsigned sequence = steps.size();
172 for(const RoutingStep *i=goal; i; i=i->prev)
173 for(vector<TrainRoutingState>::const_iterator j=i->trains.begin(); j!=i->trains.end(); ++j)
175 Track **history = j->info->track_history;
176 // Don't process the same track again.
177 if(j->track.track()==history[0])
181 bool start_new_route = true;
182 if(!j->info->routes.empty())
184 /* If we already have a route and this track or any linked track is
185 in it, start a new one to avoid loops. */
186 route = j->info->routes.front();
187 start_new_route = route->has_track(*j->track);
190 unsigned nls = j->track->get_n_link_slots();
191 for(unsigned k=0; (!start_new_route && k<nls); ++k)
193 Track *link = j->track->get_link(k);
194 start_new_route = (link && link!=history[0] && route->has_track(*link));
201 route = new Route(j->info->train->get_layout());
202 route->set_name("Router");
203 route->set_temporary(true);
204 /* Have the routes overlap by two tracks to ensure that turnout
205 paths can be deduced. */
206 for(unsigned k=0; (k<2 && history[k]); ++k)
207 route->add_track(*history[k]);
208 j->info->routes.push_front(route);
211 route->add_track(*j->track.track());
212 history[1] = history[0];
213 history[0] = j->track.track();
215 bool waitable = j->track.endpoint().paths!=j->track->get_type().get_paths();
216 map<Track *, TrainRouter::SequencePoint *>::iterator k = sequenced_tracks.find(j->track.track());
217 if(k!=sequenced_tracks.end())
219 // Add a sequence point if another train uses this track afterwards.
220 if(!k->second->preceding_train)
222 k->second->preceding_train = j->info->train;
223 k->second->sequence_in = sequence;
225 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
227 k->second = &j->info->sequence.front();
232 /* Create a sequence point if it's possible to wait and let another
234 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
235 sequenced_tracks[j->track.track()] = &j->info->sequence.front();
244 TrainRoutePlanner::TrainRoutingInfo::TrainRoutingInfo(Train &t):
247 speed(train->get_maximum_speed()),
248 first_noncritical(train->get_last_critical_block().next().block()),
249 router(train->get_ai_of_type<TrainRouter>()),
252 if(unsigned n_wps = router->get_n_waypoints())
254 waypoints.reserve(n_wps),
255 metrics.reserve(n_wps);
256 for(unsigned i=0; i<n_wps; ++i)
258 waypoints.push_back(router->get_waypoint(i));
259 metrics.push_back(&router->get_metric(i));
261 has_duration = router->get_trip_duration();
264 unsigned n_vehs = train->get_n_vehicles();
265 for(unsigned i=0; i<n_vehs; ++i)
266 length += train->get_vehicle(i).get_type().get_length();
268 // If no maximum speed is specified, use a sensible default
270 speed = 20*train->get_layout().get_catalogue().get_scale();
274 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(Track &t, unsigned p, OccupiedTrack *n):
276 path_length(track->get_type().get_path_length(p)),
278 n_tracks(next ? next->n_tracks+1 : 1),
285 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(const OccupiedTrack &other):
287 path_length(other.path_length),
289 n_tracks(other.n_tracks),
296 TrainRoutePlanner::OccupiedTrack::~OccupiedTrack()
298 if(next && !--next->refcount)
303 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(TrainRoutingInfo &inf):
308 delay(info->router->get_departure_delay()),
309 duration(info->router->get_trip_duration()),
313 const Vehicle *veh = &info->train->get_vehicle(0);
315 TrackOffsetIter track_and_offs = veh->get_placement().get_position(VehiclePlacement::FRONT_BUFFER);
316 track = track_and_offs.track_iter();
317 offset = track_and_offs.offset();
318 path = track->get_active_path();
320 while(Vehicle *next = veh->get_link(1))
322 track_and_offs = veh->get_placement().get_position(VehiclePlacement::BACK_BUFFER);
323 back_offset = track_and_offs.offset();
325 TrackIter iter = track_and_offs.track_iter();
328 occupied_tracks = new OccupiedTrack(*iter, iter->get_active_path(), occupied_tracks);
329 if(iter.track()==track.track())
334 travel_multiplier = info->metrics[waypoint]->get_travel_multiplier(*track, track.reverse(path).entry());
339 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(const TrainRoutingState &other):
343 critical(other.critical),
344 occupied_tracks(other.occupied_tracks),
345 offset(other.offset),
346 back_offset(other.back_offset),
349 duration(other.duration),
350 waypoint(other.waypoint),
351 travel_multiplier(other.travel_multiplier),
352 distance_traveled(other.distance_traveled),
353 remaining_estimate(other.remaining_estimate),
354 wait_time(other.wait_time),
355 estimated_wait(other.estimated_wait),
356 blocked_by(other.blocked_by)
358 ++occupied_tracks->refcount;
361 TrainRoutePlanner::TrainRoutingState::~TrainRoutingState()
363 if(occupied_tracks && !--occupied_tracks->refcount)
364 delete occupied_tracks;
367 Time::TimeDelta TrainRoutePlanner::TrainRoutingState::get_time_to_next_track() const
369 return ((occupied_tracks->path_length-offset)/info->speed)*Time::sec+delay;
372 Time::TimeDelta TrainRoutePlanner::TrainRoutingState::get_time_to_pass(Track &trk) const
374 if(is_occupying(trk))
376 float passed_length = 0;
377 for(const OccupiedTrack *occ=occupied_tracks; (occ && occ->track!=&trk); occ=occ->next)
378 passed_length += occ->path_length;
379 return (max(info->length-passed_length, 0.0f)/info->speed)*Time::sec+delay;
382 for(unsigned wp=waypoint; wp<info->waypoints.size(); ++wp)
384 float distance = info->metrics[wp]->get_distance_from(trk);
385 if(distance>=0 && distance<remaining_estimate)
386 return ((remaining_estimate-distance+info->length)/info->speed)*Time::sec+delay;
392 bool TrainRoutePlanner::TrainRoutingState::is_occupying(Track &trk) const
394 if(state==ARRIVED && !duration && info->has_duration)
397 OccupiedTrack *occ = occupied_tracks;
398 for(unsigned n=occ->n_tracks; n>0; --n, occ=occ->next)
404 bool TrainRoutePlanner::TrainRoutingState::check_arrival()
406 TrackIter next_track = track.next(path);
408 // Check if we're about the exit the current waypoint's tracks.
409 const TrainRouter::Waypoint &wp = info->waypoints[waypoint];
410 if(wp.chain->has_track(*track) && !wp.chain->has_track(*next_track))
411 if(wp.direction==TrackChain::UNSPECIFIED || track==wp.chain->iter_for(*track, wp.direction))
413 if(waypoint+1<info->waypoints.size())
422 // If we're entering the first non-critical block, clear the critical flag.
423 if(info->first_noncritical->has_track(*next_track))
429 void TrainRoutePlanner::TrainRoutingState::advance(float distance)
432 back_offset += distance;
434 // See if the tail end of the train has passed any sensors.
435 unsigned count_to_free = 0;
436 unsigned last_sensor_addr = 0;
437 float distance_after_sensor = 0;
438 OccupiedTrack *occ = occupied_tracks;
439 for(unsigned n=occupied_tracks->n_tracks; n>0; --n)
441 if(unsigned saddr = occ->track->get_sensor_address())
443 if(saddr!=last_sensor_addr)
446 distance_after_sensor = 0;
448 last_sensor_addr = saddr;
452 distance_after_sensor += occ->path_length;
457 // Free the last passed sensor and any tracks behind it.
458 if(count_to_free && back_offset>distance_after_sensor)
460 back_offset -= distance_after_sensor;
461 if(occupied_tracks->refcount>1)
463 --occupied_tracks->refcount;
464 occupied_tracks = new OccupiedTrack(*occupied_tracks);
466 occupied_tracks->n_tracks -= count_to_free;
469 distance_traveled += distance*travel_multiplier;
470 remaining_estimate -= distance*travel_multiplier;
473 void TrainRoutePlanner::TrainRoutingState::advance(const Time::TimeDelta &dt)
481 float secs = dt/Time::sec;
482 // There may be negative delay remaining after previous step.
485 secs -= delay/Time::sec;
490 duration = max(duration-secs*Time::sec, Time::zero);
493 estimated_wait = max(estimated_wait-secs*Time::sec, Time::zero);
496 advance(info->speed*secs);
497 else if(state!=ARRIVED)
498 wait_time += secs*Time::sec;
501 void TrainRoutePlanner::TrainRoutingState::advance_track(unsigned next_path)
503 float distance = occupied_tracks->path_length-offset;
505 track = track.next(path);
507 occupied_tracks = new OccupiedTrack(*track, path, occupied_tracks);
511 travel_multiplier = info->metrics[waypoint]->get_travel_multiplier(*track, track.reverse(path).entry());
514 void TrainRoutePlanner::TrainRoutingState::set_path(unsigned p)
517 OccupiedTrack *next_occ = occupied_tracks->next;
518 if(!--occupied_tracks->refcount)
519 delete occupied_tracks;
520 occupied_tracks = new OccupiedTrack(*track, path, next_occ);
524 void TrainRoutePlanner::TrainRoutingState::update_estimate()
526 TrackIter iter = track.reverse(path);
527 const TrainRouteMetric *metric = info->metrics[waypoint];
528 remaining_estimate = metric->get_distance_from(*iter, iter.entry());
529 travel_multiplier = metric->get_travel_multiplier(*iter, iter.entry());
530 if(remaining_estimate>=0)
531 remaining_estimate += (occupied_tracks->path_length-offset)*travel_multiplier;
534 bool TrainRoutePlanner::TrainRoutingState::is_viable() const
536 if(remaining_estimate<0)
538 if(critical && state==BLOCKED)
544 TrainRoutePlanner::RoutingStep::RoutingStep():
549 TrainRoutePlanner::RoutingStep::RoutingStep(const RoutingStep *p):
551 cost_estimate(p->cost_estimate),
557 void TrainRoutePlanner::RoutingStep::create_successors(list<RoutingStep> &new_steps) const
559 RoutingStep next(this);
560 if(next.update_states() && next.check_deadlocks())
563 int train_index = find_next_train();
567 TrainRoutingState &train = next.trains[train_index];
569 Time::TimeDelta dt = train.get_time_to_next_track();
572 /* Check arrival after the train has advanced to the end of its current track
573 so travel time and occupied tracks will be correct. */
574 if(train.check_arrival())
576 new_steps.push_back(next);
580 train.advance_track(0);
582 const TrackType::Endpoint &entry_ep = train.track.endpoint();
585 /* Only create a successor step matching the currently set path for a
587 unsigned critical_path = train.track->get_type().coerce_path(train.track.entry(), train.track->get_active_path());
588 create_successor(next, train_index, critical_path, new_steps);
592 // Create successor steps for all possible paths through the new track.
593 for(unsigned i=0; entry_ep.paths>>i; ++i)
594 if(entry_ep.has_path(i))
595 create_successor(next, train_index, i, new_steps);
598 if(entry_ep.paths!=train.track->get_type().get_paths() && !train.critical)
600 /* Create a waiting state before the track if there's at least one path
601 that doesn't pass through the entry endpoint. */
602 RoutingStep wait(this);
604 wait.trains[train_index].state = WAITING;
606 Time::TimeDelta estimated_wait = Time::day;
607 for(unsigned i=0; i<wait.trains.size(); ++i)
608 if(i!=static_cast<unsigned>(train_index) && wait.trains[i].state!=ARRIVED)
610 Time::TimeDelta ttp = wait.trains[i].get_time_to_pass(*train.track);
611 estimated_wait = min(estimated_wait, ttp);
613 wait.trains[train_index].estimated_wait = estimated_wait;
615 wait.update_estimate();
617 new_steps.push_back(wait);
621 void TrainRoutePlanner::RoutingStep::create_successor(RoutingStep &next, unsigned train_index, unsigned path, list<RoutingStep> &new_steps)
623 TrainRoutingState &train = next.trains[train_index];
625 train.set_path(path);
626 next.update_estimate();
628 new_steps.push_back(next);
631 bool TrainRoutePlanner::RoutingStep::update_states()
633 bool changes = false;
634 for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
636 if(i->state==ARRIVED)
639 TrainState old_state = i->state;
641 TrackIter next_track = i->track.next(i->path);
644 i->blocked_by = get_occupant(*next_track);
647 /* If the train is still traversing its last critical track, the
648 flag needs to be cleared here to pass viability test. */
649 if(i->info->first_noncritical->has_track(*next_track))
652 if(i->state!=BLOCKED)
653 i->estimated_wait = trains[i->blocked_by].get_time_to_pass(*next_track);
655 /* Trains in the WAITING state will also transition to BLOCKED and
656 then to MOVING when the other train has passed. */
659 else if(i->state==BLOCKED)
661 i->estimated_wait = Time::zero;
668 if(i->state!=old_state)
675 bool TrainRoutePlanner::RoutingStep::check_deadlocks() const
677 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
679 if(i->state!=BLOCKED)
682 // A train blocked by end of track is always considered a deadlock.
686 /* Use the tortoise and hare algorithm to check if trains are blocked
687 cyclically (A blocks B, which blocks ..., which blocks A). */
688 int slow = i->blocked_by;
689 int fast = trains[slow].blocked_by;
690 while(fast>=0 && trains[fast].blocked_by>=0)
695 slow = trains[slow].blocked_by;
696 fast = trains[trains[fast].blocked_by].blocked_by;
703 int TrainRoutePlanner::RoutingStep::get_occupant(Track &track) const
705 for(unsigned i=0; i<trains.size(); ++i)
706 if(trains[i].is_occupying(track))
712 int TrainRoutePlanner::RoutingStep::find_next_train() const
714 Time::TimeDelta min_dt;
716 for(unsigned i=0; i<trains.size(); ++i)
717 if(trains[i].state==MOVING)
719 Time::TimeDelta dt = trains[i].get_time_to_next_track();
720 if(dt<min_dt || next_train<0)
730 void TrainRoutePlanner::RoutingStep::advance(const Time::TimeDelta &dt)
733 for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
737 void TrainRoutePlanner::RoutingStep::update_estimate()
739 cost_estimate = Time::zero;
740 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
741 if(i->remaining_estimate>=0)
742 cost_estimate += i->wait_time+i->estimated_wait+((i->distance_traveled+i->remaining_estimate)/i->info->speed)*Time::sec;
745 bool TrainRoutePlanner::RoutingStep::is_viable() const
747 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
751 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
758 bool TrainRoutePlanner::RoutingStep::is_goal() const
760 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
761 if(i->state!=ARRIVED)
766 bool TrainRoutePlanner::RoutingStep::operator<(const RoutingStep &other) const
768 if(preferred!=other.preferred)
769 return preferred>other.preferred;
770 return cost_estimate<other.cost_estimate;
774 TrainRoutePlanner::PlanningThread::PlanningThread(TrainRoutePlanner &p):
780 void TrainRoutePlanner::PlanningThread::main()
782 planner.create_plan();