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_timetable(Timetable *tt)
150 void Train::set_route(const Route *r)
152 if(!rsv_blocks.empty())
154 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
155 if(i->block->get_sensor_id())
157 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
164 end_of_route = false;
168 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
169 BlockRef next = last.next();
170 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
171 if(!route->get_tracks().count(ep.track))
174 route = Route::find(*ep.track, ep.track_ep, *next_route);
180 signal_route_changed.emit(route);
183 void Train::go_to(const Track &to)
185 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
186 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
188 signal_arrived.emit();
194 if(rsv_blocks.empty())
195 last = &cur_blocks.back();
198 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
199 if(i->block->get_sensor_id())
203 BlockRef next = last->next();
204 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
206 set_route(Route::find(*ep.track, ep.track_ep, to));
209 void Train::place(Block &block, unsigned entry)
211 if(control->get_speed())
212 throw InvalidState("Must be stopped before placing");
214 release_blocks(rsv_blocks);
215 release_blocks(cur_blocks);
218 accurate_position = false;
220 if(!block.reserve(this))
222 set_status("Unplaced");
226 cur_blocks.push_back(BlockRef(&block, entry));
229 unsigned exit = block.traverse(entry);
230 const Block::Endpoint &bep = block.get_endpoints()[exit];
231 Track *track = bep.track->get_link(bep.track_ep);
232 unsigned ep = track->get_endpoint_by_link(*bep.track);
233 vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
237 const Block::Endpoint &bep = block.get_endpoints()[entry];
238 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
242 bool Train::free_block(Block &block)
245 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
251 release_blocks(rsv_blocks, i, rsv_blocks.end());
254 else if(i->block->get_sensor_id())
261 int Train::get_entry_to_block(Block &block) const
263 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
266 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
272 float Train::get_reserved_distance() const
274 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
275 const VehicleType &vtype = veh.get_type();
277 Track *track = veh.get_track();
280 unsigned entry = veh.get_entry();
282 float result = -vtype.get_length()/2;
285 entry = track->traverse(entry);
286 result += veh.get_offset();
289 result -= veh.get_offset();
292 list<BlockRef>::const_iterator block = cur_blocks.begin();
295 if(!first || !reverse)
296 result += track->get_type().get_path_length(track->get_active_path());
299 if(track->get_type().get_endpoints().size()<2)
302 unsigned exit = track->traverse(entry);
303 Track *next = track->get_link(exit);
305 while(!block->block->get_tracks().count(next))
308 if(block==cur_blocks.end())
309 block = rsv_blocks.begin();
310 if(block==rsv_blocks.end())
314 entry = next->get_endpoint_by_link(*track);
319 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
321 if(!active && stop_timeout && t>=stop_timeout)
323 release_blocks(rsv_blocks);
324 end_of_route = false;
325 stop_timeout = Time::TimeStamp();
328 Driver &driver = layout.get_driver();
333 float speed = control->get_speed();
334 unsigned speed_notch = find_speed(abs(speed));
336 if(control->get_reverse()!=reverse)
338 reverse = control->get_reverse();
339 driver.set_loco_reverse(address, reverse);
341 release_blocks(rsv_blocks);
342 reverse_blocks(cur_blocks);
346 if(speed_notch!=current_speed && !speed_changing && !driver.is_halted() && driver.get_power())
348 speed_changing = true;
349 driver.set_loco_speed(address, speed_notch);
354 set_status(format("Traveling %d kmh", get_travel_speed()));
356 set_status("Waiting");
364 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
365 Track *track = vehicle.get_track();
368 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
369 ok = i->block->get_tracks().count(track);
371 float d = get_real_speed(current_speed)*(dt/Time::sec);
373 vehicle.advance(reverse ? -d : d);
374 else if(accurate_position)
377 if(overshoot_dist>40*layout.get_catalogue().get_scale())
379 layout.emergency(name+" has not arrived at sensor");
380 accurate_position = false;
384 else if(end_of_route)
387 if(!cur_blocks.empty() && !cur_blocks.front().block->get_sensor_id())
389 Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
391 list<BlockRef>::iterator i = cur_blocks.begin();
392 const Block::Endpoint &bep = i->block->get_endpoints()[i->entry];
394 Track *track = bep.track;
395 unsigned entry = bep.track_ep;
398 float dist = veh.get_offset()-veh.get_type().get_length()/2;
401 if(track==veh.get_track())
407 if(i!=cur_blocks.begin())
409 float path_len = track->get_type().get_path_length(track->get_active_path());
413 unsigned exit = track->traverse(entry);
414 Track *next = track->get_link(exit);
415 entry = next->get_endpoint_by_link(*track);
418 if(!i->block->get_tracks().count(track))
421 if(i==cur_blocks.end())
426 if(found && i!=cur_blocks.begin() && dist>10*layout.get_catalogue().get_scale())
428 cur_blocks.front().block->reserve(0);
429 cur_blocks.erase(cur_blocks.begin());
434 void Train::save(list<DataFile::Statement> &st) const
436 st.push_back((DataFile::Statement("name"), name));
438 st.push_back((DataFile::Statement("priority"), priority));
440 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
441 if(i!=vehicles.begin())
442 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
444 for(unsigned i=0; i<=14; ++i)
445 if(real_speed[i].weight)
446 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
448 if(!cur_blocks.empty())
450 list<BlockRef> blocks = cur_blocks;
452 reverse_blocks(blocks);
454 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
455 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
457 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
458 st.push_back((DataFile::Statement("block"), i->block->get_id()));
463 if(!route->is_temporary())
464 st.push_back((DataFile::Statement("route"), route->get_name()));
465 else if(next_route && !next_route->is_temporary())
466 st.push_back((DataFile::Statement("route"), next_route->get_name()));
471 DataFile::Statement ss("timetable");
472 timetable->save(ss.sub);
477 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
481 current_speed = speed;
482 speed_changing = false;
487 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
489 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
494 functions |= 1<<func;
496 functions &= ~(1<<func);
498 signal_function_changed.emit(func, state);
502 void Train::sensor_event(unsigned addr, bool state)
506 // Find the first sensor block from our reserved blocks that isn't this sensor
507 list<BlockRef>::iterator i;
509 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
510 if(i->block->get_sensor_id())
512 if(i->block->get_sensor_id()!=addr)
525 if(result==1 && i!=rsv_blocks.begin())
527 // Compute speed and update related state
528 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
534 RealSpeed &rs = real_speed[current_speed];
535 rs.add(travel_dist/travel_time_secs, travel_time_secs);
537 set_status(format("Traveling %d kmh", get_travel_speed()));
542 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
544 j->block->traverse(j->entry, &block_len);
545 travel_dist += block_len;
547 if(j->block->get_sensor_id()==addr)
549 const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
552 Track *track = bep.track->get_link(bep.track_ep);
553 unsigned ep = track->get_endpoint_by_link(*bep.track);
554 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
557 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
560 last_entry_time = Time::now();
562 accurate_position = true;
565 // Check if we've reached the next route
568 const set<const Track *> &rtracks = next_route->get_tracks();
569 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
570 if(rtracks.count(j->block->get_endpoints()[j->entry].track))
575 signal_route_changed.emit(route);
580 // Move blocks up to the next sensor to our current blocks
581 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
583 // Try to get more blocks if we're moving
586 unsigned nsens = reserve_more();
587 if(!nsens && end_of_route)
588 signal_arrived.emit();
592 layout.emergency("Sensor for "+name+" triggered out of order");
596 // Find the first sensor in our current blocks that's still active
597 list<BlockRef>::iterator end = cur_blocks.begin();
598 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
599 if(i->block->get_sensor_id())
601 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
610 if(end!=cur_blocks.begin())
611 // Free blocks up to the last inactive sensor
612 release_blocks(cur_blocks, cur_blocks.begin(), end);
616 void Train::turnout_event(unsigned addr, bool)
620 unsigned pending_addr = pending_block->get_turnout_id();
621 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
622 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
627 void Train::halt_event(bool h)
630 accurate_position = false;
633 void Train::block_reserved(const Block &block, const Train *train)
635 if(&block==pending_block && !train)
639 unsigned Train::reserve_more()
645 if(!rsv_blocks.empty())
646 last = &rsv_blocks.back();
647 else if(!cur_blocks.empty())
648 last = &cur_blocks.back();
654 // See how many sensor blocks we already have
656 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
657 if(i->block->get_sensor_id())
663 const Route *cur_route = 0;
666 const set<Track *> &tracks = last->block->get_tracks();
667 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
669 if(route->get_tracks().count(*i))
671 else if(next_route && next_route->get_tracks().count(*i))
672 cur_route = next_route;
676 bool got_more = false;
677 BlockRef *good = last;
678 unsigned good_sens = nsens;
681 if(last->block->get_endpoints().size()<2)
688 // Traverse to the next block
689 unsigned exit = last->block->traverse(last->entry);
690 Block *link = last->block->get_link(exit);
694 int entry = link->get_endpoint_by_link(*last->block);
696 throw LogicError("Block links are inconsistent!");
698 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
702 if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
703 cur_route = next_route;
704 else if(!cur_route->get_tracks().count(entry_ep.track))
706 // Keep the blocks if we arrived at the end of the route
713 else if(route && route->get_tracks().count(entry_ep.track))
716 bool reserved = link->reserve(this);
719 // Ask a lesser priority train to free the block for us
720 if(link->get_train()->get_priority()<priority)
721 if(link->get_train()->free_block(*link))
722 reserved = link->reserve(this);
726 // If we found another train and it's not headed straight for us, we can keep the blocks we got
727 int other_entry = link->get_train()->get_entry_to_block(*link);
729 throw LogicError("Block reservation inconsistency");
730 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
735 pending_block = link;
740 if(link->get_turnout_id())
742 const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
744 // Keep the blocks reserved so far, as either us or the other train can diverge
748 // Figure out what path we'd like to take on the turnout
751 path = cur_route->get_turnout(link->get_turnout_id());
753 path = entry_ep.track->get_active_path();
754 if(!((track_ep.paths>>path)&1))
756 for(unsigned i=0; track_ep.paths>>i; ++i)
757 if((track_ep.paths>>i)&1)
761 if(path!=static_cast<int>(entry_ep.track->get_active_path()))
763 // The turnout is set to wrong path - switch and wait for it
765 pending_block = link;
766 entry_ep.track->set_active_path(path);
771 rsv_blocks.push_back(BlockRef(link, entry));
772 last = &rsv_blocks.back();
773 if(last->block->get_sensor_id())
780 // Unreserve blocks that were not good
781 while(!rsv_blocks.empty() && last!=good)
783 last->block->reserve(0);
784 rsv_blocks.erase(--rsv_blocks.end());
785 if(!rsv_blocks.empty())
786 last = &rsv_blocks.back();
789 // Make any sensorless blocks at the beginning immediately current
790 list<BlockRef>::iterator i;
791 for(i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !i->block->get_sensor_id()); ++i) ;
792 if(i!=rsv_blocks.begin())
793 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
798 float Train::get_real_speed(unsigned i) const
800 if(real_speed[i].weight)
801 return real_speed[i].speed;
805 for(low=i; low>0; --low)
806 if(real_speed[low].weight)
808 for(high=i; high<14; ++high)
809 if(real_speed[high].weight)
812 if(real_speed[high].weight)
814 if(real_speed[low].weight)
816 float f = float(i-low)/(high-low);
817 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
820 return real_speed[high].speed*float(i)/high;
822 else if(real_speed[low].weight)
823 return real_speed[low].speed*float(i)/low;
828 unsigned Train::find_speed(float real) const
830 if(real<=real_speed[0].speed)
835 for(unsigned i=0; (!high && i<=14); ++i)
836 if(real_speed[i].weight)
838 if(real_speed[i].speed<real)
852 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
855 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
856 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
859 float Train::get_travel_speed() const
861 float speed = get_real_speed(current_speed);
862 float scale = layout.get_catalogue().get_scale();
863 return static_cast<int>(round(speed/scale*3.6/5))*5;
866 void Train::set_status(const string &s)
869 signal_status_changed.emit(s);
872 void Train::release_blocks(list<BlockRef> &blocks)
874 release_blocks(blocks, blocks.begin(), blocks.end());
877 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
881 Block *block = begin->block;
882 blocks.erase(begin++);
887 void Train::reverse_blocks(list<BlockRef> &blocks) const
890 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
891 i->entry = i->block->traverse(i->entry);
895 Train::BlockRef::BlockRef(Block *b, unsigned e):
900 Train::BlockRef Train::BlockRef::next() const
902 Block *blk = block->get_endpoints()[block->traverse(entry)].link;
904 throw InvalidState("At end of line");
906 int ep = blk->get_endpoint_by_link(*block);
908 throw LogicError("Block links are inconsistent");
910 return BlockRef(blk, ep);
914 Train::RealSpeed::RealSpeed():
919 void Train::RealSpeed::add(float s, float w)
921 speed = (speed*weight+s*w)/(weight+w);
922 weight = min(weight+w, 300.0f);
926 Train::Loader::Loader(Train &t):
927 DataFile::BasicLoader<Train>(t),
930 add("block", &Loader::block);
931 add("block_hint", &Loader::block_hint);
932 add("name", &Loader::name);
933 add("priority", &Train::priority);
934 add("real_speed", &Loader::real_speed);
935 add("route", &Loader::route);
936 add("timetable", &Loader::timetable);
937 add("vehicle", &Loader::vehicle);
940 void Train::Loader::block(unsigned id)
942 Block &blk = obj.layout.get_block(id);
945 entry = blk.get_endpoint_by_link(*prev_block);
950 obj.cur_blocks.push_back(BlockRef(&blk, entry));
951 obj.set_status("Stopped");
952 const Block::Endpoint &bep = blk.get_endpoints()[entry];
953 obj.vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
955 if(blk.get_sensor_id())
956 obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
961 void Train::Loader::block_hint(unsigned id)
963 prev_block = &obj.layout.get_block(id);
966 void Train::Loader::name(const string &n)
971 void Train::Loader::real_speed(unsigned i, float speed, float weight)
973 obj.real_speed[i].speed = speed;
974 obj.real_speed[i].weight = weight;
977 void Train::Loader::route(const string &n)
979 obj.set_route(&obj.layout.get_route(n));
982 void Train::Loader::timetable()
985 throw InvalidState("A timetable has already been loaded");
987 obj.timetable = new Timetable(obj);
988 load_sub(*obj.timetable);
991 void Train::Loader::vehicle(unsigned n)
993 const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(n);
994 Vehicle *veh = new Vehicle(obj.layout, vtype);
995 obj.vehicles.back()->attach_back(*veh);
996 obj.vehicles.push_back(veh);
999 } // namespace Marklin