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"
17 #include "simplecontroller.h"
18 #include "timetable.h"
19 #include "tracktype.h"
22 #include "vehicletype.h"
29 Train::Train(Layout &l, const VehicleType &t, unsigned a):
37 controller(new AIControl(*this, new SimpleController)),
41 speed_changing(false),
51 accurate_position(false),
54 if(!loco_type.is_locomotive())
55 throw InvalidParameterValue("Initial vehicle must be a locomotive");
57 vehicles.push_back(new Vehicle(layout, loco_type));
59 layout.add_train(*this);
61 layout.get_driver().add_loco(address);
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_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
66 layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
67 layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
69 layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
71 controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
78 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
80 layout.remove_train(*this);
83 void Train::set_name(const string &n)
87 signal_name_changed.emit(name);
90 void Train::set_priority(int p)
95 void Train::add_vehicle(const VehicleType &vt)
97 Vehicle *veh = new Vehicle(layout, vt);
98 vehicles.back()->attach_back(*veh);
99 vehicles.push_back(veh);
102 void Train::remove_vehicle(unsigned i)
104 if(i>=vehicles.size())
105 throw InvalidParameterValue("Vehicle index out of range");
107 throw InvalidParameterValue("Can't remove the locomotive");
109 vehicles.erase(vehicles.begin()+i);
110 if(i<vehicles.size())
111 vehicles[i-1]->attach_back(*vehicles[i]);
114 unsigned Train::get_n_vehicles() const
116 return vehicles.size();
119 Vehicle &Train::get_vehicle(unsigned i)
121 if(i>=vehicles.size())
122 throw InvalidParameterValue("Vehicle index out of range");
126 const Vehicle &Train::get_vehicle(unsigned i) const
128 if(i>=vehicles.size())
129 throw InvalidParameterValue("Vehicle index out of range");
133 void Train::set_control(const string &n, float v)
135 controller->set_control(n, v);
138 void Train::set_active(bool a)
142 if(!a && controller->get_speed())
143 throw InvalidState("Can't deactivate while moving");
148 stop_timeout = Time::TimeStamp();
153 stop_timeout = Time::now()+2*Time::sec;
154 set_status("Stopped");
158 void Train::set_function(unsigned func, bool state)
160 if(!loco_type.get_functions().count(func))
161 throw InvalidParameterValue("Invalid function");
163 layout.get_driver().set_loco_function(address, func, state);
165 layout.get_driver().set_loco_function(address+1, func-4, state);
168 float Train::get_control(const string &ctrl) const
170 return controller->get_control(ctrl).value;
173 float Train::get_speed() const
175 return controller->get_speed();
178 bool Train::get_function(unsigned func) const
180 return (functions>>func)&1;
183 void Train::set_timetable(Timetable *tt)
189 void Train::set_route(const Route *r)
191 if(!rsv_blocks.empty())
193 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
194 if(i->block->get_sensor_id())
196 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
203 end_of_route = false;
207 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
208 BlockRef next = last.next();
209 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
210 if(!route->get_tracks().count(ep.track))
213 route = Route::find(*ep.track, ep.track_ep, *next_route);
219 signal_route_changed.emit(route);
222 void Train::go_to(const Track &to)
224 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
225 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
227 signal_arrived.emit();
233 if(rsv_blocks.empty())
234 last = &cur_blocks.back();
237 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
238 if(i->block->get_sensor_id())
242 BlockRef next = last->next();
243 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
245 set_route(Route::find(*ep.track, ep.track_ep, to));
248 void Train::place(Block &block, unsigned entry)
250 if(controller->get_speed())
251 throw InvalidState("Must be stopped before placing");
253 release_blocks(rsv_blocks);
254 release_blocks(cur_blocks);
257 accurate_position = false;
259 if(!block.reserve(this))
261 set_status("Unplaced");
265 cur_blocks.push_back(BlockRef(&block, entry));
268 unsigned exit = block.traverse(entry);
269 const Block::Endpoint &bep = block.get_endpoints()[exit];
270 Track *track = bep.track->get_link(bep.track_ep);
271 unsigned ep = track->get_endpoint_by_link(*bep.track);
272 vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
276 const Block::Endpoint &bep = block.get_endpoints()[entry];
277 vehicles.back()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
281 bool Train::free_block(Block &block)
284 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
290 release_blocks(rsv_blocks, i, rsv_blocks.end());
293 else if(i->block->get_sensor_id())
300 int Train::get_entry_to_block(Block &block) const
302 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
305 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
311 float Train::get_reserved_distance() const
313 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
314 const VehicleType &vtype = veh.get_type();
316 Track *track = veh.get_track();
319 unsigned entry = veh.get_entry();
321 float result = -vtype.get_length()/2;
324 entry = track->traverse(entry);
325 result += veh.get_offset();
328 result -= veh.get_offset();
331 list<BlockRef>::const_iterator block = cur_blocks.begin();
334 if(!first || !reverse)
335 result += track->get_type().get_path_length(track->get_active_path());
338 if(track->get_type().get_endpoints().size()<2)
341 unsigned exit = track->traverse(entry);
342 Track *next = track->get_link(exit);
344 while(!block->block->get_tracks().count(next))
347 if(block==cur_blocks.end())
348 block = rsv_blocks.begin();
349 if(block==rsv_blocks.end())
353 entry = next->get_endpoint_by_link(*track);
358 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
360 if(!active && stop_timeout && t>=stop_timeout)
362 release_blocks(rsv_blocks);
363 end_of_route = false;
364 stop_timeout = Time::TimeStamp();
367 Driver &driver = layout.get_driver();
371 controller->tick(dt);
372 float speed = controller->get_speed();
373 unsigned speed_notch = find_speed(speed);
375 if(controller->get_reverse()!=reverse)
377 reverse = controller->get_reverse();
378 driver.set_loco_reverse(address, reverse);
380 release_blocks(rsv_blocks);
381 reverse_blocks(cur_blocks);
385 if(speed_notch!=current_speed && !speed_changing && !driver.is_halted() && driver.get_power())
387 speed_changing = true;
388 driver.set_loco_speed(address, speed_notch);
393 set_status(format("Traveling %d kmh", get_travel_speed()));
395 set_status("Waiting");
403 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
404 Track *track = vehicle.get_track();
407 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
408 ok = i->block->get_tracks().count(track);
410 float d = get_real_speed(current_speed)*(dt/Time::sec);
414 vehicle.advance(reverse ? -d : d);
417 else if(accurate_position)
420 if(overshoot_dist>40*layout.get_catalogue().get_scale())
422 layout.emergency(name+" has not arrived at sensor");
423 accurate_position = false;
427 else if(end_of_route && rsv_blocks.empty())
429 signal_arrived.emit();
433 if(!cur_blocks.empty() && !cur_blocks.front().block->get_sensor_id())
435 Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
437 list<BlockRef>::iterator i = cur_blocks.begin();
438 const Block::Endpoint &bep = i->block->get_endpoints()[i->entry];
440 Track *track = bep.track;
441 unsigned entry = bep.track_ep;
444 float dist = veh.get_offset();
446 dist = veh.get_track()->get_type().get_path_length(veh.get_track()->get_active_path())-dist;
447 dist -= veh.get_type().get_length()/2;
450 if(track==veh.get_track())
456 if(i!=cur_blocks.begin())
458 float path_len = track->get_type().get_path_length(track->get_active_path());
462 unsigned exit = track->traverse(entry);
463 Track *next = track->get_link(exit);
464 entry = next->get_endpoint_by_link(*track);
467 if(!i->block->get_tracks().count(track))
470 if(i==cur_blocks.end())
475 if(found && i!=cur_blocks.begin() && dist>10*layout.get_catalogue().get_scale())
477 cur_blocks.front().block->reserve(0);
478 cur_blocks.erase(cur_blocks.begin());
483 void Train::save(list<DataFile::Statement> &st) const
485 st.push_back((DataFile::Statement("name"), name));
487 st.push_back((DataFile::Statement("priority"), priority));
489 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
490 if(i!=vehicles.begin())
491 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
493 for(unsigned i=0; i<=14; ++i)
494 if(real_speed[i].weight)
495 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
497 if(!cur_blocks.empty())
499 list<BlockRef> blocks = cur_blocks;
501 reverse_blocks(blocks);
503 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
504 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
506 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
507 st.push_back((DataFile::Statement("block"), i->block->get_id()));
512 if(!route->is_temporary())
513 st.push_back((DataFile::Statement("route"), route->get_name()));
514 else if(next_route && !next_route->is_temporary())
515 st.push_back((DataFile::Statement("route"), next_route->get_name()));
520 DataFile::Statement ss("timetable");
521 timetable->save(ss.sub);
526 void Train::control_changed(const Controller::Control &ctrl)
528 signal_control_changed.emit(ctrl.name, ctrl.value);
531 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
535 current_speed = speed;
536 speed_changing = false;
541 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
543 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
548 functions |= 1<<func;
550 functions &= ~(1<<func);
552 signal_function_changed.emit(func, state);
556 void Train::sensor_event(unsigned addr, bool state)
560 // Find the first sensor block from our reserved blocks that isn't this sensor
561 list<BlockRef>::iterator i;
563 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
564 if(i->block->get_sensor_id())
566 if(i->block->get_sensor_id()!=addr)
579 if(result==1 && i!=rsv_blocks.begin())
581 // Compute speed and update related state
582 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
588 RealSpeed &rs = real_speed[current_speed];
589 rs.add(travel_dist/travel_time_secs, travel_time_secs);
591 set_status(format("Traveling %d kmh", get_travel_speed()));
596 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
598 j->block->traverse(j->entry, &block_len);
599 travel_dist += block_len;
601 if(j->block->get_sensor_id()==addr && !advancing)
603 const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
606 Track *track = bep.track->get_link(bep.track_ep);
607 unsigned ep = track->get_endpoint_by_link(*bep.track);
608 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
611 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
614 last_entry_time = Time::now();
616 accurate_position = true;
619 // Check if we've reached the next route
622 const set<const Track *> &rtracks = next_route->get_tracks();
623 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
624 if(rtracks.count(j->block->get_endpoints()[j->entry].track))
629 signal_route_changed.emit(route);
634 // Move blocks up to the next sensor to our current blocks
635 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
637 // Try to get more blocks if we're moving
642 layout.emergency("Sensor for "+name+" triggered out of order");
646 // Find the first sensor in our current blocks that's still active
647 list<BlockRef>::iterator end = cur_blocks.begin();
648 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
649 if(i->block->get_sensor_id())
651 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
660 if(end!=cur_blocks.begin())
661 // Free blocks up to the last inactive sensor
662 release_blocks(cur_blocks, cur_blocks.begin(), end);
666 void Train::turnout_event(unsigned addr, bool)
670 unsigned pending_addr = pending_block->get_turnout_id();
671 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
672 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
682 void Train::halt_event(bool h)
685 accurate_position = false;
688 void Train::block_reserved(const Block &block, const Train *train)
690 if(&block==pending_block && !train)
694 unsigned Train::reserve_more()
700 if(!rsv_blocks.empty())
701 last = &rsv_blocks.back();
702 else if(!cur_blocks.empty())
703 last = &cur_blocks.back();
709 // See how many sensor blocks we already have
711 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
712 if(i->block->get_sensor_id())
718 const Route *cur_route = 0;
721 const set<Track *> &tracks = last->block->get_tracks();
722 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
724 if(route->get_tracks().count(*i))
726 else if(next_route && next_route->get_tracks().count(*i))
727 cur_route = next_route;
733 bool got_more = false;
734 BlockRef *good = last;
735 unsigned good_sens = nsens;
738 // Traverse to the next block
739 unsigned exit = last->block->traverse(last->entry);
740 Block *link = last->block->get_link(exit);
744 int entry = link->get_endpoint_by_link(*last->block);
746 throw LogicError("Block links are inconsistent!");
748 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
752 if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
753 cur_route = next_route;
754 else if(!cur_route->get_tracks().count(entry_ep.track))
756 // Keep the blocks if we arrived at the end of the route
763 else if(route && route->get_tracks().count(entry_ep.track))
766 if(link->get_endpoints().size()<2)
773 bool reserved = link->reserve(this);
776 // Ask a lesser priority train to free the block for us
777 if(link->get_train()->get_priority()<priority)
778 if(link->get_train()->free_block(*link))
779 reserved = link->reserve(this);
783 // If we found another train and it's not headed straight for us, we can keep the blocks we got
784 int other_entry = link->get_train()->get_entry_to_block(*link);
786 throw LogicError("Block reservation inconsistency");
787 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
792 pending_block = link;
797 if(link->get_turnout_id())
799 const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
801 // Keep the blocks reserved so far, as either us or the other train can diverge
805 // Figure out what path we'd like to take on the turnout
808 path = cur_route->get_turnout(link->get_turnout_id());
810 path = entry_ep.track->get_active_path();
811 if(!((track_ep.paths>>path)&1))
813 for(unsigned i=0; track_ep.paths>>i; ++i)
814 if((track_ep.paths>>i)&1)
818 if(path!=static_cast<int>(entry_ep.track->get_active_path()))
820 // The turnout is set to wrong path - switch and wait for it
821 pending_block = link;
822 entry_ep.track->set_active_path(path);
831 rsv_blocks.push_back(BlockRef(link, entry));
832 last = &rsv_blocks.back();
833 if(last->block->get_sensor_id())
840 // Unreserve blocks that were not good
841 while(!rsv_blocks.empty() && last!=good)
843 last->block->reserve(0);
844 rsv_blocks.erase(--rsv_blocks.end());
845 if(!rsv_blocks.empty())
846 last = &rsv_blocks.back();
851 // Make any sensorless blocks at the beginning immediately current
852 list<BlockRef>::iterator i;
853 for(i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !i->block->get_sensor_id()); ++i) ;
854 if(i!=rsv_blocks.begin())
855 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
860 float Train::get_real_speed(unsigned i) const
862 if(real_speed[i].weight)
863 return real_speed[i].speed;
867 for(low=i; low>0; --low)
868 if(real_speed[low].weight)
870 for(high=i; high<14; ++high)
871 if(real_speed[high].weight)
874 if(real_speed[high].weight)
876 if(real_speed[low].weight)
878 float f = float(i-low)/(high-low);
879 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
882 return real_speed[high].speed*float(i)/high;
884 else if(real_speed[low].weight)
885 return real_speed[low].speed*float(i)/low;
890 unsigned Train::find_speed(float real) const
892 if(real<=real_speed[0].speed)
897 for(unsigned i=0; (!high && i<=14); ++i)
898 if(real_speed[i].weight)
900 if(real_speed[i].speed<real)
914 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
917 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
918 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
921 float Train::get_travel_speed() const
923 float speed = get_real_speed(current_speed);
924 float scale = layout.get_catalogue().get_scale();
925 return static_cast<int>(round(speed/scale*3.6/5))*5;
928 void Train::set_status(const string &s)
931 signal_status_changed.emit(s);
934 void Train::release_blocks(list<BlockRef> &blocks)
936 release_blocks(blocks, blocks.begin(), blocks.end());
939 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
943 Block *block = begin->block;
944 blocks.erase(begin++);
949 void Train::reverse_blocks(list<BlockRef> &blocks) const
952 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
953 i->entry = i->block->traverse(i->entry);
957 Train::BlockRef::BlockRef(Block *b, unsigned e):
962 Train::BlockRef Train::BlockRef::next() const
964 Block *blk = block->get_endpoints()[block->traverse(entry)].link;
966 throw InvalidState("At end of line");
968 int ep = blk->get_endpoint_by_link(*block);
970 throw LogicError("Block links are inconsistent");
972 return BlockRef(blk, ep);
976 Train::RealSpeed::RealSpeed():
981 void Train::RealSpeed::add(float s, float w)
983 speed = (speed*weight+s*w)/(weight+w);
984 weight = min(weight+w, 300.0f);
988 Train::Loader::Loader(Train &t):
989 DataFile::BasicLoader<Train>(t),
993 add("block", &Loader::block);
994 add("block_hint", &Loader::block_hint);
995 add("name", &Loader::name);
996 add("priority", &Train::priority);
997 add("real_speed", &Loader::real_speed);
998 add("route", &Loader::route);
999 add("timetable", &Loader::timetable);
1000 add("vehicle", &Loader::vehicle);
1003 void Train::Loader::finish()
1005 if(!obj.cur_blocks.empty())
1007 const BlockRef &blkref = obj.cur_blocks.front();
1008 const Block::Endpoint &bep = blkref.block->get_endpoints()[blkref.entry];
1009 obj.vehicles.back()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
1011 obj.set_status("Stopped");
1015 void Train::Loader::block(unsigned id)
1023 blk = &obj.layout.get_block(id);
1025 catch(const KeyError &)
1027 blocks_valid = false;
1033 entry = blk->get_endpoint_by_link(*prev_block);
1038 obj.cur_blocks.push_back(BlockRef(blk, entry));
1040 if(blk->get_sensor_id())
1041 obj.layout.get_driver().set_sensor(blk->get_sensor_id(), true);
1046 void Train::Loader::block_hint(unsigned id)
1050 prev_block = &obj.layout.get_block(id);
1052 catch(const KeyError &)
1054 blocks_valid = false;
1058 void Train::Loader::name(const string &n)
1063 void Train::Loader::real_speed(unsigned i, float speed, float weight)
1065 obj.real_speed[i].speed = speed;
1066 obj.real_speed[i].weight = weight;
1069 void Train::Loader::route(const string &n)
1071 obj.set_route(&obj.layout.get_route(n));
1074 void Train::Loader::timetable()
1077 throw InvalidState("A timetable has already been loaded");
1079 obj.timetable = new Timetable(obj);
1080 load_sub(*obj.timetable);
1083 void Train::Loader::vehicle(unsigned n)
1085 const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(n);
1086 Vehicle *veh = new Vehicle(obj.layout, vtype);
1087 obj.vehicles.back()->attach_back(*veh);
1088 obj.vehicles.push_back(veh);
1091 } // namespace Marklin