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),
49 vehicles.push_back(new Vehicle(layout, loco_type));
51 layout.add_train(*this);
53 layout.get_driver().add_loco(address);
54 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
55 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
57 layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
58 layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
59 layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
61 control->signal_control_changed.connect(signal_control_changed);
66 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
68 layout.remove_train(*this);
71 void Train::set_name(const string &n)
75 signal_name_changed.emit(name);
78 Vehicle &Train::get_vehicle(unsigned i)
80 if(i>=vehicles.size())
81 throw InvalidParameterValue("Vehicle index out of range");
85 const Vehicle &Train::get_vehicle(unsigned i) const
87 if(i>=vehicles.size())
88 throw InvalidParameterValue("Vehicle index out of range");
92 void Train::set_control(const string &n, float v)
94 control->set_control(n, v);
97 void Train::set_active(bool a)
101 if(!a && control->get_speed())
102 throw InvalidState("Can't deactivate while moving");
107 stop_timeout = Time::TimeStamp();
112 stop_timeout = Time::now()+2*Time::sec;
113 set_status("Stopped");
117 void Train::set_function(unsigned func, bool state)
119 if(!loco_type.get_functions().count(func))
120 throw InvalidParameterValue("Invalid function");
122 layout.get_driver().set_loco_function(address, func, state);
124 layout.get_driver().set_loco_function(address+1, func-4, state);
127 bool Train::get_function(unsigned func) const
129 return (functions>>func)&1;
132 void Train::set_route(const Route *r)
134 if(!rsv_blocks.empty())
136 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
137 if(i->block->get_sensor_id())
139 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
146 end_of_route = false;
150 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
151 BlockRef next = last.next();
152 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
153 if(!route->get_tracks().count(ep.track))
156 route = Route::find(*ep.track, ep.track_ep, *next_route);
163 signal_route_changed.emit(route);
166 void Train::go_to(const Track &to)
168 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
169 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
171 signal_arrived.emit();
177 if(rsv_blocks.empty())
178 last = &cur_blocks.back();
181 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
182 if(i->block->get_sensor_id())
186 BlockRef next = last->next();
187 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
189 set_route(Route::find(*ep.track, ep.track_ep, to));
192 void Train::place(Block &block, unsigned entry)
194 if(control->get_speed())
195 throw InvalidState("Must be stopped before placing");
197 release_blocks(rsv_blocks);
198 release_blocks(cur_blocks);
202 if(!block.reserve(this))
204 set_status("Unplaced");
208 cur_blocks.push_back(BlockRef(&block, entry));
211 unsigned exit = block.traverse(entry);
212 const Block::Endpoint &bep = block.get_endpoints()[exit];
213 Track *track = bep.track->get_link(bep.track_ep);
214 unsigned ep = track->get_endpoint_by_link(*bep.track);
215 vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
219 const Block::Endpoint &bep = block.get_endpoints()[entry];
220 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
224 bool Train::free_block(Block &block)
227 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
233 release_blocks(rsv_blocks, i, rsv_blocks.end());
236 else if(i->block->get_sensor_id())
243 int Train::get_entry_to_block(Block &block) const
245 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
248 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
254 float Train::get_reserved_distance() const
256 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
257 const VehicleType &vtype = veh.get_type();
259 Track *track = veh.get_track();
260 unsigned entry = veh.get_entry();
262 float result = -vtype.get_length()/2;
265 entry = track->traverse(entry);
266 result += veh.get_offset();
269 result -= veh.get_offset();
272 list<BlockRef>::const_iterator block = cur_blocks.begin();
275 if(!first || !reverse)
276 result += track->get_type().get_path_length(track->get_active_path());
279 unsigned exit = track->traverse(entry);
280 Track *next = track->get_link(exit);
282 while(!block->block->get_tracks().count(next))
285 if(block==cur_blocks.end())
286 block = rsv_blocks.begin();
287 if(block==rsv_blocks.end())
291 entry = next->get_endpoint_by_link(*track);
296 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
298 if(!active && stop_timeout && t>=stop_timeout)
300 release_blocks(rsv_blocks);
301 end_of_route = false;
302 stop_timeout = Time::TimeStamp();
308 float speed = control->get_speed();
309 unsigned speed_notch = find_speed(abs(speed));
311 if(speed && (speed<0)!=reverse)
313 layout.get_driver().set_loco_reverse(address, speed<0);
316 release_blocks(rsv_blocks);
317 reverse_blocks(cur_blocks);
321 if(speed_notch!=current_speed && !speed_changing)
323 speed_changing = true;
324 layout.get_driver().set_loco_speed(address, speed_notch);
329 set_status(format("Traveling %d kmh", get_travel_speed()));
331 set_status("Waiting");
339 Track *track = vehicles[0]->get_track();
342 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
343 ok = i->block->get_tracks().count(track);
347 float d = get_real_speed(current_speed)*(dt/Time::sec);
348 vehicles[0]->advance(reverse ? -d : d);
351 else if(end_of_route)
355 void Train::save(list<DataFile::Statement> &st) const
357 st.push_back((DataFile::Statement("name"), name));
358 for(unsigned i=0; i<=14; ++i)
359 if(real_speed[i].weight)
360 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
362 if(!cur_blocks.empty())
364 list<BlockRef> blocks = cur_blocks;
366 reverse_blocks(blocks);
368 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
369 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
371 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
372 st.push_back((DataFile::Statement("block"), i->block->get_id()));
376 st.push_back((DataFile::Statement("route"), route->get_name()));
380 DataFile::Statement ss("timetable");
381 timetable->save(ss.sub);
386 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
390 current_speed = speed;
391 speed_changing = false;
395 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
397 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
402 functions |= 1<<func;
404 functions &= ~(1<<func);
406 signal_function_changed.emit(func, state);
410 void Train::sensor_event(unsigned addr, bool state)
414 // Find the first sensor block from our reserved blocks that isn't this sensor
415 list<BlockRef>::iterator i;
416 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
417 if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
420 if(i!=rsv_blocks.begin())
422 // Compute speed and update related state
423 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
427 RealSpeed &rs = real_speed[current_speed];
428 rs.add(travel_dist/travel_time_secs, travel_time_secs);
429 set_status(format("Traveling %d kmh", get_travel_speed()));
434 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
436 j->block->traverse(j->entry, &block_len);
437 travel_dist += block_len;
439 if(j->block->get_sensor_id()==addr)
441 const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
444 Track *track = bep.track->get_link(bep.track_ep);
445 unsigned ep = track->get_endpoint_by_link(*bep.track);
446 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
449 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
452 last_entry_time = Time::now();
455 // Check if we've reached the next route
458 const set<const Track *> &rtracks = next_route->get_tracks();
459 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
460 if(rtracks.count(j->block->get_endpoints()[j->entry].track))
465 signal_route_changed.emit(route);
470 // Move blocks up to the next sensor to our current blocks
471 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
473 // Try to get more blocks if we're moving
476 unsigned nsens = reserve_more();
477 if(!nsens && end_of_route)
478 signal_arrived.emit();
484 // Find the first sensor in our current blocks that's still active
485 list<BlockRef>::iterator end = cur_blocks.begin();
486 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
487 if(i->block->get_sensor_id())
489 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
495 if(end!=cur_blocks.begin())
497 // Free blocks up to the last inactive sensor
499 release_blocks(cur_blocks, cur_blocks.begin(), end);
504 void Train::turnout_event(unsigned addr, bool)
508 unsigned pending_addr = pending_block->get_turnout_id();
509 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
510 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
515 void Train::block_reserved(const Block &block, const Train *train)
517 if(&block==pending_block && !train)
521 unsigned Train::reserve_more()
524 if(!rsv_blocks.empty())
525 last = &rsv_blocks.back();
526 else if(!cur_blocks.empty())
527 last = &cur_blocks.back();
533 // See how many sensor blocks we already have
535 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
536 if(i->block->get_sensor_id())
542 const Route *cur_route = 0;
545 const set<Track *> &tracks = last->block->get_tracks();
546 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
548 if(route->get_tracks().count(*i))
550 else if(next_route && next_route->get_tracks().count(*i))
551 cur_route = next_route;
555 bool got_more = false;
556 BlockRef *good = last;
557 unsigned good_sens = nsens;
560 // Traverse to the next block
561 unsigned exit = last->block->traverse(last->entry);
562 Block *link = last->block->get_link(exit);
566 int entry = link->get_endpoint_by_link(*last->block);
568 throw LogicError("Block links are inconsistent!");
570 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
574 if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
575 cur_route = next_route;
576 else if(!cur_route->get_tracks().count(entry_ep.track))
578 // Keep the blocks if we arrived at the end of the route
585 else if(route && route->get_tracks().count(entry_ep.track))
588 if(!link->reserve(this))
590 // If we found another train and it's not headed straight for us, we can keep the blocks we got
591 int other_entry = link->get_train()->get_entry_to_block(*link);
593 throw LogicError("Block reservation inconsistency");
594 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
599 pending_block = link;
603 if(link->get_turnout_id())
605 const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
607 // Keep the blocks reserved so far, as either us or the other train can diverge
611 // Figure out what path we'd like to take on the turnout
614 path = cur_route->get_turnout(link->get_turnout_id());
616 path = entry_ep.track->get_active_path();
617 if(!((track_ep.paths>>path)&1))
619 for(unsigned i=0; track_ep.paths>>i; ++i)
620 if((track_ep.paths>>i)&1)
624 if(path!=static_cast<int>(entry_ep.track->get_active_path()))
626 // The turnout is set to wrong path - switch and wait for it
628 pending_block = link;
629 entry_ep.track->set_active_path(path);
634 rsv_blocks.push_back(BlockRef(link, entry));
635 last = &rsv_blocks.back();
636 if(last->block->get_sensor_id())
643 // Unreserve blocks that were not good
644 while(!rsv_blocks.empty() && last!=good)
646 last->block->reserve(0);
647 rsv_blocks.erase(--rsv_blocks.end());
648 if(!rsv_blocks.empty())
649 last = &rsv_blocks.back();
655 float Train::get_real_speed(unsigned i) const
657 if(real_speed[i].weight)
658 return real_speed[i].speed;
662 for(low=i; low>0; --low)
663 if(real_speed[low].weight)
665 for(high=i; high<14; ++high)
666 if(real_speed[high].weight)
669 if(real_speed[high].weight)
671 if(real_speed[low].weight)
673 float f = float(i-low)/(high-low);
674 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
677 return real_speed[high].speed*float(i)/high;
679 else if(real_speed[low].weight)
680 return real_speed[low].speed*float(i)/low;
685 unsigned Train::find_speed(float real) const
687 if(real<=real_speed[0].speed)
692 for(unsigned i=0; (!high && i<=14); ++i)
693 if(real_speed[i].weight)
695 if(real_speed[i].speed<real)
704 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
707 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
708 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
711 float Train::get_travel_speed() const
713 float speed = get_real_speed(current_speed);
714 float scale = layout.get_catalogue().get_scale();
715 return static_cast<int>(round(speed/scale*3.6/5))*5;
718 void Train::set_status(const string &s)
721 signal_status_changed.emit(s);
724 void Train::release_blocks(list<BlockRef> &blocks)
726 release_blocks(blocks, blocks.begin(), blocks.end());
729 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
733 Block *block = begin->block;
734 blocks.erase(begin++);
739 void Train::reverse_blocks(list<BlockRef> &blocks) const
742 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
743 i->entry = i->block->traverse(i->entry);
747 Train::BlockRef::BlockRef(Block *b, unsigned e):
752 Train::BlockRef Train::BlockRef::next() const
754 Block *blk = block->get_endpoints()[block->traverse(entry)].link;
756 throw InvalidState("At end of line");
758 int ep = blk->get_endpoint_by_link(*block);
760 throw LogicError("Block links are inconsistent");
762 return BlockRef(blk, ep);
766 Train::RealSpeed::RealSpeed():
771 void Train::RealSpeed::add(float s, float w)
773 speed = (speed*weight+s*w)/(weight+w);
774 weight = min(weight+w, 300.0f);
778 Train::Loader::Loader(Train &t):
779 DataFile::BasicLoader<Train>(t),
782 add("block", &Loader::block);
783 add("block_hint", &Loader::block_hint);
784 add("name", &Loader::name);
785 add("real_speed", &Loader::real_speed);
786 add("route", &Loader::route);
787 add("timetable", &Loader::timetable);
790 void Train::Loader::block(unsigned id)
792 Block &blk = obj.layout.get_block(id);
795 entry = blk.get_endpoint_by_link(*prev_block);
800 obj.cur_blocks.push_back(BlockRef(&blk, entry));
801 obj.set_status("Stopped");
802 const Block::Endpoint &bep = blk.get_endpoints()[entry];
803 obj.vehicles.back()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
805 if(blk.get_sensor_id())
806 obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
811 void Train::Loader::block_hint(unsigned id)
813 prev_block = &obj.layout.get_block(id);
816 void Train::Loader::name(const string &n)
821 void Train::Loader::real_speed(unsigned i, float speed, float weight)
823 obj.real_speed[i].speed = speed;
824 obj.real_speed[i].weight = weight;
827 void Train::Loader::route(const string &n)
829 obj.set_route(&obj.layout.get_route(n));
832 void Train::Loader::timetable()
835 throw InvalidState("A timetable has already been loaded");
837 obj.timetable = new Timetable(obj);
838 load_sub(*obj.timetable);
841 } // namespace Marklin