3 This file is part of the MSP Märklin suite
4 Copyright © 2006-2010 Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
9 #include <msp/strings/formatter.h>
10 #include <msp/time/units.h>
11 #include <msp/time/utils.h>
12 #include "aicontrol.h"
13 #include "catalogue.h"
18 #include "simplephysics.h"
19 #include "timetable.h"
20 #include "tracktype.h"
29 Train::Train(Layout &l, const LocoType &t, unsigned a):
35 control(new AIControl(*this, new SimplePhysics)),
39 speed_changing(false),
49 accurate_position(false),
52 vehicles.push_back(new Vehicle(layout, loco_type));
54 layout.add_train(*this);
56 layout.get_driver().add_loco(address);
57 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
58 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
60 layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
61 layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
62 layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
64 layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
66 control->signal_control_changed.connect(signal_control_changed);
73 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
75 layout.remove_train(*this);
78 void Train::set_name(const string &n)
82 signal_name_changed.emit(name);
85 void Train::set_priority(int p)
90 Vehicle &Train::get_vehicle(unsigned i)
92 if(i>=vehicles.size())
93 throw InvalidParameterValue("Vehicle index out of range");
97 const Vehicle &Train::get_vehicle(unsigned i) const
99 if(i>=vehicles.size())
100 throw InvalidParameterValue("Vehicle index out of range");
104 void Train::set_control(const string &n, float v)
106 control->set_control(n, v);
109 void Train::set_active(bool a)
113 if(!a && control->get_speed())
114 throw InvalidState("Can't deactivate while moving");
119 stop_timeout = Time::TimeStamp();
124 stop_timeout = Time::now()+2*Time::sec;
125 set_status("Stopped");
129 void Train::set_function(unsigned func, bool state)
131 if(!loco_type.get_functions().count(func))
132 throw InvalidParameterValue("Invalid function");
134 layout.get_driver().set_loco_function(address, func, state);
136 layout.get_driver().set_loco_function(address+1, func-4, state);
139 bool Train::get_function(unsigned func) const
141 return (functions>>func)&1;
144 void Train::set_route(const Route *r)
146 if(!rsv_blocks.empty())
148 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
149 if(i->block->get_sensor_id())
151 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
158 end_of_route = false;
162 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
163 BlockRef next = last.next();
164 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
165 if(!route->get_tracks().count(ep.track))
168 route = Route::find(*ep.track, ep.track_ep, *next_route);
174 signal_route_changed.emit(route);
177 void Train::go_to(const Track &to)
179 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
180 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
182 signal_arrived.emit();
188 if(rsv_blocks.empty())
189 last = &cur_blocks.back();
192 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
193 if(i->block->get_sensor_id())
197 BlockRef next = last->next();
198 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
200 set_route(Route::find(*ep.track, ep.track_ep, to));
203 void Train::place(Block &block, unsigned entry)
205 if(control->get_speed())
206 throw InvalidState("Must be stopped before placing");
208 release_blocks(rsv_blocks);
209 release_blocks(cur_blocks);
212 accurate_position = false;
214 if(!block.reserve(this))
216 set_status("Unplaced");
220 cur_blocks.push_back(BlockRef(&block, entry));
223 unsigned exit = block.traverse(entry);
224 const Block::Endpoint &bep = block.get_endpoints()[exit];
225 Track *track = bep.track->get_link(bep.track_ep);
226 unsigned ep = track->get_endpoint_by_link(*bep.track);
227 vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
231 const Block::Endpoint &bep = block.get_endpoints()[entry];
232 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
236 bool Train::free_block(Block &block)
239 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
245 release_blocks(rsv_blocks, i, rsv_blocks.end());
248 else if(i->block->get_sensor_id())
255 int Train::get_entry_to_block(Block &block) const
257 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
260 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
266 float Train::get_reserved_distance() const
268 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
269 const VehicleType &vtype = veh.get_type();
271 Track *track = veh.get_track();
274 unsigned entry = veh.get_entry();
276 float result = -vtype.get_length()/2;
279 entry = track->traverse(entry);
280 result += veh.get_offset();
283 result -= veh.get_offset();
286 list<BlockRef>::const_iterator block = cur_blocks.begin();
289 if(!first || !reverse)
290 result += track->get_type().get_path_length(track->get_active_path());
293 if(track->get_type().get_endpoints().size()<2)
296 unsigned exit = track->traverse(entry);
297 Track *next = track->get_link(exit);
299 while(!block->block->get_tracks().count(next))
302 if(block==cur_blocks.end())
303 block = rsv_blocks.begin();
304 if(block==rsv_blocks.end())
308 entry = next->get_endpoint_by_link(*track);
313 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
315 if(!active && stop_timeout && t>=stop_timeout)
317 release_blocks(rsv_blocks);
318 end_of_route = false;
319 stop_timeout = Time::TimeStamp();
322 Driver &driver = layout.get_driver();
327 float speed = control->get_speed();
328 unsigned speed_notch = find_speed(abs(speed));
330 if(control->get_reverse()!=reverse)
332 reverse = control->get_reverse();
333 driver.set_loco_reverse(address, reverse);
335 release_blocks(rsv_blocks);
336 reverse_blocks(cur_blocks);
340 if(speed_notch!=current_speed && !speed_changing && !driver.is_halted() && driver.get_power())
342 speed_changing = true;
343 driver.set_loco_speed(address, speed_notch);
348 set_status(format("Traveling %d kmh", get_travel_speed()));
350 set_status("Waiting");
358 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
359 Track *track = vehicle.get_track();
362 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
363 ok = i->block->get_tracks().count(track);
365 float d = get_real_speed(current_speed)*(dt/Time::sec);
367 vehicle.advance(reverse ? -d : d);
368 else if(accurate_position)
371 if(overshoot_dist>40*layout.get_catalogue().get_scale())
373 layout.emergency(name+" has not arrived at sensor");
374 accurate_position = false;
378 else if(end_of_route)
381 if(!cur_blocks.empty() && !cur_blocks.front().block->get_sensor_id())
383 Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
385 list<BlockRef>::iterator i = cur_blocks.begin();
386 const Block::Endpoint &bep = i->block->get_endpoints()[i->entry];
388 Track *track = bep.track;
389 unsigned entry = bep.track_ep;
392 float dist = veh.get_offset()-veh.get_type().get_length()/2;
395 if(track==veh.get_track())
401 if(i!=cur_blocks.begin())
403 float path_len = track->get_type().get_path_length(track->get_active_path());
407 unsigned exit = track->traverse(entry);
408 Track *next = track->get_link(exit);
409 entry = next->get_endpoint_by_link(*track);
412 if(!i->block->get_tracks().count(track))
415 if(i==cur_blocks.end())
420 if(found && i!=cur_blocks.begin() && dist>10*layout.get_catalogue().get_scale())
422 cur_blocks.front().block->reserve(0);
423 cur_blocks.erase(cur_blocks.begin());
428 void Train::save(list<DataFile::Statement> &st) const
430 st.push_back((DataFile::Statement("name"), name));
432 st.push_back((DataFile::Statement("priority"), priority));
434 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
435 if(i!=vehicles.begin())
436 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
438 for(unsigned i=0; i<=14; ++i)
439 if(real_speed[i].weight)
440 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
442 if(!cur_blocks.empty())
444 list<BlockRef> blocks = cur_blocks;
446 reverse_blocks(blocks);
448 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
449 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
451 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
452 st.push_back((DataFile::Statement("block"), i->block->get_id()));
457 if(!route->is_temporary())
458 st.push_back((DataFile::Statement("route"), route->get_name()));
459 else if(next_route && !next_route->is_temporary())
460 st.push_back((DataFile::Statement("route"), next_route->get_name()));
465 DataFile::Statement ss("timetable");
466 timetable->save(ss.sub);
471 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
475 current_speed = speed;
476 speed_changing = false;
481 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
483 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
488 functions |= 1<<func;
490 functions &= ~(1<<func);
492 signal_function_changed.emit(func, state);
496 void Train::sensor_event(unsigned addr, bool state)
500 // Find the first sensor block from our reserved blocks that isn't this sensor
501 list<BlockRef>::iterator i;
503 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
504 if(i->block->get_sensor_id())
506 if(i->block->get_sensor_id()!=addr)
519 if(result==1 && i!=rsv_blocks.begin())
521 // Compute speed and update related state
522 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
528 RealSpeed &rs = real_speed[current_speed];
529 rs.add(travel_dist/travel_time_secs, travel_time_secs);
531 set_status(format("Traveling %d kmh", get_travel_speed()));
536 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
538 j->block->traverse(j->entry, &block_len);
539 travel_dist += block_len;
541 if(j->block->get_sensor_id()==addr)
543 const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
546 Track *track = bep.track->get_link(bep.track_ep);
547 unsigned ep = track->get_endpoint_by_link(*bep.track);
548 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
551 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
554 last_entry_time = Time::now();
556 accurate_position = true;
559 // Check if we've reached the next route
562 const set<const Track *> &rtracks = next_route->get_tracks();
563 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
564 if(rtracks.count(j->block->get_endpoints()[j->entry].track))
569 signal_route_changed.emit(route);
574 // Move blocks up to the next sensor to our current blocks
575 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
577 // Try to get more blocks if we're moving
580 unsigned nsens = reserve_more();
581 if(!nsens && end_of_route)
582 signal_arrived.emit();
586 layout.emergency("Sensor for "+name+" triggered out of order");
590 // Find the first sensor in our current blocks that's still active
591 list<BlockRef>::iterator end = cur_blocks.begin();
592 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
593 if(i->block->get_sensor_id())
595 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
604 if(end!=cur_blocks.begin())
605 // Free blocks up to the last inactive sensor
606 release_blocks(cur_blocks, cur_blocks.begin(), end);
610 void Train::turnout_event(unsigned addr, bool)
614 unsigned pending_addr = pending_block->get_turnout_id();
615 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
616 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
621 void Train::halt_event(bool h)
624 accurate_position = false;
627 void Train::block_reserved(const Block &block, const Train *train)
629 if(&block==pending_block && !train)
633 unsigned Train::reserve_more()
639 if(!rsv_blocks.empty())
640 last = &rsv_blocks.back();
641 else if(!cur_blocks.empty())
642 last = &cur_blocks.back();
648 // See how many sensor blocks we already have
650 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
651 if(i->block->get_sensor_id())
657 const Route *cur_route = 0;
660 const set<Track *> &tracks = last->block->get_tracks();
661 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
663 if(route->get_tracks().count(*i))
665 else if(next_route && next_route->get_tracks().count(*i))
666 cur_route = next_route;
670 bool got_more = false;
671 BlockRef *good = last;
672 unsigned good_sens = nsens;
675 if(last->block->get_endpoints().size()<2)
682 // Traverse to the next block
683 unsigned exit = last->block->traverse(last->entry);
684 Block *link = last->block->get_link(exit);
688 int entry = link->get_endpoint_by_link(*last->block);
690 throw LogicError("Block links are inconsistent!");
692 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
696 if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
697 cur_route = next_route;
698 else if(!cur_route->get_tracks().count(entry_ep.track))
700 // Keep the blocks if we arrived at the end of the route
707 else if(route && route->get_tracks().count(entry_ep.track))
710 bool reserved = link->reserve(this);
713 // Ask a lesser priority train to free the block for us
714 if(link->get_train()->get_priority()<priority)
715 if(link->get_train()->free_block(*link))
716 reserved = link->reserve(this);
720 // If we found another train and it's not headed straight for us, we can keep the blocks we got
721 int other_entry = link->get_train()->get_entry_to_block(*link);
723 throw LogicError("Block reservation inconsistency");
724 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
729 pending_block = link;
734 if(link->get_turnout_id())
736 const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
738 // Keep the blocks reserved so far, as either us or the other train can diverge
742 // Figure out what path we'd like to take on the turnout
745 path = cur_route->get_turnout(link->get_turnout_id());
747 path = entry_ep.track->get_active_path();
748 if(!((track_ep.paths>>path)&1))
750 for(unsigned i=0; track_ep.paths>>i; ++i)
751 if((track_ep.paths>>i)&1)
755 if(path!=static_cast<int>(entry_ep.track->get_active_path()))
757 // The turnout is set to wrong path - switch and wait for it
759 pending_block = link;
760 entry_ep.track->set_active_path(path);
765 rsv_blocks.push_back(BlockRef(link, entry));
766 last = &rsv_blocks.back();
767 if(last->block->get_sensor_id())
774 // Unreserve blocks that were not good
775 while(!rsv_blocks.empty() && last!=good)
777 last->block->reserve(0);
778 rsv_blocks.erase(--rsv_blocks.end());
779 if(!rsv_blocks.empty())
780 last = &rsv_blocks.back();
783 // Make any sensorless blocks at the beginning immediately current
784 list<BlockRef>::iterator i;
785 for(i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !i->block->get_sensor_id()); ++i) ;
786 if(i!=rsv_blocks.begin())
787 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
792 float Train::get_real_speed(unsigned i) const
794 if(real_speed[i].weight)
795 return real_speed[i].speed;
799 for(low=i; low>0; --low)
800 if(real_speed[low].weight)
802 for(high=i; high<14; ++high)
803 if(real_speed[high].weight)
806 if(real_speed[high].weight)
808 if(real_speed[low].weight)
810 float f = float(i-low)/(high-low);
811 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
814 return real_speed[high].speed*float(i)/high;
816 else if(real_speed[low].weight)
817 return real_speed[low].speed*float(i)/low;
822 unsigned Train::find_speed(float real) const
824 if(real<=real_speed[0].speed)
829 for(unsigned i=0; (!high && i<=14); ++i)
830 if(real_speed[i].weight)
832 if(real_speed[i].speed<real)
846 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
849 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
850 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
853 float Train::get_travel_speed() const
855 float speed = get_real_speed(current_speed);
856 float scale = layout.get_catalogue().get_scale();
857 return static_cast<int>(round(speed/scale*3.6/5))*5;
860 void Train::set_status(const string &s)
863 signal_status_changed.emit(s);
866 void Train::release_blocks(list<BlockRef> &blocks)
868 release_blocks(blocks, blocks.begin(), blocks.end());
871 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
875 Block *block = begin->block;
876 blocks.erase(begin++);
881 void Train::reverse_blocks(list<BlockRef> &blocks) const
884 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
885 i->entry = i->block->traverse(i->entry);
889 Train::BlockRef::BlockRef(Block *b, unsigned e):
894 Train::BlockRef Train::BlockRef::next() const
896 Block *blk = block->get_endpoints()[block->traverse(entry)].link;
898 throw InvalidState("At end of line");
900 int ep = blk->get_endpoint_by_link(*block);
902 throw LogicError("Block links are inconsistent");
904 return BlockRef(blk, ep);
908 Train::RealSpeed::RealSpeed():
913 void Train::RealSpeed::add(float s, float w)
915 speed = (speed*weight+s*w)/(weight+w);
916 weight = min(weight+w, 300.0f);
920 Train::Loader::Loader(Train &t):
921 DataFile::BasicLoader<Train>(t),
924 add("block", &Loader::block);
925 add("block_hint", &Loader::block_hint);
926 add("name", &Loader::name);
927 add("priority", &Train::priority);
928 add("real_speed", &Loader::real_speed);
929 add("route", &Loader::route);
930 add("timetable", &Loader::timetable);
931 add("vehicle", &Loader::vehicle);
934 void Train::Loader::block(unsigned id)
936 Block &blk = obj.layout.get_block(id);
939 entry = blk.get_endpoint_by_link(*prev_block);
944 obj.cur_blocks.push_back(BlockRef(&blk, entry));
945 obj.set_status("Stopped");
946 const Block::Endpoint &bep = blk.get_endpoints()[entry];
947 obj.vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
949 if(blk.get_sensor_id())
950 obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
955 void Train::Loader::block_hint(unsigned id)
957 prev_block = &obj.layout.get_block(id);
960 void Train::Loader::name(const string &n)
965 void Train::Loader::real_speed(unsigned i, float speed, float weight)
967 obj.real_speed[i].speed = speed;
968 obj.real_speed[i].weight = weight;
971 void Train::Loader::route(const string &n)
973 obj.set_route(&obj.layout.get_route(n));
976 void Train::Loader::timetable()
979 throw InvalidState("A timetable has already been loaded");
981 obj.timetable = new Timetable(obj);
982 load_sub(*obj.timetable);
985 void Train::Loader::vehicle(unsigned n)
987 const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(n);
988 Vehicle *veh = new Vehicle(obj.layout, vtype);
989 obj.vehicles.back()->attach_back(*veh);
990 obj.vehicles.push_back(veh);
993 } // namespace Marklin