]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/train.cpp
Simplify some interfaces by using track and block iterators
[r2c2.git] / source / libr2c2 / train.cpp
1 #include <algorithm>
2 #include <cmath>
3 #include <msp/core/maputils.h>
4 #include <msp/core/raii.h>
5 #include <msp/strings/format.h>
6 #include <msp/time/units.h>
7 #include <msp/time/utils.h>
8 #include "aicontrol.h"
9 #include "catalogue.h"
10 #include "driver.h"
11 #include "layout.h"
12 #include "route.h"
13 #include "simplecontroller.h"
14 #include "speedquantizer.h"
15 #include "timetable.h"
16 #include "trackiter.h"
17 #include "tracktype.h"
18 #include "train.h"
19 #include "trainrouter.h"
20 #include "vehicle.h"
21 #include "vehicletype.h"
22 #include "zone.h"
23
24 using namespace std;
25 using namespace Msp;
26
27 namespace R2C2 {
28
29 Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
30         layout(l),
31         loco_type(t),
32         address(a),
33         protocol(p),
34         preceding_train(0),
35         allocator(*this),
36         advancing(false),
37         controller(new SimpleController),
38         active(false),
39         current_speed_step(0),
40         speed_changing(false),
41         reverse(false),
42         functions(0),
43         travel_dist(0),
44         pure_speed(false),
45         speed_quantizer(0),
46         accurate_position(false),
47         overshoot_dist(false)
48 {
49         if(!loco_type.is_locomotive())
50                 throw invalid_argument("Train::Train");
51
52         unsigned speed_steps = layout.get_driver().get_protocol_speed_steps(protocol);
53         if(speed_steps)
54                 speed_quantizer = new SpeedQuantizer(speed_steps);
55
56         vehicles.push_back(new Vehicle(layout, loco_type));
57
58         layout.add_train(*this);
59
60         layout.get_driver().add_loco(address, protocol, loco_type);
61         layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
62         layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
63
64         layout.signal_block_state_changed.connect(sigc::mem_fun(this, &Train::block_state_changed));
65
66         layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
67
68         controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
69 }
70
71 Train::~Train()
72 {
73         delete controller;
74         for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
75                 delete *i;
76         layout.remove_train(*this);
77 }
78
79 void Train::set_name(const string &n)
80 {
81         name = n;
82
83         signal_name_changed.emit(name);
84 }
85
86 void Train::add_vehicle(const VehicleType &vt)
87 {
88         Vehicle *veh = new Vehicle(layout, vt);
89         vehicles.back()->attach_back(*veh);
90         vehicles.push_back(veh);
91 }
92
93 void Train::remove_vehicle(unsigned i)
94 {
95         if(i>=vehicles.size())
96                 throw out_of_range("Train::remove_vehicle");
97         if(i==0)
98                 throw logic_error("can't remove locomotive");
99         delete vehicles[i];
100         vehicles.erase(vehicles.begin()+i);
101         if(i<vehicles.size())
102                 vehicles[i-1]->attach_back(*vehicles[i]);
103 }
104
105 unsigned Train::get_n_vehicles() const
106 {
107         return vehicles.size();
108 }
109
110 Vehicle &Train::get_vehicle(unsigned i)
111 {
112         if(i>=vehicles.size())
113                 throw out_of_range("Train::get_vehicle");
114         return *vehicles[i];
115 }
116
117 const Vehicle &Train::get_vehicle(unsigned i) const
118 {
119         if(i>=vehicles.size())
120                 throw out_of_range("Train::get_vehicle");
121         return *vehicles[i];
122 }
123
124 void Train::set_control(const string &n, float v)
125 {
126         controller->set_control(n, v);
127 }
128
129 void Train::set_active(bool a)
130 {
131         if(a==active)
132                 return;
133         if(!a && controller->get_speed())
134                 throw logic_error("moving");
135
136         active = a;
137         if(active)
138         {
139                 stop_timeout = Time::TimeStamp();
140                 allocator.reserve_more();
141         }
142         else
143                 stop_timeout = Time::now()+2*Time::sec;
144 }
145
146 void Train::set_function(unsigned func, bool state)
147 {
148         if(!loco_type.get_functions().count(func))
149                 throw invalid_argument("Train::set_function");
150         layout.get_driver().set_loco_function(address, func, state);
151 }
152
153 float Train::get_control(const string &ctrl) const
154 {
155         return controller->get_control(ctrl).value;
156 }
157
158 float Train::get_speed() const
159 {
160         return controller->get_speed();
161 }
162
163 float Train::get_quantized_speed() const
164 {
165         if(speed_quantizer)
166                 return speed_quantizer->quantize_speed(controller->get_speed());
167         else
168                 return controller->get_speed();
169 }
170
171 bool Train::get_function(unsigned func) const
172 {
173         return (functions>>func)&1;
174 }
175
176 void Train::add_ai(TrainAI &ai)
177 {
178         ais.push_back(&ai);
179         ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
180 }
181
182 void Train::remove_ai(TrainAI &ai)
183 {
184         list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
185         if(i!=ais.end())
186                 ais.erase(i);
187 }
188
189 void Train::ai_message(const TrainAI::Message &msg)
190 {
191         for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
192                 (*i)->message(msg);
193 }
194
195 void Train::place(const BlockIter &block)
196 {
197         if(!block)
198                 throw invalid_argument("Train::place");
199         if(controller->get_speed())
200                 throw logic_error("moving");
201
202         set_active(false);
203         accurate_position = false;
204
205         allocator.start_from(block);
206
207         if(reverse)
208                 vehicles.front()->place(block.reverse().track_iter(), 0, Vehicle::FRONT_BUFFER);
209         else
210                 vehicles.back()->place(block.track_iter(), 0, Vehicle::BACK_BUFFER);
211 }
212
213 void Train::unplace()
214 {
215         if(controller->get_speed())
216                 throw logic_error("moving");
217
218         allocator.clear();
219
220         set_active(false);
221         accurate_position = false;
222
223         for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
224                 (*i)->unplace();
225 }
226
227 void Train::stop_at(Block *block)
228 {
229         allocator.stop_at(block);
230         if(active && !block)
231                 allocator.reserve_more();
232 }
233
234 bool Train::free_block(Block &block)
235 {
236         if(get_reserved_distance_until(&block, false)<controller->get_braking_distance()*1.3)
237                 return false;
238
239         return allocator.release_from(block);
240 }
241
242 void Train::free_noncritical_blocks()
243 {
244         if(allocator.empty())
245                 return;
246
247         if(controller->get_speed()==0)
248         {
249                 allocator.release_noncurrent();
250                 return;
251         }
252
253         float margin = 10*layout.get_catalogue().get_scale();
254         float min_dist = controller->get_braking_distance()*1.3+margin;
255
256         Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
257
258         TrackIter track = veh.get_track_iter();
259         BlockIter block = allocator.first();
260         const BlockIter &last_cur = allocator.last_current();
261         const BlockIter &last = allocator.last();
262         bool in_rsv = false;
263         while(!block->has_track(*track))
264         {
265                 if(&*block==&*last_cur)
266                         in_rsv = true;
267                 if(&*block==&*last)
268                         break;
269                 block = block.next();
270         }
271
272         float dist = veh.get_offset();
273         if(reverse)
274                 track.reverse();
275         else
276                 dist = track->get_type().get_path_length(track->get_active_path())-dist;
277         dist -= veh.get_type().get_length()/2;
278
279         bool nsens = 0;
280         while(1)
281         {
282                 track = track.next();
283
284                 if(!block->has_track(*track))
285                 {
286                         if(&*block==&*last_cur)
287                                 in_rsv = true;
288                         if(&*block==&*last)
289                                 return;
290                         block = block.next();
291
292                         if(dist>min_dist && nsens>0)
293                         {
294                                 allocator.release_from(*block);
295                                 return;
296                         }
297
298                         if(in_rsv && block->get_sensor_id())
299                                 ++nsens;
300                 }
301
302                 dist += track->get_type().get_path_length(track->get_active_path());
303         }
304 }
305
306 float Train::get_reserved_distance() const
307 {
308         if(allocator.empty())
309                 return 0;
310
311         float margin = 0;
312         TrackIter next = allocator.last().next().track_iter();
313         if(next && next->get_type().is_turnout())
314                 margin = 15*layout.get_catalogue().get_scale();
315
316         return max(get_reserved_distance_until(0, false)-margin, 0.0f);
317 }
318
319 void Train::reserve_more()
320 {
321         allocator.reserve_more();
322 }
323
324 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
325 {
326         if(!active && stop_timeout && t>=stop_timeout)
327         {
328                 allocator.release_noncurrent();
329                 stop_timeout = Time::TimeStamp();
330         }
331
332         Driver &driver = layout.get_driver();
333
334         for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
335                 (*i)->tick(t, dt);
336         controller->tick(dt);
337         float speed = controller->get_speed();
338         bool moving = speed>0;
339
340         if(controller->get_reverse()!=reverse)
341         {
342                 reverse = controller->get_reverse();
343                 bool r = reverse;
344                 if(loco_type.get_swap_direction())
345                         r = !r;
346                 driver.set_loco_reverse(address, r);
347
348                 allocator.reverse();
349                 if(active)
350                         allocator.reserve_more();
351         }
352
353         if(speed_quantizer)
354         {
355                 unsigned speed_step = speed_quantizer->find_speed_step(speed);
356                 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
357                 {
358                         speed_changing = true;
359                         driver.set_loco_speed(address, speed_step);
360
361                         pure_speed = false;
362                 }
363
364                 speed = speed_quantizer->get_speed(current_speed_step);
365         }
366
367         if(moving)
368         {
369                 if(!active)
370                         set_active(true);
371
372                 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
373                 Track *track = vehicle.get_track();
374
375                 BlockIter first = allocator.first();
376                 BlockIter last_current = allocator.last_current();
377                 bool ok = false;
378                 for(BlockIter i=first; !ok; i=i.next())
379                 {
380                         ok = i->has_track(*track);
381                         if(i==last_current)
382                                 break;
383                 }
384
385                 float d = speed*(dt/Time::sec);
386                 if(ok)
387                 {
388                         SetFlag setf(advancing);
389                         vehicle.advance(reverse ? -d : d);
390                 }
391                 else if(accurate_position)
392                 {
393                         overshoot_dist += d;
394                         if(overshoot_dist>40*layout.get_catalogue().get_scale())
395                         {
396                                 layout.emergency(name+" has not arrived at sensor");
397                                 accurate_position = false;
398                         }
399                 }
400         }
401
402         if(!allocator.empty() && !allocator.first()->get_sensor_id())
403         {
404                 float dist = get_reserved_distance_until(&*allocator.first(), true);
405
406                 if(dist>10*layout.get_catalogue().get_scale())
407                         allocator.release_until(*allocator.first());
408         }
409 }
410
411 void Train::save(list<DataFile::Statement> &st) const
412 {
413         st.push_back((DataFile::Statement("name"), name));
414
415         for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
416                 if(i!=vehicles.begin())
417                         st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
418
419         if(speed_quantizer)
420         {
421                 DataFile::Statement ss("quantized_speed");
422                 speed_quantizer->save(ss.sub);
423                 st.push_back(ss);
424         }
425
426         {
427                 DataFile::Statement ss("blocks");
428                 allocator.save(ss.sub);
429                 st.push_back(ss);
430         }
431
432         // XXX Need more generic way of saving AI state
433         for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
434         {
435                 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
436                 {
437                         DataFile::Statement ss("router");
438                         router->save(ss.sub);
439                         st.push_back(ss);
440                 }
441                 else if(Timetable *timetable = dynamic_cast<Timetable *>(*i))
442                 {
443                         DataFile::Statement ss("timetable");
444                         timetable->save(ss.sub);
445                         st.push_back(ss);
446                 }
447         }
448 }
449
450 void Train::control_changed(const Controller::Control &ctrl)
451 {
452         signal_control_changed.emit(ctrl.name, ctrl.value);
453 }
454
455 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
456 {
457         if(addr==address)
458         {
459                 current_speed_step = speed;
460                 bool r = reverse;
461                 if(loco_type.get_swap_direction())
462                         r = !r;
463                 if(rev!=r)
464                         layout.get_driver().set_loco_reverse(address, r);
465                 speed_changing = false;
466                 pure_speed = false;
467         }
468 }
469
470 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
471 {
472         if(addr==address)
473         {
474                 if(state)
475                         functions |= 1<<func;
476                 else
477                         functions &= ~(1<<func);
478
479                 signal_function_changed.emit(func, state);
480         }
481 }
482
483 void Train::block_state_changed(Block &block, Block::State state)
484 {
485         if(state==Block::MAYBE_ACTIVE)
486         {
487                 const BlockIter &first = allocator.first();
488                 const BlockIter &last_cur = allocator.last_current();
489                 bool valid = false;
490                 for(BlockIter i=first; !valid; i=i.next())
491                 {
492                         if(&*i==&block)
493                                 valid = true;
494                         if(&*i==&*last_cur)
495                                 break;
496                 }
497
498                 if(valid)
499                 {
500                         // Compute speed and update related state
501                         float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
502
503                         if(pure_speed && speed_quantizer && current_speed_step>0 && travel_time_secs>=2)
504                                 speed_quantizer->learn(current_speed_step, travel_dist/travel_time_secs, travel_time_secs);
505
506                         travel_dist = 0;
507                         unsigned entry = allocator.get_entry_to_block(block);
508                         for(BlockIter i(&block, entry);; i=i.next())
509                         {
510                                 travel_dist += i->get_path_length(i.entry());
511
512                                 if(&*i==&block && !advancing && vehicles.front()->get_track())
513                                 {
514                                         TrackIter track = i.track_iter();
515                                         if(reverse)
516                                         {
517                                                 track = track.flip();
518                                                 vehicles.back()->place(track, 0, Vehicle::BACK_AXLE);
519                                         }
520                                         else
521                                                 vehicles.front()->place(track, 0, Vehicle::FRONT_AXLE);
522                                 }
523
524                                 if(i==last_cur)
525                                         break;
526                         }
527                         last_entry_time = Time::now();
528                         pure_speed = true;
529                         accurate_position = true;
530                         overshoot_dist = 0;
531                 }
532         }
533 }
534
535 void Train::halt_event(bool h)
536 {
537         if(h)
538                 accurate_position = false;
539 }
540
541 float Train::get_reserved_distance_until(const Block *until_block, bool back) const
542 {
543         if(allocator.empty())
544                 return 0;
545
546         Vehicle &veh = *(reverse!=back ? vehicles.back() : vehicles.front());
547         const VehicleType &vtype = veh.get_type();
548
549         TrackIter track = veh.get_track_iter();
550         if(!track)  // XXX Probably unnecessary
551                 return 0;
552
553         const BlockIter &first = allocator.first();
554         const BlockIter &last = allocator.last();
555         BlockIter block = first;
556         while(!block->has_track(*track))
557         {
558                 if(&*block==&*last)
559                         return 0;
560                 block = block.next();
561         }
562         if(&*block==until_block)
563                 return 0;
564
565         if(back)
566                 block = block.reverse();
567
568         float result = veh.get_offset();
569         if(reverse!=back)
570                 track = track.reverse();
571         else
572                 result = track->get_type().get_path_length(track->get_active_path())-result;
573         result -= vtype.get_length()/2;
574
575         while(1)
576         {
577                 track = track.next();
578                 if(!track)
579                         break;
580
581                 if(!block->has_track(*track))
582                 {
583                         if(back)
584                         {
585                                 if(&*block==&*first)
586                                         break;
587                         }
588                         else
589                         {
590                                 if(&*block==&*last)
591                                         break;
592                         }
593                         block = block.next();
594
595                         if(&*block==until_block)
596                                 break;
597                 }
598
599                 result += track->get_type().get_path_length(track->get_active_path());
600         }
601
602         return result;
603 }
604
605
606 Train::Loader::Loader(Train &t):
607         DataFile::ObjectLoader<Train>(t),
608         prev_block(0),
609         blocks_valid(true)
610 {
611         add("blocks",      &Loader::blocks);
612         add("name",        &Loader::name);
613         add("quantized_speed",  &Loader::quantized_speed);
614         add("router",      &Loader::router);
615         add("timetable",   &Loader::timetable);
616         add("vehicle",     &Loader::vehicle);
617 }
618
619 void Train::Loader::finish()
620 {
621         if(!obj.allocator.empty())
622         {
623                 TrackIter track = obj.allocator.first().track_iter();
624                 float offset = 2*obj.layout.get_catalogue().get_scale();
625                 obj.vehicles.back()->place(track, offset, Vehicle::BACK_BUFFER);
626         }
627 }
628
629 void Train::Loader::blocks()
630 {
631         load_sub(obj.allocator);
632 }
633
634 void Train::Loader::name(const string &n)
635 {
636         obj.set_name(n);
637 }
638
639 void Train::Loader::quantized_speed()
640 {
641         if(obj.speed_quantizer)
642                 load_sub(*obj.speed_quantizer);
643 }
644
645 void Train::Loader::router()
646 {
647         TrainRouter *rtr = new TrainRouter(obj);
648         load_sub(*rtr);
649 }
650
651 void Train::Loader::timetable()
652 {
653         Timetable *ttbl = new Timetable(obj);
654         load_sub(*ttbl);
655 }
656
657 void Train::Loader::vehicle(ArticleNumber art_nr)
658 {
659         const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(art_nr);
660         Vehicle *veh = new Vehicle(obj.layout, vtype);
661         obj.vehicles.back()->attach_back(*veh);
662         obj.vehicles.push_back(veh);
663 }
664
665 } // namespace R2C2