3 #include <msp/core/maputils.h>
4 #include <msp/strings/format.h>
5 #include <msp/time/units.h>
6 #include <msp/time/utils.h>
12 #include "simplecontroller.h"
13 #include "speedquantizer.h"
14 #include "timetable.h"
15 #include "trackiter.h"
16 #include "tracktype.h"
18 #include "trainrouter.h"
20 #include "vehicletype.h"
32 SetFlag(bool &f): flag(f) { flag = true; }
33 ~SetFlag() { flag = false; }
41 Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
47 cur_blocks_end(blocks.end()),
51 controller(new SimpleController),
53 current_speed_step(0),
54 speed_changing(false),
60 accurate_position(false),
63 if(!loco_type.is_locomotive())
64 throw invalid_argument("Train::Train");
66 unsigned speed_steps = layout.get_driver().get_protocol_speed_steps(protocol);
68 speed_quantizer = new SpeedQuantizer(speed_steps);
70 vehicles.push_back(new Vehicle(layout, loco_type));
72 layout.add_train(*this);
74 layout.get_driver().add_loco(address, protocol, loco_type);
75 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
76 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
78 layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
79 layout.signal_block_state_changed.connect(sigc::mem_fun(this, &Train::block_state_changed));
81 layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
83 const set<Track *> &tracks = layout.get_tracks();
84 for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
85 if((*i)->get_turnout_id())
86 (*i)->signal_path_changed.connect(sigc::hide(sigc::bind(sigc::mem_fun(this, &Train::turnout_path_changed), sigc::ref(**i))));
88 controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
94 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
96 layout.remove_train(*this);
99 void Train::set_name(const string &n)
103 signal_name_changed.emit(name);
106 void Train::add_vehicle(const VehicleType &vt)
108 Vehicle *veh = new Vehicle(layout, vt);
109 vehicles.back()->attach_back(*veh);
110 vehicles.push_back(veh);
113 void Train::remove_vehicle(unsigned i)
115 if(i>=vehicles.size())
116 throw out_of_range("Train::remove_vehicle");
118 throw logic_error("can't remove locomotive");
120 vehicles.erase(vehicles.begin()+i);
121 if(i<vehicles.size())
122 vehicles[i-1]->attach_back(*vehicles[i]);
125 unsigned Train::get_n_vehicles() const
127 return vehicles.size();
130 Vehicle &Train::get_vehicle(unsigned i)
132 if(i>=vehicles.size())
133 throw out_of_range("Train::get_vehicle");
137 const Vehicle &Train::get_vehicle(unsigned i) const
139 if(i>=vehicles.size())
140 throw out_of_range("Train::get_vehicle");
144 void Train::set_control(const string &n, float v)
146 controller->set_control(n, v);
149 void Train::set_active(bool a)
153 if(!a && controller->get_speed())
154 throw logic_error("moving");
159 stop_timeout = Time::TimeStamp();
163 stop_timeout = Time::now()+2*Time::sec;
166 void Train::set_function(unsigned func, bool state)
168 if(!loco_type.get_functions().count(func))
169 throw invalid_argument("Train::set_function");
170 layout.get_driver().set_loco_function(address, func, state);
173 float Train::get_control(const string &ctrl) const
175 return controller->get_control(ctrl).value;
178 float Train::get_speed() const
180 return controller->get_speed();
183 float Train::get_quantized_speed() const
186 return speed_quantizer->quantize_speed(controller->get_speed());
188 return controller->get_speed();
191 bool Train::get_function(unsigned func) const
193 return (functions>>func)&1;
196 void Train::add_ai(TrainAI &ai)
199 ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
202 void Train::remove_ai(TrainAI &ai)
204 list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
209 void Train::ai_message(const TrainAI::Message &msg)
211 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
215 void Train::place(Block &block, unsigned entry)
217 if(controller->get_speed())
218 throw logic_error("moving");
223 accurate_position = false;
225 blocks.push_back(BlockIter(&block, entry));
226 if(!block.reserve(this))
234 TrackIter track = BlockIter(&block, entry).reverse().track_iter();
235 vehicles.front()->place(*track, track.entry(), 0, Vehicle::FRONT_BUFFER);
239 const Block::Endpoint &bep = block.get_endpoint(entry);
240 vehicles.back()->place(*bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
244 void Train::unplace()
246 if(controller->get_speed())
247 throw logic_error("moving");
252 accurate_position = false;
254 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
258 void Train::stop_at(Block *block)
260 stop_at_block = block;
263 bool Train::free_block(Block &block)
265 if(get_reserved_distance_until(&block, false)<controller->get_braking_distance()*1.3)
269 for(BlockList::iterator i=cur_blocks_end; i!=blocks.end(); ++i)
271 if(i->block()==&block)
275 release_blocks(i, blocks.end());
278 else if((*i)->get_sensor_id())
285 void Train::free_noncritical_blocks()
290 if(controller->get_speed()==0)
292 release_blocks(cur_blocks_end, blocks.end());
296 float margin = 10*layout.get_catalogue().get_scale();
297 float min_dist = controller->get_braking_distance()*1.3+margin;
299 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
301 TrackIter track(veh.get_track(), veh.get_entry());
302 BlockList::iterator block = blocks.begin();
304 while(block!=blocks.end() && !(*block)->has_track(*track))
307 if(block==cur_blocks_end)
311 float dist = veh.get_offset();
315 dist = track->get_type().get_path_length(track->get_active_path())-dist;
316 dist -= veh.get_type().get_length()/2;
321 track = track.next();
323 if(!(*block)->has_track(*track))
326 if(block==cur_blocks_end)
328 if(block==blocks.end())
331 if(dist>min_dist && nsens>0)
333 release_blocks(block, blocks.end());
337 if(in_rsv && (*block)->get_sensor_id())
341 dist += track->get_type().get_path_length(track->get_active_path());
345 const BlockIter &Train::get_head_block() const
348 throw logic_error("no blocks");
349 return blocks.back();
352 const BlockIter &Train::get_tail_block() const
355 throw logic_error("no blocks");
356 return blocks.front();
359 int Train::get_entry_to_block(const Block &block) const
361 for(BlockList::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
362 if(i->block()==&block)
367 float Train::get_reserved_distance() const
373 TrackIter next = blocks.back().next().track_iter();
374 if(next && next->get_type().is_turnout())
375 margin = 15*layout.get_catalogue().get_scale();
377 return max(get_reserved_distance_until(pending_block, false)-margin, 0.0f);
380 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
382 if(!active && stop_timeout && t>=stop_timeout)
384 release_blocks(cur_blocks_end, blocks.end());
385 stop_timeout = Time::TimeStamp();
388 Driver &driver = layout.get_driver();
390 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
392 controller->tick(dt);
393 float speed = controller->get_speed();
394 bool moving = speed>0;
396 if(controller->get_reverse()!=reverse)
398 reverse = controller->get_reverse();
400 if(loco_type.get_swap_direction())
402 driver.set_loco_reverse(address, r);
404 release_blocks(cur_blocks_end, blocks.end());
405 reverse_blocks(blocks);
412 unsigned speed_step = speed_quantizer->find_speed_step(speed);
413 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
415 speed_changing = true;
416 driver.set_loco_speed(address, speed_step);
421 speed = speed_quantizer->get_speed(current_speed_step);
429 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
430 Track *track = vehicle.get_track();
433 for(BlockList::const_iterator i=blocks.begin(); (!ok && i!=cur_blocks_end); ++i)
434 ok = (*i)->has_track(*track);
436 float d = speed*(dt/Time::sec);
439 SetFlag setf(advancing);
440 vehicle.advance(reverse ? -d : d);
442 else if(accurate_position)
445 if(overshoot_dist>40*layout.get_catalogue().get_scale())
447 layout.emergency(name+" has not arrived at sensor");
448 accurate_position = false;
453 if(!blocks.empty() && !blocks.front()->get_sensor_id())
455 float dist = get_reserved_distance_until(&*blocks.front(), true);
457 if(dist>10*layout.get_catalogue().get_scale())
459 Block &block = *blocks.front();
466 void Train::save(list<DataFile::Statement> &st) const
468 st.push_back((DataFile::Statement("name"), name));
470 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
471 if(i!=vehicles.begin())
472 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
476 DataFile::Statement ss("quantized_speed");
477 speed_quantizer->save(ss.sub);
481 if(!blocks.empty() && cur_blocks_end!=blocks.begin())
483 BlockList blks(blocks.begin(), BlockList::const_iterator(cur_blocks_end));
485 reverse_blocks(blks);
487 BlockIter prev = blks.front().flip();
488 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
490 for(BlockList::const_iterator i=blks.begin(); i!=blks.end(); ++i)
491 st.push_back((DataFile::Statement("block"), (*i)->get_id()));
494 // XXX Need more generic way of saving AI state
495 for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
497 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
499 DataFile::Statement ss("router");
500 router->save(ss.sub);
503 else if(Timetable *timetable = dynamic_cast<Timetable *>(*i))
505 DataFile::Statement ss("timetable");
506 timetable->save(ss.sub);
512 void Train::control_changed(const Controller::Control &ctrl)
514 signal_control_changed.emit(ctrl.name, ctrl.value);
517 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
521 current_speed_step = speed;
523 if(loco_type.get_swap_direction())
526 layout.get_driver().set_loco_reverse(address, r);
527 speed_changing = false;
532 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
537 functions |= 1<<func;
539 functions &= ~(1<<func);
541 signal_function_changed.emit(func, state);
545 void Train::block_state_changed(Block &block, Block::State state)
547 if(state==Block::MAYBE_ACTIVE)
549 // Find the first sensor block from our reserved blocks that isn't this sensor
550 BlockList::iterator end;
552 for(end=cur_blocks_end; end!=blocks.end(); ++end)
553 if((*end)->get_sensor_id())
570 // Compute speed and update related state
571 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
573 if(pure_speed && speed_quantizer && current_speed_step>0 && travel_time_secs>=2)
574 speed_quantizer->learn(current_speed_step, travel_dist/travel_time_secs, travel_time_secs);
577 for(BlockList::iterator j=cur_blocks_end; j!=end; ++j)
579 travel_dist += (*j)->get_path_length(j->entry());
581 if(&**j==&block && !advancing)
583 TrackIter track = j->track_iter();
586 track = track.flip();
587 vehicles.back()->place(*track, track.entry(), 0, Vehicle::BACK_AXLE);
590 vehicles.front()->place(*track, track.entry(), 0, Vehicle::FRONT_AXLE);
593 last_entry_time = Time::now();
595 accurate_position = true;
598 // Move blocks up to the next sensor to our current blocks
599 for(BlockList::iterator j=cur_blocks_end; j!=end; ++j)
600 signal_advanced.emit(**j);
601 cur_blocks_end = end;
603 // Try to get more blocks if we're moving
608 layout.emergency("Sensor for "+name+" triggered out of order");
610 else if(state==Block::INACTIVE)
612 const Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
614 // Find the first sensor in our current blocks that's still active
615 BlockList::iterator end = blocks.begin();
616 for(BlockList::iterator i=blocks.begin(); i!=cur_blocks_end; ++i)
618 if((*i)->has_track(*veh.get_track()))
620 if((*i)->get_sensor_id())
622 if(layout.get_driver().get_sensor((*i)->get_sensor_id()))
632 if(end!=blocks.begin() && end!=cur_blocks_end)
633 // Free blocks up to the last inactive sensor
634 release_blocks(blocks.begin(), end);
638 void Train::turnout_path_changed(Track &track)
640 for(list<BlockIter>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
641 if((*i)->get_turnout_id()==track.get_turnout_id() && !reserving && &**i==pending_block)
645 void Train::halt_event(bool h)
648 accurate_position = false;
651 void Train::block_reserved(const Block &block, const Train *train)
653 if(&block==pending_block && !train && !reserving)
657 void Train::reserve_more()
659 if(!active || blocks.empty())
662 BlockIter start = blocks.back();
663 if(&*start==stop_at_block)
665 else if(&*start==pending_block)
667 TrackIter track = start.track_iter();
668 if(!track.endpoint().has_path(track->get_active_path()))
675 // See how many sensor blocks and how much track we already have
678 for(BlockList::const_iterator i=cur_blocks_end; i!=blocks.end(); ++i)
680 if((*i)->get_sensor_id())
683 dist += (*i)->get_path_length(i->entry());
686 float approach_margin = 50*layout.get_catalogue().get_scale();
687 float min_dist = controller->get_braking_distance()*1.3+approach_margin*2;
689 BlockIter block = start;
691 SetFlag setf(reserving);
695 BlockIter last = block;
696 block = block.next();
697 if(!block || block->get_endpoints().size()<2)
698 // The track ends here
701 if(block->get_turnout_id() && !last->get_turnout_id())
703 /* We are arriving at a turnout. See if we have enough blocks and
704 distance reserved. */
705 if(nsens>=3 && dist>=min_dist)
709 blocks.push_back(block);
710 if(!block->reserve(this))
713 pending_block = &*block;
717 if(cur_blocks_end==blocks.end())
720 TrackIter track = block.track_iter();
721 if(track->is_path_changing())
723 pending_block = &*block;
728 const TrackType::Endpoint &entry_ep = track.endpoint();
729 unsigned path = track->get_active_path();
730 if(!entry_ep.has_path(path))
732 const TrackType::Endpoint &exit_ep = track.reverse().endpoint();
733 if(entry_ep.has_common_paths(exit_ep))
735 unsigned mask = entry_ep.paths&exit_ep.paths;
736 for(path=0; mask>1; ++path, mask>>=1) ;
738 track->set_active_path(path);
739 if(track->is_path_changing())
741 pending_block = &*block;
746 // XXX Do something here
751 if(&*block==stop_at_block)
754 if(block->get_sensor_id())
757 dist += block->get_path_length(block.entry());
760 // Make any sensorless blocks at the beginning immediately current
761 while(cur_blocks_end!=blocks.end() && !(*cur_blocks_end)->get_sensor_id())
765 float Train::get_reserved_distance_until(const Block *until_block, bool back) const
770 Vehicle &veh = *(reverse!=back ? vehicles.back() : vehicles.front());
771 const VehicleType &vtype = veh.get_type();
773 TrackIter track(veh.get_track(), veh.get_entry());
774 if(!track) // XXX Probably unnecessary
777 BlockList::const_iterator block = blocks.begin();
778 while(block!=blocks.end() && !(*block)->has_track(*track))
780 if(block==blocks.end() || &**block==until_block)
783 float result = veh.get_offset();
785 track = track.reverse();
787 result = track->get_type().get_path_length(track->get_active_path())-result;
788 result -= vtype.get_length()/2;
792 track = track.next();
796 if(!(*block)->has_track(*track))
800 if(block==blocks.begin())
807 if(block==blocks.end())
811 if(&**block==until_block)
815 result += track->get_type().get_path_length(track->get_active_path());
821 void Train::release_blocks()
823 release_blocks(blocks.begin(), blocks.end());
826 void Train::release_blocks(BlockList::iterator begin, BlockList::iterator end)
830 if(begin==cur_blocks_end)
831 cur_blocks_end = end;
833 Block &block = **begin;
834 blocks.erase(begin++);
839 void Train::reverse_blocks(BlockList &blks) const
842 for(BlockList::iterator i=blks.begin(); i!=blks.end(); ++i)
847 Train::Loader::Loader(Train &t):
848 DataFile::ObjectLoader<Train>(t),
852 add("block", &Loader::block);
853 add("block_hint", &Loader::block_hint);
854 add("name", &Loader::name);
855 add("quantized_speed", &Loader::quantized_speed);
856 add("router", &Loader::router);
857 add("timetable", &Loader::timetable);
858 add("vehicle", &Loader::vehicle);
861 void Train::Loader::finish()
863 if(!obj.blocks.empty())
865 TrackIter track = obj.blocks.front().track_iter();
866 float offset = 2*obj.layout.get_catalogue().get_scale();
867 obj.vehicles.back()->place(*track, track.entry(), offset, Vehicle::BACK_BUFFER);
871 void Train::Loader::block(unsigned id)
879 blk = &obj.layout.get_block(id);
881 catch(const key_error &)
883 blocks_valid = false;
889 entry = blk->get_endpoint_by_link(*prev_block);
893 obj.blocks.push_back(BlockIter(blk, entry));
896 if(blk->get_sensor_id())
897 obj.layout.get_driver().set_sensor(blk->get_sensor_id(), true);
902 void Train::Loader::block_hint(unsigned id)
906 prev_block = &obj.layout.get_block(id);
908 catch(const key_error &)
910 blocks_valid = false;
914 void Train::Loader::name(const string &n)
919 void Train::Loader::quantized_speed()
921 if(obj.speed_quantizer)
922 load_sub(*obj.speed_quantizer);
925 void Train::Loader::router()
927 TrainRouter *rtr = new TrainRouter(obj);
931 void Train::Loader::timetable()
933 Timetable *ttbl = new Timetable(obj);
937 void Train::Loader::vehicle(ArticleNumber art_nr)
939 const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(art_nr);
940 Vehicle *veh = new Vehicle(obj.layout, vtype);
941 obj.vehicles.back()->attach_back(*veh);
942 obj.vehicles.push_back(veh);