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>
11 #include "catalogue.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"
22 #include "trainrouter.h"
24 #include "vehicletype.h"
32 Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
40 controller(new SimpleController),
41 current_speed_step(0),
42 speed_changing(false),
47 accurate_position(false),
50 if(!loco_type.is_locomotive())
51 throw invalid_argument("Train::Train");
53 unsigned speed_steps = layout.get_driver().get_protocol_speed_steps(protocol);
55 speed_quantizer = new SpeedQuantizer(speed_steps);
57 vehicles.push_back(new Vehicle(layout, loco_type));
58 vehicles.back()->set_train(this);
60 layout.add_train(*this);
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));
66 layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
68 controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
70 allocator.signal_advanced.connect(sigc::mem_fun(this, &Train::advanced));
71 allocator.signal_rear_advanced.connect(signal_rear_advanced);
77 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
79 layout.remove_train(*this);
82 void Train::set_name(const string &n)
86 signal_name_changed.emit(name);
89 void Train::add_vehicle(const VehicleType &vt)
91 Vehicle *veh = new Vehicle(layout, vt);
92 vehicles.back()->attach_back(*veh);
93 vehicles.push_back(veh);
95 signal_vehicle_added.emit(vehicles.size()-1, *veh);
98 void Train::remove_vehicle(unsigned i)
100 if(i>=vehicles.size())
101 throw out_of_range("Train::remove_vehicle");
103 throw logic_error("can't remove locomotive");
105 Vehicle *veh = vehicles[i];
106 vehicles.erase(vehicles.begin()+i);
108 if(i<vehicles.size())
111 vehicles[i-1]->attach_back(*vehicles[i]);
113 signal_vehicle_removed.emit(i, *veh);
117 unsigned Train::get_n_vehicles() const
119 return vehicles.size();
122 Vehicle &Train::get_vehicle(unsigned i)
124 if(i>=vehicles.size())
125 throw out_of_range("Train::get_vehicle");
129 const Vehicle &Train::get_vehicle(unsigned i) const
131 if(i>=vehicles.size())
132 throw out_of_range("Train::get_vehicle");
136 void Train::set_control(const string &n, float v)
138 controller->set_control(n, v);
141 void Train::set_function(unsigned func, bool state)
143 if(!loco_type.get_functions().count(func))
144 throw invalid_argument("Train::set_function");
145 layout.get_driver().set_loco_function(loco_id, func, state);
148 float Train::get_control(const string &ctrl) const
150 return controller->get_control(ctrl).value;
153 float Train::get_speed() const
155 return controller->get_speed();
158 float Train::get_quantized_speed() const
161 return speed_quantizer->quantize_speed(controller->get_speed());
163 return controller->get_speed();
166 float Train::get_maximum_speed() const
169 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
171 float vms = (*i)->get_type().get_maximum_speed();
172 if(ms<=0 || (vms>0 && vms<ms))
178 bool Train::get_function(unsigned func) const
180 return (functions>>func)&1;
183 void Train::add_ai(TrainAI &ai)
186 ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
189 void Train::remove_ai(TrainAI &ai)
191 list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
196 void Train::ai_message(const TrainAI::Message &msg)
198 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
202 bool Train::place(const BlockIter &block)
205 throw invalid_argument("Train::place");
206 if(controller->get_speed())
207 throw logic_error("moving");
209 accurate_position = false;
210 last_entry_block = BlockIter();
212 if(allocator.start_from(block))
215 vehicles.front()->place(block.reverse().track_iter(), VehiclePlacement::FRONT_BUFFER);
217 vehicles.back()->place(block.track_iter(), VehiclePlacement::BACK_BUFFER);
227 void Train::unplace()
229 if(controller->get_speed())
230 throw logic_error("moving");
233 accurate_position = false;
234 last_entry_block = BlockIter();
236 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
240 void Train::stop_at(Block *block)
242 allocator.stop_at(block);
245 bool Train::is_block_critical(const Block &block) const
247 return get_reserved_distance_until(&block)<=controller->get_braking_distance()*1.3;
250 BlockIter Train::get_first_noncritical_block() const
252 if(allocator.empty())
255 BlockIter i = allocator.last_current().next();
257 if(controller->get_speed()==0)
260 float margin = 10*layout.get_catalogue().get_scale();
261 float min_dist = controller->get_braking_distance()*1.3+margin;
264 bool sensor_seen = false;
265 for(; i->get_train()==this; i=i.next())
267 if(dist>min_dist && sensor_seen)
270 dist += i->get_path_length(i.entry());
272 if(i->get_sensor_address())
279 void Train::refresh_blocks_from(Block &block)
281 if(is_block_critical(block))
282 allocator.rewind_to(*get_first_noncritical_block());
284 allocator.rewind_to(block);
287 float Train::get_reserved_distance() const
289 if(allocator.empty())
293 TrackIter next = allocator.last().next().track_iter();
294 if(next && next->get_type().is_turnout())
295 margin = 15*layout.get_catalogue().get_scale();
297 return max(get_reserved_distance_until(0)-margin, 0.0f);
300 void Train::tick(const Time::TimeDelta &dt)
305 if(stop_timeout<=Time::zero)
307 allocator.set_active(false);
308 stop_timeout = Time::TimeDelta();
314 Driver &driver = layout.get_driver();
316 bool intent_to_move = false;
317 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
320 if((*i)->has_intent_to_move())
321 intent_to_move = true;
324 controller->tick(dt);
325 float speed = controller->get_speed();
326 bool moving = speed>0;
328 if(controller->get_reverse()!=reverse)
330 reverse = controller->get_reverse();
332 if(loco_type.get_swap_direction())
334 driver.set_loco_reverse(loco_id, r);
337 last_entry_block = BlockIter();
342 unsigned speed_step = speed_quantizer->find_speed_step(speed);
343 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
345 speed_changing = true;
346 driver.set_loco_speed(loco_id, speed_step);
351 speed = speed_quantizer->get_speed(current_speed_step);
356 if(!allocator.is_active())
357 allocator.set_active(true);
359 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
361 float d = speed*(dt/Time::sec);
362 Block &block = vehicle.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE)->get_block();
363 if(allocator.is_block_current(block))
365 SetFlag setf(advancing);
366 vehicle.advance(reverse ? -d : d);
368 else if(accurate_position)
371 if(overshoot_dist>40*layout.get_catalogue().get_scale())
373 layout.emergency(&block, name+" has not arrived at sensor");
374 accurate_position = false;
378 else if(intent_to_move && !allocator.is_active())
379 allocator.set_active(true);
380 else if(allocator.is_active() && !intent_to_move && !stop_timeout)
381 stop_timeout = 2*Time::sec;
384 void Train::save(list<DataFile::Statement> &st) const
386 st.push_back((DataFile::Statement("name"), name));
388 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
389 if(i!=vehicles.begin())
390 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
394 DataFile::Statement ss("quantized_speed");
395 speed_quantizer->save(ss.sub);
400 DataFile::Statement ss("blocks");
401 allocator.save(ss.sub);
405 // XXX Need more generic way of saving AI state
406 for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
408 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
410 DataFile::Statement ss("router");
411 router->save(ss.sub);
414 else if(Timetable *timetable = dynamic_cast<Timetable *>(*i))
416 DataFile::Statement ss("timetable");
417 timetable->save(ss.sub);
423 void Train::control_changed(const Controller::Control &ctrl)
425 signal_control_changed.emit(ctrl.name, ctrl.value);
428 void Train::loco_speed_event(unsigned id, unsigned speed, bool rev)
432 current_speed_step = speed;
434 if(loco_type.get_swap_direction())
437 layout.get_driver().set_loco_reverse(loco_id, r);
438 speed_changing = false;
443 void Train::loco_func_event(unsigned id, unsigned func, bool state)
448 functions |= 1<<func;
450 functions &= ~(1<<func);
452 signal_function_changed.emit(func, state);
456 void Train::advanced(Block &block, Sensor *sensor)
458 if(!sensor || sensor==block.get_sensor())
459 signal_advanced.emit(block);
464 if(sensor==block.get_sensor())
466 if(last_entry_block && pure_speed && speed_quantizer)
468 float travel_distance = 0;
470 for(BlockIter i=last_entry_block; &*i!=█ i=i.next())
471 travel_distance += i->get_path_length(i.entry());
473 if(travel_distance>0)
475 float travel_time_secs = travel_time/Time::sec;
477 if(travel_time_secs>=2)
478 speed_quantizer->learn(current_speed_step, travel_distance/travel_time_secs, travel_time_secs);
482 last_entry_block = allocator.iter_for(block);
483 travel_time = Time::zero;
484 if(!layout.get_driver().is_halted())
487 accurate_position = true;
491 if(!advancing && vehicles.front()->is_placed())
493 TrackIter track = last_entry_block.track_iter();
496 track = track.flip();
497 vehicles.back()->place(track, VehiclePlacement::BACK_AXLE);
500 vehicles.front()->place(track, VehiclePlacement::FRONT_AXLE);
503 else if(BeamGate *gate = dynamic_cast<BeamGate *>(sensor))
505 if(!advancing && vehicles.front()->is_placed())
507 TrackIter track = allocator.iter_for(block).track_iter();
508 for(; (track && &track->get_block()==&block); track=track.next())
509 if(track.track()==gate->get_track())
512 track = track.reverse();
513 float offset = gate->get_offset_from_endpoint(track.entry());
515 vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
517 vehicles.front()->place(TrackOffsetIter(track, offset), VehiclePlacement::FRONT_BUFFER);
524 void Train::halt_event(bool h)
527 accurate_position = false;
530 float Train::get_reserved_distance_until(const Block *until_block) const
532 if(allocator.empty())
535 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
537 TrackOffsetIter track = veh.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE);
538 if(!track) // XXX Probably unnecessary
541 if(&track->get_block()==until_block)
544 // Account for the vehicle's offset on its current track
545 float result = track.offset();
547 track = track.reverse();
549 result = track->get_path_length()-result;
550 result -= veh.get_type().get_length()/2;
552 BlockIter block = track.block_iter();
554 // Count remaining distance in the vehicle's current block
555 for(track=track.next(); &track->get_block()==&*block; track=track.next())
556 result += track->get_path_length();
558 const BlockIter &last = allocator.last();
562 // Count any remaining blocks
563 for(block=block.next(); (&*block!=until_block && block->get_train()==this); block=block.next())
565 result += block->get_path_length(block.entry());
575 Train::Loader::Loader(Train &t):
576 DataFile::ObjectLoader<Train>(t),
580 add("blocks", &Loader::blocks);
581 add("name", &Loader::name);
582 add("quantized_speed", &Loader::quantized_speed);
583 add("router", &Loader::router);
584 add("timetable", &Loader::timetable);
585 add("vehicle", &Loader::vehicle);
588 void Train::Loader::finish()
590 if(!obj.allocator.empty())
592 TrackIter track = obj.allocator.first().track_iter();
593 float offset = 2*obj.layout.get_catalogue().get_scale();
594 obj.vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
598 void Train::Loader::blocks()
600 load_sub(obj.allocator);
603 void Train::Loader::name(const string &n)
608 void Train::Loader::quantized_speed()
610 if(obj.speed_quantizer)
611 load_sub(*obj.speed_quantizer);
614 void Train::Loader::router()
616 TrainRouter *rtr = new TrainRouter(obj);
620 void Train::Loader::timetable()
622 Timetable *ttbl = new Timetable(obj);
623 load_sub(*ttbl, obj.layout);
626 void Train::Loader::vehicle(ArticleNumber art_nr)
628 const VehicleType &vtype = obj.layout.get_catalogue().get<VehicleType>(art_nr);
629 Vehicle *veh = new Vehicle(obj.layout, vtype);
630 obj.vehicles.back()->attach_back(*veh);
631 obj.vehicles.push_back(veh);
632 veh->set_train(&obj);