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 "trackcircuit.h"
18 #include "trackiter.h"
19 #include "tracktype.h"
21 #include "trainrouter.h"
23 #include "vehicletype.h"
31 Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
39 controller(new SimpleController),
40 current_speed_step(0),
41 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));
57 vehicles.back()->set_train(this);
59 layout.add_train(*this);
61 layout.get_driver().add_loco(address, protocol, loco_type);
62 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
63 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
65 layout.signal_sensor_state_changed.connect(sigc::mem_fun(this, &Train::sensor_state_changed));
67 layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
69 controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
75 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
77 layout.remove_train(*this);
80 void Train::set_name(const string &n)
84 signal_name_changed.emit(name);
87 void Train::add_vehicle(const VehicleType &vt)
89 Vehicle *veh = new Vehicle(layout, vt);
90 vehicles.back()->attach_back(*veh);
91 vehicles.push_back(veh);
93 signal_vehicle_added.emit(vehicles.size()-1, *veh);
96 void Train::remove_vehicle(unsigned i)
98 if(i>=vehicles.size())
99 throw out_of_range("Train::remove_vehicle");
101 throw logic_error("can't remove locomotive");
103 Vehicle *veh = vehicles[i];
104 vehicles.erase(vehicles.begin()+i);
106 if(i<vehicles.size())
109 vehicles[i-1]->attach_back(*vehicles[i]);
111 signal_vehicle_removed.emit(i, *veh);
115 unsigned Train::get_n_vehicles() const
117 return vehicles.size();
120 Vehicle &Train::get_vehicle(unsigned i)
122 if(i>=vehicles.size())
123 throw out_of_range("Train::get_vehicle");
127 const Vehicle &Train::get_vehicle(unsigned i) const
129 if(i>=vehicles.size())
130 throw out_of_range("Train::get_vehicle");
134 void Train::set_control(const string &n, float v)
136 controller->set_control(n, v);
139 void Train::set_function(unsigned func, bool state)
141 if(!loco_type.get_functions().count(func))
142 throw invalid_argument("Train::set_function");
143 layout.get_driver().set_loco_function(address, func, state);
146 float Train::get_control(const string &ctrl) const
148 return controller->get_control(ctrl).value;
151 float Train::get_speed() const
153 return controller->get_speed();
156 float Train::get_quantized_speed() const
159 return speed_quantizer->quantize_speed(controller->get_speed());
161 return controller->get_speed();
164 bool Train::get_function(unsigned func) const
166 return (functions>>func)&1;
169 void Train::add_ai(TrainAI &ai)
172 ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
175 void Train::remove_ai(TrainAI &ai)
177 list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
182 void Train::ai_message(const TrainAI::Message &msg)
184 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
188 void Train::place(const BlockIter &block)
191 throw invalid_argument("Train::place");
192 if(controller->get_speed())
193 throw logic_error("moving");
195 allocator.start_from(block);
196 accurate_position = false;
197 last_entry_block = BlockIter();
200 vehicles.front()->place(block.reverse().track_iter(), 0, Vehicle::FRONT_BUFFER);
202 vehicles.back()->place(block.track_iter(), 0, Vehicle::BACK_BUFFER);
205 void Train::unplace()
207 if(controller->get_speed())
208 throw logic_error("moving");
211 accurate_position = false;
212 last_entry_block = BlockIter();
214 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
218 void Train::stop_at(Block *block)
220 allocator.stop_at(block);
223 bool Train::is_block_critical(const Block &block) const
225 return get_reserved_distance_until(&block)<controller->get_braking_distance()*1.3;
228 BlockIter Train::get_first_noncritical_block() const
230 if(allocator.empty())
233 BlockIter i = allocator.last_current().next();
235 if(controller->get_speed()==0)
238 float margin = 10*layout.get_catalogue().get_scale();
239 float min_dist = controller->get_braking_distance()*1.3+margin;
242 bool sensor_seen = false;
243 for(; i->get_train()==this; i=i.next())
245 if(dist>min_dist && sensor_seen)
248 dist += i->get_path_length(i.entry());
250 if(i->get_sensor_id())
257 void Train::refresh_blocks_from(Block &block)
259 if(is_block_critical(block))
260 allocator.rewind_to(*get_first_noncritical_block());
262 allocator.rewind_to(block);
265 float Train::get_reserved_distance() const
267 if(allocator.empty())
271 TrackIter next = allocator.last().next().track_iter();
272 if(next && next->get_type().is_turnout())
273 margin = 15*layout.get_catalogue().get_scale();
275 return max(get_reserved_distance_until(0)-margin, 0.0f);
278 void Train::tick(const Time::TimeDelta &dt)
283 if(stop_timeout<=Time::zero)
285 allocator.set_active(false);
286 stop_timeout = Time::TimeDelta();
292 Driver &driver = layout.get_driver();
294 bool intent_to_move = false;
295 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
298 if((*i)->has_intent_to_move())
299 intent_to_move = true;
302 controller->tick(dt);
303 float speed = controller->get_speed();
304 bool moving = speed>0;
306 if(controller->get_reverse()!=reverse)
308 reverse = controller->get_reverse();
310 if(loco_type.get_swap_direction())
312 driver.set_loco_reverse(address, r);
315 last_entry_block = BlockIter();
320 unsigned speed_step = speed_quantizer->find_speed_step(speed);
321 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
323 speed_changing = true;
324 driver.set_loco_speed(address, speed_step);
329 speed = speed_quantizer->get_speed(current_speed_step);
334 if(!allocator.is_active())
335 allocator.set_active(true);
337 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
339 float d = speed*(dt/Time::sec);
340 if(allocator.is_block_current(vehicle.get_track()->get_block()))
342 SetFlag setf(advancing);
343 vehicle.advance(reverse ? -d : d);
345 else if(accurate_position)
348 if(overshoot_dist>40*layout.get_catalogue().get_scale())
350 layout.emergency(name+" has not arrived at sensor");
351 accurate_position = false;
355 else if(intent_to_move && !allocator.is_active())
356 allocator.set_active(true);
357 else if(allocator.is_active() && !intent_to_move && !stop_timeout)
358 stop_timeout = 2*Time::sec;
361 void Train::save(list<DataFile::Statement> &st) const
363 st.push_back((DataFile::Statement("name"), name));
365 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
366 if(i!=vehicles.begin())
367 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
371 DataFile::Statement ss("quantized_speed");
372 speed_quantizer->save(ss.sub);
377 DataFile::Statement ss("blocks");
378 allocator.save(ss.sub);
382 // XXX Need more generic way of saving AI state
383 for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
385 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
387 DataFile::Statement ss("router");
388 router->save(ss.sub);
394 void Train::control_changed(const Controller::Control &ctrl)
396 signal_control_changed.emit(ctrl.name, ctrl.value);
399 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
403 current_speed_step = speed;
405 if(loco_type.get_swap_direction())
408 layout.get_driver().set_loco_reverse(address, r);
409 speed_changing = false;
414 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
419 functions |= 1<<func;
421 functions &= ~(1<<func);
423 signal_function_changed.emit(func, state);
427 void Train::sensor_state_changed(Sensor &sensor, Sensor::State state)
429 if(!current_speed_step || state!=Sensor::MAYBE_ACTIVE)
432 Block *block = sensor.get_block();
433 if(!block || block->get_train()!=this)
436 if(last_entry_block && &*last_entry_block!=block)
438 for(BlockIter i=last_entry_block.next(); (i && &*i!=block); i=i.next())
439 if(i->get_train()!=this || i->get_sensor_id())
443 if(dynamic_cast<TrackCircuit *>(&sensor))
445 if(last_entry_block && pure_speed && speed_quantizer)
447 float travel_distance = 0;
449 for(BlockIter i=last_entry_block; &*i!=block; i=i.next())
450 travel_distance += i->get_path_length(i.entry());
452 if(travel_distance>0)
454 float travel_time_secs = travel_time/Time::sec;
456 if(travel_time_secs>=2)
457 speed_quantizer->learn(current_speed_step, travel_distance/travel_time_secs, travel_time_secs);
461 last_entry_block = allocator.iter_for(*block);
462 travel_time = Time::zero;
464 accurate_position = true;
467 if(!advancing && vehicles.front()->get_track())
469 TrackIter track = last_entry_block.track_iter();
472 track = track.flip();
473 vehicles.back()->place(track, 0, Vehicle::BACK_AXLE);
476 vehicles.front()->place(track, 0, Vehicle::FRONT_AXLE);
479 else if(BeamGate *gate = dynamic_cast<BeamGate *>(&sensor))
481 if(!advancing && vehicles.front()->get_track())
483 TrackIter track = allocator.iter_for(*block).track_iter();
484 for(; (track && &track->get_block()==block); track=track.next())
485 if(track.track()==gate->get_track())
488 track = track.reverse();
489 float offset = gate->get_offset_from_endpoint(track.entry());
491 vehicles.back()->place(track, offset, Vehicle::BACK_BUFFER);
493 vehicles.front()->place(track, offset, Vehicle::FRONT_BUFFER);
500 void Train::halt_event(bool h)
503 accurate_position = false;
506 float Train::get_reserved_distance_until(const Block *until_block) const
508 if(allocator.empty())
511 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
513 TrackIter track = veh.get_track_iter().track_iter();
514 if(!track) // XXX Probably unnecessary
517 if(&track->get_block()==until_block)
520 // Account for the vehicle's offset on its current track
521 float result = veh.get_offset();
523 track = track.reverse();
525 result = track->get_type().get_path_length(track->get_active_path())-result;
526 result -= veh.get_type().get_length()/2;
528 BlockIter block = track.block_iter();
530 // Count remaining distance in the vehicle's current block
531 for(track=track.next(); &track->get_block()==&*block; track=track.next())
532 result += track->get_type().get_path_length(track->get_active_path());
534 const BlockIter &last = allocator.last();
538 // Count any remaining blocks
539 for(block=block.next(); (&*block!=until_block && block->get_train()==this); block=block.next())
541 result += block->get_path_length(block.entry());
551 Train::Loader::Loader(Train &t):
552 DataFile::ObjectLoader<Train>(t),
556 add("blocks", &Loader::blocks);
557 add("name", &Loader::name);
558 add("quantized_speed", &Loader::quantized_speed);
559 add("router", &Loader::router);
560 add("vehicle", &Loader::vehicle);
563 void Train::Loader::finish()
565 if(!obj.allocator.empty())
567 TrackIter track = obj.allocator.first().track_iter();
568 float offset = 2*obj.layout.get_catalogue().get_scale();
569 obj.vehicles.back()->place(track, offset, Vehicle::BACK_BUFFER);
573 void Train::Loader::blocks()
575 load_sub(obj.allocator);
578 void Train::Loader::name(const string &n)
583 void Train::Loader::quantized_speed()
585 if(obj.speed_quantizer)
586 load_sub(*obj.speed_quantizer);
589 void Train::Loader::router()
591 TrainRouter *rtr = new TrainRouter(obj);
595 void Train::Loader::vehicle(ArticleNumber art_nr)
597 const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(art_nr);
598 Vehicle *veh = new Vehicle(obj.layout, vtype);
599 obj.vehicles.back()->attach_back(*veh);
600 obj.vehicles.push_back(veh);
601 veh->set_train(&obj);