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