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>
13 #include "simplecontroller.h"
14 #include "speedquantizer.h"
15 #include "timetable.h"
16 #include "trackiter.h"
17 #include "tracktype.h"
19 #include "trainrouter.h"
21 #include "vehicletype.h"
29 Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
37 controller(new SimpleController),
39 current_speed_step(0),
40 speed_changing(false),
46 accurate_position(false),
49 if(!loco_type.is_locomotive())
50 throw invalid_argument("Train::Train");
52 unsigned speed_steps = layout.get_driver().get_protocol_speed_steps(protocol);
54 speed_quantizer = new SpeedQuantizer(speed_steps);
56 vehicles.push_back(new Vehicle(layout, loco_type));
58 layout.add_train(*this);
60 layout.get_driver().add_loco(address, protocol, loco_type);
61 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
62 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
64 layout.signal_block_state_changed.connect(sigc::mem_fun(this, &Train::block_state_changed));
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));
74 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
76 layout.remove_train(*this);
79 void Train::set_name(const string &n)
83 signal_name_changed.emit(name);
86 void Train::add_vehicle(const VehicleType &vt)
88 Vehicle *veh = new Vehicle(layout, vt);
89 vehicles.back()->attach_back(*veh);
90 vehicles.push_back(veh);
93 void Train::remove_vehicle(unsigned i)
95 if(i>=vehicles.size())
96 throw out_of_range("Train::remove_vehicle");
98 throw logic_error("can't remove locomotive");
100 vehicles.erase(vehicles.begin()+i);
101 if(i<vehicles.size())
102 vehicles[i-1]->attach_back(*vehicles[i]);
105 unsigned Train::get_n_vehicles() const
107 return vehicles.size();
110 Vehicle &Train::get_vehicle(unsigned i)
112 if(i>=vehicles.size())
113 throw out_of_range("Train::get_vehicle");
117 const Vehicle &Train::get_vehicle(unsigned i) const
119 if(i>=vehicles.size())
120 throw out_of_range("Train::get_vehicle");
124 void Train::set_control(const string &n, float v)
126 controller->set_control(n, v);
129 void Train::set_active(bool a)
133 if(!a && controller->get_speed())
134 throw logic_error("moving");
139 stop_timeout = Time::TimeStamp();
140 allocator.reserve_more();
143 stop_timeout = Time::now()+2*Time::sec;
146 void Train::set_function(unsigned func, bool state)
148 if(!loco_type.get_functions().count(func))
149 throw invalid_argument("Train::set_function");
150 layout.get_driver().set_loco_function(address, func, state);
153 float Train::get_control(const string &ctrl) const
155 return controller->get_control(ctrl).value;
158 float Train::get_speed() const
160 return controller->get_speed();
163 float Train::get_quantized_speed() const
166 return speed_quantizer->quantize_speed(controller->get_speed());
168 return controller->get_speed();
171 bool Train::get_function(unsigned func) const
173 return (functions>>func)&1;
176 void Train::add_ai(TrainAI &ai)
179 ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
182 void Train::remove_ai(TrainAI &ai)
184 list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
189 void Train::ai_message(const TrainAI::Message &msg)
191 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
195 void Train::place(const BlockIter &block)
198 throw invalid_argument("Train::place");
199 if(controller->get_speed())
200 throw logic_error("moving");
203 accurate_position = false;
205 allocator.start_from(block);
208 vehicles.front()->place(block.reverse().track_iter(), 0, Vehicle::FRONT_BUFFER);
210 vehicles.back()->place(block.track_iter(), 0, Vehicle::BACK_BUFFER);
213 void Train::unplace()
215 if(controller->get_speed())
216 throw logic_error("moving");
221 accurate_position = false;
223 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
227 void Train::stop_at(Block *block)
229 allocator.stop_at(block);
231 allocator.reserve_more();
234 bool Train::free_block(Block &block)
236 if(get_reserved_distance_until(&block, false)<controller->get_braking_distance()*1.3)
239 return allocator.release_from(block);
242 void Train::free_noncritical_blocks()
244 if(allocator.empty())
247 if(controller->get_speed()==0)
249 allocator.release_noncurrent();
253 float margin = 10*layout.get_catalogue().get_scale();
254 float min_dist = controller->get_braking_distance()*1.3+margin;
256 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
258 TrackIter track = veh.get_track_iter();
259 BlockIter block = allocator.first();
260 const BlockIter &last_cur = allocator.last_current();
261 const BlockIter &last = allocator.last();
263 while(!block->has_track(*track))
265 if(&*block==&*last_cur)
269 block = block.next();
272 float dist = veh.get_offset();
276 dist = track->get_type().get_path_length(track->get_active_path())-dist;
277 dist -= veh.get_type().get_length()/2;
282 track = track.next();
284 if(!block->has_track(*track))
286 if(&*block==&*last_cur)
290 block = block.next();
292 if(dist>min_dist && nsens>0)
294 allocator.release_from(*block);
298 if(in_rsv && block->get_sensor_id())
302 dist += track->get_type().get_path_length(track->get_active_path());
306 float Train::get_reserved_distance() const
308 if(allocator.empty())
312 TrackIter next = allocator.last().next().track_iter();
313 if(next && next->get_type().is_turnout())
314 margin = 15*layout.get_catalogue().get_scale();
316 return max(get_reserved_distance_until(0, false)-margin, 0.0f);
319 void Train::reserve_more()
321 allocator.reserve_more();
324 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
326 if(!active && stop_timeout && t>=stop_timeout)
328 allocator.release_noncurrent();
329 stop_timeout = Time::TimeStamp();
332 Driver &driver = layout.get_driver();
334 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
336 controller->tick(dt);
337 float speed = controller->get_speed();
338 bool moving = speed>0;
340 if(controller->get_reverse()!=reverse)
342 reverse = controller->get_reverse();
344 if(loco_type.get_swap_direction())
346 driver.set_loco_reverse(address, r);
350 allocator.reserve_more();
355 unsigned speed_step = speed_quantizer->find_speed_step(speed);
356 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
358 speed_changing = true;
359 driver.set_loco_speed(address, speed_step);
364 speed = speed_quantizer->get_speed(current_speed_step);
372 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
373 Track *track = vehicle.get_track();
375 BlockIter first = allocator.first();
376 BlockIter last_current = allocator.last_current();
378 for(BlockIter i=first; !ok; i=i.next())
380 ok = i->has_track(*track);
385 float d = speed*(dt/Time::sec);
388 SetFlag setf(advancing);
389 vehicle.advance(reverse ? -d : d);
391 else if(accurate_position)
394 if(overshoot_dist>40*layout.get_catalogue().get_scale())
396 layout.emergency(name+" has not arrived at sensor");
397 accurate_position = false;
402 if(!allocator.empty() && !allocator.first()->get_sensor_id())
404 float dist = get_reserved_distance_until(&*allocator.first(), true);
406 if(dist>10*layout.get_catalogue().get_scale())
407 allocator.release_until(*allocator.first());
411 void Train::save(list<DataFile::Statement> &st) const
413 st.push_back((DataFile::Statement("name"), name));
415 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
416 if(i!=vehicles.begin())
417 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
421 DataFile::Statement ss("quantized_speed");
422 speed_quantizer->save(ss.sub);
427 DataFile::Statement ss("blocks");
428 allocator.save(ss.sub);
432 // XXX Need more generic way of saving AI state
433 for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
435 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
437 DataFile::Statement ss("router");
438 router->save(ss.sub);
441 else if(Timetable *timetable = dynamic_cast<Timetable *>(*i))
443 DataFile::Statement ss("timetable");
444 timetable->save(ss.sub);
450 void Train::control_changed(const Controller::Control &ctrl)
452 signal_control_changed.emit(ctrl.name, ctrl.value);
455 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
459 current_speed_step = speed;
461 if(loco_type.get_swap_direction())
464 layout.get_driver().set_loco_reverse(address, r);
465 speed_changing = false;
470 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
475 functions |= 1<<func;
477 functions &= ~(1<<func);
479 signal_function_changed.emit(func, state);
483 void Train::block_state_changed(Block &block, Block::State state)
485 if(state==Block::MAYBE_ACTIVE)
487 const BlockIter &first = allocator.first();
488 const BlockIter &last_cur = allocator.last_current();
490 for(BlockIter i=first; !valid; i=i.next())
500 // Compute speed and update related state
501 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
503 if(pure_speed && speed_quantizer && current_speed_step>0 && travel_time_secs>=2)
504 speed_quantizer->learn(current_speed_step, travel_dist/travel_time_secs, travel_time_secs);
507 unsigned entry = allocator.get_entry_to_block(block);
508 for(BlockIter i(&block, entry);; i=i.next())
510 travel_dist += i->get_path_length(i.entry());
512 if(&*i==&block && !advancing && vehicles.front()->get_track())
514 TrackIter track = i.track_iter();
517 track = track.flip();
518 vehicles.back()->place(track, 0, Vehicle::BACK_AXLE);
521 vehicles.front()->place(track, 0, Vehicle::FRONT_AXLE);
527 last_entry_time = Time::now();
529 accurate_position = true;
535 void Train::halt_event(bool h)
538 accurate_position = false;
541 float Train::get_reserved_distance_until(const Block *until_block, bool back) const
543 if(allocator.empty())
546 Vehicle &veh = *(reverse!=back ? vehicles.back() : vehicles.front());
547 const VehicleType &vtype = veh.get_type();
549 TrackIter track = veh.get_track_iter();
550 if(!track) // XXX Probably unnecessary
553 const BlockIter &first = allocator.first();
554 const BlockIter &last = allocator.last();
555 BlockIter block = first;
556 while(!block->has_track(*track))
560 block = block.next();
562 if(&*block==until_block)
566 block = block.reverse();
568 float result = veh.get_offset();
570 track = track.reverse();
572 result = track->get_type().get_path_length(track->get_active_path())-result;
573 result -= vtype.get_length()/2;
577 track = track.next();
581 if(!block->has_track(*track))
593 block = block.next();
595 if(&*block==until_block)
599 result += track->get_type().get_path_length(track->get_active_path());
606 Train::Loader::Loader(Train &t):
607 DataFile::ObjectLoader<Train>(t),
611 add("blocks", &Loader::blocks);
612 add("name", &Loader::name);
613 add("quantized_speed", &Loader::quantized_speed);
614 add("router", &Loader::router);
615 add("timetable", &Loader::timetable);
616 add("vehicle", &Loader::vehicle);
619 void Train::Loader::finish()
621 if(!obj.allocator.empty())
623 TrackIter track = obj.allocator.first().track_iter();
624 float offset = 2*obj.layout.get_catalogue().get_scale();
625 obj.vehicles.back()->place(track, offset, Vehicle::BACK_BUFFER);
629 void Train::Loader::blocks()
631 load_sub(obj.allocator);
634 void Train::Loader::name(const string &n)
639 void Train::Loader::quantized_speed()
641 if(obj.speed_quantizer)
642 load_sub(*obj.speed_quantizer);
645 void Train::Loader::router()
647 TrainRouter *rtr = new TrainRouter(obj);
651 void Train::Loader::timetable()
653 Timetable *ttbl = new Timetable(obj);
657 void Train::Loader::vehicle(ArticleNumber art_nr)
659 const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(art_nr);
660 Vehicle *veh = new Vehicle(obj.layout, vtype);
661 obj.vehicles.back()->attach_back(*veh);
662 obj.vehicles.push_back(veh);