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