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 bool Train::place(const BlockIter &block)
191 throw invalid_argument("Train::place");
192 if(controller->get_speed())
193 throw logic_error("moving");
195 accurate_position = false;
196 last_entry_block = BlockIter();
198 if(allocator.start_from(block))
201 vehicles.front()->place(block.reverse().track_iter(), VehiclePlacement::FRONT_BUFFER);
203 vehicles.back()->place(block.track_iter(), VehiclePlacement::BACK_BUFFER);
213 void Train::unplace()
215 if(controller->get_speed())
216 throw logic_error("moving");
219 accurate_position = false;
220 last_entry_block = BlockIter();
222 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
226 void Train::stop_at(Block *block)
228 allocator.stop_at(block);
231 bool Train::is_block_critical(const Block &block) const
233 return get_reserved_distance_until(&block)<=controller->get_braking_distance()*1.3;
236 BlockIter Train::get_first_noncritical_block() const
238 if(allocator.empty())
241 BlockIter i = allocator.last_current().next();
243 if(controller->get_speed()==0)
246 float margin = 10*layout.get_catalogue().get_scale();
247 float min_dist = controller->get_braking_distance()*1.3+margin;
250 bool sensor_seen = false;
251 for(; i->get_train()==this; i=i.next())
253 if(dist>min_dist && sensor_seen)
256 dist += i->get_path_length(i.entry());
258 if(i->get_sensor_id())
265 void Train::refresh_blocks_from(Block &block)
267 if(is_block_critical(block))
268 allocator.rewind_to(*get_first_noncritical_block());
270 allocator.rewind_to(block);
273 float Train::get_reserved_distance() const
275 if(allocator.empty())
279 TrackIter next = allocator.last().next().track_iter();
280 if(next && next->get_type().is_turnout())
281 margin = 15*layout.get_catalogue().get_scale();
283 return max(get_reserved_distance_until(0)-margin, 0.0f);
286 void Train::tick(const Time::TimeDelta &dt)
291 if(stop_timeout<=Time::zero)
293 allocator.set_active(false);
294 stop_timeout = Time::TimeDelta();
300 Driver &driver = layout.get_driver();
302 bool intent_to_move = false;
303 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
306 if((*i)->has_intent_to_move())
307 intent_to_move = true;
310 controller->tick(dt);
311 float speed = controller->get_speed();
312 bool moving = speed>0;
314 if(controller->get_reverse()!=reverse)
316 reverse = controller->get_reverse();
318 if(loco_type.get_swap_direction())
320 driver.set_loco_reverse(address, r);
323 last_entry_block = BlockIter();
328 unsigned speed_step = speed_quantizer->find_speed_step(speed);
329 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
331 speed_changing = true;
332 driver.set_loco_speed(address, speed_step);
337 speed = speed_quantizer->get_speed(current_speed_step);
342 if(!allocator.is_active())
343 allocator.set_active(true);
345 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
347 float d = speed*(dt/Time::sec);
348 if(allocator.is_block_current(vehicle.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE)->get_block()))
350 SetFlag setf(advancing);
351 vehicle.advance(reverse ? -d : d);
353 else if(accurate_position)
356 if(overshoot_dist>40*layout.get_catalogue().get_scale())
358 layout.emergency(name+" has not arrived at sensor");
359 accurate_position = false;
363 else if(intent_to_move && !allocator.is_active())
364 allocator.set_active(true);
365 else if(allocator.is_active() && !intent_to_move && !stop_timeout)
366 stop_timeout = 2*Time::sec;
369 void Train::save(list<DataFile::Statement> &st) const
371 st.push_back((DataFile::Statement("name"), name));
373 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
374 if(i!=vehicles.begin())
375 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
379 DataFile::Statement ss("quantized_speed");
380 speed_quantizer->save(ss.sub);
385 DataFile::Statement ss("blocks");
386 allocator.save(ss.sub);
390 // XXX Need more generic way of saving AI state
391 for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
393 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
395 DataFile::Statement ss("router");
396 router->save(ss.sub);
402 void Train::control_changed(const Controller::Control &ctrl)
404 signal_control_changed.emit(ctrl.name, ctrl.value);
407 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
411 current_speed_step = speed;
413 if(loco_type.get_swap_direction())
416 layout.get_driver().set_loco_reverse(address, r);
417 speed_changing = false;
422 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
427 functions |= 1<<func;
429 functions &= ~(1<<func);
431 signal_function_changed.emit(func, state);
435 void Train::sensor_state_changed(Sensor &sensor, Sensor::State state)
437 if(!current_speed_step || state!=Sensor::MAYBE_ACTIVE)
440 Block *block = sensor.get_block();
441 if(!block || block->get_train()!=this)
444 if(last_entry_block && &*last_entry_block!=block)
446 for(BlockIter i=last_entry_block.next(); (i && &*i!=block); i=i.next())
447 if(i->get_train()!=this || i->get_sensor_id())
451 if(dynamic_cast<TrackCircuit *>(&sensor))
453 if(last_entry_block && pure_speed && speed_quantizer)
455 float travel_distance = 0;
457 for(BlockIter i=last_entry_block; &*i!=block; i=i.next())
458 travel_distance += i->get_path_length(i.entry());
460 if(travel_distance>0)
462 float travel_time_secs = travel_time/Time::sec;
464 if(travel_time_secs>=2)
465 speed_quantizer->learn(current_speed_step, travel_distance/travel_time_secs, travel_time_secs);
469 last_entry_block = allocator.iter_for(*block);
470 travel_time = Time::zero;
472 accurate_position = true;
475 if(!advancing && vehicles.front()->is_placed())
477 TrackIter track = last_entry_block.track_iter();
480 track = track.flip();
481 vehicles.back()->place(track, VehiclePlacement::BACK_AXLE);
484 vehicles.front()->place(track, VehiclePlacement::FRONT_AXLE);
487 else if(BeamGate *gate = dynamic_cast<BeamGate *>(&sensor))
489 if(!advancing && vehicles.front()->is_placed())
491 TrackIter track = allocator.iter_for(*block).track_iter();
492 for(; (track && &track->get_block()==block); track=track.next())
493 if(track.track()==gate->get_track())
496 track = track.reverse();
497 float offset = gate->get_offset_from_endpoint(track.entry());
499 vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
501 vehicles.front()->place(TrackOffsetIter(track, offset), VehiclePlacement::FRONT_BUFFER);
508 void Train::halt_event(bool h)
511 accurate_position = false;
514 float Train::get_reserved_distance_until(const Block *until_block) const
516 if(allocator.empty())
519 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
521 TrackOffsetIter track = veh.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE);
522 if(!track) // XXX Probably unnecessary
525 if(&track->get_block()==until_block)
528 // Account for the vehicle's offset on its current track
529 float result = track.offset();
531 track = track.reverse();
533 result = track->get_type().get_path_length(track->get_active_path())-result;
534 result -= veh.get_type().get_length()/2;
536 BlockIter block = track.block_iter();
538 // Count remaining distance in the vehicle's current block
539 for(track=track.next(); &track->get_block()==&*block; track=track.next())
540 result += track->get_type().get_path_length(track->get_active_path());
542 const BlockIter &last = allocator.last();
546 // Count any remaining blocks
547 for(block=block.next(); (&*block!=until_block && block->get_train()==this); block=block.next())
549 result += block->get_path_length(block.entry());
559 Train::Loader::Loader(Train &t):
560 DataFile::ObjectLoader<Train>(t),
564 add("blocks", &Loader::blocks);
565 add("name", &Loader::name);
566 add("quantized_speed", &Loader::quantized_speed);
567 add("router", &Loader::router);
568 add("vehicle", &Loader::vehicle);
571 void Train::Loader::finish()
573 if(!obj.allocator.empty())
575 TrackIter track = obj.allocator.first().track_iter();
576 float offset = 2*obj.layout.get_catalogue().get_scale();
577 obj.vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
581 void Train::Loader::blocks()
583 load_sub(obj.allocator);
586 void Train::Loader::name(const string &n)
591 void Train::Loader::quantized_speed()
593 if(obj.speed_quantizer)
594 load_sub(*obj.speed_quantizer);
597 void Train::Loader::router()
599 TrainRouter *rtr = new TrainRouter(obj);
603 void Train::Loader::vehicle(ArticleNumber art_nr)
605 const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(art_nr);
606 Vehicle *veh = new Vehicle(obj.layout, vtype);
607 obj.vehicles.back()->attach_back(*veh);
608 obj.vehicles.push_back(veh);
609 veh->set_train(&obj);