]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/trainrouteplanner.cpp
Don't crash if a train has no router
[r2c2.git] / source / libr2c2 / trainrouteplanner.cpp
1 #include <msp/core/maputils.h>
2 #include <msp/time/utils.h>
3 #include "catalogue.h"
4 #include "layout.h"
5 #include "route.h"
6 #include "train.h"
7 #include "trainroutemetric.h"
8 #include "trainrouteplanner.h"
9 #include "trainrouter.h"
10 #include "vehicle.h"
11
12 using namespace std;
13 using namespace Msp;
14
15 namespace R2C2 {
16
17 TrainRoutePlanner::TrainRoutePlanner(Layout &layout):
18         goal(0),
19         path_switch_bias(15*Time::sec),
20         timeout(10*Time::sec),
21         result(PENDING),
22         thread(0)
23 {
24         const map<unsigned, Train *> &trains = layout.get_trains();
25         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
26         {
27                 TrainRoutingInfo info(*i->second);
28                 if(!info.waypoints.empty())
29                         routed_trains.push_back(info);
30         }
31 }
32
33 TrainRoutePlanner::~TrainRoutePlanner()
34 {
35         if(thread)
36         {
37                 thread->join();
38                 delete thread;
39         }
40 }
41
42 void TrainRoutePlanner::set_timeout(const Time::TimeDelta &t)
43 {
44         timeout = t;
45 }
46
47 TrainRoutePlanner::Result TrainRoutePlanner::plan()
48 {
49         prepare_plan();
50         create_plan();
51         if(result==PENDING)
52                 finalize_plan();
53
54         return result;
55 }
56
57 void TrainRoutePlanner::plan_async()
58 {
59         if(thread)
60                 throw logic_error("already planning");
61
62         prepare_plan();
63         thread = new PlanningThread(*this);
64 }
65
66 TrainRoutePlanner::Result TrainRoutePlanner::check()
67 {
68         if(result==PENDING && goal)
69         {
70                 if(thread)
71                 {
72                         thread->join();
73                         delete thread;
74                         thread = 0;
75                 }
76                 finalize_plan();
77         }
78
79         return result;
80 }
81
82 const list<Route *> &TrainRoutePlanner::get_routes_for(const Train &train) const
83 {
84         return get_train_info(train).routes;
85 }
86
87 const list<TrainRouter::SequencePoint> &TrainRoutePlanner::get_sequence_for(const Train &train) const
88 {
89         return get_train_info(train).sequence;
90 }
91
92 const TrainRoutePlanner::TrainRoutingInfo &TrainRoutePlanner::get_train_info(const Train &train) const
93 {
94         for(vector<TrainRoutingInfo>::const_iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
95                 if(i->train==&train)
96                         return *i;
97
98         throw key_error(train.get_name());
99 }
100
101 const TrainRoutePlanner::RoutingStep &TrainRoutePlanner::get_step()
102 {
103         steps.splice(steps.end(), queue, queue.begin());
104         return steps.back();
105 }
106
107 void TrainRoutePlanner::prepare_plan()
108 {
109         steps.clear();
110         queue.clear();
111         goal = 0;
112         result = PENDING;
113
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();
119 }
120
121 void TrainRoutePlanner::create_plan()
122 {
123         Time::TimeStamp timeout_stamp = Time::now()+timeout;
124         unsigned count = 0;
125         while(!queue.empty())
126         {
127                 const RoutingStep &step = get_step();
128                 if(step.is_goal())
129                 {
130                         goal = &step;
131                         return;
132                 }
133
134                 add_steps(step);
135
136                 if(++count>=1000)
137                 {
138                         if(Time::now()>timeout_stamp)
139                                 break;
140                         count = 0;
141                 }
142         }
143
144         result = FAILED;
145 }
146
147 void TrainRoutePlanner::add_steps(const RoutingStep &step)
148 {
149         list<RoutingStep> new_steps;
150         step.create_successors(new_steps);
151         if(new_steps.empty())
152                 return;
153
154         new_steps.sort();
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);
158 }
159
160 void TrainRoutePlanner::finalize_plan()
161 {
162         for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
163         {
164                 i->routes.clear();
165                 i->sequence.clear();
166                 for(unsigned j=0; j<2; ++j)
167                         i->track_history[j] = 0;
168         }
169
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)
174                 {
175                         Track **history = j->info->track_history;
176                         // Don't process the same track again.
177                         if(j->track.track()==history[0])
178                                 continue;
179
180                         Route *route = 0;
181                         bool start_new_route = true;
182                         if(!j->info->routes.empty())
183                         {
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);
188                                 if(!start_new_route)
189                                 {
190                                         unsigned nls = j->track->get_n_link_slots();
191                                         for(unsigned k=0; (!start_new_route && k<nls); ++k)
192                                         {
193                                                 Track *link = j->track->get_link(k);
194                                                 start_new_route = (link && link!=history[0] && route->has_track(*link));
195                                         }
196                                 }
197                         }
198
199                         if(start_new_route)
200                         {
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);
209                         }
210
211                         route->add_track(*j->track.track());
212                         history[1] = history[0];
213                         history[0] = j->track.track();
214
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())
218                         {
219                                 // Add a sequence point if another train uses this track afterwards.
220                                 if(!k->second->preceding_train)
221                                 {
222                                         k->second->preceding_train = j->info->train;
223                                         k->second->sequence_in = sequence;
224                                 }
225                                 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
226                                 if(waitable)
227                                         k->second = &j->info->sequence.front();
228                                 --sequence;
229                         }
230                         else if(waitable)
231                         {
232                                 /* Create a sequence point if it's possible to wait and let another
233                                 train past. */
234                                 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
235                                 sequenced_tracks[j->track.track()] = &j->info->sequence.front();
236                                 --sequence;
237                         }
238                 }
239
240         result = COMPLETE;
241 }
242
243
244 TrainRoutePlanner::TrainRoutingInfo::TrainRoutingInfo(Train &t):
245         train(&t),
246         length(0),
247         speed(train->get_maximum_speed()),
248         first_noncritical(train->get_last_critical_block().next().block()),
249         router(train->get_ai_of_type<TrainRouter>()),
250         has_duration(false)
251 {
252         if(!router)
253                 return;
254
255         if(unsigned n_wps = router->get_n_waypoints())
256         {
257                 waypoints.reserve(n_wps),
258                 metrics.reserve(n_wps);
259                 for(unsigned i=0; i<n_wps; ++i)
260                 {
261                         waypoints.push_back(router->get_waypoint(i));
262                         metrics.push_back(&router->get_metric(i));
263                 }
264                 has_duration = router->get_trip_duration();
265         }
266
267         unsigned n_vehs = train->get_n_vehicles();
268         for(unsigned i=0; i<n_vehs; ++i)
269                 length += train->get_vehicle(i).get_type().get_length();
270
271         // If no maximum speed is specified, use a sensible default
272         if(!speed)
273                 speed = 20*train->get_layout().get_catalogue().get_scale();
274 }
275
276
277 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(Track &t, unsigned p, OccupiedTrack *n):
278         track(&t),
279         path_length(track->get_type().get_path_length(p)),
280         next(n),
281         n_tracks(next ? next->n_tracks+1 : 1),
282         refcount(1)
283 {
284         if(next)
285                 ++next->refcount;
286 }
287
288 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(const OccupiedTrack &other):
289         track(other.track),
290         path_length(other.path_length),
291         next(other.next),
292         n_tracks(other.n_tracks),
293         refcount(1)
294 {
295         if(next)
296                 ++next->refcount;
297 }
298
299 TrainRoutePlanner::OccupiedTrack::~OccupiedTrack()
300 {
301         if(next && !--next->refcount)
302                 delete next;
303 }
304
305
306 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(TrainRoutingInfo &inf):
307         info(&inf),
308         critical(true),
309         occupied_tracks(0),
310         state(MOVING),
311         delay(info->router->get_departure_delay()),
312         duration(info->router->get_trip_duration()),
313         waypoint(0),
314         distance_traveled(0),
315         blocked_by(-1)
316 {
317         const Vehicle *veh = &info->train->get_vehicle(0);
318         // TODO margins
319         TrackOffsetIter track_and_offs = veh->get_placement().get_position(VehiclePlacement::FRONT_BUFFER);
320         track = track_and_offs.track_iter();
321         offset = track_and_offs.offset();
322         path = track->get_active_path();
323
324         while(Vehicle *next = veh->get_link(1))
325                 veh = next;
326         track_and_offs = veh->get_placement().get_position(VehiclePlacement::BACK_BUFFER);
327         back_offset = track_and_offs.offset();
328
329         TrackIter iter = track_and_offs.track_iter();
330         while(1)
331         {
332                 occupied_tracks = new OccupiedTrack(*iter, iter->get_active_path(), occupied_tracks);
333                 if(iter.track()==track.track())
334                         break;
335                 iter = iter.next();
336         }
337
338         travel_multiplier = info->metrics[waypoint]->get_travel_multiplier(*track, track.reverse(path).entry());
339
340         update_estimate();
341 }
342
343 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(const TrainRoutingState &other):
344         info(other.info),
345         track(other.track),
346         path(other.path),
347         critical(other.critical),
348         occupied_tracks(other.occupied_tracks),
349         offset(other.offset),
350         back_offset(other.back_offset),
351         state(other.state),
352         delay(other.delay),
353         duration(other.duration),
354         waypoint(other.waypoint),
355         travel_multiplier(other.travel_multiplier),
356         distance_traveled(other.distance_traveled),
357         remaining_estimate(other.remaining_estimate),
358         wait_time(other.wait_time),
359         estimated_wait(other.estimated_wait),
360         blocked_by(other.blocked_by)
361 {
362         ++occupied_tracks->refcount;
363 }
364
365 TrainRoutePlanner::TrainRoutingState::~TrainRoutingState()
366 {
367         if(occupied_tracks && !--occupied_tracks->refcount)
368                 delete occupied_tracks;
369 }
370
371 Time::TimeDelta TrainRoutePlanner::TrainRoutingState::get_time_to_next_track() const
372 {
373         return ((occupied_tracks->path_length-offset)/info->speed)*Time::sec+delay+estimated_wait;
374 }
375
376 Time::TimeDelta TrainRoutePlanner::TrainRoutingState::get_time_to_pass(Track &trk) const
377 {
378         if(is_occupying(trk))
379         {
380                 if(state==ARRIVED && info->has_duration)
381                         return duration;
382
383                 float passed_length = 0;
384                 for(const OccupiedTrack *occ=occupied_tracks; (occ && occ->track!=&trk); occ=occ->next)
385                         passed_length += occ->path_length;
386                 return (max(info->length-passed_length, 0.0f)/info->speed)*Time::sec+delay;
387         }
388
389         for(unsigned wp=waypoint; wp<info->waypoints.size(); ++wp)
390         {
391                 float distance = info->metrics[wp]->get_distance_from(trk);
392                 if(distance>=0 && distance<remaining_estimate)
393                         return ((remaining_estimate-distance+info->length)/info->speed)*Time::sec+delay;
394         }
395
396         return Time::day;
397 }
398
399 bool TrainRoutePlanner::TrainRoutingState::is_occupying(Track &trk) const
400 {
401         if(state==ARRIVED && !duration && info->has_duration)
402                 return false;
403
404         OccupiedTrack *occ = occupied_tracks;
405         for(unsigned n=occ->n_tracks; n>0; --n, occ=occ->next)
406                 if(occ->track==&trk)
407                         return true;
408         return false;
409 }
410
411 bool TrainRoutePlanner::TrainRoutingState::check_arrival()
412 {
413         TrackIter next_track = track.next(path);
414
415         // Check if we're about the exit the current waypoint's tracks.
416         const TrainRouter::Waypoint &wp = info->waypoints[waypoint];
417         if(wp.chain->has_track(*track) && !wp.chain->has_track(*next_track))
418                 if(wp.direction==TrackChain::UNSPECIFIED || track==wp.chain->iter_for(*track, wp.direction))
419                 {
420                         if(waypoint+1<info->waypoints.size())
421                                 ++waypoint;
422                         else
423                         {
424                                 state = ARRIVED;
425                                 return true;
426                         }
427                 }
428
429         // If we're entering the first non-critical block, clear the critical flag.
430         if(info->first_noncritical->has_track(*next_track))
431                 critical = false;
432
433         return false;
434 }
435
436 void TrainRoutePlanner::TrainRoutingState::advance(float distance)
437 {
438         offset += distance;
439         back_offset += distance;
440
441         // See if the tail end of the train has passed any sensors.
442         unsigned count_to_free = 0;
443         unsigned last_sensor_addr = 0;
444         float distance_after_sensor = 0;
445         OccupiedTrack *occ = occupied_tracks;
446         for(unsigned n=occupied_tracks->n_tracks; n>0; --n)
447         {
448                 if(unsigned saddr = occ->track->get_sensor_address())
449                 {
450                         if(saddr!=last_sensor_addr)
451                         {
452                                 count_to_free = 0;
453                                 distance_after_sensor = 0;
454                         }
455                         last_sensor_addr = saddr;
456                 }
457
458                 ++count_to_free;
459                 distance_after_sensor += occ->path_length;
460
461                 occ = occ->next;
462         }
463
464         // Free the last passed sensor and any tracks behind it.
465         if(count_to_free && back_offset>distance_after_sensor)
466         {
467                 back_offset -= distance_after_sensor;
468                 if(occupied_tracks->refcount>1)
469                 {
470                         --occupied_tracks->refcount;
471                         occupied_tracks = new OccupiedTrack(*occupied_tracks);
472                 }
473                 occupied_tracks->n_tracks -= count_to_free;
474         }
475
476         distance_traveled += distance*travel_multiplier;
477         remaining_estimate -= distance*travel_multiplier;
478 }
479
480 void TrainRoutePlanner::TrainRoutingState::advance(const Time::TimeDelta &dt)
481 {
482         if(delay>=dt)
483         {
484                 delay -= dt;
485                 return;
486         }
487
488         float secs = dt/Time::sec;
489         // There may be some delay remaining.
490         if(delay)
491         {
492                 secs -= delay/Time::sec;
493                 delay = Time::zero;
494         }
495
496         if(duration)
497                 duration = max(duration-secs*Time::sec, Time::zero);
498
499         if(estimated_wait)
500                 estimated_wait = max(estimated_wait-secs*Time::sec, Time::zero);
501
502         float distance = info->speed*secs;
503         float remaining_on_track = occupied_tracks->path_length-offset;
504         if(state==MOVING || distance<remaining_on_track)
505                 advance(info->speed*secs);
506         else if(state!=ARRIVED)
507         {
508                 if(remaining_on_track>0)
509                 {
510                         advance(remaining_on_track);
511                         wait_time += (secs-remaining_on_track/info->speed)*Time::sec;
512                 }
513                 else
514                         wait_time += secs*Time::sec;
515         }
516 }
517
518 void TrainRoutePlanner::TrainRoutingState::advance_track(unsigned next_path)
519 {
520         float distance = occupied_tracks->path_length-offset;
521
522         track = track.next(path);
523         path = next_path;
524         occupied_tracks = new OccupiedTrack(*track, path, occupied_tracks);
525
526         advance(distance);
527         offset = 0;
528         travel_multiplier = info->metrics[waypoint]->get_travel_multiplier(*track, track.reverse(path).entry());
529 }
530
531 void TrainRoutePlanner::TrainRoutingState::set_path(unsigned p)
532 {
533         path = p;
534         OccupiedTrack *next_occ = occupied_tracks->next;
535         if(!--occupied_tracks->refcount)
536                 delete occupied_tracks;
537         occupied_tracks = new OccupiedTrack(*track, path, next_occ);
538         update_estimate();
539 }
540
541 void TrainRoutePlanner::TrainRoutingState::update_estimate()
542 {
543         TrackIter iter = track.reverse(path);
544         const TrainRouteMetric *metric = info->metrics[waypoint];
545         remaining_estimate = metric->get_distance_from(*iter, iter.entry());
546         travel_multiplier = metric->get_travel_multiplier(*iter, iter.entry());
547         if(remaining_estimate>=0)
548                 remaining_estimate += (occupied_tracks->path_length-offset)*travel_multiplier;
549 }
550
551 bool TrainRoutePlanner::TrainRoutingState::is_viable() const
552 {
553         if(remaining_estimate<0)
554                 return false;
555         if(critical && state==BLOCKED)
556                 return false;
557         return true;
558 }
559
560
561 TrainRoutePlanner::RoutingStep::RoutingStep():
562         preferred(false),
563         prev(0)
564 { }
565
566 TrainRoutePlanner::RoutingStep::RoutingStep(const RoutingStep *p):
567         time(p->time),
568         cost_estimate(p->cost_estimate),
569         preferred(false),
570         trains(p->trains),
571         prev(p)
572 { }
573
574 void TrainRoutePlanner::RoutingStep::create_successors(list<RoutingStep> &new_steps) const
575 {
576         RoutingStep next(this);
577         if(next.update_states() && next.check_deadlocks())
578                 return;
579
580         int train_index = next.find_next_train();
581         if(train_index<0)
582                 return;
583
584         TrainRoutingState &train = next.trains[train_index];
585
586         Time::TimeDelta dt = train.get_time_to_next_track();
587         next.advance(dt);
588
589         /* Check arrival after the train has advanced to the end of its current track
590         so travel time and occupied tracks will be correct. */
591         if(train.check_arrival())
592         {
593                 new_steps.push_back(next);
594                 return;
595         }
596
597         if(train.state==MOVING)
598                 train.advance_track(0);
599         else
600         {
601                 new_steps.push_back(next);
602                 return;
603         }
604
605         const TrackType::Endpoint &entry_ep = train.track.endpoint();
606         if(train.critical)
607         {
608                 /* Only create a successor step matching the currently set path for a
609                 critical track. */
610                 unsigned critical_path = train.track->get_type().coerce_path(train.track.entry(), train.track->get_active_path());
611                 create_successor(next, train_index, critical_path, new_steps);
612         }
613         else
614         {
615                 // Create successor steps for all possible paths through the new track.
616                 for(unsigned i=0; entry_ep.paths>>i; ++i)
617                         if(entry_ep.has_path(i))
618                                 create_successor(next, train_index, i, new_steps);
619         }
620
621         if(entry_ep.paths!=train.track->get_type().get_paths() && !train.critical)
622         {
623                 /* Create a waiting state before the track if there's at least one path
624                 that doesn't pass through the entry endpoint. */
625                 RoutingStep wait(this);
626                 wait.advance(dt);
627                 wait.trains[train_index].state = WAITING;
628
629                 Time::TimeDelta estimated_wait = Time::day;
630                 for(unsigned i=0; i<wait.trains.size(); ++i)
631                         if(i!=static_cast<unsigned>(train_index) && wait.trains[i].state!=ARRIVED)
632                         {
633                                 Time::TimeDelta ttp = wait.trains[i].get_time_to_pass(*train.track);
634                                 estimated_wait = min(estimated_wait, ttp);
635                         }
636                 wait.trains[train_index].estimated_wait = estimated_wait;
637
638                 wait.update_estimate();
639                 if(wait.is_viable())
640                         new_steps.push_back(wait);
641         }
642 }
643
644 void TrainRoutePlanner::RoutingStep::create_successor(RoutingStep &next, unsigned train_index, unsigned path, list<RoutingStep> &new_steps)
645 {
646         TrainRoutingState &train = next.trains[train_index];
647
648         train.set_path(path);
649         next.update_estimate();
650         if(next.is_viable())
651                 new_steps.push_back(next);
652 }
653
654 bool TrainRoutePlanner::RoutingStep::update_states()
655 {
656         bool changes = false;
657         for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
658         {
659                 if(i->state==ARRIVED)
660                         continue;
661
662                 TrainState old_state = i->state;
663
664                 TrackIter next_track = i->track.next(i->path);
665                 if(next_track)
666                 {
667                         i->blocked_by = get_occupant(*next_track);
668                         if(i->blocked_by>=0)
669                         {
670                                 /* If the train is still traversing its last critical track, the
671                                 flag needs to be cleared here to pass viability test. */
672                                 if(i->info->first_noncritical->has_track(*next_track))
673                                         i->critical = false;
674
675                                 if(i->state!=BLOCKED)
676                                         i->estimated_wait = trains[i->blocked_by].get_time_to_pass(*next_track);
677
678                                 /* Trains in the WAITING state will also transition to BLOCKED and
679                                 then to MOVING when the other train has passed. */
680                                 i->state = BLOCKED;
681                         }
682                         else if(i->state==BLOCKED)
683                         {
684                                 i->estimated_wait = Time::zero;
685                                 i->state = MOVING;
686                         }
687                 }
688                 else
689                         i->state = BLOCKED;
690
691                 if(i->state!=old_state)
692                         changes = true;
693         }
694
695         return changes;
696 }
697
698 bool TrainRoutePlanner::RoutingStep::check_deadlocks() const
699 {
700         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
701         {
702                 if(i->state!=BLOCKED)
703                         continue;
704
705                 // A train blocked by end of track is always considered a deadlock.
706                 if(i->blocked_by<0)
707                         return true;
708
709                 /* Use the tortoise and hare algorithm to check if trains are blocked
710                 cyclically (A blocks B, which blocks ..., which blocks A). */
711                 int slow = i->blocked_by;
712                 int fast = trains[slow].blocked_by;
713                 while(fast>=0 && trains[fast].blocked_by>=0)
714                 {
715                         if(fast==slow)
716                                 return true;
717
718                         slow = trains[slow].blocked_by;
719                         fast = trains[trains[fast].blocked_by].blocked_by;
720                 }
721         }
722
723         return false;
724 }
725
726 int TrainRoutePlanner::RoutingStep::get_occupant(Track &track) const
727 {
728         for(unsigned i=0; i<trains.size(); ++i)
729                 if(trains[i].is_occupying(track))
730                         return i;
731
732         return -1;
733 }
734
735 int TrainRoutePlanner::RoutingStep::find_next_train() const
736 {
737         /* Pick a moving train with the lowest time to next track.  A train that
738         just became blocked can still travel until the end of its current track,
739         so consider those too. */
740         Time::TimeDelta min_dt;
741         int next_train = -1;
742         for(unsigned i=0; i<trains.size(); ++i)
743         {
744                 Time::TimeDelta dt;
745                 if(trains[i].state==MOVING || (trains[i].state==BLOCKED && prev && prev->trains[i].state==MOVING))
746                         dt = trains[i].get_time_to_next_track();
747                 else if(trains[i].state==BLOCKED && trains[trains[i].blocked_by].state==ARRIVED)
748                         dt = trains[i].estimated_wait;
749                 else
750                         continue;
751
752                 if(dt<min_dt || next_train<0)
753                 {
754                         min_dt = dt;
755                         next_train = i;
756                 }
757         }
758
759         return next_train;
760 }
761
762 void TrainRoutePlanner::RoutingStep::advance(const Time::TimeDelta &dt)
763 {
764         time += dt;
765         for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
766                 i->advance(dt);
767 }
768
769 void TrainRoutePlanner::RoutingStep::update_estimate()
770 {
771         cost_estimate = Time::zero;
772         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
773                 if(i->remaining_estimate>=0)
774                         cost_estimate += i->wait_time+i->estimated_wait+((i->distance_traveled+i->remaining_estimate)/i->info->speed)*Time::sec;
775 }
776
777 bool TrainRoutePlanner::RoutingStep::is_viable() const
778 {
779         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
780                 if(!i->is_viable())
781                         return false;
782
783         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
784                 if(i->state==MOVING)
785                         return true;
786
787         return false;
788 }
789
790 bool TrainRoutePlanner::RoutingStep::is_goal() const
791 {
792         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
793                 if(i->state!=ARRIVED)
794                         return false;
795         return true;
796 }
797
798 bool TrainRoutePlanner::RoutingStep::operator<(const RoutingStep &other) const
799 {
800         if(preferred!=other.preferred)
801                 return preferred>other.preferred;
802         return cost_estimate<other.cost_estimate;
803 }
804
805
806 TrainRoutePlanner::PlanningThread::PlanningThread(TrainRoutePlanner &p):
807         planner(p)
808 {
809         launch();
810 }
811
812 void TrainRoutePlanner::PlanningThread::main()
813 {
814         planner.create_plan();
815 }
816
817 } // namespace R2C2