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),
45 accurate_position(false),
48 if(!loco_type.is_locomotive())
49 throw invalid_argument("Train::Train");
51 unsigned speed_steps = layout.get_driver().get_protocol_speed_steps(protocol);
53 speed_quantizer = new SpeedQuantizer(speed_steps);
55 vehicles.push_back(new Vehicle(layout, loco_type));
57 layout.add_train(*this);
59 layout.get_driver().add_loco(address, protocol, loco_type);
60 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
61 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
63 layout.signal_block_state_changed.connect(sigc::mem_fun(this, &Train::block_state_changed));
65 layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
67 controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
73 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
75 layout.remove_train(*this);
78 void Train::set_name(const string &n)
82 signal_name_changed.emit(name);
85 void Train::add_vehicle(const VehicleType &vt)
87 Vehicle *veh = new Vehicle(layout, vt);
88 vehicles.back()->attach_back(*veh);
89 vehicles.push_back(veh);
92 void Train::remove_vehicle(unsigned i)
94 if(i>=vehicles.size())
95 throw out_of_range("Train::remove_vehicle");
97 throw logic_error("can't remove locomotive");
99 vehicles.erase(vehicles.begin()+i);
100 if(i<vehicles.size())
101 vehicles[i-1]->attach_back(*vehicles[i]);
104 unsigned Train::get_n_vehicles() const
106 return vehicles.size();
109 Vehicle &Train::get_vehicle(unsigned i)
111 if(i>=vehicles.size())
112 throw out_of_range("Train::get_vehicle");
116 const Vehicle &Train::get_vehicle(unsigned i) const
118 if(i>=vehicles.size())
119 throw out_of_range("Train::get_vehicle");
123 void Train::set_control(const string &n, float v)
125 controller->set_control(n, v);
128 void Train::set_active(bool a)
132 if(!a && controller->get_speed())
133 throw logic_error("moving");
138 stop_timeout = Time::TimeStamp();
139 allocator.reserve_more();
142 stop_timeout = Time::now()+2*Time::sec;
145 void Train::set_function(unsigned func, bool state)
147 if(!loco_type.get_functions().count(func))
148 throw invalid_argument("Train::set_function");
149 layout.get_driver().set_loco_function(address, func, state);
152 float Train::get_control(const string &ctrl) const
154 return controller->get_control(ctrl).value;
157 float Train::get_speed() const
159 return controller->get_speed();
162 float Train::get_quantized_speed() const
165 return speed_quantizer->quantize_speed(controller->get_speed());
167 return controller->get_speed();
170 bool Train::get_function(unsigned func) const
172 return (functions>>func)&1;
175 void Train::add_ai(TrainAI &ai)
178 ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
181 void Train::remove_ai(TrainAI &ai)
183 list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
188 void Train::ai_message(const TrainAI::Message &msg)
190 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
194 void Train::place(const BlockIter &block)
197 throw invalid_argument("Train::place");
198 if(controller->get_speed())
199 throw logic_error("moving");
202 accurate_position = false;
204 allocator.start_from(block);
207 vehicles.front()->place(block.reverse().track_iter(), 0, Vehicle::FRONT_BUFFER);
209 vehicles.back()->place(block.track_iter(), 0, Vehicle::BACK_BUFFER);
212 void Train::unplace()
214 if(controller->get_speed())
215 throw logic_error("moving");
220 accurate_position = false;
222 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
226 void Train::stop_at(Block *block)
228 allocator.stop_at(block);
230 allocator.reserve_more();
233 bool Train::free_block(Block &block)
235 if(get_reserved_distance_until(&block, false)<controller->get_braking_distance()*1.3)
238 return allocator.release_from(block);
241 void Train::free_noncritical_blocks()
243 if(allocator.empty())
246 if(controller->get_speed()==0)
248 allocator.release_noncurrent();
252 float margin = 10*layout.get_catalogue().get_scale();
253 float min_dist = controller->get_braking_distance()*1.3+margin;
255 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
257 TrackIter track = veh.get_track_iter();
258 BlockIter block = allocator.first();
259 const BlockIter &last_cur = allocator.last_current();
260 const BlockIter &last = allocator.last();
262 while(!block->has_track(*track))
264 if(&*block==&*last_cur)
268 block = block.next();
271 float dist = veh.get_offset();
275 dist = track->get_type().get_path_length(track->get_active_path())-dist;
276 dist -= veh.get_type().get_length()/2;
281 track = track.next();
283 if(!block->has_track(*track))
285 if(&*block==&*last_cur)
289 block = block.next();
291 if(dist>min_dist && nsens>0)
293 allocator.release_from(*block);
297 if(in_rsv && block->get_sensor_id())
301 dist += track->get_type().get_path_length(track->get_active_path());
305 float Train::get_reserved_distance() const
307 if(allocator.empty())
311 TrackIter next = allocator.last().next().track_iter();
312 if(next && next->get_type().is_turnout())
313 margin = 15*layout.get_catalogue().get_scale();
315 return max(get_reserved_distance_until(0, false)-margin, 0.0f);
318 void Train::reserve_more()
320 allocator.reserve_more();
323 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
325 if(!active && stop_timeout && t>=stop_timeout)
327 allocator.release_noncurrent();
328 stop_timeout = Time::TimeStamp();
331 Driver &driver = layout.get_driver();
333 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
335 controller->tick(dt);
336 float speed = controller->get_speed();
337 bool moving = speed>0;
339 if(controller->get_reverse()!=reverse)
341 reverse = controller->get_reverse();
343 if(loco_type.get_swap_direction())
345 driver.set_loco_reverse(address, r);
349 allocator.reserve_more();
354 unsigned speed_step = speed_quantizer->find_speed_step(speed);
355 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
357 speed_changing = true;
358 driver.set_loco_speed(address, speed_step);
363 speed = speed_quantizer->get_speed(current_speed_step);
371 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
373 float d = speed*(dt/Time::sec);
374 if(allocator.is_block_current(vehicle.get_track()->get_block()))
376 SetFlag setf(advancing);
377 vehicle.advance(reverse ? -d : d);
379 else if(accurate_position)
382 if(overshoot_dist>40*layout.get_catalogue().get_scale())
384 layout.emergency(name+" has not arrived at sensor");
385 accurate_position = false;
390 if(!allocator.empty() && !allocator.first()->get_sensor_id())
392 float dist = get_reserved_distance_until(&*allocator.first(), true);
394 if(dist>10*layout.get_catalogue().get_scale())
395 allocator.release_until(*allocator.first());
399 void Train::save(list<DataFile::Statement> &st) const
401 st.push_back((DataFile::Statement("name"), name));
403 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
404 if(i!=vehicles.begin())
405 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
409 DataFile::Statement ss("quantized_speed");
410 speed_quantizer->save(ss.sub);
415 DataFile::Statement ss("blocks");
416 allocator.save(ss.sub);
420 // XXX Need more generic way of saving AI state
421 for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
423 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
425 DataFile::Statement ss("router");
426 router->save(ss.sub);
429 else if(Timetable *timetable = dynamic_cast<Timetable *>(*i))
431 DataFile::Statement ss("timetable");
432 timetable->save(ss.sub);
438 void Train::control_changed(const Controller::Control &ctrl)
440 signal_control_changed.emit(ctrl.name, ctrl.value);
443 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
447 current_speed_step = speed;
449 if(loco_type.get_swap_direction())
452 layout.get_driver().set_loco_reverse(address, r);
453 speed_changing = false;
458 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
463 functions |= 1<<func;
465 functions &= ~(1<<func);
467 signal_function_changed.emit(func, state);
471 void Train::block_state_changed(Block &block, Block::State state)
473 if(block.get_train()==this && state==Block::MAYBE_ACTIVE)
477 float travel_distance = -1;
478 if(pure_speed && speed_quantizer && current_speed_step>0)
481 for(BlockIter i=last_entry_block; &*i!=█ i=i.next())
483 if(i->get_sensor_id())
485 if(travel_distance>=0)
486 travel_distance += i->get_path_length(i.entry());
489 if(travel_distance>0)
491 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
493 if(travel_time_secs>=2)
494 speed_quantizer->learn(current_speed_step, travel_distance/travel_time_secs, travel_time_secs);
498 last_entry_block = allocator.iter_for(block);
499 last_entry_time = Time::now();
501 accurate_position = true;
504 if(!advancing && vehicles.front()->get_track())
506 TrackIter track = last_entry_block.track_iter();
509 track = track.flip();
510 vehicles.back()->place(track, 0, Vehicle::BACK_AXLE);
513 vehicles.front()->place(track, 0, Vehicle::FRONT_AXLE);
518 void Train::halt_event(bool h)
521 accurate_position = false;
524 float Train::get_reserved_distance_until(const Block *until_block, bool back) const
526 if(allocator.empty())
529 Vehicle &veh = *(reverse!=back ? vehicles.back() : vehicles.front());
530 const VehicleType &vtype = veh.get_type();
532 TrackIter track = veh.get_track_iter();
533 if(!track) // XXX Probably unnecessary
536 const BlockIter &first = allocator.first();
537 const BlockIter &last = allocator.last();
538 BlockIter block = first;
539 while(!block->has_track(*track))
543 block = block.next();
545 if(&*block==until_block)
549 block = block.reverse();
551 float result = veh.get_offset();
553 track = track.reverse();
555 result = track->get_type().get_path_length(track->get_active_path())-result;
556 result -= vtype.get_length()/2;
560 track = track.next();
564 if(!block->has_track(*track))
576 block = block.next();
578 if(&*block==until_block)
582 result += track->get_type().get_path_length(track->get_active_path());
589 Train::Loader::Loader(Train &t):
590 DataFile::ObjectLoader<Train>(t),
594 add("blocks", &Loader::blocks);
595 add("name", &Loader::name);
596 add("quantized_speed", &Loader::quantized_speed);
597 add("router", &Loader::router);
598 add("timetable", &Loader::timetable);
599 add("vehicle", &Loader::vehicle);
602 void Train::Loader::finish()
604 if(!obj.allocator.empty())
606 TrackIter track = obj.allocator.first().track_iter();
607 float offset = 2*obj.layout.get_catalogue().get_scale();
608 obj.vehicles.back()->place(track, offset, Vehicle::BACK_BUFFER);
612 void Train::Loader::blocks()
614 load_sub(obj.allocator);
617 void Train::Loader::name(const string &n)
622 void Train::Loader::quantized_speed()
624 if(obj.speed_quantizer)
625 load_sub(*obj.speed_quantizer);
628 void Train::Loader::router()
630 TrainRouter *rtr = new TrainRouter(obj);
634 void Train::Loader::timetable()
636 Timetable *ttbl = new Timetable(obj);
640 void Train::Loader::vehicle(ArticleNumber art_nr)
642 const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(art_nr);
643 Vehicle *veh = new Vehicle(obj.layout, vtype);
644 obj.vehicles.back()->attach_back(*veh);
645 obj.vehicles.push_back(veh);