]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/trainrouter.cpp
Unoccupy destination during planning when the train has departed again
[r2c2.git] / source / libr2c2 / trainrouter.cpp
1 #include "layout.h"
2 #include "route.h"
3 #include "trackiter.h"
4 #include "train.h"
5 #include "trackchain.h"
6 #include "trainroutemetric.h"
7 #include "trainrouteplanner.h"
8 #include "trainrouter.h"
9
10 using namespace std;
11 using namespace Msp;
12
13 namespace R2C2 {
14
15 TrainRouter::TrainRouter(Train &t):
16         TrainAI(t),
17         priority(0),
18         arrival(ON_THE_WAY),
19         destination(0),
20         destination_changed(false),
21         metrics_stale(false),
22         current_sequence(0),
23         sequence_check_pending(false)
24 {
25         train.get_layout().signal_block_reserved.connect(sigc::mem_fun(this, &TrainRouter::block_reserved));
26         train.signal_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_advanced));
27         train.signal_rear_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_rear_advanced));
28 }
29
30 TrainRouter::~TrainRouter()
31 {
32         for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
33                 delete *i;
34 }
35
36 void TrainRouter::set_priority(int p)
37 {
38         priority = p;
39 }
40
41 bool TrainRouter::set_route(const Route *r)
42 {
43         BlockIter fncb = train.get_first_noncritical_block();
44
45         Route *lead = 0;
46         if(r && train.is_placed())
47         {
48                 const BlockAllocator &allocator = train.get_block_allocator();
49                 TrackIter first = allocator.first().track_iter();
50                 TrackIter next = fncb.track_iter();
51                 if(!r->has_track(*next))
52                 {
53                         lead = Route::find(next, *r);
54                         if(!lead)
55                                 return false;
56                         create_lead_route(lead, lead);
57                 }
58                 else if(!r->has_track(*first))
59                         lead = create_lead_route(0, r);
60         }
61
62         routes.clear();
63         if(lead)
64                 routes.push_back(lead);
65         // TODO Check if eclipsed by lead route
66         if(r)
67                 routes.push_back(r);
68
69         destination = 0;
70         waypoints.clear();
71         sequence_points.clear();
72         current_sequence = 0;
73         sequence_check_pending = false;
74
75         route_changed();
76
77         return true;
78 }
79
80 const Route *TrainRouter::get_route() const
81 {
82         if(routes.empty())
83                 return 0;
84         return routes.front();
85 }
86
87 void TrainRouter::route_changed()
88 {
89         BlockIter fncb = train.get_first_noncritical_block();
90
91         reserving_route = routes.begin();
92         bool already_at_end = false;
93         if(!routes.empty())
94         {
95                 /* Find the route that should be used for the next allocated block.  We
96                 can't rely on the resync code in block_reserved since we may need to
97                 clear the stop marker to continue allocation. */
98                 TrackIter track = train.get_block_allocator().first().track_iter();
99                 for(; track; track=track.next())
100                 {
101                         if(!advance_to_track(reserving_route, *track))
102                         {
103                                 already_at_end = true;
104                                 break;
105                         }
106                         if(&track->get_block()==fncb.block())
107                                 break;
108                 }
109         }
110
111         if(!already_at_end)
112         {
113                 // We are not at the end of the route now, but might have been before.
114                 arrival = ON_THE_WAY;
115                 train.refresh_blocks_from(*fncb);
116                 if(!arrival)
117                         train.stop_at(0);
118         }
119         else if(!arrival)
120         {
121                 /* If arrival wasn't set before (perhaps because we weren't on a route),
122                 set it now. */
123                 arrival = RESERVED_TO_END;
124                 train.stop_at(&*fncb.flip());
125                 train.refresh_blocks_from(*fncb);
126         }
127
128         const Route *route = get_route();
129         signal_route_changed.emit(route);
130         signal_event.emit(Message("route-changed", route));
131 }
132
133 void TrainRouter::set_destination(const TrackChain &d)
134 {
135         destination = &d;
136         destination_changed = true;
137         metrics_stale = true;
138 }
139
140 bool TrainRouter::is_destination(Track &track) const
141 {
142         if(destination)
143                 return destination->has_track(track);
144         else
145                 return false;
146 }
147
148 void TrainRouter::add_waypoint(const TrackChain &wp)
149 {
150         waypoints.push_back(&wp);
151         destination_changed = true;
152         metrics_stale = true;
153 }
154
155 bool TrainRouter::is_waypoint(unsigned index, Track &track) const
156 {
157         if(index>=waypoints.size())
158                 throw out_of_range("TrainRouter::is_waypoint");
159
160         return waypoints[index]->has_track(track);
161 }
162
163 const TrainRouteMetric &TrainRouter::get_metric(int index) const
164 {
165         if(!destination)
166                 throw logic_error("no metrics");
167         else if(metrics_stale)
168                 throw logic_error("metrics are stale");
169
170         if(index<0)
171                 return *metrics.front();
172         else if(static_cast<unsigned>(index)>=waypoints.size())
173                 throw out_of_range("TrainRouter::get_metric");
174         else
175                 return *metrics[index+1];
176 }
177
178 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
179 {
180         delay = d;
181         destination_changed = true;
182 }
183
184 void TrainRouter::set_trip_duration(const Time::TimeDelta &d)
185 {
186         duration = d;
187 }
188
189 void TrainRouter::message(const Message &msg)
190 {
191         if(msg.type=="set-route")
192         {
193                 if(msg.value.check_type<Route *>())
194                         set_route(msg.value.value<Route *>());
195                 else
196                         set_route(msg.value.value<const Route *>());
197         }
198         else if(msg.type=="clear-route")
199                 set_route(0);
200         else if(msg.type=="set-destination")
201         {
202                 if(msg.value.check_type<TrackChain *>())
203                         set_destination(*msg.value.value<TrackChain *>());
204                 else
205                         set_destination(*msg.value.value<const TrackChain *>());
206         }
207         else if(msg.type=="add-waypoint")
208         {
209                 if(msg.value.check_type<TrackChain *>())
210                         add_waypoint(*msg.value.value<TrackChain *>());
211                 else
212                         add_waypoint(*msg.value.value<const TrackChain *>());
213         }
214         else if(msg.type=="set-departure-delay")
215                 set_departure_delay(msg.value.value<Time::TimeDelta>());
216         else if(msg.type=="set-trip-duration")
217                 set_trip_duration(msg.value.value<Time::TimeDelta>());
218 }
219
220 void TrainRouter::tick(const Time::TimeDelta &dt)
221 {
222         if(delay)
223         {
224                 delay -= dt;
225                 if(delay<Time::zero)
226                 {
227                         duration = max(duration+delay, Time::zero);
228                         delay = Time::zero;
229                 }
230         }
231         else if(duration)
232                 duration = max(duration-dt, Time::zero);
233
234         if(destination_changed && !planner)
235                 start_planning(train.get_layout());
236
237         if(planner && planner->check()!=TrainRoutePlanner::PENDING)
238         {
239                 destination_changed = false;
240                 if(planner->get_result()==TrainRoutePlanner::COMPLETE)
241                 {
242                         const list<Route *> &planned_routes = planner->get_routes_for(train);
243
244                         routes.clear();
245                         Route *lead = create_lead_route(0, planned_routes.front());
246                         routes.push_back(lead);
247
248                         list<Route *>::const_iterator begin = planned_routes.begin();
249                         for(; begin!=planned_routes.end(); ++begin)
250                         {
251                                 const Route::TrackSet &tracks = (*begin)->get_tracks();
252                                 bool eclipsed = true;
253                                 for(Route::TrackSet::const_iterator i=tracks.begin(); (eclipsed && i!=tracks.end()); ++i)
254                                         eclipsed = lead->has_track(**i);
255                                 if(!eclipsed)
256                                         break;
257                         }
258                         routes.insert(routes.end(), begin, planned_routes.end());
259
260                         sequence_points = planner->get_sequence_for(train);
261                         current_sequence = 0;
262                         sequence_check_pending = false;
263
264                         route_changed();
265                 }
266                 planner = 0;
267         }
268
269         if(sequence_check_pending)
270         {
271                 if(sequence_points.front().is_cleared())
272                         train.stop_at(0);
273                 sequence_check_pending = false;
274         }
275
276         if(arrival==RESERVED_TO_END && !train.get_speed())
277         {
278                 signal_arrived.emit(destination);
279                 signal_event.emit(Message("arrived", destination));
280                 arrival = ARRIVED;
281         }
282         else if(arrival==ARRIVED && !train.get_block_allocator().is_active())
283                 set_route(0);
284 }
285
286 void TrainRouter::save(list<DataFile::Statement> &st) const
287 {
288         st.push_back((DataFile::Statement("priority"), priority));
289
290         if(!routes.empty())
291         {
292                 RouteList::const_iterator i = routes.begin();
293                 for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
294                 if(i!=routes.end())
295                         st.push_back((DataFile::Statement("route"), (*i)->get_name()));
296         }
297 }
298
299 void TrainRouter::block_reserved(Block &block, Train *t)
300 {
301         if(routes.empty())
302                 return;
303
304         if(t!=&train)
305         {
306                 if(!t)
307                         return;
308
309                 // Are we waiting for the other train to pass a sequence point?
310                 SequencePoint &sp = sequence_points.front();
311                 if(sp.preceding_train==t && sp.block==&block)
312                         /* The other train's router will advance its sequence on the same
313                         signal and may not have handled it yet. */
314                         sequence_check_pending = true;
315
316                 return;
317         }
318
319         // Did we reach our next sequence point?
320         if(!sequence_points.empty())
321         {
322                 SequencePoint &sp = sequence_points.front();
323                 if(sp.block==&block)
324                 {
325                         current_sequence = sp.sequence_out;
326                         sequence_points.pop_front();
327                 }
328         }
329
330         TrackIter track = train.get_block_allocator().iter_for(block).track_iter();
331
332         // Is the block a turnout?  If it is, set it to the correct path.
333         if(unsigned taddr = block.get_turnout_address())
334         {
335                 int path = (*reserving_route)->get_turnout(taddr);
336                 if(path>=0)
337                         track->set_active_path(path);
338         }
339
340         /* If the allocator has released blocks from the front, we may need to
341         resync reserving_route. */
342         if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
343         {
344                 reserving_route = routes.begin();
345                 arrival = ON_THE_WAY;
346                 track = t->get_block_allocator().first().track_iter();
347                 for(; track; track=track.next())
348                 {
349                         if(!advance_to_track(reserving_route, *track))
350                                 throw logic_error("internal error (reservation outside of route)");
351                         else if(&track->get_block()==&block)
352                                 break;
353                 }
354         }
355
356         /* Keep reserving_route pointing to the route containing the block that is
357         expected to be allocated next. */
358         for(; track; track=track.next((*reserving_route)->get_path(*track)))
359         {
360                 if(!advance_to_track(reserving_route, *track))
361                 {
362                         // We've reached the end of the route.  Stop here.
363                         arrival = RESERVED_TO_END;
364                         train.stop_at(&block);
365                         return;
366                 }
367                 if(&track->get_block()!=&block)
368                         break;
369         }
370
371         // Do we need to wait for another train to pass?
372         if(!sequence_points.empty())
373         {
374                 SequencePoint &sp = sequence_points.front();
375                 if(sp.block==&track->get_block() && !sp.is_cleared())
376                         train.stop_at(&block);
377         }
378 }
379
380 void TrainRouter::train_advanced(Block &block)
381 {
382         BlockIter b_iter = train.get_block_allocator().iter_for(block);
383
384         if(!waypoints.empty())
385         {
386                 // A waypoint is considered reached when the train has advanced through it.
387                 const TrackChain &wp = *waypoints.front();
388                 TrackIter t_iter = b_iter.track_iter();
389                 if(wp.has_track(*t_iter))
390                 {
391                         for(; t_iter; t_iter=t_iter.next())
392                         {
393                                 if(!wp.has_track(*t_iter))
394                                 {
395                                         waypoints.erase(waypoints.begin());
396                                         signal_waypoint_reached.emit(&wp);
397                                         signal_event.emit(Message("waypoint-reached", &wp));
398                                         break;
399                                 }
400                                 else if(!block.has_track(*t_iter))
401                                         break;
402                         }
403                 }
404         }
405 }
406
407 void TrainRouter::train_rear_advanced(Block &block)
408 {
409         Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
410
411         // Drop any routes that are now completely behind the train.
412         for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
413                 if((*i)->has_track(track))
414                 {
415                         if(i!=routes.begin())
416                         {
417                                 routes.erase(routes.begin(), i);
418                                 const Route *route = get_route();
419                                 signal_route_changed.emit(route);
420                                 signal_event.emit(Message("route-changed", route));
421                         }
422                         break;
423                 }
424 }
425
426 void TrainRouter::create_metrics()
427 {
428         for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
429                 delete *i;
430         metrics.clear();
431
432         if(!destination)
433                 return;
434
435         metrics.push_back(new TrainRouteMetric(*destination));
436         for(vector<const TrackChain *>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
437                 metrics.push_back(new TrainRouteMetric(**i));
438
439         for(unsigned i=metrics.size(); --i>0; )
440                 metrics[i]->chain_to(*metrics[(i+1)%metrics.size()]);
441 }
442
443 Route *TrainRouter::create_lead_route(Route *lead, const Route *target)
444 {
445         if(!lead)
446         {
447                 lead = new Route(train.get_layout());
448                 lead->set_name("Lead");
449                 lead->set_temporary(true);
450         }
451
452         bool target_tracks = 0;
453         for(TrackIter i=train.get_block_allocator().first().track_iter(); (target_tracks<2 && i); i=i.next())
454         {
455                 if(i->get_block().get_train()!=&train)
456                         break;
457                 if(target)
458                 {
459                         if(target->has_track(*i))
460                                 ++target_tracks;
461                         else if(target_tracks>0)
462                                 break;
463                 }
464                 lead->add_track(*i);
465         }
466
467         return lead;
468 }
469
470 bool TrainRouter::is_valid_for_track(const Route &route, Track &track) const
471 {
472         if(!route.has_track(track))
473                 return false;
474         if(track.get_type().is_turnout() && route.get_turnout(track.get_turnout_address())<0)
475                 return false;
476         return true;
477 }
478
479 bool TrainRouter::advance_to_track(RouteList::iterator &route, Track &track)
480 {
481         if(!is_valid_for_track(**route, track))
482         {
483                 ++route;
484                 if(route==routes.end())
485                         return false;
486                 if(!is_valid_for_track(**route, track))
487                         throw logic_error("internal error (routes are not continuous)");
488         }
489
490         return true;
491 }
492
493 void TrainRouter::start_planning(Layout &layout)
494 {
495         RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
496
497         const map<unsigned, Train *> &trains = layout.get_trains();
498         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
499                 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
500                 {
501                         if(router->metrics_stale)
502                         {
503                                 router->create_metrics();
504                                 router->metrics_stale = false;
505                         }
506                         router->planner = planner;
507                 }
508
509         planner->plan_async();
510 }
511
512
513 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
514         block(&b),
515         preceding_train(0),
516         sequence_in(0),
517         sequence_out(o)
518 { }
519
520 bool TrainRouter::SequencePoint::is_cleared() const
521 {
522         if(!preceding_train)
523                 return true;
524
525         TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
526         return router->get_current_sequence()>=sequence_in;
527 }
528
529
530 TrainRouter::Loader::Loader(TrainRouter &r):
531         DataFile::ObjectLoader<TrainRouter>(r)
532 {
533         add("priority", &TrainRouter::priority);
534         add("route",    &Loader::route);
535 }
536
537 void TrainRouter::Loader::route(const string &n)
538 {
539         obj.set_route(&obj.train.get_layout().get_route(n));
540 }
541
542 } // namespace R2C2