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