1 #include <msp/core/maputils.h>
6 #include "trainroutemetric.h"
7 #include "trainrouteplanner.h"
8 #include "trainrouter.h"
16 TrainRoutePlanner::TrainRoutePlanner(Layout &layout):
21 const map<unsigned, Train *> &trains = layout.get_trains();
22 for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
24 TrainRoutingInfo info(*i->second);
26 routed_trains.push_back(info);
30 TrainRoutePlanner::~TrainRoutePlanner()
39 TrainRoutePlanner::Result TrainRoutePlanner::plan()
49 void TrainRoutePlanner::plan_async()
52 throw logic_error("already planning");
55 thread = new PlanningThread(*this);
58 TrainRoutePlanner::Result TrainRoutePlanner::check()
60 if(result==PENDING && goal)
74 const list<Route *> &TrainRoutePlanner::get_routes_for(const Train &train) const
76 return get_train_info(train).routes;
79 const list<TrainRouter::SequencePoint> &TrainRoutePlanner::get_sequence_for(const Train &train) const
81 return get_train_info(train).sequence;
84 const TrainRoutePlanner::TrainRoutingInfo &TrainRoutePlanner::get_train_info(const Train &train) const
86 for(vector<TrainRoutingInfo>::const_iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
90 throw key_error(train.get_name());
93 const TrainRoutePlanner::RoutingStep &TrainRoutePlanner::get_step()
95 steps.splice(steps.end(), queue, queue.begin());
99 void TrainRoutePlanner::prepare_plan()
106 queue.push_back(RoutingStep());
107 RoutingStep &start = queue.back();
108 for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
109 start.trains.push_back(TrainRoutingState(*i));
110 start.update_estimate();
113 void TrainRoutePlanner::create_plan()
115 while(!queue.empty())
117 const RoutingStep &step = get_step();
130 void TrainRoutePlanner::add_steps(const RoutingStep &step)
132 list<RoutingStep> new_steps;
133 step.create_successors(new_steps);
135 queue.merge(new_steps);
138 void TrainRoutePlanner::finalize_plan()
140 for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
144 for(unsigned j=0; j<2; ++j)
145 i->track_history[j] = 0;
148 map<Track *, TrainRouter::SequencePoint *> sequenced_tracks;
149 unsigned sequence = steps.size();
150 for(const RoutingStep *i=goal; i; i=i->prev)
151 for(vector<TrainRoutingState>::const_iterator j=i->trains.begin(); j!=i->trains.end(); ++j)
153 Track **history = j->info->track_history;
154 if(j->track.track()==history[0])
158 bool start_new_route = true;
159 if(!j->info->routes.empty())
161 route = j->info->routes.front();
162 start_new_route = route->has_track(*j->track);
165 unsigned nls = j->track->get_n_link_slots();
166 for(unsigned k=0; (!start_new_route && k<nls); ++k)
168 Track *link = j->track->get_link(k);
169 start_new_route = (link && link!=history[0] && route->has_track(*link));
176 route = new Route(j->info->train->get_layout());
177 route->set_name("Router");
178 route->set_temporary(true);
179 for(unsigned k=0; (k<2 && history[k]); ++k)
180 route->add_track(*history[k]);
181 j->info->routes.push_front(route);
184 route->add_track(*j->track.track());
185 history[1] = history[0];
186 history[0] = j->track.track();
188 bool waitable = j->track.endpoint().paths!=j->track->get_type().get_paths();
189 map<Track *, TrainRouter::SequencePoint *>::iterator k = sequenced_tracks.find(j->track.track());
190 if(k!=sequenced_tracks.end())
192 if(!k->second->preceding_train)
194 k->second->preceding_train = j->info->train;
195 k->second->sequence_in = sequence;
197 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
199 k->second = &j->info->sequence.front();
204 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
205 sequenced_tracks[j->track.track()] = &j->info->sequence.front();
214 TrainRoutePlanner::TrainRoutingInfo::TrainRoutingInfo(Train &t):
216 speed(train->get_maximum_speed()),
217 first_noncritical(train->get_first_noncritical_block().block()),
218 router(train->get_ai_of_type<TrainRouter>()),
224 destination = router->get_destination();
227 waypoints.resize(router->get_n_waypoints());
228 metrics.resize(waypoints.size()+1);
229 metrics[0] = &router->get_metric(-1);
230 for(unsigned i=0; i<waypoints.size(); ++i)
232 waypoints[i] = &router->get_waypoint(i);
233 metrics[i+1] = &router->get_metric(i);
235 has_duration = router->get_trip_duration();
239 // If no maximum speed is specified, use a sensible default
241 speed = 20*train->get_layout().get_catalogue().get_scale();
245 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(Track &t, unsigned p, OccupiedTrack *n):
247 path_length(track->get_type().get_path_length(p)),
249 n_tracks(next ? next->n_tracks+1 : 1),
256 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(const OccupiedTrack &other):
258 path_length(other.path_length),
260 n_tracks(other.n_tracks),
267 TrainRoutePlanner::OccupiedTrack::~OccupiedTrack()
269 if(next && !--next->refcount)
274 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(TrainRoutingInfo &inf):
279 delay(info->router->get_departure_delay()),
280 duration(info->router->get_trip_duration()),
281 waypoint(info->waypoints.empty() ? -1 : 0),
284 const Vehicle *veh = &info->train->get_vehicle(0);
286 TrackOffsetIter track_and_offs = veh->get_placement().get_position(VehiclePlacement::FRONT_BUFFER);
287 track = track_and_offs.track_iter();
288 offset = track_and_offs.offset();
289 path = track->get_active_path();
291 while(Vehicle *next = veh->get_link(1))
293 track_and_offs = veh->get_placement().get_position(VehiclePlacement::BACK_BUFFER);
294 back_offset = track_and_offs.offset();
296 TrackIter iter = track_and_offs.track_iter();
299 occupied_tracks = new OccupiedTrack(*iter, iter->get_active_path(), occupied_tracks);
300 if(iter.track()==track.track())
308 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(const TrainRoutingState &other):
312 critical(other.critical),
313 occupied_tracks(other.occupied_tracks),
314 offset(other.offset),
315 back_offset(other.back_offset),
318 duration(other.duration),
319 waypoint(other.waypoint),
320 distance_traveled(other.distance_traveled),
321 remaining_estimate(other.remaining_estimate),
322 wait_time(other.wait_time),
323 blocked_by(other.blocked_by)
325 ++occupied_tracks->refcount;
328 TrainRoutePlanner::TrainRoutingState::~TrainRoutingState()
330 if(occupied_tracks && !--occupied_tracks->refcount)
331 delete occupied_tracks;
334 Time::TimeDelta TrainRoutePlanner::TrainRoutingState::get_time_to_next_track() const
336 return ((track->get_type().get_path_length(path)-offset)/info->speed)*Time::sec+delay;
339 bool TrainRoutePlanner::TrainRoutingState::is_occupying(Track &trk) const
341 if(state==ARRIVED && !duration && info->has_duration)
344 OccupiedTrack *occ = occupied_tracks;
345 for(unsigned n=occ->n_tracks; n>0; --n, occ=occ->next)
351 bool TrainRoutePlanner::TrainRoutingState::check_arrival()
353 TrackIter next_track = track.next(path);
355 if(waypoint<0 && info->destination->has_track(*track) && !info->destination->has_track(*next_track))
360 else if(waypoint>=0 && info->waypoints[waypoint]->has_track(*track) && !info->waypoints[waypoint]->has_track(*next_track))
363 if(waypoint>=static_cast<int>(info->waypoints.size()))
367 if(info->first_noncritical->has_track(*track))
373 void TrainRoutePlanner::TrainRoutingState::advance(float distance)
376 back_offset += distance;
378 unsigned count_to_free = 0;
379 unsigned last_sensor_addr = 0;
380 float distance_after_sensor = 0;
381 OccupiedTrack *occ = occupied_tracks;
382 for(unsigned n=occupied_tracks->n_tracks; n>0; --n)
384 if(unsigned saddr = occ->track->get_sensor_address())
386 if(saddr!=last_sensor_addr)
389 distance_after_sensor = 0;
391 last_sensor_addr = saddr;
395 distance_after_sensor += occ->path_length;
400 if(count_to_free && back_offset>distance_after_sensor)
402 back_offset -= distance_after_sensor;
403 if(occupied_tracks->refcount>1)
405 --occupied_tracks->refcount;
406 occupied_tracks = new OccupiedTrack(*occupied_tracks);
408 occupied_tracks->n_tracks -= count_to_free;
411 distance_traveled += distance;
412 remaining_estimate -= distance;
415 void TrainRoutePlanner::TrainRoutingState::advance(const Time::TimeDelta &dt)
423 float secs = dt/Time::sec;
426 secs -= delay/Time::sec;
431 duration = max(duration-secs*Time::sec, Time::zero);
434 advance(info->speed*secs);
435 else if(state!=ARRIVED)
436 wait_time += secs*Time::sec;
439 void TrainRoutePlanner::TrainRoutingState::advance_track(unsigned next_path)
441 float distance = occupied_tracks->path_length-offset;
442 track = track.next(path);
444 occupied_tracks = new OccupiedTrack(*track, path, occupied_tracks);
449 void TrainRoutePlanner::TrainRoutingState::update_estimate()
451 TrackIter iter = track.reverse(path);
452 float distance = info->metrics[waypoint+1]->get_distance_from(*iter.track(), iter.entry());
453 distance += track->get_type().get_path_length(path)-offset;
454 remaining_estimate = distance;
458 TrainRoutePlanner::RoutingStep::RoutingStep():
462 TrainRoutePlanner::RoutingStep::RoutingStep(const RoutingStep *p):
465 cost_estimate(p->cost_estimate),
470 void TrainRoutePlanner::RoutingStep::create_successors(list<RoutingStep> &new_steps) const
472 RoutingStep next(this);
473 if(next.update_states())
475 if(next.check_deadlocks())
478 new_steps.push_back(next);
482 int train_index = find_next_train();
486 TrainRoutingState &train = next.trains[train_index];
488 Time::TimeDelta dt = train.get_time_to_next_track();
491 if(train.check_arrival())
493 new_steps.push_back(next);
497 TrackIter next_track = train.track.next(train.path);
498 train.advance_track(0);
500 const TrackType::Endpoint &next_entry_ep = next_track.endpoint();
503 train.path = train.track->get_type().coerce_path(train.track.entry(), train.track->get_active_path());
504 train.update_estimate();
505 next.update_estimate();
507 new_steps.push_back(next);
511 for(unsigned i=0; next_entry_ep.paths>>i; ++i)
512 if(next_entry_ep.has_path(i))
515 train.update_estimate();
516 next.update_estimate();
518 new_steps.push_back(next);
523 for(list<RoutingStep>::iterator i=new_steps.begin(); ++i!=new_steps.end(); )
525 i->penalty += 5*Time::sec;
526 i->update_estimate();
529 if(next_entry_ep.paths!=next_track->get_type().get_paths() && !train.critical)
531 RoutingStep wait(this);
533 wait.trains[train_index].state = WAITING;
534 wait.penalty += 15*Time::sec;
535 wait.update_estimate();
537 new_steps.push_back(wait);
541 bool TrainRoutePlanner::RoutingStep::update_states()
543 bool changes = false;
544 for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
546 if(i->state==ARRIVED)
549 TrainState old_state = i->state;
551 TrackIter next_track = i->track.next(i->path);
554 i->blocked_by = get_occupant(*next_track);
557 else if(i->state==BLOCKED)
563 if(i->state!=old_state)
570 bool TrainRoutePlanner::RoutingStep::check_deadlocks() const
572 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
574 if(i->state!=BLOCKED)
580 int slow = i->blocked_by;
581 int fast = trains[slow].blocked_by;
582 while(fast>=0 && trains[fast].blocked_by>=0)
587 slow = trains[slow].blocked_by;
588 fast = trains[trains[fast].blocked_by].blocked_by;
595 int TrainRoutePlanner::RoutingStep::get_occupant(Track &track) const
597 for(unsigned i=0; i<trains.size(); ++i)
598 if(trains[i].is_occupying(track))
604 int TrainRoutePlanner::RoutingStep::find_next_train() const
606 Time::TimeDelta min_dt;
608 for(unsigned i=0; i<trains.size(); ++i)
609 if(trains[i].state==MOVING)
611 Time::TimeDelta dt = trains[i].get_time_to_next_track();
612 if(dt<min_dt || next_train<0)
622 void TrainRoutePlanner::RoutingStep::advance(const Time::TimeDelta &dt)
625 for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
629 void TrainRoutePlanner::RoutingStep::update_estimate()
631 cost_estimate = penalty;
632 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
633 if(i->remaining_estimate>=0)
634 cost_estimate += i->wait_time+((i->distance_traveled+i->remaining_estimate)/i->info->speed)*Time::sec;
637 bool TrainRoutePlanner::RoutingStep::is_viable() const
639 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
640 if(i->remaining_estimate<0)
643 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
650 bool TrainRoutePlanner::RoutingStep::is_goal() const
652 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
653 if(i->state!=ARRIVED)
658 bool TrainRoutePlanner::RoutingStep::operator<(const RoutingStep &other) const
660 return cost_estimate<other.cost_estimate;
664 TrainRoutePlanner::PlanningThread::PlanningThread(TrainRoutePlanner &p):
670 void TrainRoutePlanner::PlanningThread::main()
672 planner.create_plan();