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>
10 #include "catalogue.h"
13 #include "simplecontroller.h"
14 #include "speedquantizer.h"
15 #include "timetable.h"
16 #include "trackcircuit.h"
17 #include "trackiter.h"
18 #include "tracktype.h"
20 #include "trainrouter.h"
22 #include "vehicletype.h"
29 Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
37 controller(new SimpleController),
38 current_speed_step(0),
39 speed_changing(false),
44 accurate_position(false),
47 if(!loco_type.is_locomotive())
48 throw invalid_argument("Train::Train");
50 unsigned speed_steps = layout.get_driver().get_protocol_speed_steps(protocol);
52 speed_quantizer = new SpeedQuantizer(speed_steps);
54 vehicles.push_back(new Vehicle(layout, loco_type));
55 vehicles.back()->set_train(this);
57 layout.add_train(*this);
59 loco_id = 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.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
65 controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
67 allocator.signal_advanced.connect(sigc::mem_fun(this, &Train::advanced));
68 allocator.signal_rear_advanced.connect(signal_rear_advanced);
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);
92 signal_vehicle_added.emit(vehicles.size()-1, *veh);
95 void Train::remove_vehicle(unsigned i)
97 if(i>=vehicles.size())
98 throw out_of_range("Train::remove_vehicle");
100 throw logic_error("can't remove locomotive");
102 Vehicle *veh = vehicles[i];
103 vehicles.erase(vehicles.begin()+i);
105 if(i<vehicles.size())
108 vehicles[i-1]->attach_back(*vehicles[i]);
110 signal_vehicle_removed.emit(i, *veh);
114 unsigned Train::get_n_vehicles() const
116 return vehicles.size();
119 Vehicle &Train::get_vehicle(unsigned i)
121 if(i>=vehicles.size())
122 throw out_of_range("Train::get_vehicle");
126 const Vehicle &Train::get_vehicle(unsigned i) const
128 if(i>=vehicles.size())
129 throw out_of_range("Train::get_vehicle");
133 void Train::set_control(const string &n, float v)
135 controller->set_control(n, v);
138 void Train::set_function(unsigned func, bool state)
140 if(!loco_type.get_functions().count(func))
141 throw invalid_argument("Train::set_function");
142 layout.get_driver().set_loco_function(loco_id, func, state);
145 float Train::get_control(const string &ctrl) const
147 return controller->get_control(ctrl).value;
150 float Train::get_speed() const
152 return controller->get_speed();
155 float Train::get_quantized_speed() const
158 return speed_quantizer->quantize_speed(controller->get_speed());
160 return controller->get_speed();
163 float Train::get_maximum_speed() const
166 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
168 float vms = (*i)->get_type().get_maximum_speed();
169 if(ms<=0 || (vms>0 && vms<ms))
175 bool Train::get_function(unsigned func) const
177 return (functions>>func)&1;
180 void Train::add_ai(TrainAI &ai)
183 ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
186 void Train::remove_ai(TrainAI &ai)
188 list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
193 void Train::ai_message(const TrainAI::Message &msg)
195 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
199 bool Train::place(const BlockIter &block)
202 throw invalid_argument("Train::place");
203 if(controller->get_speed())
204 throw logic_error("moving");
206 accurate_position = false;
207 last_entry_block = BlockIter();
209 if(allocator.start_from(block))
212 vehicles.front()->place(block.reverse().track_iter(), VehiclePlacement::FRONT_BUFFER);
214 vehicles.back()->place(block.track_iter(), VehiclePlacement::BACK_BUFFER);
224 void Train::unplace()
226 if(controller->get_speed())
227 throw logic_error("moving");
230 accurate_position = false;
231 last_entry_block = BlockIter();
233 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
237 void Train::stop_at(Block *block)
239 allocator.stop_at(block);
242 bool Train::is_block_critical(const Block &block) const
244 if(allocator.is_block_current(block))
247 BlockIter i = check_critical_blocks(&block);
248 return i.block()==█
251 BlockIter Train::get_last_critical_block() const
253 return check_critical_blocks(0);
256 BlockIter Train::check_critical_blocks(const Block *check) const
258 if(allocator.empty())
261 BlockIter i = allocator.last_current();
263 if(controller->get_speed()==0)
266 BlockIter last = allocator.last();
267 if(i.block()==last.block())
270 float margin = 10*layout.get_catalogue().get_scale();
271 float min_dist = controller->get_braking_distance()*1.3+margin;
274 bool sensor_seen = false;
276 while(i.block()!=last.block() && i.block()!=check)
278 dist += i->get_path_length(i.entry());
280 if(i->get_sensor_address())
283 if(dist>min_dist && sensor_seen)
286 BlockIter j = i.next();
287 if(j->get_train()!=this)
296 void Train::refresh_blocks_from(Block &block)
298 if(is_block_critical(block))
299 allocator.rewind_to(*get_last_critical_block().next());
301 allocator.rewind_to(block);
304 float Train::get_reserved_distance() const
306 if(allocator.empty())
310 TrackIter next = allocator.last().next().track_iter();
311 if(next && next->get_type().is_turnout())
312 margin = 15*layout.get_catalogue().get_scale();
314 return max(get_reserved_distance_until(0)-margin, 0.0f);
317 void Train::tick(const Time::TimeDelta &dt)
321 stop_timeout = max(stop_timeout-dt, Time::zero);
322 if(stop_timeout<=Time::zero)
323 allocator.set_active(false);
328 Driver &driver = layout.get_driver();
330 bool intent_to_move = false;
331 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
334 if((*i)->has_intent_to_move())
335 intent_to_move = true;
338 controller->tick(dt);
339 float speed = controller->get_speed();
340 bool moving = speed>0;
342 if(controller->get_reverse()!=reverse)
344 reverse = controller->get_reverse();
346 if(loco_type.get_swap_direction())
348 driver.set_loco_reverse(loco_id, r);
351 last_entry_block = BlockIter();
356 unsigned speed_step = speed_quantizer->find_speed_step(speed);
357 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
359 speed_changing = true;
360 driver.set_loco_speed(loco_id, speed_step);
365 speed = speed_quantizer->get_speed(current_speed_step);
370 if(!allocator.is_active())
371 allocator.set_active(true);
373 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
375 float d = speed*(dt/Time::sec);
376 Block &block = vehicle.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE)->get_block();
377 if(allocator.is_block_current(block))
379 SetFlag setf(advancing);
380 vehicle.advance(reverse ? -d : d);
382 else if(accurate_position)
385 if(overshoot_dist>40*layout.get_catalogue().get_scale())
387 layout.emergency(&block, name+" has not arrived at sensor");
388 accurate_position = false;
392 else if(intent_to_move && !allocator.is_active())
393 allocator.set_active(true);
394 else if(allocator.is_active() && !intent_to_move && !stop_timeout)
395 stop_timeout = 2*Time::sec;
398 void Train::save(list<DataFile::Statement> &st) const
400 st.push_back((DataFile::Statement("name"), name));
402 const Catalogue &cat = layout.get_catalogue();
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"), cat.get_name(&(*i)->get_type())));
409 DataFile::Statement ss("quantized_speed");
410 speed_quantizer->save(ss.sub);
415 DataFile::Statement ss("blocks");
416 allocator.save(ss.sub);
420 const VehicleType::FunctionMap &func_map = loco_type.get_functions();
421 for(VehicleType::FunctionMap::const_iterator i=func_map.begin(); i!=func_map.end(); ++i)
422 st.push_back((DataFile::Statement("function"), i->first, static_cast<bool>(functions&(1<<i->first))));
424 // XXX Need more generic way of saving AI state
425 for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
427 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
429 DataFile::Statement ss("router");
430 router->save(ss.sub);
433 else if(Timetable *timetable = dynamic_cast<Timetable *>(*i))
435 DataFile::Statement ss("timetable");
436 timetable->save(ss.sub);
442 void Train::control_changed(const Controller::Control &ctrl)
444 signal_control_changed.emit(ctrl.name, ctrl.value);
447 void Train::loco_speed_event(unsigned id, unsigned speed, bool rev)
451 current_speed_step = speed;
453 if(loco_type.get_swap_direction())
456 layout.get_driver().set_loco_reverse(loco_id, r);
457 speed_changing = false;
462 void Train::loco_func_event(unsigned id, unsigned func, bool state)
467 functions |= 1<<func;
469 functions &= ~(1<<func);
471 signal_function_changed.emit(func, state);
475 void Train::advanced(Block &block, Sensor *sensor)
477 if(!sensor || sensor==block.get_sensor())
478 signal_advanced.emit(block);
483 if(sensor==block.get_sensor())
485 if(last_entry_block && pure_speed && speed_quantizer)
487 float travel_distance = 0;
489 for(BlockIter i=last_entry_block; &*i!=█ i=i.next())
490 travel_distance += i->get_path_length(i.entry());
492 if(travel_distance>0)
494 float travel_time_secs = travel_time/Time::sec;
496 if(travel_time_secs>=2)
497 speed_quantizer->learn(current_speed_step, travel_distance/travel_time_secs, travel_time_secs);
501 last_entry_block = allocator.iter_for(block);
502 travel_time = Time::zero;
503 if(!layout.get_driver().is_halted())
506 accurate_position = true;
510 if(!advancing && vehicles.front()->is_placed())
512 TrackIter track = last_entry_block.track_iter();
515 track = track.flip();
516 vehicles.back()->place(track, VehiclePlacement::BACK_AXLE);
519 vehicles.front()->place(track, VehiclePlacement::FRONT_AXLE);
522 else if(BeamGate *gate = dynamic_cast<BeamGate *>(sensor))
524 if(!advancing && vehicles.front()->is_placed())
526 TrackIter track = allocator.iter_for(block).track_iter();
527 for(; (track && &track->get_block()==&block); track=track.next())
528 if(track.track()==gate->get_track())
531 track = track.reverse();
532 float offset = gate->get_offset_from_endpoint(track.entry());
534 vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
536 vehicles.front()->place(TrackOffsetIter(track, offset), VehiclePlacement::FRONT_BUFFER);
543 void Train::halt_event(bool h)
546 accurate_position = false;
549 float Train::get_reserved_distance_until(const Block *until_block) const
551 if(allocator.empty())
554 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
556 TrackOffsetIter track = veh.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE);
557 if(!track) // XXX Probably unnecessary
560 if(&track->get_block()==until_block)
563 // Account for the vehicle's offset on its current track
564 float result = track.offset();
566 track = track.reverse();
568 result = track->get_path_length()-result;
569 result -= veh.get_type().get_length()/2;
571 BlockIter block = track.block_iter();
573 // Count remaining distance in the vehicle's current block
574 for(track=track.next(); &track->get_block()==&*block; track=track.next())
575 result += track->get_path_length();
577 const BlockIter &last = allocator.last();
581 // Count any remaining blocks
582 for(block=block.next(); (&*block!=until_block && block->get_train()==this); block=block.next())
584 result += block->get_path_length(block.entry());
594 Train::Loader::Loader(Train &t):
595 DataFile::ObjectLoader<Train>(t),
599 add("blocks", &Loader::blocks);
600 add("function", &Loader::function);
601 add("name", &Loader::name);
602 add("quantized_speed", &Loader::quantized_speed);
603 add("router", &Loader::router);
604 add("timetable", &Loader::timetable);
605 add("vehicle", &Loader::vehicle);
608 void Train::Loader::finish()
610 if(!obj.allocator.empty())
612 TrackIter track = obj.allocator.first().track_iter();
613 float offset = 2*obj.layout.get_catalogue().get_scale();
614 obj.vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
618 void Train::Loader::blocks()
620 load_sub(obj.allocator);
623 void Train::Loader::function(unsigned f, bool s)
625 obj.set_function(f, s);
628 void Train::Loader::name(const string &n)
633 void Train::Loader::quantized_speed()
635 if(obj.speed_quantizer)
636 load_sub(*obj.speed_quantizer);
639 void Train::Loader::router()
641 TrainRouter *rtr = new TrainRouter(obj);
645 void Train::Loader::timetable()
647 Timetable *ttbl = new Timetable(obj);
648 load_sub(*ttbl, obj.layout);
651 void Train::Loader::vehicle(const string &n)
653 const VehicleType &vtype = obj.layout.get_catalogue().get<VehicleType>(n);
654 Vehicle *veh = new Vehicle(obj.layout, vtype);
655 obj.vehicles.back()->attach_back(*veh);
656 obj.vehicles.push_back(veh);
657 veh->set_train(&obj);