]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/trainrouteplanner.cpp
Don't diverge from critical blocks
[r2c2.git] / source / libr2c2 / trainrouteplanner.cpp
1 #include <msp/core/maputils.h>
2 #include "catalogue.h"
3 #include "layout.h"
4 #include "route.h"
5 #include "train.h"
6 #include "trainroutemetric.h"
7 #include "trainrouteplanner.h"
8 #include "trainrouter.h"
9 #include "vehicle.h"
10
11 using namespace std;
12 using namespace Msp;
13
14 namespace R2C2 {
15
16 TrainRoutePlanner::TrainRoutePlanner(Layout &layout):
17         goal(0),
18         result(PENDING),
19         thread(0)
20 {
21         const map<unsigned, Train *> &trains = layout.get_trains();
22         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
23         {
24                 TrainRoutingInfo info(*i->second);
25                 if(info.destination)
26                         routed_trains.push_back(info);
27         }
28 }
29
30 TrainRoutePlanner::~TrainRoutePlanner()
31 {
32         if(thread)
33         {
34                 thread->join();
35                 delete thread;
36         }
37 }
38
39 TrainRoutePlanner::Result TrainRoutePlanner::plan()
40 {
41         prepare_plan();
42         create_plan();
43         if(result==PENDING)
44                 finalize_plan();
45
46         return result;
47 }
48
49 void TrainRoutePlanner::plan_async()
50 {
51         if(thread)
52                 throw logic_error("already planning");
53
54         prepare_plan();
55         thread = new PlanningThread(*this);
56 }
57
58 TrainRoutePlanner::Result TrainRoutePlanner::check()
59 {
60         if(result==PENDING && goal)
61         {
62                 if(thread)
63                 {
64                         thread->join();
65                         delete thread;
66                         thread = 0;
67                 }
68                 finalize_plan();
69         }
70
71         return result;
72 }
73
74 const list<Route *> &TrainRoutePlanner::get_routes_for(const Train &train) const
75 {
76         return get_train_info(train).routes;
77 }
78
79 const list<TrainRouter::SequencePoint> &TrainRoutePlanner::get_sequence_for(const Train &train) const
80 {
81         return get_train_info(train).sequence;
82 }
83
84 const TrainRoutePlanner::TrainRoutingInfo &TrainRoutePlanner::get_train_info(const Train &train) const
85 {
86         for(vector<TrainRoutingInfo>::const_iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
87                 if(i->train==&train)
88                         return *i;
89
90         throw key_error(train.get_name());
91 }
92
93 const TrainRoutePlanner::RoutingStep &TrainRoutePlanner::get_step()
94 {
95         steps.splice(steps.end(), queue, queue.begin());
96         return steps.back();
97 }
98
99 void TrainRoutePlanner::prepare_plan()
100 {
101         steps.clear();
102         queue.clear();
103         goal = 0;
104         result = PENDING;
105
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();
111 }
112
113 void TrainRoutePlanner::create_plan()
114 {
115         while(!queue.empty())
116         {
117                 const RoutingStep &step = get_step();
118                 if(step.is_goal())
119                 {
120                         goal = &step;
121                         return;
122                 }
123
124                 add_steps(step);
125         }
126
127         result = FAILED;
128 }
129
130 void TrainRoutePlanner::add_steps(const RoutingStep &step)
131 {
132         list<RoutingStep> new_steps;
133         step.create_successors(new_steps);
134         new_steps.sort();
135         queue.merge(new_steps);
136 }
137
138 void TrainRoutePlanner::finalize_plan()
139 {
140         for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
141         {
142                 i->routes.clear();
143                 i->sequence.clear();
144                 for(unsigned j=0; j<2; ++j)
145                         i->track_history[j] = 0;
146         }
147
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)
152                 {
153                         Track **history = j->info->track_history;
154                         if(j->track.track()==history[0])
155                                 continue;
156
157                         Route *route = 0;
158                         bool start_new_route = true;
159                         if(!j->info->routes.empty())
160                         {
161                                 route = j->info->routes.front();
162                                 start_new_route = route->has_track(*j->track);
163                                 if(!start_new_route)
164                                 {
165                                         unsigned nls = j->track->get_n_link_slots();
166                                         for(unsigned k=0; (!start_new_route && k<nls); ++k)
167                                         {
168                                                 Track *link = j->track->get_link(k);
169                                                 start_new_route = (link && link!=history[0] && route->has_track(*link));
170                                         }
171                                 }
172                         }
173
174                         if(start_new_route)
175                         {
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);
182                         }
183
184                         route->add_track(*j->track.track());
185                         history[1] = history[0];
186                         history[0] = j->track.track();
187
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())
191                         {
192                                 if(!k->second->preceding_train)
193                                 {
194                                         k->second->preceding_train = j->info->train;
195                                         k->second->sequence_in = sequence;
196                                 }
197                                 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
198                                 if(waitable)
199                                         k->second = &j->info->sequence.front();
200                                 --sequence;
201                         }
202                         else if(waitable)
203                         {
204                                 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
205                                 sequenced_tracks[j->track.track()] = &j->info->sequence.front();
206                                 --sequence;
207                         }
208                 }
209
210         result = COMPLETE;
211 }
212
213
214 TrainRoutePlanner::TrainRoutingInfo::TrainRoutingInfo(Train &t):
215         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>()),
219         destination(0),
220         has_duration(false)
221 {
222         if(router)
223         {
224                 destination = router->get_destination();
225                 if(destination)
226                 {
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)
231                         {
232                                 waypoints[i] = &router->get_waypoint(i);
233                                 metrics[i+1] = &router->get_metric(i);
234                         }
235                         has_duration = router->get_trip_duration();
236                 }
237         }
238
239         // If no maximum speed is specified, use a sensible default
240         if(!speed)
241                 speed = 20*train->get_layout().get_catalogue().get_scale();
242 }
243
244
245 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(Track &t, unsigned p, OccupiedTrack *n):
246         track(&t),
247         path_length(track->get_type().get_path_length(p)),
248         next(n),
249         n_tracks(next ? next->n_tracks+1 : 1),
250         refcount(1)
251 {
252         if(next)
253                 ++next->refcount;
254 }
255
256 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(const OccupiedTrack &other):
257         track(other.track),
258         path_length(other.path_length),
259         next(other.next),
260         n_tracks(other.n_tracks),
261         refcount(1)
262 {
263         if(next)
264                 ++next->refcount;
265 }
266
267 TrainRoutePlanner::OccupiedTrack::~OccupiedTrack()
268 {
269         if(next && !--next->refcount)
270                 delete next;
271 }
272
273
274 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(TrainRoutingInfo &inf):
275         info(&inf),
276         critical(true),
277         occupied_tracks(0),
278         state(MOVING),
279         delay(info->router->get_departure_delay()),
280         duration(info->router->get_trip_duration()),
281         waypoint(info->waypoints.empty() ? -1 : 0),
282         blocked_by(-1)
283 {
284         const Vehicle *veh = &info->train->get_vehicle(0);
285         // TODO margins
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();
290
291         while(Vehicle *next = veh->get_link(1))
292                 veh = next;
293         track_and_offs = veh->get_placement().get_position(VehiclePlacement::BACK_BUFFER);
294         back_offset = track_and_offs.offset();
295
296         TrackIter iter = track_and_offs.track_iter();
297         while(1)
298         {
299                 occupied_tracks = new OccupiedTrack(*iter, iter->get_active_path(), occupied_tracks);
300                 if(iter.track()==track.track())
301                         break;
302                 iter = iter.next();
303         }
304
305         update_estimate();
306 }
307
308 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(const TrainRoutingState &other):
309         info(other.info),
310         track(other.track),
311         path(other.path),
312         critical(other.critical),
313         occupied_tracks(other.occupied_tracks),
314         offset(other.offset),
315         back_offset(other.back_offset),
316         state(other.state),
317         delay(other.delay),
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)
324 {
325         ++occupied_tracks->refcount;
326 }
327
328 TrainRoutePlanner::TrainRoutingState::~TrainRoutingState()
329 {
330         if(occupied_tracks && !--occupied_tracks->refcount)
331                 delete occupied_tracks;
332 }
333
334 Time::TimeDelta TrainRoutePlanner::TrainRoutingState::get_time_to_next_track() const
335 {
336         return ((track->get_type().get_path_length(path)-offset)/info->speed)*Time::sec+delay;
337 }
338
339 bool TrainRoutePlanner::TrainRoutingState::is_occupying(Track &trk) const
340 {
341         if(state==ARRIVED && !duration && info->has_duration)
342                 return false;
343
344         OccupiedTrack *occ = occupied_tracks;
345         for(unsigned n=occ->n_tracks; n>0; --n, occ=occ->next)
346                 if(occ->track==&trk)
347                         return true;
348         return false;
349 }
350
351 bool TrainRoutePlanner::TrainRoutingState::check_arrival()
352 {
353         TrackIter next_track = track.next(path);
354
355         if(waypoint<0 && info->destination->has_track(*track) && !info->destination->has_track(*next_track))
356         {
357                 state = ARRIVED;
358                 return true;
359         }
360         else if(waypoint>=0 && info->waypoints[waypoint]->has_track(*track) && !info->waypoints[waypoint]->has_track(*next_track))
361         {
362                 ++waypoint;
363                 if(waypoint>=static_cast<int>(info->waypoints.size()))
364                         waypoint = -1;
365         }
366
367         if(info->first_noncritical->has_track(*track))
368                 critical = false;
369
370         return false;
371 }
372
373 void TrainRoutePlanner::TrainRoutingState::advance(float distance)
374 {
375         offset += distance;
376         back_offset += distance;
377
378         OccupiedTrack *last_occ = occupied_tracks;
379         for(unsigned n=occupied_tracks->n_tracks; n>1; --n)
380                 last_occ = last_occ->next;
381
382         // XXX What if there's multiple tracks to remove?
383         if(back_offset>last_occ->path_length)
384         {
385                 back_offset -= last_occ->path_length;
386                 if(occupied_tracks->refcount>1)
387                 {
388                         --occupied_tracks->refcount;
389                         occupied_tracks = new OccupiedTrack(*occupied_tracks);
390                 }
391                 --occupied_tracks->n_tracks;
392         }
393
394         distance_traveled += distance;
395         remaining_estimate -= distance;
396 }
397
398 void TrainRoutePlanner::TrainRoutingState::advance(const Time::TimeDelta &dt)
399 {
400         if(delay>=dt)
401         {
402                 delay -= dt;
403                 return;
404         }
405
406         float secs = dt/Time::sec;
407         if(delay)
408         {
409                 secs -= delay/Time::sec;
410                 delay = Time::zero;
411         }
412
413         if(duration)
414                 duration = max(duration-secs*Time::sec, Time::zero);
415
416         if(state==MOVING)
417                 advance(info->speed*secs);
418         else if(state!=ARRIVED)
419                 wait_time += secs*Time::sec;
420 }
421
422 void TrainRoutePlanner::TrainRoutingState::advance_track(unsigned next_path)
423 {
424         float distance = occupied_tracks->path_length-offset;
425         track = track.next(path);
426         path = next_path;
427         occupied_tracks = new OccupiedTrack(*track, path, occupied_tracks);
428         advance(distance);
429         offset = 0;
430 }
431
432 void TrainRoutePlanner::TrainRoutingState::update_estimate()
433 {
434         TrackIter iter = track.reverse(path);
435         float distance = info->metrics[waypoint+1]->get_distance_from(*iter.track(), iter.entry());
436         distance += track->get_type().get_path_length(path)-offset;
437         remaining_estimate = distance;
438 }
439
440
441 TrainRoutePlanner::RoutingStep::RoutingStep():
442         prev(0)
443 { }
444
445 TrainRoutePlanner::RoutingStep::RoutingStep(const RoutingStep *p):
446         time(p->time),
447         penalty(p->penalty),
448         cost_estimate(p->cost_estimate),
449         trains(p->trains),
450         prev(p)
451 { }
452
453 void TrainRoutePlanner::RoutingStep::create_successors(list<RoutingStep> &new_steps) const
454 {
455         RoutingStep next(this);
456         if(next.update_states())
457         {
458                 if(next.check_deadlocks())
459                         return;
460
461                 new_steps.push_back(next);
462                 return;
463         }
464
465         int train_index = find_next_train();
466         if(train_index<0)
467                 return;
468
469         TrainRoutingState &train = next.trains[train_index];
470
471         Time::TimeDelta dt = train.get_time_to_next_track();
472         next.advance(dt);
473
474         if(train.check_arrival())
475         {
476                 new_steps.push_back(next);
477                 return;
478         }
479
480         TrackIter next_track = train.track.next(train.path);
481         train.advance_track(0);
482
483         const TrackType::Endpoint &next_entry_ep = next_track.endpoint();
484         if(train.critical)
485         {
486                 train.path = train.track->get_type().coerce_path(train.track.entry(), train.track->get_active_path());
487                 train.update_estimate();
488                 next.update_estimate();
489                 if(next.is_viable())
490                         new_steps.push_back(next);
491         }
492         else
493         {
494                 for(unsigned i=0; next_entry_ep.paths>>i; ++i)
495                         if(next_entry_ep.has_path(i))
496                         {
497                                 train.path = i;
498                                 train.update_estimate();
499                                 next.update_estimate();
500                                 if(next.is_viable())
501                                         new_steps.push_back(next);
502                         }
503         }
504
505         new_steps.sort();
506         for(list<RoutingStep>::iterator i=new_steps.begin(); ++i!=new_steps.end(); )
507         {
508                 i->penalty += 5*Time::sec;
509                 i->update_estimate();
510         }
511
512         if(next_entry_ep.paths!=next_track->get_type().get_paths() && !train.critical)
513         {
514                 RoutingStep wait(this);
515                 wait.advance(dt);
516                 wait.trains[train_index].state = WAITING;
517                 wait.penalty += 15*Time::sec;
518                 wait.update_estimate();
519                 if(wait.is_viable())
520                         new_steps.push_back(wait);
521         }
522 }
523
524 bool TrainRoutePlanner::RoutingStep::update_states()
525 {
526         bool changes = false;
527         for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
528         {
529                 if(i->state==ARRIVED)
530                         continue;
531
532                 TrainState old_state = i->state;
533
534                 TrackIter next_track = i->track.next(i->path);
535                 if(next_track)
536                 {
537                         i->blocked_by = get_occupant(*next_track);
538                         if(i->blocked_by>=0)
539                                 i->state = BLOCKED;
540                         else if(i->state==BLOCKED)
541                                 i->state = MOVING;
542                 }
543                 else
544                         i->state = BLOCKED;
545
546                 if(i->state!=old_state)
547                         changes = true;
548         }
549
550         return changes;
551 }
552
553 bool TrainRoutePlanner::RoutingStep::check_deadlocks() const
554 {
555         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
556         {
557                 if(i->state!=BLOCKED)
558                         continue;
559
560                 if(i->blocked_by<0)
561                         return true;
562
563                 int slow = i->blocked_by;
564                 int fast = trains[slow].blocked_by;
565                 while(fast>=0 && trains[fast].blocked_by>=0)
566                 {
567                         if(fast==slow)
568                                 return true;
569
570                         slow = trains[slow].blocked_by;
571                         fast = trains[trains[fast].blocked_by].blocked_by;
572                 }
573         }
574
575         return false;
576 }
577
578 int TrainRoutePlanner::RoutingStep::get_occupant(Track &track) const
579 {
580         for(unsigned i=0; i<trains.size(); ++i)
581                 if(trains[i].is_occupying(track))
582                         return i;
583
584         return -1;
585 }
586
587 int TrainRoutePlanner::RoutingStep::find_next_train() const
588 {
589         Time::TimeDelta min_dt;
590         int next_train = -1;
591         for(unsigned i=0; i<trains.size(); ++i)
592                 if(trains[i].state==MOVING)
593                 {
594                         Time::TimeDelta dt = trains[i].get_time_to_next_track();
595                         if(dt<min_dt || next_train<0)
596                         {
597                                 min_dt = dt;
598                                 next_train = i;
599                         }
600                 }
601
602         return next_train;
603 }
604
605 void TrainRoutePlanner::RoutingStep::advance(const Time::TimeDelta &dt)
606 {
607         time += dt;
608         for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
609                 i->advance(dt);
610 }
611
612 void TrainRoutePlanner::RoutingStep::update_estimate()
613 {
614         cost_estimate = penalty;
615         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
616                 if(i->remaining_estimate>=0)
617                         cost_estimate += i->wait_time+((i->distance_traveled+i->remaining_estimate)/i->info->speed)*Time::sec;
618 }
619
620 bool TrainRoutePlanner::RoutingStep::is_viable() const
621 {
622         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
623                 if(i->remaining_estimate<0)
624                         return false;
625
626         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
627                 if(i->state==MOVING)
628                         return true;
629
630         return false;
631 }
632
633 bool TrainRoutePlanner::RoutingStep::is_goal() const
634 {
635         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
636                 if(i->state!=ARRIVED)
637                         return false;
638         return true;
639 }
640
641 bool TrainRoutePlanner::RoutingStep::operator<(const RoutingStep &other) const
642 {
643         return cost_estimate<other.cost_estimate;
644 }
645
646
647 TrainRoutePlanner::PlanningThread::PlanningThread(TrainRoutePlanner &p):
648         planner(p)
649 {
650         launch();
651 }
652
653 void TrainRoutePlanner::PlanningThread::main()
654 {
655         planner.create_plan();
656 }
657
658 } // namespace R2C2