]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/trainrouter.cpp
f0870d250f2b7b95293797a2c86a8c72addf56c1
[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         state(ON_THE_WAY),
20         waypoints_changed(false),
21         metrics_stale(false),
22         current_sequence(0)
23 {
24         train.get_layout().signal_block_reserved.connect(sigc::mem_fun(this, &TrainRouter::block_reserved));
25         train.signal_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_advanced));
26         train.signal_rear_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_rear_advanced));
27 }
28
29 TrainRouter::~TrainRouter()
30 {
31         for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
32                 delete *i;
33 }
34
35 void TrainRouter::set_priority(int p)
36 {
37         priority = p;
38 }
39
40 bool TrainRouter::set_route(const Route *r)
41 {
42         routes.clear();
43         if(r)
44         {
45                 routes.push_back(r);
46                 create_lead_route();
47         }
48
49         waypoints.clear();
50         sequence_points.clear();
51         current_sequence = 0;
52
53         route_changed();
54
55         return true;
56 }
57
58 const Route *TrainRouter::get_route() const
59 {
60         if(routes.empty())
61                 return 0;
62         return routes.front();
63 }
64
65 void TrainRouter::use_planned_route()
66 {
67         if(!planner || planner->get_result()!=TrainRoutePlanner::COMPLETE)
68                 return;
69         if(waypoints.empty())
70                 return;
71
72         const list<Route *> &planned_routes = planner->get_routes_for(train);
73
74         routes.clear();
75         routes.insert(routes.end(), planned_routes.begin(), planned_routes.end());
76         create_lead_route();
77
78         sequence_points = planner->get_sequence_for(train);
79         current_sequence = 0;
80
81         route_changed();
82 }
83
84 void TrainRouter::route_changed()
85 {
86         BlockIter fncb = train.get_last_critical_block().next();
87
88         state = ON_THE_WAY;
89         reserving_route = routes.begin();
90         if(!routes.empty())
91         {
92                 /* Find the route that should be used for the next allocated block.  We
93                 can't rely on the resync code in block_reserved since we may need to
94                 clear the stop marker to continue allocation. */
95                 const BlockAllocator &allocator = train.get_block_allocator();
96                 TrackIter track = allocator.first().track_iter();
97                 list<SequencePoint>::iterator seq_begin = sequence_points.begin();
98                 for(; track; track=track.next())
99                 {
100                         if(!advance_to_track(reserving_route, track))
101                         {
102                                 state = (allocator.is_block_current(track->get_block()) ? ADVANCED_TO_END : RESERVED_TO_END);
103                                 break;
104                         }
105                         if(&track->get_block()==fncb.block())
106                                 break;
107
108                         if(seq_begin!=sequence_points.end() && seq_begin->block==&track->get_block())
109                         {
110                                 // Assume any sequence points within critical blocks to be cleared
111                                 current_sequence = seq_begin->sequence_out;
112                                 ++seq_begin;
113                         }
114                 }
115
116                 sequence_points.erase(sequence_points.begin(), seq_begin);
117
118                 if(!sequence_points.empty())
119                 {
120                         const SequencePoint &sp = sequence_points.front();
121                         if(sp.block==fncb.block() && sp.preceding_train)
122                                 state = SEQUENCE_CHECK_PENDING;
123                 }
124         }
125
126         /* Refresh from the first non-critical block to pick up any changes in the
127         route.  Set stop marker first in case a stopping state was set within the
128         critical blocks. */
129         if(state!=ON_THE_WAY)
130                 train.stop_at(&*fncb.flip());
131         train.refresh_blocks_from(*fncb);
132         // If we don't need to stop, clear a possible previous stop marker.
133         if(state==ON_THE_WAY)
134                 train.stop_at(0);
135
136         const Route *route = get_route();
137         signal_route_changed.emit(route);
138         signal_event.emit(Message("route-changed", route));
139 }
140
141 void TrainRouter::set_destination(const TrackChain &d)
142 {
143         if(waypoints.empty())
144                 waypoints.push_back(Waypoint(d));
145         else
146                 waypoints.back() = Waypoint(d);
147         waypoints_changed = true;
148         metrics_stale = true;
149 }
150
151 void TrainRouter::add_waypoint(const TrackChain &chain, TrackChain::Direction dir)
152 {
153         waypoints.push_back(Waypoint(chain, dir));
154         waypoints_changed = true;
155         metrics_stale = true;
156 }
157
158 const TrainRouter::Waypoint &TrainRouter::get_waypoint(unsigned index) const
159 {
160         if(index>=waypoints.size())
161                 throw out_of_range("TrainRouter::is_waypoint");
162
163         return waypoints[index];
164 }
165
166 const TrainRouteMetric &TrainRouter::get_metric(int index) const
167 {
168         if(waypoints.empty())
169                 throw logic_error("no metrics");
170         else if(metrics_stale)
171                 throw logic_error("metrics are stale");
172
173         if(index<0)
174                 return *metrics.back();
175         else if(static_cast<unsigned>(index)>=waypoints.size())
176                 throw out_of_range("TrainRouter::get_metric");
177         else
178                 return *metrics[index];
179 }
180
181 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
182 {
183         delay = d;
184         waypoints_changed = true;
185 }
186
187 void TrainRouter::set_trip_duration(const Time::TimeDelta &d)
188 {
189         duration = d;
190 }
191
192 void TrainRouter::message(const Message &msg)
193 {
194         if(msg.type=="set-route")
195         {
196                 if(msg.value.check_type<Route *>())
197                         set_route(msg.value.value<Route *>());
198                 else
199                         set_route(msg.value.value<const Route *>());
200         }
201         else if(msg.type=="clear-route")
202                 set_route(0);
203         else if(msg.type=="set-destination")
204         {
205                 if(msg.value.check_type<TrackChain *>())
206                         set_destination(*msg.value.value<TrackChain *>());
207                 else
208                         set_destination(*msg.value.value<const TrackChain *>());
209         }
210         else if(msg.type=="add-waypoint")
211         {
212                 if(msg.value.check_type<Waypoint>())
213                 {
214                         Waypoint wp = msg.value.value<Waypoint>();
215                         add_waypoint(*wp.chain, wp.direction);
216                 }
217                 else if(msg.value.check_type<TrackChain *>())
218                         add_waypoint(*msg.value.value<TrackChain *>());
219                 else
220                         add_waypoint(*msg.value.value<const TrackChain *>());
221         }
222         else if(msg.type=="set-departure-delay")
223                 set_departure_delay(msg.value.value<Time::TimeDelta>());
224         else if(msg.type=="set-trip-duration")
225                 set_trip_duration(msg.value.value<Time::TimeDelta>());
226 }
227
228 void TrainRouter::tick(const Time::TimeDelta &dt)
229 {
230         if(waypoints_changed && !planner)
231                 start_planning(train.get_layout());
232
233         if(planner && planner->check()!=TrainRoutePlanner::PENDING)
234                 apply_plan(train.get_layout(), *planner);
235
236         Layout &layout = train.get_layout();
237         if(!layout.get_driver().is_halted() && !layout.get_clock().is_stopped())
238         {
239                 if(delay)
240                 {
241                         delay -= dt;
242                         if(delay<Time::zero)
243                         {
244                                 duration = max(duration+delay, Time::zero);
245                                 delay = Time::zero;
246                         }
247                 }
248                 else if(duration)
249                         duration = max(duration-dt, Time::zero);
250         }
251
252         if(state==SEQUENCE_CHECK_PENDING)
253         {
254                 if(sequence_points.front().is_cleared())
255                 {
256                         state = ON_THE_WAY;
257                         train.stop_at(0);
258                 }
259                 else
260                         state = WAITING_FOR_SEQUENCE;
261         }
262
263         if(state==ADVANCED_TO_END && !train.get_speed())
264         {
265                 signal_arrived.emit(waypoints.back().chain);
266                 signal_event.emit(Message("arrived", waypoints.back().chain));
267                 state = ARRIVED;
268         }
269         else if(state==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                         state = SEQUENCE_CHECK_PENDING;
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                 state = 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                         state = 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                         state = WAITING_FOR_SEQUENCE;
365                         train.stop_at(&block);
366                 }
367         }
368 }
369
370 void TrainRouter::train_advanced(Block &block)
371 {
372         if(!waypoints.empty())
373         {
374                 // A waypoint is considered reached when the train has advanced through it.
375                 BlockIter b_iter = train.get_block_allocator().iter_for(block);
376                 const Waypoint &wp = waypoints.front();
377                 TrackIter t_iter = b_iter.track_iter();
378                 if(wp.chain->has_track(*t_iter))
379                 {
380                         while(1)
381                         {
382                                 TrackIter next = t_iter.next();
383                                 if(!next)
384                                         break;
385
386                                 if(!wp.chain->has_track(*next))
387                                 {
388                                         if(wp.direction!=TrackChain::UNSPECIFIED)
389                                                 if(t_iter!=wp.chain->iter_for(*t_iter, wp.direction))
390                                                         break;
391
392                                         if(waypoints.size()==1)
393                                         {
394                                                 if(state==RESERVED_TO_END)
395                                                         state = ADVANCED_TO_END;
396                                         }
397                                         else
398                                         {
399                                                 const TrackChain *chain = wp.chain;
400                                                 waypoints.erase(waypoints.begin());
401                                                 metrics_stale = true;
402                                                 signal_waypoint_reached.emit(chain);
403                                                 signal_event.emit(Message("waypoint-reached", chain));
404                                         }
405                                         break;
406                                 }
407                                 else if(!block.has_track(*next))
408                                         break;
409
410                                 t_iter = next;
411                         }
412                 }
413         }
414 }
415
416 void TrainRouter::train_rear_advanced(Block &block)
417 {
418         Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
419
420         // Drop any routes that are now completely behind the train.
421         for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
422                 if((*i)->has_track(track))
423                 {
424                         if(i!=routes.begin())
425                         {
426                                 routes.erase(routes.begin(), i);
427                                 const Route *route = get_route();
428                                 signal_route_changed.emit(route);
429                                 signal_event.emit(Message("route-changed", route));
430                         }
431                         break;
432                 }
433 }
434
435 void TrainRouter::create_metrics()
436 {
437         for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
438                 delete *i;
439         metrics.clear();
440
441         metrics_stale = false;
442
443         if(waypoints.empty())
444                 return;
445
446         for(vector<Waypoint>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
447                 metrics.push_back(new TrainRouteMetric(*i->chain, i->direction));
448
449         for(unsigned i=metrics.size()-1; i-->0; )
450                 metrics[i]->chain_to(*metrics[i+1]);
451 }
452
453 bool TrainRouter::create_lead_route()
454 {
455         if(routes.empty() || !train.is_placed())
456                 return false;
457
458         BlockIter lcb = train.get_last_critical_block();
459         TrackIter last_track_rev = lcb.reverse().track_iter();
460
461         unsigned count = 0;
462         for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
463         {
464                 if(routes.front()->has_track(*i))
465                         ++count;
466                 else if(count>0)
467                 {
468                         if(count==routes.front()->get_tracks().size())
469                                 last_track_rev = i;
470                         break;
471                 }
472         }
473
474         TrackIter next_track = last_track_rev.flip();
475         if(!routes.front()->has_track(*last_track_rev) && !routes.front()->has_track(*next_track))
476         {
477                 Route *pf = Route::find(next_track, *routes.front());
478                 if(!pf)
479                         return false;
480
481                 routes.push_front(pf);
482         }
483
484         Route *lead = 0;
485         for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
486         {
487                 if(!lead && !routes.front()->has_track(*i))
488                 {
489                         lead = new Route(train.get_layout());
490                         lead->set_name("Lead");
491                         lead->set_temporary(true);
492                         routes.push_front(lead);
493
494                         TrackIter j = i.flip();
495                         lead->add_track(*j);
496                         lead->add_track(*j.next());
497                 }
498
499                 if(lead)
500                         lead->add_track(*i);
501         }
502
503         return true;
504 }
505
506 bool TrainRouter::advance_to_track(RouteList::iterator &route, const TrackIter &track)
507 {
508         Track &prev_track = *track.flip();
509         unsigned taddr = (track->get_type().is_turnout() ? track->get_turnout_address() : 0);
510         for(unsigned i=0; route!=routes.end(); ++i)
511         {
512                 bool in_route = (*route)->has_track(*track);
513                 bool prev_in_route = (*route)->has_track(prev_track);
514                 bool known_path = (!taddr || (*route)->get_turnout(taddr)>=0);
515
516                 if(in_route && (known_path || !prev_in_route))
517                         return true;
518                 else if(i==0 || prev_in_route)
519                         ++route;
520                 else
521                         throw logic_error("internal error (routes are not continuous)");
522         }
523
524         return false;
525 }
526
527 void TrainRouter::get_routers(Layout &layout, vector<TrainRouter *> &routers)
528 {
529         const map<unsigned, Train *> &trains = layout.get_trains();
530         routers.reserve(trains.size());
531         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
532                 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
533                         routers.push_back(router);
534 }
535
536 void TrainRouter::start_planning(Layout &layout)
537 {
538         vector<TrainRouter *> routers;
539         get_routers(layout, routers);
540
541         for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
542                 if((*i)->metrics_stale)
543                         (*i)->create_metrics();
544
545         RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
546         for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
547         {
548                 (*i)->waypoints_changed = false;
549                 (*i)->planner = planner;
550         }
551
552         planner->plan_async();
553 }
554
555 void TrainRouter::apply_plan(Layout &layout, TrainRoutePlanner &planner)
556 {
557         if(planner.get_result()==TrainRoutePlanner::FAILED)
558                 layout.emergency(0, "Route planning failed");
559
560         vector<TrainRouter *> routers;
561         get_routers(layout, routers);
562
563         for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
564                 if((*i)->planner.get()==&planner)
565                 {
566                         (*i)->use_planned_route();
567                         (*i)->planner = 0;
568                 }
569 }
570
571
572 TrainRouter::Waypoint::Waypoint(const TrackChain &c, TrackChain::Direction d):
573         chain(&c),
574         direction(d)
575 { }
576
577
578 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
579         block(&b),
580         preceding_train(0),
581         sequence_in(0),
582         sequence_out(o)
583 { }
584
585 bool TrainRouter::SequencePoint::is_cleared() const
586 {
587         if(!preceding_train)
588                 return true;
589
590         TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
591         return router->get_current_sequence()>=sequence_in;
592 }
593
594
595 TrainRouter::Loader::Loader(TrainRouter &r):
596         DataFile::ObjectLoader<TrainRouter>(r)
597 {
598         add("priority", &TrainRouter::priority);
599         add("route",    &Loader::route);
600 }
601
602 void TrainRouter::Loader::route(const string &n)
603 {
604         obj.set_route(&obj.train.get_layout().get_route(n));
605 }
606
607 } // namespace R2C2