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);
25 if(!info.waypoints.empty())
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_last_critical_block().next().block()),
218 router(train->get_ai_of_type<TrainRouter>()),
219 waypoints(router ? router->get_n_waypoints() : 0),
222 if(!waypoints.empty())
224 metrics.resize(waypoints.size());
225 for(unsigned i=0; i<waypoints.size(); ++i)
227 waypoints[i] = &router->get_waypoint(i);
228 metrics[i] = &router->get_metric(i);
230 has_duration = router->get_trip_duration();
233 // If no maximum speed is specified, use a sensible default
235 speed = 20*train->get_layout().get_catalogue().get_scale();
239 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(Track &t, unsigned p, OccupiedTrack *n):
241 path_length(track->get_type().get_path_length(p)),
243 n_tracks(next ? next->n_tracks+1 : 1),
250 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(const OccupiedTrack &other):
252 path_length(other.path_length),
254 n_tracks(other.n_tracks),
261 TrainRoutePlanner::OccupiedTrack::~OccupiedTrack()
263 if(next && !--next->refcount)
268 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(TrainRoutingInfo &inf):
273 delay(info->router->get_departure_delay()),
274 duration(info->router->get_trip_duration()),
278 const Vehicle *veh = &info->train->get_vehicle(0);
280 TrackOffsetIter track_and_offs = veh->get_placement().get_position(VehiclePlacement::FRONT_BUFFER);
281 track = track_and_offs.track_iter();
282 offset = track_and_offs.offset();
283 path = track->get_active_path();
285 while(Vehicle *next = veh->get_link(1))
287 track_and_offs = veh->get_placement().get_position(VehiclePlacement::BACK_BUFFER);
288 back_offset = track_and_offs.offset();
290 TrackIter iter = track_and_offs.track_iter();
293 occupied_tracks = new OccupiedTrack(*iter, iter->get_active_path(), occupied_tracks);
294 if(iter.track()==track.track())
302 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(const TrainRoutingState &other):
306 critical(other.critical),
307 occupied_tracks(other.occupied_tracks),
308 offset(other.offset),
309 back_offset(other.back_offset),
312 duration(other.duration),
313 waypoint(other.waypoint),
314 distance_traveled(other.distance_traveled),
315 remaining_estimate(other.remaining_estimate),
316 wait_time(other.wait_time),
317 blocked_by(other.blocked_by)
319 ++occupied_tracks->refcount;
322 TrainRoutePlanner::TrainRoutingState::~TrainRoutingState()
324 if(occupied_tracks && !--occupied_tracks->refcount)
325 delete occupied_tracks;
328 Time::TimeDelta TrainRoutePlanner::TrainRoutingState::get_time_to_next_track() const
330 return ((track->get_type().get_path_length(path)-offset)/info->speed)*Time::sec+delay;
333 bool TrainRoutePlanner::TrainRoutingState::is_occupying(Track &trk) const
335 if(state==ARRIVED && !duration && info->has_duration)
338 OccupiedTrack *occ = occupied_tracks;
339 for(unsigned n=occ->n_tracks; n>0; --n, occ=occ->next)
345 bool TrainRoutePlanner::TrainRoutingState::check_arrival()
347 TrackIter next_track = track.next(path);
349 const TrackChain *wp_chain = info->waypoints[waypoint];
350 if(wp_chain->has_track(*track) && !wp_chain->has_track(*next_track))
352 if(waypoint+1<info->waypoints.size())
361 if(info->first_noncritical->has_track(*track))
367 void TrainRoutePlanner::TrainRoutingState::advance(float distance)
370 back_offset += distance;
372 unsigned count_to_free = 0;
373 unsigned last_sensor_addr = 0;
374 float distance_after_sensor = 0;
375 OccupiedTrack *occ = occupied_tracks;
376 for(unsigned n=occupied_tracks->n_tracks; n>0; --n)
378 if(unsigned saddr = occ->track->get_sensor_address())
380 if(saddr!=last_sensor_addr)
383 distance_after_sensor = 0;
385 last_sensor_addr = saddr;
389 distance_after_sensor += occ->path_length;
394 if(count_to_free && back_offset>distance_after_sensor)
396 back_offset -= distance_after_sensor;
397 if(occupied_tracks->refcount>1)
399 --occupied_tracks->refcount;
400 occupied_tracks = new OccupiedTrack(*occupied_tracks);
402 occupied_tracks->n_tracks -= count_to_free;
405 distance_traveled += distance;
406 remaining_estimate -= distance;
409 void TrainRoutePlanner::TrainRoutingState::advance(const Time::TimeDelta &dt)
417 float secs = dt/Time::sec;
420 secs -= delay/Time::sec;
425 duration = max(duration-secs*Time::sec, Time::zero);
428 advance(info->speed*secs);
429 else if(state!=ARRIVED)
430 wait_time += secs*Time::sec;
433 void TrainRoutePlanner::TrainRoutingState::advance_track(unsigned next_path)
435 float distance = occupied_tracks->path_length-offset;
436 track = track.next(path);
438 occupied_tracks = new OccupiedTrack(*track, path, occupied_tracks);
443 void TrainRoutePlanner::TrainRoutingState::update_estimate()
445 TrackIter iter = track.reverse(path);
446 float distance = info->metrics[waypoint]->get_distance_from(*iter.track(), iter.entry());
447 distance += track->get_type().get_path_length(path)-offset;
448 remaining_estimate = distance;
451 bool TrainRoutePlanner::TrainRoutingState::is_viable() const
453 if(remaining_estimate<0)
455 if(critical && state==BLOCKED)
461 TrainRoutePlanner::RoutingStep::RoutingStep():
465 TrainRoutePlanner::RoutingStep::RoutingStep(const RoutingStep *p):
468 cost_estimate(p->cost_estimate),
473 void TrainRoutePlanner::RoutingStep::create_successors(list<RoutingStep> &new_steps) const
475 RoutingStep next(this);
476 if(next.update_states())
478 if(next.check_deadlocks())
481 new_steps.push_back(next);
485 int train_index = find_next_train();
489 TrainRoutingState &train = next.trains[train_index];
491 Time::TimeDelta dt = train.get_time_to_next_track();
494 if(train.check_arrival())
496 new_steps.push_back(next);
500 train.advance_track(0);
502 const TrackType::Endpoint &entry_ep = train.track.endpoint();
505 train.path = train.track->get_type().coerce_path(train.track.entry(), train.track->get_active_path());
506 train.update_estimate();
507 next.update_estimate();
509 new_steps.push_back(next);
513 for(unsigned i=0; entry_ep.paths>>i; ++i)
514 if(entry_ep.has_path(i))
517 train.update_estimate();
518 next.update_estimate();
520 new_steps.push_back(next);
525 for(list<RoutingStep>::iterator i=new_steps.begin(); ++i!=new_steps.end(); )
527 i->penalty += 5*Time::sec;
528 i->update_estimate();
531 if(entry_ep.paths!=train.track->get_type().get_paths() && !train.critical)
533 RoutingStep wait(this);
535 wait.trains[train_index].state = WAITING;
536 wait.penalty += 15*Time::sec;
537 wait.update_estimate();
539 new_steps.push_back(wait);
543 bool TrainRoutePlanner::RoutingStep::update_states()
545 bool changes = false;
546 for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
548 if(i->state==ARRIVED)
551 TrainState old_state = i->state;
553 TrackIter next_track = i->track.next(i->path);
556 i->blocked_by = get_occupant(*next_track);
559 if(i->info->first_noncritical->has_track(*next_track))
563 else if(i->state==BLOCKED)
569 if(i->state!=old_state)
576 bool TrainRoutePlanner::RoutingStep::check_deadlocks() const
578 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
580 if(i->state!=BLOCKED)
586 int slow = i->blocked_by;
587 int fast = trains[slow].blocked_by;
588 while(fast>=0 && trains[fast].blocked_by>=0)
593 slow = trains[slow].blocked_by;
594 fast = trains[trains[fast].blocked_by].blocked_by;
601 int TrainRoutePlanner::RoutingStep::get_occupant(Track &track) const
603 for(unsigned i=0; i<trains.size(); ++i)
604 if(trains[i].is_occupying(track))
610 int TrainRoutePlanner::RoutingStep::find_next_train() const
612 Time::TimeDelta min_dt;
614 for(unsigned i=0; i<trains.size(); ++i)
615 if(trains[i].state==MOVING)
617 Time::TimeDelta dt = trains[i].get_time_to_next_track();
618 if(dt<min_dt || next_train<0)
628 void TrainRoutePlanner::RoutingStep::advance(const Time::TimeDelta &dt)
631 for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
635 void TrainRoutePlanner::RoutingStep::update_estimate()
637 cost_estimate = penalty;
638 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
639 if(i->remaining_estimate>=0)
640 cost_estimate += i->wait_time+((i->distance_traveled+i->remaining_estimate)/i->info->speed)*Time::sec;
643 bool TrainRoutePlanner::RoutingStep::is_viable() const
645 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
649 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
656 bool TrainRoutePlanner::RoutingStep::is_goal() const
658 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
659 if(i->state!=ARRIVED)
664 bool TrainRoutePlanner::RoutingStep::operator<(const RoutingStep &other) const
666 return cost_estimate<other.cost_estimate;
670 TrainRoutePlanner::PlanningThread::PlanningThread(TrainRoutePlanner &p):
676 void TrainRoutePlanner::PlanningThread::main()
678 planner.create_plan();