]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/trainrouteplanner.cpp
Add a distance metric to turn the routing into an A* search
[r2c2.git] / source / libr2c2 / trainrouteplanner.cpp
1 #include "catalogue.h"
2 #include "layout.h"
3 #include "route.h"
4 #include "train.h"
5 #include "trainroutemetric.h"
6 #include "trainrouteplanner.h"
7 #include "trainrouter.h"
8 #include "vehicle.h"
9
10 using namespace std;
11 using namespace Msp;
12
13 namespace R2C2 {
14
15 TrainRoutePlanner::TrainRoutePlanner(Layout &layout)
16 {
17         const map<unsigned, Train *> &trains = layout.get_trains();
18         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
19         {
20                 TrainRoutingInfo info(*i->second);
21                 if(info.router && info.router->get_destination())
22                         routed_trains.push_back(info);
23         }
24
25         queue.push_back(RoutingStep());
26         RoutingStep &start = queue.back();
27         for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
28                 start.trains.push_back(TrainRoutingState(*i));
29         start.update_estimate();
30 }
31
32 void TrainRoutePlanner::plan()
33 {
34         const RoutingStep *goal = 0;
35         while(!queue.empty())
36         {
37                 const RoutingStep &step = get_step();
38                 if(step.is_goal())
39                 {
40                         goal = &step;
41                         break;
42                 }
43
44                 add_steps(step);
45         }
46
47         if(goal)
48                 create_routes(*goal);
49 }
50
51 const TrainRoutePlanner::RoutingStep &TrainRoutePlanner::get_step()
52 {
53         steps.splice(steps.end(), queue, queue.begin());
54         return steps.back();
55 }
56
57 void TrainRoutePlanner::add_steps(const RoutingStep &step)
58 {
59         list<RoutingStep> new_steps;
60         step.create_successors(new_steps);
61         new_steps.sort();
62         queue.merge(new_steps);
63 }
64
65 void TrainRoutePlanner::create_routes(const RoutingStep &goal)
66 {
67         for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
68         {
69                 i->route = new Route(i->train->get_layout());
70                 i->route->set_name("Router");
71                 i->route->set_temporary(true);
72         }
73
74         for(const RoutingStep *i=&goal; i; i=i->prev)
75         {
76                 for(vector<TrainRoutingState>::const_iterator j=i->trains.begin(); j!=i->trains.end(); ++j)
77                 {
78                         if(j->state==WAITING || j->state==BLOCKED)
79                                 j->info->waits.push_front(&*j);
80                         j->info->route->add_track(*j->track);
81                 }
82         }
83
84         for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
85         {
86                 i->router->set_route(i->route);
87                 const TrainRoutingState *current_wait = 0;
88                 for(list<const TrainRoutingState *>::const_iterator j=i->waits.begin(); j!=i->waits.end(); ++j)
89                         if(!current_wait || (*j)->track.track()!=current_wait->track.track())
90                         {
91                                 Block &block = (*j)->track.next()->get_block();
92                                 i->router->add_wait(block, 0);
93                                 current_wait = *j;
94                         }
95         }
96 }
97
98
99 TrainRoutePlanner::TrainRoutingInfo::TrainRoutingInfo(Train &t):
100         train(&t),
101         speed(train->get_maximum_speed()),
102         router(train->get_ai_of_type<TrainRouter>()),
103         route(0)
104 {
105         // If no maximum speed is specified, use a sensible default
106         if(!speed)
107                 speed = 20*train->get_layout().get_catalogue().get_scale();
108 }
109
110
111 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(Track &t, unsigned p, OccupiedTrack *n):
112         track(&t),
113         path_length(track->get_type().get_path_length(p)),
114         next(n),
115         n_tracks(next ? next->n_tracks+1 : 1),
116         refcount(1)
117 {
118         if(next)
119                 ++next->refcount;
120 }
121
122 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(const OccupiedTrack &other):
123         track(other.track),
124         path_length(other.path_length),
125         next(other.next),
126         n_tracks(other.n_tracks),
127         refcount(1)
128 {
129         if(next)
130                 ++next->refcount;
131 }
132
133 TrainRoutePlanner::OccupiedTrack::~OccupiedTrack()
134 {
135         if(next && !--next->refcount)
136                 delete next;
137 }
138
139
140 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(TrainRoutingInfo &inf):
141         info(&inf),
142         occupied_tracks(0),
143         state(MOVING),
144         delay(info->router->get_departure_delay()),
145         waypoint(info->router->get_n_waypoints() ? 0 : -1),
146         blocked_by(-1)
147 {
148         const Vehicle *veh = &info->train->get_vehicle(0);
149         // TODO margins
150         TrackOffsetIter track_and_offs = veh->get_placement().get_position(VehiclePlacement::FRONT_BUFFER);
151         track = track_and_offs.track_iter();
152         offset = track_and_offs.offset();
153         path = track->get_active_path();
154
155         while(Vehicle *next = veh->get_link(1))
156                 veh = next;
157         track_and_offs = veh->get_placement().get_position(VehiclePlacement::BACK_BUFFER);
158         back_offset = track_and_offs.offset();
159
160         TrackIter iter = track_and_offs.track_iter();
161         while(1)
162         {
163                 occupied_tracks = new OccupiedTrack(*iter, iter->get_active_path(), occupied_tracks);
164                 if(iter.track()==track.track())
165                         break;
166                 iter = iter.next();
167         }
168
169         update_estimate();
170 }
171
172 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(const TrainRoutingState &other):
173         info(other.info),
174         track(other.track),
175         path(other.path),
176         occupied_tracks(other.occupied_tracks),
177         offset(other.offset),
178         back_offset(other.back_offset),
179         state(other.state),
180         delay(other.delay),
181         waypoint(other.waypoint),
182         remaining_estimate(other.remaining_estimate),
183         blocked_by(other.blocked_by)
184 {
185         ++occupied_tracks->refcount;
186 }
187
188 TrainRoutePlanner::TrainRoutingState::~TrainRoutingState()
189 {
190         if(occupied_tracks && !--occupied_tracks->refcount)
191                 delete occupied_tracks;
192 }
193
194 Time::TimeDelta TrainRoutePlanner::TrainRoutingState::get_time_to_next_track() const
195 {
196         return ((track->get_type().get_path_length(path)-offset)/info->speed)*Time::sec+delay;
197 }
198
199 bool TrainRoutePlanner::TrainRoutingState::is_occupying(Track &trk) const
200 {
201         OccupiedTrack *occ = occupied_tracks;
202         for(unsigned n=occ->n_tracks; n>0; --n, occ=occ->next)
203                 if(occ->track==&trk)
204                         return true;
205         return false;
206 }
207
208 bool TrainRoutePlanner::TrainRoutingState::check_arrival()
209 {
210         TrainRouter &router = *info->router;
211         TrackIter next_track = track.next(path);
212
213         if(waypoint<0 && router.is_destination(*track) && !router.is_destination(*next_track))
214         {
215                 state = ARRIVED;
216                 return true;
217         }
218         else if(waypoint>=0 && router.is_waypoint(waypoint, *track) && !router.is_waypoint(waypoint, *next_track))
219         {
220                 ++waypoint;
221                 if(waypoint>=static_cast<int>(router.get_n_waypoints()))
222                         waypoint = -1;
223         }
224
225         return false;
226 }
227
228 void TrainRoutePlanner::TrainRoutingState::advance(float distance)
229 {
230         offset += distance;
231         back_offset += distance;
232
233         OccupiedTrack *last_occ = occupied_tracks;
234         for(unsigned n=occupied_tracks->n_tracks; n>1; --n)
235                 last_occ = last_occ->next;
236
237         // XXX What if there's multiple tracks to remove?
238         if(back_offset>last_occ->path_length)
239         {
240                 back_offset -= last_occ->path_length;
241                 if(occupied_tracks->refcount>1)
242                 {
243                         --occupied_tracks->refcount;
244                         occupied_tracks = new OccupiedTrack(*occupied_tracks);
245                 }
246                 --occupied_tracks->n_tracks;
247         }
248
249         remaining_estimate -= (distance/info->speed)*Time::sec;
250         if(remaining_estimate<Time::zero)
251                 remaining_estimate = Time::zero;
252 }
253
254 void TrainRoutePlanner::TrainRoutingState::advance_track(unsigned next_path)
255 {
256         float distance = occupied_tracks->path_length-offset;
257         track = track.next(path);
258         path = next_path;
259         occupied_tracks = new OccupiedTrack(*track, path, occupied_tracks);
260         advance(distance);
261         offset = 0;
262 }
263
264 void TrainRoutePlanner::TrainRoutingState::update_estimate()
265 {
266         TrackIter iter = track.reverse(path);
267         float distance = info->router->get_metric(waypoint).get_distance_from(*iter.track(), iter.entry());
268         distance += track->get_type().get_path_length(path)-offset;
269         remaining_estimate = (distance/info->speed)*Time::sec+delay;
270 }
271
272
273 TrainRoutePlanner::RoutingStep::RoutingStep():
274         prev(0)
275 { }
276
277 TrainRoutePlanner::RoutingStep::RoutingStep(const RoutingStep *p):
278         time(p->time),
279         total_estimate(p->total_estimate),
280         trains(p->trains),
281         prev(p)
282 { }
283
284 void TrainRoutePlanner::RoutingStep::create_successors(list<RoutingStep> &new_steps) const
285 {
286         RoutingStep next(this);
287         if(next.update_states())
288         {
289                 if(next.check_deadlocks())
290                         return;
291
292                 new_steps.push_back(next);
293                 return;
294         }
295
296         int train_index = find_next_train();
297         if(train_index<0)
298                 return;
299
300         TrainRoutingState &train = next.trains[train_index];
301
302         Time::TimeDelta dt = train.get_time_to_next_track();
303         next.advance(dt);
304
305         if(train.check_arrival())
306         {
307                 new_steps.push_back(next);
308                 return;
309         }
310
311         TrackIter next_track = train.track.next(train.path);
312         train.advance_track(0);
313
314         const TrackType::Endpoint &next_entry_ep = next_track.endpoint();
315         for(unsigned i=0; next_entry_ep.paths>>i; ++i)
316                 if(next_entry_ep.has_path(i))
317                 {
318                         train.path = i;
319                         train.update_estimate();
320                         next.update_estimate();
321                         if(next.is_viable())
322                                 new_steps.push_back(next);
323                 }
324
325         if(next_entry_ep.paths!=next_track->get_type().get_paths())
326         {
327                 RoutingStep wait(this);
328                 wait.advance(dt);
329                 wait.trains[train_index].state = WAITING;
330                 if(wait.is_viable())
331                         new_steps.push_back(wait);
332         }
333 }
334
335 bool TrainRoutePlanner::RoutingStep::update_states()
336 {
337         bool changes = false;
338         for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
339         {
340                 if(i->state==ARRIVED)
341                         continue;
342
343                 TrainState old_state = i->state;
344
345                 TrackIter next_track = i->track.next(i->path);
346                 if(next_track)
347                 {
348                         i->blocked_by = get_occupant(*next_track);
349                         if(i->blocked_by>=0)
350                                 i->state = BLOCKED;
351                         else if(i->state==BLOCKED)
352                                 i->state = MOVING;
353                 }
354                 else
355                         i->state = BLOCKED;
356
357                 if(i->state!=old_state)
358                         changes = true;
359         }
360
361         return changes;
362 }
363
364 bool TrainRoutePlanner::RoutingStep::check_deadlocks() const
365 {
366         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
367         {
368                 if(i->state!=BLOCKED)
369                         continue;
370
371                 if(i->blocked_by<0)
372                         return true;
373
374                 int slow = i->blocked_by;
375                 int fast = trains[slow].blocked_by;
376                 while(fast>=0 && trains[fast].blocked_by>=0)
377                 {
378                         if(fast==slow)
379                                 return true;
380
381                         slow = trains[slow].blocked_by;
382                         fast = trains[trains[fast].blocked_by].blocked_by;
383                 }
384         }
385
386         return false;
387 }
388
389 int TrainRoutePlanner::RoutingStep::get_occupant(Track &track) const
390 {
391         for(unsigned i=0; i<trains.size(); ++i)
392                 if(trains[i].is_occupying(track))
393                         return i;
394
395         return -1;
396 }
397
398 int TrainRoutePlanner::RoutingStep::find_next_train() const
399 {
400         Time::TimeDelta min_dt;
401         int next_train = -1;
402         for(unsigned i=0; i<trains.size(); ++i)
403                 if(trains[i].state==MOVING)
404                 {
405                         Time::TimeDelta dt = trains[i].get_time_to_next_track();
406                         if(dt<min_dt || next_train<0)
407                         {
408                                 min_dt = dt;
409                                 next_train = i;
410                         }
411                 }
412
413         return next_train;
414 }
415
416 void TrainRoutePlanner::RoutingStep::advance(const Time::TimeDelta &dt)
417 {
418         time += dt;
419         for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
420         {
421                 if(i->delay)
422                 {
423                         i->delay -= dt;
424                         if(i->delay>Time::zero)
425                                 continue;
426                         i->delay = Time::zero;
427                 }
428                 else if(i->state==MOVING)
429                         i->advance(i->info->speed*(dt/Time::sec));
430         }
431 }
432
433 void TrainRoutePlanner::RoutingStep::update_estimate()
434 {
435         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
436         {
437                 if(i->remaining_estimate<Time::zero)
438                 {
439                         total_estimate = i->remaining_estimate;
440                         return;
441                 }
442
443                 Time::TimeDelta t = time+i->remaining_estimate;
444                 if(i==trains.begin() || t>total_estimate)
445                         total_estimate = t;
446         }
447 }
448
449 bool TrainRoutePlanner::RoutingStep::is_viable() const
450 {
451         if(total_estimate<Time::zero)
452                 return false;
453
454         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
455                 if(i->state==MOVING)
456                         return true;
457
458         return false;
459 }
460
461 bool TrainRoutePlanner::RoutingStep::is_goal() const
462 {
463         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
464                 if(i->state!=ARRIVED)
465                         return false;
466         return true;
467 }
468
469 bool TrainRoutePlanner::RoutingStep::operator<(const RoutingStep &other) const
470 {
471         return total_estimate<other.total_estimate;
472 }
473
474 } // namespace R2C2