]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/train.cpp
8e10026f182bee49987318eb0daee177ad679873
[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                 if(allocator.is_block_current(vehicle.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE)->get_block()))
362                 {
363                         SetFlag setf(advancing);
364                         vehicle.advance(reverse ? -d : d);
365                 }
366                 else if(accurate_position)
367                 {
368                         overshoot_dist += d;
369                         if(overshoot_dist>40*layout.get_catalogue().get_scale())
370                         {
371                                 layout.emergency(name+" has not arrived at sensor");
372                                 accurate_position = false;
373                         }
374                 }
375         }
376         else if(intent_to_move && !allocator.is_active())
377                 allocator.set_active(true);
378         else if(allocator.is_active() && !intent_to_move && !stop_timeout)
379                 stop_timeout = 2*Time::sec;
380 }
381
382 void Train::save(list<DataFile::Statement> &st) const
383 {
384         st.push_back((DataFile::Statement("name"), name));
385
386         for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
387                 if(i!=vehicles.begin())
388                         st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
389
390         if(speed_quantizer)
391         {
392                 DataFile::Statement ss("quantized_speed");
393                 speed_quantizer->save(ss.sub);
394                 st.push_back(ss);
395         }
396
397         {
398                 DataFile::Statement ss("blocks");
399                 allocator.save(ss.sub);
400                 st.push_back(ss);
401         }
402
403         // XXX Need more generic way of saving AI state
404         for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
405         {
406                 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
407                 {
408                         DataFile::Statement ss("router");
409                         router->save(ss.sub);
410                         st.push_back(ss);
411                 }
412                 else if(Timetable *timetable = dynamic_cast<Timetable *>(*i))
413                 {
414                         DataFile::Statement ss("timetable");
415                         timetable->save(ss.sub);
416                         st.push_back(ss);
417                 }
418         }
419 }
420
421 void Train::control_changed(const Controller::Control &ctrl)
422 {
423         signal_control_changed.emit(ctrl.name, ctrl.value);
424 }
425
426 void Train::loco_speed_event(unsigned id, unsigned speed, bool rev)
427 {
428         if(id==loco_id)
429         {
430                 current_speed_step = speed;
431                 bool r = reverse;
432                 if(loco_type.get_swap_direction())
433                         r = !r;
434                 if(rev!=r)
435                         layout.get_driver().set_loco_reverse(loco_id, r);
436                 speed_changing = false;
437                 pure_speed = false;
438         }
439 }
440
441 void Train::loco_func_event(unsigned id, unsigned func, bool state)
442 {
443         if(id==loco_id)
444         {
445                 if(state)
446                         functions |= 1<<func;
447                 else
448                         functions &= ~(1<<func);
449
450                 signal_function_changed.emit(func, state);
451         }
452 }
453
454 void Train::sensor_state_changed(Sensor &sensor, Sensor::State state)
455 {
456         if(!current_speed_step || state!=Sensor::MAYBE_ACTIVE)
457                 return;
458
459         Block *block = sensor.get_block();
460         if(!block || block->get_train()!=this)
461                 return;
462
463         if(last_entry_block && &*last_entry_block!=block)
464         {
465                 for(BlockIter i=last_entry_block.next(); (i && &*i!=block); i=i.next())
466                         if(i->get_train()!=this || i->get_sensor_address())
467                                 return;
468         }
469
470         if(dynamic_cast<TrackCircuit *>(&sensor))
471         {
472                 if(last_entry_block && pure_speed && speed_quantizer)
473                 {
474                         float travel_distance = 0;
475
476                         for(BlockIter i=last_entry_block; &*i!=block; i=i.next())
477                                 travel_distance += i->get_path_length(i.entry());
478
479                         if(travel_distance>0)
480                         {
481                                 float travel_time_secs = travel_time/Time::sec;
482
483                                 if(travel_time_secs>=2)
484                                         speed_quantizer->learn(current_speed_step, travel_distance/travel_time_secs, travel_time_secs);
485                         }
486                 }
487
488                 last_entry_block = allocator.iter_for(*block);
489                 travel_time = Time::zero;
490                 if(!layout.get_driver().is_halted())
491                 {
492                         pure_speed = true;
493                         accurate_position = true;
494                 }
495                 overshoot_dist = 0;
496
497                 if(!advancing && vehicles.front()->is_placed())
498                 {
499                         TrackIter track = last_entry_block.track_iter();
500                         if(reverse)
501                         {
502                                 track = track.flip();
503                                 vehicles.back()->place(track, VehiclePlacement::BACK_AXLE);
504                         }
505                         else
506                                 vehicles.front()->place(track, VehiclePlacement::FRONT_AXLE);
507                 }
508         }
509         else if(BeamGate *gate = dynamic_cast<BeamGate *>(&sensor))
510         {
511                 if(!advancing && vehicles.front()->is_placed())
512                 {
513                         TrackIter track = allocator.iter_for(*block).track_iter();
514                         for(; (track && &track->get_block()==block); track=track.next())
515                                 if(track.track()==gate->get_track())
516                                 {
517                                         if(reverse)
518                                                 track = track.reverse();
519                                         float offset = gate->get_offset_from_endpoint(track.entry());
520                                         if(reverse)
521                                                 vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
522                                         else
523                                                 vehicles.front()->place(TrackOffsetIter(track, offset), VehiclePlacement::FRONT_BUFFER);
524                                         break;
525                                 }
526                 }
527         }
528 }
529
530 void Train::halt_event(bool h)
531 {
532         if(h)
533                 accurate_position = false;
534 }
535
536 float Train::get_reserved_distance_until(const Block *until_block) const
537 {
538         if(allocator.empty())
539                 return 0;
540
541         Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
542
543         TrackOffsetIter track = veh.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE);
544         if(!track)  // XXX Probably unnecessary
545                 return 0;
546
547         if(&track->get_block()==until_block)
548                 return 0;
549
550         // Account for the vehicle's offset on its current track
551         float result = track.offset();
552         if(reverse)
553                 track = track.reverse();
554         else
555                 result = track->get_path_length()-result;
556         result -= veh.get_type().get_length()/2;
557
558         BlockIter block = track.block_iter();
559
560         // Count remaining distance in the vehicle's current block
561         for(track=track.next(); &track->get_block()==&*block; track=track.next())
562                 result += track->get_path_length();
563
564         const BlockIter &last = allocator.last();
565         if(&*block==&*last)
566                 return result;
567
568         // Count any remaining blocks
569         for(block=block.next(); (&*block!=until_block && block->get_train()==this); block=block.next())
570         {
571                 result += block->get_path_length(block.entry());
572
573                 if(&*block==&*last)
574                         break;
575         }
576
577         return result;
578 }
579
580
581 Train::Loader::Loader(Train &t):
582         DataFile::ObjectLoader<Train>(t),
583         prev_block(0),
584         blocks_valid(true)
585 {
586         add("blocks",      &Loader::blocks);
587         add("name",        &Loader::name);
588         add("quantized_speed",  &Loader::quantized_speed);
589         add("router",      &Loader::router);
590         add("timetable",   &Loader::timetable);
591         add("vehicle",     &Loader::vehicle);
592 }
593
594 void Train::Loader::finish()
595 {
596         if(!obj.allocator.empty())
597         {
598                 TrackIter track = obj.allocator.first().track_iter();
599                 float offset = 2*obj.layout.get_catalogue().get_scale();
600                 obj.vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
601         }
602 }
603
604 void Train::Loader::blocks()
605 {
606         load_sub(obj.allocator);
607 }
608
609 void Train::Loader::name(const string &n)
610 {
611         obj.set_name(n);
612 }
613
614 void Train::Loader::quantized_speed()
615 {
616         if(obj.speed_quantizer)
617                 load_sub(*obj.speed_quantizer);
618 }
619
620 void Train::Loader::router()
621 {
622         TrainRouter *rtr = new TrainRouter(obj);
623         load_sub(*rtr);
624 }
625
626 void Train::Loader::timetable()
627 {
628         Timetable *ttbl = new Timetable(obj);
629         load_sub(*ttbl, obj.layout);
630 }
631
632 void Train::Loader::vehicle(ArticleNumber art_nr)
633 {
634         const VehicleType &vtype = obj.layout.get_catalogue().get<VehicleType>(art_nr);
635         Vehicle *veh = new Vehicle(obj.layout, vtype);
636         obj.vehicles.back()->attach_back(*veh);
637         obj.vehicles.push_back(veh);
638         veh->set_train(&obj);
639 }
640
641 } // namespace R2C2