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