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