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