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 "simplephysics.h"
18 #include "timetable.h"
19 #include "tracktype.h"
22 #include "vehicletype.h"
29 Train::Train(Layout &l, const VehicleType &t, unsigned a):
35 control(new AIControl(*this, new SimplePhysics)),
39 speed_changing(false),
49 accurate_position(false),
52 if(!loco_type.is_locomotive())
53 throw InvalidParameterValue("Initial vehicle must be a locomotive");
55 vehicles.push_back(new Vehicle(layout, loco_type));
57 layout.add_train(*this);
59 layout.get_driver().add_loco(address);
60 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
61 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
63 layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
64 layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
65 layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
67 layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
69 control->signal_control_changed.connect(signal_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::set_priority(int p)
93 void Train::add_vehicle(const VehicleType &vt)
95 Vehicle *veh = new Vehicle(layout, vt);
96 vehicles.back()->attach_back(*veh);
97 vehicles.push_back(veh);
100 void Train::remove_vehicle(unsigned i)
102 if(i>=vehicles.size())
103 throw InvalidParameterValue("Vehicle index out of range");
105 throw InvalidParameterValue("Can't remove the locomotive");
107 vehicles.erase(vehicles.begin()+i);
108 if(i<vehicles.size())
109 vehicles[i-1]->attach_back(*vehicles[i]);
112 unsigned Train::get_n_vehicles() const
114 return vehicles.size();
117 Vehicle &Train::get_vehicle(unsigned i)
119 if(i>=vehicles.size())
120 throw InvalidParameterValue("Vehicle index out of range");
124 const Vehicle &Train::get_vehicle(unsigned i) const
126 if(i>=vehicles.size())
127 throw InvalidParameterValue("Vehicle index out of range");
131 void Train::set_control(const string &n, float v)
133 control->set_control(n, v);
136 void Train::set_active(bool a)
140 if(!a && control->get_speed())
141 throw InvalidState("Can't deactivate while moving");
146 stop_timeout = Time::TimeStamp();
151 stop_timeout = Time::now()+2*Time::sec;
152 set_status("Stopped");
156 void Train::set_function(unsigned func, bool state)
158 if(!loco_type.get_functions().count(func))
159 throw InvalidParameterValue("Invalid function");
161 layout.get_driver().set_loco_function(address, func, state);
163 layout.get_driver().set_loco_function(address+1, func-4, state);
166 bool Train::get_function(unsigned func) const
168 return (functions>>func)&1;
171 void Train::set_timetable(Timetable *tt)
177 void Train::set_route(const Route *r)
179 if(!rsv_blocks.empty())
181 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
182 if(i->block->get_sensor_id())
184 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
191 end_of_route = false;
195 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
196 BlockRef next = last.next();
197 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
198 if(!route->get_tracks().count(ep.track))
201 route = Route::find(*ep.track, ep.track_ep, *next_route);
207 signal_route_changed.emit(route);
210 void Train::go_to(const Track &to)
212 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
213 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
215 signal_arrived.emit();
221 if(rsv_blocks.empty())
222 last = &cur_blocks.back();
225 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
226 if(i->block->get_sensor_id())
230 BlockRef next = last->next();
231 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
233 set_route(Route::find(*ep.track, ep.track_ep, to));
236 void Train::place(Block &block, unsigned entry)
238 if(control->get_speed())
239 throw InvalidState("Must be stopped before placing");
241 release_blocks(rsv_blocks);
242 release_blocks(cur_blocks);
245 accurate_position = false;
247 if(!block.reserve(this))
249 set_status("Unplaced");
253 cur_blocks.push_back(BlockRef(&block, entry));
256 unsigned exit = block.traverse(entry);
257 const Block::Endpoint &bep = block.get_endpoints()[exit];
258 Track *track = bep.track->get_link(bep.track_ep);
259 unsigned ep = track->get_endpoint_by_link(*bep.track);
260 vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
264 const Block::Endpoint &bep = block.get_endpoints()[entry];
265 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
269 bool Train::free_block(Block &block)
272 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
278 release_blocks(rsv_blocks, i, rsv_blocks.end());
281 else if(i->block->get_sensor_id())
288 int Train::get_entry_to_block(Block &block) const
290 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
293 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
299 float Train::get_reserved_distance() const
301 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
302 const VehicleType &vtype = veh.get_type();
304 Track *track = veh.get_track();
307 unsigned entry = veh.get_entry();
309 float result = -vtype.get_length()/2;
312 entry = track->traverse(entry);
313 result += veh.get_offset();
316 result -= veh.get_offset();
319 list<BlockRef>::const_iterator block = cur_blocks.begin();
322 if(!first || !reverse)
323 result += track->get_type().get_path_length(track->get_active_path());
326 if(track->get_type().get_endpoints().size()<2)
329 unsigned exit = track->traverse(entry);
330 Track *next = track->get_link(exit);
332 while(!block->block->get_tracks().count(next))
335 if(block==cur_blocks.end())
336 block = rsv_blocks.begin();
337 if(block==rsv_blocks.end())
341 entry = next->get_endpoint_by_link(*track);
346 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
348 if(!active && stop_timeout && t>=stop_timeout)
350 release_blocks(rsv_blocks);
351 end_of_route = false;
352 stop_timeout = Time::TimeStamp();
355 Driver &driver = layout.get_driver();
360 float speed = control->get_speed();
361 unsigned speed_notch = find_speed(abs(speed));
363 if(control->get_reverse()!=reverse)
365 reverse = control->get_reverse();
366 driver.set_loco_reverse(address, reverse);
368 release_blocks(rsv_blocks);
369 reverse_blocks(cur_blocks);
373 if(speed_notch!=current_speed && !speed_changing && !driver.is_halted() && driver.get_power())
375 speed_changing = true;
376 driver.set_loco_speed(address, speed_notch);
381 set_status(format("Traveling %d kmh", get_travel_speed()));
383 set_status("Waiting");
391 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
392 Track *track = vehicle.get_track();
395 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
396 ok = i->block->get_tracks().count(track);
398 float d = get_real_speed(current_speed)*(dt/Time::sec);
400 vehicle.advance(reverse ? -d : d);
401 else if(accurate_position)
404 if(overshoot_dist>40*layout.get_catalogue().get_scale())
406 layout.emergency(name+" has not arrived at sensor");
407 accurate_position = false;
411 else if(end_of_route)
414 if(!cur_blocks.empty() && !cur_blocks.front().block->get_sensor_id())
416 Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
418 list<BlockRef>::iterator i = cur_blocks.begin();
419 const Block::Endpoint &bep = i->block->get_endpoints()[i->entry];
421 Track *track = bep.track;
422 unsigned entry = bep.track_ep;
425 float dist = veh.get_offset()-veh.get_type().get_length()/2;
428 if(track==veh.get_track())
434 if(i!=cur_blocks.begin())
436 float path_len = track->get_type().get_path_length(track->get_active_path());
440 unsigned exit = track->traverse(entry);
441 Track *next = track->get_link(exit);
442 entry = next->get_endpoint_by_link(*track);
445 if(!i->block->get_tracks().count(track))
448 if(i==cur_blocks.end())
453 if(found && i!=cur_blocks.begin() && dist>10*layout.get_catalogue().get_scale())
455 cur_blocks.front().block->reserve(0);
456 cur_blocks.erase(cur_blocks.begin());
461 void Train::save(list<DataFile::Statement> &st) const
463 st.push_back((DataFile::Statement("name"), name));
465 st.push_back((DataFile::Statement("priority"), priority));
467 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
468 if(i!=vehicles.begin())
469 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
471 for(unsigned i=0; i<=14; ++i)
472 if(real_speed[i].weight)
473 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
475 if(!cur_blocks.empty())
477 list<BlockRef> blocks = cur_blocks;
479 reverse_blocks(blocks);
481 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
482 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
484 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
485 st.push_back((DataFile::Statement("block"), i->block->get_id()));
490 if(!route->is_temporary())
491 st.push_back((DataFile::Statement("route"), route->get_name()));
492 else if(next_route && !next_route->is_temporary())
493 st.push_back((DataFile::Statement("route"), next_route->get_name()));
498 DataFile::Statement ss("timetable");
499 timetable->save(ss.sub);
504 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
508 current_speed = speed;
509 speed_changing = false;
514 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
516 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
521 functions |= 1<<func;
523 functions &= ~(1<<func);
525 signal_function_changed.emit(func, state);
529 void Train::sensor_event(unsigned addr, bool state)
533 // Find the first sensor block from our reserved blocks that isn't this sensor
534 list<BlockRef>::iterator i;
536 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
537 if(i->block->get_sensor_id())
539 if(i->block->get_sensor_id()!=addr)
552 if(result==1 && i!=rsv_blocks.begin())
554 // Compute speed and update related state
555 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
561 RealSpeed &rs = real_speed[current_speed];
562 rs.add(travel_dist/travel_time_secs, travel_time_secs);
564 set_status(format("Traveling %d kmh", get_travel_speed()));
569 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
571 j->block->traverse(j->entry, &block_len);
572 travel_dist += block_len;
574 if(j->block->get_sensor_id()==addr)
576 const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
579 Track *track = bep.track->get_link(bep.track_ep);
580 unsigned ep = track->get_endpoint_by_link(*bep.track);
581 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
584 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
587 last_entry_time = Time::now();
589 accurate_position = true;
592 // Check if we've reached the next route
595 const set<const Track *> &rtracks = next_route->get_tracks();
596 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
597 if(rtracks.count(j->block->get_endpoints()[j->entry].track))
602 signal_route_changed.emit(route);
607 // Move blocks up to the next sensor to our current blocks
608 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
610 // Try to get more blocks if we're moving
613 unsigned nsens = reserve_more();
614 if(!nsens && end_of_route)
615 signal_arrived.emit();
619 layout.emergency("Sensor for "+name+" triggered out of order");
623 // Find the first sensor in our current blocks that's still active
624 list<BlockRef>::iterator end = cur_blocks.begin();
625 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
626 if(i->block->get_sensor_id())
628 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
637 if(end!=cur_blocks.begin())
638 // Free blocks up to the last inactive sensor
639 release_blocks(cur_blocks, cur_blocks.begin(), end);
643 void Train::turnout_event(unsigned addr, bool)
647 unsigned pending_addr = pending_block->get_turnout_id();
648 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
649 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
654 void Train::halt_event(bool h)
657 accurate_position = false;
660 void Train::block_reserved(const Block &block, const Train *train)
662 if(&block==pending_block && !train)
666 unsigned Train::reserve_more()
672 if(!rsv_blocks.empty())
673 last = &rsv_blocks.back();
674 else if(!cur_blocks.empty())
675 last = &cur_blocks.back();
681 // See how many sensor blocks we already have
683 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
684 if(i->block->get_sensor_id())
690 const Route *cur_route = 0;
693 const set<Track *> &tracks = last->block->get_tracks();
694 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
696 if(route->get_tracks().count(*i))
698 else if(next_route && next_route->get_tracks().count(*i))
699 cur_route = next_route;
703 bool got_more = false;
704 BlockRef *good = last;
705 unsigned good_sens = nsens;
708 if(last->block->get_endpoints().size()<2)
715 // Traverse to the next block
716 unsigned exit = last->block->traverse(last->entry);
717 Block *link = last->block->get_link(exit);
721 int entry = link->get_endpoint_by_link(*last->block);
723 throw LogicError("Block links are inconsistent!");
725 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
729 if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
730 cur_route = next_route;
731 else if(!cur_route->get_tracks().count(entry_ep.track))
733 // Keep the blocks if we arrived at the end of the route
740 else if(route && route->get_tracks().count(entry_ep.track))
743 bool reserved = link->reserve(this);
746 // Ask a lesser priority train to free the block for us
747 if(link->get_train()->get_priority()<priority)
748 if(link->get_train()->free_block(*link))
749 reserved = link->reserve(this);
753 // If we found another train and it's not headed straight for us, we can keep the blocks we got
754 int other_entry = link->get_train()->get_entry_to_block(*link);
756 throw LogicError("Block reservation inconsistency");
757 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
762 pending_block = link;
767 if(link->get_turnout_id())
769 const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
771 // Keep the blocks reserved so far, as either us or the other train can diverge
775 // Figure out what path we'd like to take on the turnout
778 path = cur_route->get_turnout(link->get_turnout_id());
780 path = entry_ep.track->get_active_path();
781 if(!((track_ep.paths>>path)&1))
783 for(unsigned i=0; track_ep.paths>>i; ++i)
784 if((track_ep.paths>>i)&1)
788 if(path!=static_cast<int>(entry_ep.track->get_active_path()))
790 // The turnout is set to wrong path - switch and wait for it
792 pending_block = link;
793 entry_ep.track->set_active_path(path);
798 rsv_blocks.push_back(BlockRef(link, entry));
799 last = &rsv_blocks.back();
800 if(last->block->get_sensor_id())
807 // Unreserve blocks that were not good
808 while(!rsv_blocks.empty() && last!=good)
810 last->block->reserve(0);
811 rsv_blocks.erase(--rsv_blocks.end());
812 if(!rsv_blocks.empty())
813 last = &rsv_blocks.back();
816 // Make any sensorless blocks at the beginning immediately current
817 list<BlockRef>::iterator i;
818 for(i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !i->block->get_sensor_id()); ++i) ;
819 if(i!=rsv_blocks.begin())
820 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
825 float Train::get_real_speed(unsigned i) const
827 if(real_speed[i].weight)
828 return real_speed[i].speed;
832 for(low=i; low>0; --low)
833 if(real_speed[low].weight)
835 for(high=i; high<14; ++high)
836 if(real_speed[high].weight)
839 if(real_speed[high].weight)
841 if(real_speed[low].weight)
843 float f = float(i-low)/(high-low);
844 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
847 return real_speed[high].speed*float(i)/high;
849 else if(real_speed[low].weight)
850 return real_speed[low].speed*float(i)/low;
855 unsigned Train::find_speed(float real) const
857 if(real<=real_speed[0].speed)
862 for(unsigned i=0; (!high && i<=14); ++i)
863 if(real_speed[i].weight)
865 if(real_speed[i].speed<real)
879 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
882 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
883 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
886 float Train::get_travel_speed() const
888 float speed = get_real_speed(current_speed);
889 float scale = layout.get_catalogue().get_scale();
890 return static_cast<int>(round(speed/scale*3.6/5))*5;
893 void Train::set_status(const string &s)
896 signal_status_changed.emit(s);
899 void Train::release_blocks(list<BlockRef> &blocks)
901 release_blocks(blocks, blocks.begin(), blocks.end());
904 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
908 Block *block = begin->block;
909 blocks.erase(begin++);
914 void Train::reverse_blocks(list<BlockRef> &blocks) const
917 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
918 i->entry = i->block->traverse(i->entry);
922 Train::BlockRef::BlockRef(Block *b, unsigned e):
927 Train::BlockRef Train::BlockRef::next() const
929 Block *blk = block->get_endpoints()[block->traverse(entry)].link;
931 throw InvalidState("At end of line");
933 int ep = blk->get_endpoint_by_link(*block);
935 throw LogicError("Block links are inconsistent");
937 return BlockRef(blk, ep);
941 Train::RealSpeed::RealSpeed():
946 void Train::RealSpeed::add(float s, float w)
948 speed = (speed*weight+s*w)/(weight+w);
949 weight = min(weight+w, 300.0f);
953 Train::Loader::Loader(Train &t):
954 DataFile::BasicLoader<Train>(t),
957 add("block", &Loader::block);
958 add("block_hint", &Loader::block_hint);
959 add("name", &Loader::name);
960 add("priority", &Train::priority);
961 add("real_speed", &Loader::real_speed);
962 add("route", &Loader::route);
963 add("timetable", &Loader::timetable);
964 add("vehicle", &Loader::vehicle);
967 void Train::Loader::block(unsigned id)
969 Block &blk = obj.layout.get_block(id);
972 entry = blk.get_endpoint_by_link(*prev_block);
977 obj.cur_blocks.push_back(BlockRef(&blk, entry));
978 obj.set_status("Stopped");
979 const Block::Endpoint &bep = blk.get_endpoints()[entry];
980 obj.vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
982 if(blk.get_sensor_id())
983 obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
988 void Train::Loader::block_hint(unsigned id)
990 prev_block = &obj.layout.get_block(id);
993 void Train::Loader::name(const string &n)
998 void Train::Loader::real_speed(unsigned i, float speed, float weight)
1000 obj.real_speed[i].speed = speed;
1001 obj.real_speed[i].weight = weight;
1004 void Train::Loader::route(const string &n)
1006 obj.set_route(&obj.layout.get_route(n));
1009 void Train::Loader::timetable()
1012 throw InvalidState("A timetable has already been loaded");
1014 obj.timetable = new Timetable(obj);
1015 load_sub(*obj.timetable);
1018 void Train::Loader::vehicle(unsigned n)
1020 const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(n);
1021 Vehicle *veh = new Vehicle(obj.layout, vtype);
1022 obj.vehicles.back()->attach_back(*veh);
1023 obj.vehicles.push_back(veh);
1026 } // namespace Marklin