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