]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/trainrouter.cpp
d530687af92fc9612e3f30f7823eafc5425a62ab
[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.is_cleared())
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                 if(state==WAITING_FOR_SEQUENCE)
298                 {
299                         SequencePoint &sp = sequence_points.front();
300                         if(sp.preceding_train==t && sp.block==&block)
301                                 /* The other train's router will advance its sequence on the same
302                                 signal and may not have handled it yet. */
303                                 state = SEQUENCE_CHECK_PENDING;
304                 }
305
306                 return;
307         }
308
309         // Did we reach our next sequence point?
310         if(!sequence_points.empty())
311         {
312                 SequencePoint &sp = sequence_points.front();
313                 if(sp.block==&block)
314                 {
315                         current_sequence = sp.sequence_out;
316                         sequence_points.pop_front();
317                 }
318         }
319
320         TrackIter track = train.get_block_allocator().iter_for(block).track_iter();
321
322         // Is the block a turnout?  If it is, set it to the correct path.
323         if(unsigned taddr = block.get_turnout_address())
324         {
325                 int path = (*reserving_route)->get_turnout(taddr);
326                 if(path>=0)
327                         track->set_active_path(path);
328         }
329
330         /* If the allocator has released blocks from the front, we may need to
331         resync reserving_route. */
332         if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
333         {
334                 reserving_route = routes.begin();
335                 state = ON_THE_WAY;
336                 track = t->get_block_allocator().first().track_iter();
337                 for(; track; track=track.next())
338                 {
339                         if(!advance_to_track(reserving_route, track))
340                                 throw logic_error("internal error (reservation outside of route)");
341                         else if(&track->get_block()==&block)
342                                 break;
343                 }
344         }
345
346         /* Keep reserving_route pointing to the route containing the block that is
347         expected to be allocated next. */
348         for(; track; track=track.next((*reserving_route)->get_path(*track)))
349         {
350                 if(!advance_to_track(reserving_route, track))
351                 {
352                         // We've reached the end of the route.  Stop here.
353                         state = RESERVED_TO_END;
354                         train.stop_at(&block);
355                         return;
356                 }
357                 if(&track->get_block()!=&block)
358                         break;
359         }
360
361         // Do we need to wait for another train to pass?
362         if(!sequence_points.empty())
363         {
364                 SequencePoint &sp = sequence_points.front();
365                 if(sp.block==&track->get_block() && !sp.is_cleared())
366                 {
367                         state = SEQUENCE_CHECK_PENDING;
368                         train.stop_at(&block);
369                 }
370         }
371 }
372
373 void TrainRouter::train_advanced(Block &block)
374 {
375         if(!waypoints.empty())
376         {
377                 // A waypoint is considered reached when the train has advanced through it.
378                 BlockIter b_iter = train.get_block_allocator().iter_for(block);
379                 const Waypoint &wp = waypoints.front();
380                 TrackIter t_iter = b_iter.track_iter();
381                 if(wp.chain->has_track(*t_iter))
382                 {
383                         while(1)
384                         {
385                                 TrackIter next = t_iter.next();
386                                 if(!next)
387                                         break;
388
389                                 if(!wp.chain->has_track(*next))
390                                 {
391                                         if(wp.direction!=TrackChain::UNSPECIFIED)
392                                                 if(t_iter!=wp.chain->iter_for(*t_iter, wp.direction))
393                                                         break;
394
395                                         if(waypoints.size()==1)
396                                         {
397                                                 if(state==RESERVED_TO_END)
398                                                         state = ADVANCED_TO_END;
399                                         }
400                                         else
401                                         {
402                                                 const TrackChain *chain = wp.chain;
403                                                 waypoints.erase(waypoints.begin());
404                                                 metrics_stale = true;
405                                                 signal_waypoint_reached.emit(chain);
406                                                 signal_event.emit(Message("waypoint-reached", chain));
407                                         }
408                                         break;
409                                 }
410                                 else if(!block.has_track(*next))
411                                         break;
412
413                                 t_iter = next;
414                         }
415                 }
416         }
417 }
418
419 void TrainRouter::train_rear_advanced(Block &block)
420 {
421         Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
422
423         // Drop any routes that are now completely behind the train.
424         for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
425                 if((*i)->has_track(track))
426                 {
427                         if(i!=routes.begin())
428                         {
429                                 routes.erase(routes.begin(), i);
430                                 const Route *route = get_route();
431                                 signal_route_changed.emit(route);
432                                 signal_event.emit(Message("route-changed", route));
433                         }
434                         break;
435                 }
436 }
437
438 void TrainRouter::create_metrics()
439 {
440         for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
441                 delete *i;
442         metrics.clear();
443
444         metrics_stale = false;
445
446         if(waypoints.empty())
447                 return;
448
449         for(vector<Waypoint>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
450                 metrics.push_back(new TrainRouteMetric(*i->chain, i->direction));
451
452         for(unsigned i=metrics.size()-1; i-->0; )
453                 metrics[i]->chain_to(*metrics[i+1]);
454 }
455
456 bool TrainRouter::create_lead_route()
457 {
458         if(routes.empty() || !train.is_placed())
459                 return false;
460
461         BlockIter lcb = train.get_last_critical_block();
462         TrackIter last_track_rev = lcb.reverse().track_iter();
463
464         unsigned count = 0;
465         for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
466         {
467                 if(routes.front()->has_track(*i))
468                         ++count;
469                 else if(count>0)
470                 {
471                         if(count==routes.front()->get_tracks().size())
472                                 last_track_rev = i;
473                         break;
474                 }
475         }
476
477         TrackIter next_track = last_track_rev.flip();
478         if(!routes.front()->has_track(*last_track_rev) && !routes.front()->has_track(*next_track))
479         {
480                 Route *pf = Route::find(next_track, *routes.front());
481                 if(!pf)
482                         return false;
483
484                 routes.push_front(pf);
485         }
486
487         Route *lead = 0;
488         for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
489         {
490                 if(!lead && !routes.front()->has_track(*i))
491                 {
492                         lead = new Route(train.get_layout());
493                         lead->set_name("Lead");
494                         lead->set_temporary(true);
495                         routes.push_front(lead);
496
497                         TrackIter j = i.flip();
498                         lead->add_track(*j);
499                         lead->add_track(*j.next());
500                 }
501
502                 if(lead)
503                         lead->add_track(*i);
504         }
505
506         return true;
507 }
508
509 bool TrainRouter::advance_to_track(RouteList::iterator &route, const TrackIter &track)
510 {
511         Track &prev_track = *track.flip();
512         unsigned taddr = (track->get_type().is_turnout() ? track->get_turnout_address() : 0);
513         for(unsigned i=0; route!=routes.end(); ++i)
514         {
515                 bool in_route = (*route)->has_track(*track);
516                 bool prev_in_route = (*route)->has_track(prev_track);
517                 bool known_path = (!taddr || (*route)->get_turnout(taddr)>=0);
518
519                 if(in_route && (known_path || !prev_in_route))
520                         return true;
521                 else if(i==0 || prev_in_route)
522                         ++route;
523                 else
524                         throw logic_error("internal error (routes are not continuous)");
525         }
526
527         return false;
528 }
529
530 void TrainRouter::get_routers(Layout &layout, vector<TrainRouter *> &routers, TrainRoutePlanner *planner)
531 {
532         const map<unsigned, Train *> &trains = layout.get_trains();
533         routers.reserve(trains.size());
534         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
535                 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
536                         if(!planner || router->planner.get()==planner)
537                                 routers.push_back(router);
538 }
539
540 void TrainRouter::start_planning(Layout &layout)
541 {
542         vector<TrainRouter *> routers;
543         get_routers(layout, routers);
544
545         for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
546                 if((*i)->metrics_stale)
547                         (*i)->create_metrics();
548
549         RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
550         for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
551         {
552                 (*i)->waypoints_changed = false;
553                 (*i)->planner = planner;
554         }
555
556         planner->plan_async();
557 }
558
559 void TrainRouter::apply_plan(Layout &layout, TrainRoutePlanner &planner)
560 {
561         if(planner.get_result()==TrainRoutePlanner::FAILED)
562                 layout.emergency(0, "Route planning failed");
563
564         vector<TrainRouter *> routers;
565         get_routers(layout, routers, &planner);
566
567         /* Clear sequence counters first to avoid inconsistent state while applying
568         the plan. */
569         for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
570                 (*i)->current_sequence = 0;
571
572         for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
573         {
574                 (*i)->use_planned_route();
575                 (*i)->planner = 0;
576         }
577 }
578
579
580 TrainRouter::Waypoint::Waypoint(const TrackChain &c, TrackChain::Direction d):
581         chain(&c),
582         direction(d)
583 { }
584
585
586 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
587         block(&b),
588         preceding_train(0),
589         sequence_in(0),
590         sequence_out(o)
591 { }
592
593 bool TrainRouter::SequencePoint::is_cleared() const
594 {
595         if(!preceding_train)
596                 return true;
597
598         TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
599         return router->get_current_sequence()>=sequence_in;
600 }
601
602
603 TrainRouter::Loader::Loader(TrainRouter &r):
604         DataFile::ObjectLoader<TrainRouter>(r)
605 {
606         add("priority", &TrainRouter::priority);
607         add("route",    &Loader::route);
608 }
609
610 void TrainRouter::Loader::route(const string &n)
611 {
612         obj.set_route(&obj.train.get_layout().get_route(n));
613 }
614
615 } // namespace R2C2