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 "timetable.h"
18 #include "trackcircuit.h"
19 #include "trackiter.h"
20 #include "tracktype.h"
22 #include "trainrouter.h"
24 #include "vehicletype.h"
32 Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
40 controller(new SimpleController),
41 current_speed_step(0),
42 speed_changing(false),
47 accurate_position(false),
50 if(!loco_type.is_locomotive())
51 throw invalid_argument("Train::Train");
53 unsigned speed_steps = layout.get_driver().get_protocol_speed_steps(protocol);
55 speed_quantizer = new SpeedQuantizer(speed_steps);
57 vehicles.push_back(new Vehicle(layout, loco_type));
58 vehicles.back()->set_train(this);
60 layout.add_train(*this);
62 loco_id = layout.get_driver().add_loco(address, protocol, loco_type);
63 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
64 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
66 layout.signal_sensor_state_changed.connect(sigc::mem_fun(this, &Train::sensor_state_changed));
68 layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
70 controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
76 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
78 layout.remove_train(*this);
81 void Train::set_name(const string &n)
85 signal_name_changed.emit(name);
88 void Train::add_vehicle(const VehicleType &vt)
90 Vehicle *veh = new Vehicle(layout, vt);
91 vehicles.back()->attach_back(*veh);
92 vehicles.push_back(veh);
94 signal_vehicle_added.emit(vehicles.size()-1, *veh);
97 void Train::remove_vehicle(unsigned i)
99 if(i>=vehicles.size())
100 throw out_of_range("Train::remove_vehicle");
102 throw logic_error("can't remove locomotive");
104 Vehicle *veh = vehicles[i];
105 vehicles.erase(vehicles.begin()+i);
107 if(i<vehicles.size())
110 vehicles[i-1]->attach_back(*vehicles[i]);
112 signal_vehicle_removed.emit(i, *veh);
116 unsigned Train::get_n_vehicles() const
118 return vehicles.size();
121 Vehicle &Train::get_vehicle(unsigned i)
123 if(i>=vehicles.size())
124 throw out_of_range("Train::get_vehicle");
128 const Vehicle &Train::get_vehicle(unsigned i) const
130 if(i>=vehicles.size())
131 throw out_of_range("Train::get_vehicle");
135 void Train::set_control(const string &n, float v)
137 controller->set_control(n, v);
140 void Train::set_function(unsigned func, bool state)
142 if(!loco_type.get_functions().count(func))
143 throw invalid_argument("Train::set_function");
144 layout.get_driver().set_loco_function(loco_id, func, state);
147 float Train::get_control(const string &ctrl) const
149 return controller->get_control(ctrl).value;
152 float Train::get_speed() const
154 return controller->get_speed();
157 float Train::get_quantized_speed() const
160 return speed_quantizer->quantize_speed(controller->get_speed());
162 return controller->get_speed();
165 float Train::get_maximum_speed() const
168 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
170 float vms = (*i)->get_type().get_maximum_speed();
171 if(ms<=0 || (vms>0 && vms<ms))
177 bool Train::get_function(unsigned func) const
179 return (functions>>func)&1;
182 void Train::add_ai(TrainAI &ai)
185 ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
188 void Train::remove_ai(TrainAI &ai)
190 list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
195 void Train::ai_message(const TrainAI::Message &msg)
197 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
201 bool Train::place(const BlockIter &block)
204 throw invalid_argument("Train::place");
205 if(controller->get_speed())
206 throw logic_error("moving");
208 accurate_position = false;
209 last_entry_block = BlockIter();
211 if(allocator.start_from(block))
214 vehicles.front()->place(block.reverse().track_iter(), VehiclePlacement::FRONT_BUFFER);
216 vehicles.back()->place(block.track_iter(), VehiclePlacement::BACK_BUFFER);
226 void Train::unplace()
228 if(controller->get_speed())
229 throw logic_error("moving");
232 accurate_position = false;
233 last_entry_block = BlockIter();
235 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
239 void Train::stop_at(Block *block)
241 allocator.stop_at(block);
244 bool Train::is_block_critical(const Block &block) const
246 return get_reserved_distance_until(&block)<=controller->get_braking_distance()*1.3;
249 BlockIter Train::get_first_noncritical_block() const
251 if(allocator.empty())
254 BlockIter i = allocator.last_current().next();
256 if(controller->get_speed()==0)
259 float margin = 10*layout.get_catalogue().get_scale();
260 float min_dist = controller->get_braking_distance()*1.3+margin;
263 bool sensor_seen = false;
264 for(; i->get_train()==this; i=i.next())
266 if(dist>min_dist && sensor_seen)
269 dist += i->get_path_length(i.entry());
271 if(i->get_sensor_address())
278 void Train::refresh_blocks_from(Block &block)
280 if(is_block_critical(block))
281 allocator.rewind_to(*get_first_noncritical_block());
283 allocator.rewind_to(block);
286 float Train::get_reserved_distance() const
288 if(allocator.empty())
292 TrackIter next = allocator.last().next().track_iter();
293 if(next && next->get_type().is_turnout())
294 margin = 15*layout.get_catalogue().get_scale();
296 return max(get_reserved_distance_until(0)-margin, 0.0f);
299 void Train::tick(const Time::TimeDelta &dt)
304 if(stop_timeout<=Time::zero)
306 allocator.set_active(false);
307 stop_timeout = Time::TimeDelta();
313 Driver &driver = layout.get_driver();
315 bool intent_to_move = false;
316 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
319 if((*i)->has_intent_to_move())
320 intent_to_move = true;
323 controller->tick(dt);
324 float speed = controller->get_speed();
325 bool moving = speed>0;
327 if(controller->get_reverse()!=reverse)
329 reverse = controller->get_reverse();
331 if(loco_type.get_swap_direction())
333 driver.set_loco_reverse(loco_id, r);
336 last_entry_block = BlockIter();
341 unsigned speed_step = speed_quantizer->find_speed_step(speed);
342 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
344 speed_changing = true;
345 driver.set_loco_speed(loco_id, speed_step);
350 speed = speed_quantizer->get_speed(current_speed_step);
355 if(!allocator.is_active())
356 allocator.set_active(true);
358 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
360 float d = speed*(dt/Time::sec);
361 Block &block = vehicle.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE)->get_block();
362 if(allocator.is_block_current(block))
364 SetFlag setf(advancing);
365 vehicle.advance(reverse ? -d : d);
367 else if(accurate_position)
370 if(overshoot_dist>40*layout.get_catalogue().get_scale())
372 layout.emergency(&block, name+" has not arrived at sensor");
373 accurate_position = false;
377 else if(intent_to_move && !allocator.is_active())
378 allocator.set_active(true);
379 else if(allocator.is_active() && !intent_to_move && !stop_timeout)
380 stop_timeout = 2*Time::sec;
383 void Train::save(list<DataFile::Statement> &st) const
385 st.push_back((DataFile::Statement("name"), name));
387 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
388 if(i!=vehicles.begin())
389 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
393 DataFile::Statement ss("quantized_speed");
394 speed_quantizer->save(ss.sub);
399 DataFile::Statement ss("blocks");
400 allocator.save(ss.sub);
404 // XXX Need more generic way of saving AI state
405 for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
407 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
409 DataFile::Statement ss("router");
410 router->save(ss.sub);
413 else if(Timetable *timetable = dynamic_cast<Timetable *>(*i))
415 DataFile::Statement ss("timetable");
416 timetable->save(ss.sub);
422 void Train::control_changed(const Controller::Control &ctrl)
424 signal_control_changed.emit(ctrl.name, ctrl.value);
427 void Train::loco_speed_event(unsigned id, unsigned speed, bool rev)
431 current_speed_step = speed;
433 if(loco_type.get_swap_direction())
436 layout.get_driver().set_loco_reverse(loco_id, r);
437 speed_changing = false;
442 void Train::loco_func_event(unsigned id, unsigned func, bool state)
447 functions |= 1<<func;
449 functions &= ~(1<<func);
451 signal_function_changed.emit(func, state);
455 void Train::sensor_state_changed(Sensor &sensor, Sensor::State state)
457 if(!current_speed_step || state!=Sensor::MAYBE_ACTIVE)
460 Block *block = sensor.get_block();
461 if(!block || block->get_train()!=this)
464 if(last_entry_block && &*last_entry_block!=block)
466 for(BlockIter i=last_entry_block.next(); (i && &*i!=block); i=i.next())
467 if(i->get_train()!=this || i->get_sensor_address())
471 if(dynamic_cast<TrackCircuit *>(&sensor))
473 if(last_entry_block && pure_speed && speed_quantizer)
475 float travel_distance = 0;
477 for(BlockIter i=last_entry_block; &*i!=block; i=i.next())
478 travel_distance += i->get_path_length(i.entry());
480 if(travel_distance>0)
482 float travel_time_secs = travel_time/Time::sec;
484 if(travel_time_secs>=2)
485 speed_quantizer->learn(current_speed_step, travel_distance/travel_time_secs, travel_time_secs);
489 last_entry_block = allocator.iter_for(*block);
490 travel_time = Time::zero;
491 if(!layout.get_driver().is_halted())
494 accurate_position = true;
498 if(!advancing && vehicles.front()->is_placed())
500 TrackIter track = last_entry_block.track_iter();
503 track = track.flip();
504 vehicles.back()->place(track, VehiclePlacement::BACK_AXLE);
507 vehicles.front()->place(track, VehiclePlacement::FRONT_AXLE);
510 else if(BeamGate *gate = dynamic_cast<BeamGate *>(&sensor))
512 if(!advancing && vehicles.front()->is_placed())
514 TrackIter track = allocator.iter_for(*block).track_iter();
515 for(; (track && &track->get_block()==block); track=track.next())
516 if(track.track()==gate->get_track())
519 track = track.reverse();
520 float offset = gate->get_offset_from_endpoint(track.entry());
522 vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
524 vehicles.front()->place(TrackOffsetIter(track, offset), VehiclePlacement::FRONT_BUFFER);
531 void Train::halt_event(bool h)
534 accurate_position = false;
537 float Train::get_reserved_distance_until(const Block *until_block) const
539 if(allocator.empty())
542 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
544 TrackOffsetIter track = veh.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE);
545 if(!track) // XXX Probably unnecessary
548 if(&track->get_block()==until_block)
551 // Account for the vehicle's offset on its current track
552 float result = track.offset();
554 track = track.reverse();
556 result = track->get_path_length()-result;
557 result -= veh.get_type().get_length()/2;
559 BlockIter block = track.block_iter();
561 // Count remaining distance in the vehicle's current block
562 for(track=track.next(); &track->get_block()==&*block; track=track.next())
563 result += track->get_path_length();
565 const BlockIter &last = allocator.last();
569 // Count any remaining blocks
570 for(block=block.next(); (&*block!=until_block && block->get_train()==this); block=block.next())
572 result += block->get_path_length(block.entry());
582 Train::Loader::Loader(Train &t):
583 DataFile::ObjectLoader<Train>(t),
587 add("blocks", &Loader::blocks);
588 add("name", &Loader::name);
589 add("quantized_speed", &Loader::quantized_speed);
590 add("router", &Loader::router);
591 add("timetable", &Loader::timetable);
592 add("vehicle", &Loader::vehicle);
595 void Train::Loader::finish()
597 if(!obj.allocator.empty())
599 TrackIter track = obj.allocator.first().track_iter();
600 float offset = 2*obj.layout.get_catalogue().get_scale();
601 obj.vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
605 void Train::Loader::blocks()
607 load_sub(obj.allocator);
610 void Train::Loader::name(const string &n)
615 void Train::Loader::quantized_speed()
617 if(obj.speed_quantizer)
618 load_sub(*obj.speed_quantizer);
621 void Train::Loader::router()
623 TrainRouter *rtr = new TrainRouter(obj);
627 void Train::Loader::timetable()
629 Timetable *ttbl = new Timetable(obj);
630 load_sub(*ttbl, obj.layout);
633 void Train::Loader::vehicle(ArticleNumber art_nr)
635 const VehicleType &vtype = obj.layout.get_catalogue().get<VehicleType>(art_nr);
636 Vehicle *veh = new Vehicle(obj.layout, vtype);
637 obj.vehicles.back()->attach_back(*veh);
638 obj.vehicles.push_back(veh);
639 veh->set_train(&obj);