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):
34 control(new AIControl(*this, new SimplePhysics)),
38 speed_changing(false),
48 accurate_position(false),
51 vehicles.push_back(new Vehicle(layout, loco_type));
53 layout.add_train(*this);
55 layout.get_driver().add_loco(address);
56 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
57 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
59 layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
60 layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
61 layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
63 layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
65 control->signal_control_changed.connect(signal_control_changed);
72 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
74 layout.remove_train(*this);
77 void Train::set_name(const string &n)
81 signal_name_changed.emit(name);
84 Vehicle &Train::get_vehicle(unsigned i)
86 if(i>=vehicles.size())
87 throw InvalidParameterValue("Vehicle index out of range");
91 const Vehicle &Train::get_vehicle(unsigned i) const
93 if(i>=vehicles.size())
94 throw InvalidParameterValue("Vehicle index out of range");
98 void Train::set_control(const string &n, float v)
100 control->set_control(n, v);
103 void Train::set_active(bool a)
107 if(!a && control->get_speed())
108 throw InvalidState("Can't deactivate while moving");
113 stop_timeout = Time::TimeStamp();
118 stop_timeout = Time::now()+2*Time::sec;
119 set_status("Stopped");
123 void Train::set_function(unsigned func, bool state)
125 if(!loco_type.get_functions().count(func))
126 throw InvalidParameterValue("Invalid function");
128 layout.get_driver().set_loco_function(address, func, state);
130 layout.get_driver().set_loco_function(address+1, func-4, state);
133 bool Train::get_function(unsigned func) const
135 return (functions>>func)&1;
138 void Train::set_route(const Route *r)
140 if(!rsv_blocks.empty())
142 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
143 if(i->block->get_sensor_id())
145 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
152 end_of_route = false;
156 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
157 BlockRef next = last.next();
158 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
159 if(!route->get_tracks().count(ep.track))
162 route = Route::find(*ep.track, ep.track_ep, *next_route);
169 signal_route_changed.emit(route);
172 void Train::go_to(const Track &to)
174 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
175 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
177 signal_arrived.emit();
183 if(rsv_blocks.empty())
184 last = &cur_blocks.back();
187 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
188 if(i->block->get_sensor_id())
192 BlockRef next = last->next();
193 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
195 set_route(Route::find(*ep.track, ep.track_ep, to));
198 void Train::place(Block &block, unsigned entry)
200 if(control->get_speed())
201 throw InvalidState("Must be stopped before placing");
203 release_blocks(rsv_blocks);
204 release_blocks(cur_blocks);
207 accurate_position = false;
209 if(!block.reserve(this))
211 set_status("Unplaced");
215 cur_blocks.push_back(BlockRef(&block, entry));
218 unsigned exit = block.traverse(entry);
219 const Block::Endpoint &bep = block.get_endpoints()[exit];
220 Track *track = bep.track->get_link(bep.track_ep);
221 unsigned ep = track->get_endpoint_by_link(*bep.track);
222 vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
226 const Block::Endpoint &bep = block.get_endpoints()[entry];
227 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
231 bool Train::free_block(Block &block)
234 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
240 release_blocks(rsv_blocks, i, rsv_blocks.end());
243 else if(i->block->get_sensor_id())
250 int Train::get_entry_to_block(Block &block) const
252 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
255 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
261 float Train::get_reserved_distance() const
263 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
264 const VehicleType &vtype = veh.get_type();
266 Track *track = veh.get_track();
269 unsigned entry = veh.get_entry();
271 float result = -vtype.get_length()/2;
274 entry = track->traverse(entry);
275 result += veh.get_offset();
278 result -= veh.get_offset();
281 list<BlockRef>::const_iterator block = cur_blocks.begin();
284 if(!first || !reverse)
285 result += track->get_type().get_path_length(track->get_active_path());
288 if(track->get_type().get_endpoints().size()<2)
291 unsigned exit = track->traverse(entry);
292 Track *next = track->get_link(exit);
294 while(!block->block->get_tracks().count(next))
297 if(block==cur_blocks.end())
298 block = rsv_blocks.begin();
299 if(block==rsv_blocks.end())
303 entry = next->get_endpoint_by_link(*track);
308 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
310 if(!active && stop_timeout && t>=stop_timeout)
312 release_blocks(rsv_blocks);
313 end_of_route = false;
314 stop_timeout = Time::TimeStamp();
317 Driver &driver = layout.get_driver();
322 float speed = control->get_speed();
323 unsigned speed_notch = find_speed(abs(speed));
325 if(speed && (speed<0)!=reverse)
327 driver.set_loco_reverse(address, speed<0);
330 release_blocks(rsv_blocks);
331 reverse_blocks(cur_blocks);
335 if(speed_notch!=current_speed && !speed_changing && !driver.is_halted() && driver.get_power())
337 speed_changing = true;
338 driver.set_loco_speed(address, speed_notch);
343 set_status(format("Traveling %d kmh", get_travel_speed()));
345 set_status("Waiting");
353 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
354 Track *track = vehicle.get_track();
357 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
358 ok = i->block->get_tracks().count(track);
360 float d = get_real_speed(current_speed)*(dt/Time::sec);
362 vehicle.advance(reverse ? -d : d);
363 else if(accurate_position)
366 if(overshoot_dist>40*layout.get_catalogue().get_scale())
368 layout.emergency(name+" has not arrived at sensor");
369 accurate_position = false;
373 else if(end_of_route)
376 if(!cur_blocks.empty() && !cur_blocks.front().block->get_sensor_id())
378 Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
380 list<BlockRef>::iterator i = cur_blocks.begin();
381 const Block::Endpoint &bep = i->block->get_endpoints()[i->entry];
383 Track *track = bep.track;
384 unsigned entry = bep.track_ep;
387 float dist = veh.get_offset()-veh.get_type().get_length()/2;
390 if(track==veh.get_track())
396 if(i!=cur_blocks.begin())
398 float path_len = track->get_type().get_path_length(track->get_active_path());
402 unsigned exit = track->traverse(entry);
403 Track *next = track->get_link(exit);
404 entry = next->get_endpoint_by_link(*track);
407 if(!i->block->get_tracks().count(track))
410 if(i==cur_blocks.end())
415 if(found && i!=cur_blocks.begin() && dist>10*layout.get_catalogue().get_scale())
417 cur_blocks.front().block->reserve(0);
418 cur_blocks.erase(cur_blocks.begin());
423 void Train::save(list<DataFile::Statement> &st) const
425 st.push_back((DataFile::Statement("name"), name));
427 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
428 if(i!=vehicles.begin())
429 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
431 for(unsigned i=0; i<=14; ++i)
432 if(real_speed[i].weight)
433 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
435 if(!cur_blocks.empty())
437 list<BlockRef> blocks = cur_blocks;
439 reverse_blocks(blocks);
441 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
442 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
444 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
445 st.push_back((DataFile::Statement("block"), i->block->get_id()));
450 if(!route->is_temporary())
451 st.push_back((DataFile::Statement("route"), route->get_name()));
452 else if(next_route && !next_route->is_temporary())
453 st.push_back((DataFile::Statement("route"), next_route->get_name()));
458 DataFile::Statement ss("timetable");
459 timetable->save(ss.sub);
464 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
468 current_speed = speed;
469 speed_changing = false;
474 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
476 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
481 functions |= 1<<func;
483 functions &= ~(1<<func);
485 signal_function_changed.emit(func, state);
489 void Train::sensor_event(unsigned addr, bool state)
493 // Find the first sensor block from our reserved blocks that isn't this sensor
494 list<BlockRef>::iterator i;
496 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
497 if(i->block->get_sensor_id())
499 if(i->block->get_sensor_id()!=addr)
512 if(result==1 && i!=rsv_blocks.begin())
514 // Compute speed and update related state
515 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
519 RealSpeed &rs = real_speed[current_speed];
520 rs.add(travel_dist/travel_time_secs, travel_time_secs);
521 set_status(format("Traveling %d kmh", get_travel_speed()));
526 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
528 j->block->traverse(j->entry, &block_len);
529 travel_dist += block_len;
531 if(j->block->get_sensor_id()==addr)
533 const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
536 Track *track = bep.track->get_link(bep.track_ep);
537 unsigned ep = track->get_endpoint_by_link(*bep.track);
538 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
541 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
544 last_entry_time = Time::now();
546 accurate_position = true;
549 // Check if we've reached the next route
552 const set<const Track *> &rtracks = next_route->get_tracks();
553 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
554 if(rtracks.count(j->block->get_endpoints()[j->entry].track))
559 signal_route_changed.emit(route);
564 // Move blocks up to the next sensor to our current blocks
565 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
567 // Try to get more blocks if we're moving
570 unsigned nsens = reserve_more();
571 if(!nsens && end_of_route)
572 signal_arrived.emit();
576 layout.emergency("Sensor for "+name+" triggered out of order");
580 // Find the first sensor in our current blocks that's still active
581 list<BlockRef>::iterator end = cur_blocks.begin();
582 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
583 if(i->block->get_sensor_id())
585 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
594 if(end!=cur_blocks.begin())
595 // Free blocks up to the last inactive sensor
596 release_blocks(cur_blocks, cur_blocks.begin(), end);
600 void Train::turnout_event(unsigned addr, bool)
604 unsigned pending_addr = pending_block->get_turnout_id();
605 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
606 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
611 void Train::halt_event(bool h)
614 accurate_position = false;
617 void Train::block_reserved(const Block &block, const Train *train)
619 if(&block==pending_block && !train)
623 unsigned Train::reserve_more()
626 if(!rsv_blocks.empty())
627 last = &rsv_blocks.back();
628 else if(!cur_blocks.empty())
629 last = &cur_blocks.back();
635 // See how many sensor blocks we already have
637 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
638 if(i->block->get_sensor_id())
644 const Route *cur_route = 0;
647 const set<Track *> &tracks = last->block->get_tracks();
648 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
650 if(route->get_tracks().count(*i))
652 else if(next_route && next_route->get_tracks().count(*i))
653 cur_route = next_route;
657 bool got_more = false;
658 BlockRef *good = last;
659 unsigned good_sens = nsens;
662 if(last->block->get_endpoints().size()<2)
669 // Traverse to the next block
670 unsigned exit = last->block->traverse(last->entry);
671 Block *link = last->block->get_link(exit);
675 int entry = link->get_endpoint_by_link(*last->block);
677 throw LogicError("Block links are inconsistent!");
679 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
683 if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
684 cur_route = next_route;
685 else if(!cur_route->get_tracks().count(entry_ep.track))
687 // Keep the blocks if we arrived at the end of the route
694 else if(route && route->get_tracks().count(entry_ep.track))
697 if(!link->reserve(this))
699 // If we found another train and it's not headed straight for us, we can keep the blocks we got
700 int other_entry = link->get_train()->get_entry_to_block(*link);
702 throw LogicError("Block reservation inconsistency");
703 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
708 pending_block = link;
712 if(link->get_turnout_id())
714 const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
716 // Keep the blocks reserved so far, as either us or the other train can diverge
720 // Figure out what path we'd like to take on the turnout
723 path = cur_route->get_turnout(link->get_turnout_id());
725 path = entry_ep.track->get_active_path();
726 if(!((track_ep.paths>>path)&1))
728 for(unsigned i=0; track_ep.paths>>i; ++i)
729 if((track_ep.paths>>i)&1)
733 if(path!=static_cast<int>(entry_ep.track->get_active_path()))
735 // The turnout is set to wrong path - switch and wait for it
737 pending_block = link;
738 entry_ep.track->set_active_path(path);
743 rsv_blocks.push_back(BlockRef(link, entry));
744 last = &rsv_blocks.back();
745 if(last->block->get_sensor_id())
752 // Unreserve blocks that were not good
753 while(!rsv_blocks.empty() && last!=good)
755 last->block->reserve(0);
756 rsv_blocks.erase(--rsv_blocks.end());
757 if(!rsv_blocks.empty())
758 last = &rsv_blocks.back();
761 // Make any sensorless blocks at the beginning immediately current
762 list<BlockRef>::iterator i;
763 for(i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !i->block->get_sensor_id()); ++i) ;
764 if(i!=rsv_blocks.begin())
765 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
770 float Train::get_real_speed(unsigned i) const
772 if(real_speed[i].weight)
773 return real_speed[i].speed;
777 for(low=i; low>0; --low)
778 if(real_speed[low].weight)
780 for(high=i; high<14; ++high)
781 if(real_speed[high].weight)
784 if(real_speed[high].weight)
786 if(real_speed[low].weight)
788 float f = float(i-low)/(high-low);
789 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
792 return real_speed[high].speed*float(i)/high;
794 else if(real_speed[low].weight)
795 return real_speed[low].speed*float(i)/low;
800 unsigned Train::find_speed(float real) const
802 if(real<=real_speed[0].speed)
807 for(unsigned i=0; (!high && i<=14); ++i)
808 if(real_speed[i].weight)
810 if(real_speed[i].speed<real)
819 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
822 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
823 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
826 float Train::get_travel_speed() const
828 float speed = get_real_speed(current_speed);
829 float scale = layout.get_catalogue().get_scale();
830 return static_cast<int>(round(speed/scale*3.6/5))*5;
833 void Train::set_status(const string &s)
836 signal_status_changed.emit(s);
839 void Train::release_blocks(list<BlockRef> &blocks)
841 release_blocks(blocks, blocks.begin(), blocks.end());
844 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
848 Block *block = begin->block;
849 blocks.erase(begin++);
854 void Train::reverse_blocks(list<BlockRef> &blocks) const
857 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
858 i->entry = i->block->traverse(i->entry);
862 Train::BlockRef::BlockRef(Block *b, unsigned e):
867 Train::BlockRef Train::BlockRef::next() const
869 Block *blk = block->get_endpoints()[block->traverse(entry)].link;
871 throw InvalidState("At end of line");
873 int ep = blk->get_endpoint_by_link(*block);
875 throw LogicError("Block links are inconsistent");
877 return BlockRef(blk, ep);
881 Train::RealSpeed::RealSpeed():
886 void Train::RealSpeed::add(float s, float w)
888 speed = (speed*weight+s*w)/(weight+w);
889 weight = min(weight+w, 300.0f);
893 Train::Loader::Loader(Train &t):
894 DataFile::BasicLoader<Train>(t),
897 add("block", &Loader::block);
898 add("block_hint", &Loader::block_hint);
899 add("name", &Loader::name);
900 add("real_speed", &Loader::real_speed);
901 add("route", &Loader::route);
902 add("timetable", &Loader::timetable);
903 add("vehicle", &Loader::vehicle);
906 void Train::Loader::block(unsigned id)
908 Block &blk = obj.layout.get_block(id);
911 entry = blk.get_endpoint_by_link(*prev_block);
916 obj.cur_blocks.push_back(BlockRef(&blk, entry));
917 obj.set_status("Stopped");
918 const Block::Endpoint &bep = blk.get_endpoints()[entry];
919 obj.vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
921 if(blk.get_sensor_id())
922 obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
927 void Train::Loader::block_hint(unsigned id)
929 prev_block = &obj.layout.get_block(id);
932 void Train::Loader::name(const string &n)
937 void Train::Loader::real_speed(unsigned i, float speed, float weight)
939 obj.real_speed[i].speed = speed;
940 obj.real_speed[i].weight = weight;
943 void Train::Loader::route(const string &n)
945 obj.set_route(&obj.layout.get_route(n));
948 void Train::Loader::timetable()
951 throw InvalidState("A timetable has already been loaded");
953 obj.timetable = new Timetable(obj);
954 load_sub(*obj.timetable);
957 void Train::Loader::vehicle(unsigned n)
959 const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(n);
960 Vehicle *veh = new Vehicle(obj.layout, vtype);
961 obj.vehicles.back()->attach_back(*veh);
962 obj.vehicles.push_back(veh);
965 } // namespace Marklin