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