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