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>
16 #include "tracktype.h"
24 Train::Train(Layout &l, const LocoType &t, unsigned a):
43 layout.add_train(*this);
45 layout.get_driver().add_loco(address);
46 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
47 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
49 layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
50 layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
51 layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
56 layout.remove_train(*this);
59 void Train::set_name(const string &n)
63 signal_name_changed.emit(name);
66 void Train::set_speed(unsigned speed)
68 if(speed==target_speed)
70 travel_speed = static_cast<int>(round(get_real_speed(speed)*87*3.6/5))*5;
76 stop_timeout = Time::now()+(800+current_speed*150)*Time::msec;
81 signal_target_speed_changed.emit(target_speed);
87 void Train::set_reverse(bool rev)
100 layout.get_driver().set_loco_reverse(address, rev);
102 release_blocks(rsv_blocks);
103 reverse_blocks(cur_blocks);
107 unsigned path = cur_track->get_active_path();
108 cur_track_ep = cur_track->traverse(cur_track_ep, path);
109 offset = cur_track->get_type().get_path_length(path)-offset;
113 void Train::set_function(unsigned func, bool state)
115 if(!loco_type.get_functions().count(func))
116 throw InvalidParameterValue("Invalid function");
118 layout.get_driver().set_loco_function(address, func, state);
120 layout.get_driver().set_loco_function(address+1, func-4, state);
123 bool Train::get_function(unsigned func) const
125 return (functions>>func)&1;
128 void Train::set_route(const Route *r)
130 if(!rsv_blocks.empty())
132 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
133 if(i->block->get_sensor_id())
135 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
142 end_of_route = false;
146 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
147 BlockRef next = last.next();
148 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
149 if(!route->get_tracks().count(ep.track))
152 route = Route::find(*ep.track, ep.track_ep, *next_route);
156 if(target_speed && reserve_more()<2)
159 signal_route_changed.emit(route);
162 void Train::go_to(const Track &to)
164 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
165 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
173 if(rsv_blocks.empty())
174 last = &cur_blocks.back();
177 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
178 if(i->block->get_sensor_id())
182 BlockRef next = last->next();
183 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
185 set_route(Route::find(*ep.track, ep.track_ep, to));
188 void Train::place(Block &block, unsigned entry)
193 release_blocks(rsv_blocks);
194 release_blocks(cur_blocks);
196 if(!block.reserve(this))
198 set_status("Unplaced");
202 cur_blocks.push_back(BlockRef(&block, entry));
203 set_position(block.get_endpoints()[entry]);
205 set_status("Stopped");
208 bool Train::free_block(Block &block)
211 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
217 release_blocks(rsv_blocks, i, rsv_blocks.end());
221 else if(i->block->get_sensor_id())
228 int Train::get_entry_to_block(Block &block) const
230 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
233 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
239 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
241 if(stop_timeout && t>=stop_timeout)
243 release_blocks(rsv_blocks);
244 end_of_route = false;
245 stop_timeout = Time::TimeStamp();
250 unsigned path = cur_track->get_active_path();
252 offset += get_real_speed(current_speed)*(dt/Time::sec);
253 float path_len = cur_track->get_type().get_path_length(path);
256 unsigned out = cur_track->traverse(cur_track_ep, path);
257 Track *next = cur_track->get_link(out);
260 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
261 ok = i->block->get_tracks().count(next);
266 cur_track_ep = next->get_endpoint_by_link(*cur_track);
271 offset = path_len-0.001;
275 pos = cur_track->get_point(cur_track_ep, path, offset).pos;
279 void Train::save(list<DataFile::Statement> &st) const
281 st.push_back((DataFile::Statement("name"), name));
282 for(unsigned i=0; i<=14; ++i)
283 if(real_speed[i].weight)
284 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
286 if(!cur_blocks.empty())
288 list<BlockRef> blocks = cur_blocks;
290 reverse_blocks(blocks);
292 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
293 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
295 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
296 st.push_back((DataFile::Statement("block"), i->block->get_id()));
300 st.push_back((DataFile::Statement("route"), route->get_name()));
303 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
307 current_speed = speed;
310 signal_speed_changed.emit(current_speed);
311 signal_reverse_changed.emit(reverse);
315 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
317 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
322 functions |= 1<<func;
324 functions &= ~(1<<func);
326 signal_function_changed.emit(func, state);
330 void Train::sensor_event(unsigned addr, bool state)
334 // Find the first sensor block from our reserved blocks that isn't this sensor
335 list<BlockRef>::iterator i;
336 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
337 if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
340 if(i!=rsv_blocks.begin())
342 // Compute speed and update related state
343 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
344 travel_speed = static_cast<int>(round(travel_dist/travel_time_secs*87*3.6/5))*5;
348 RealSpeed &rs = real_speed[current_speed];
349 rs.add(travel_dist/travel_time_secs, travel_time_secs);
354 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
356 j->block->traverse(j->entry, &block_len);
357 travel_dist += block_len;
359 if(j->block->get_sensor_id()==addr)
360 set_position(j->block->get_endpoints()[j->entry]);
362 last_entry_time = Time::now();
365 // Check if we've reached the next route
368 const set<const Track *> &rtracks = next_route->get_tracks();
369 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
370 if(rtracks.count(j->block->get_endpoints()[j->entry].track))
375 signal_route_changed.emit(route);
380 // Move blocks up to the next sensor to our current blocks
381 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
383 // Try to get more blocks if we're moving
386 unsigned nsens = reserve_more();
387 if(!nsens && end_of_route)
399 // Find the first sensor in our current blocks that's still active
400 list<BlockRef>::iterator end = cur_blocks.begin();
401 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
402 if(i->block->get_sensor_id())
404 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
410 if(end!=cur_blocks.begin())
412 // Free blocks up to the last inactive sensor
414 release_blocks(cur_blocks, cur_blocks.begin(), end);
419 void Train::turnout_event(unsigned addr, bool)
423 unsigned pending_addr = pending_block->get_turnout_id();
424 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
425 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
430 void Train::block_reserved(const Block &block, const Train *train)
432 if(&block==pending_block && !train)
436 unsigned Train::reserve_more()
439 if(!rsv_blocks.empty())
440 last = &rsv_blocks.back();
441 else if(!cur_blocks.empty())
442 last = &cur_blocks.back();
448 // See how many sensor blocks we already have
450 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
451 if(i->block->get_sensor_id())
454 const Route *cur_route = 0;
457 unsigned exit = last->block->traverse(last->entry);
458 Track *track = last->block->get_endpoints()[exit].track;
459 if(route->get_tracks().count(track))
461 else if(next_route && next_route->get_tracks().count(track))
462 cur_route = next_route;
465 bool got_more = false;
466 BlockRef *good = last;
467 unsigned good_sens = nsens;
470 // Traverse to the next block
471 unsigned exit = last->block->traverse(last->entry);
472 Block *link = last->block->get_link(exit);
476 int entry = link->get_endpoint_by_link(*last->block);
478 throw LogicError("Block links are inconsistent!");
480 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
484 if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
485 cur_route = next_route;
486 else if(!cur_route->get_tracks().count(entry_ep.track))
488 // Keep the blocks if we arrived at the end of the route
495 else if(route && route->get_tracks().count(entry_ep.track))
498 if(!link->reserve(this))
500 // If we found another train and it's not headed straight for us, we can keep the blocks we got
501 int other_entry = link->get_train()->get_entry_to_block(*link);
503 throw LogicError("Block reservation inconsistency");
504 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
509 pending_block = link;
513 if(link->get_turnout_id())
515 const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
517 // Keep the blocks reserved so far, as either us or the other train can diverge
521 // Figure out what path we'd like to take on the turnout
524 path = cur_route->get_turnout(link->get_turnout_id());
526 path = entry_ep.track->get_active_path();
527 if(!((track_ep.paths>>path)&1))
529 for(unsigned i=0; track_ep.paths>>i; ++i)
530 if((track_ep.paths>>i)&1)
534 if(path!=static_cast<int>(entry_ep.track->get_active_path()))
536 // The turnout is set to wrong path - switch and wait for it
538 pending_block = link;
539 entry_ep.track->set_active_path(path);
544 rsv_blocks.push_back(BlockRef(link, entry));
545 last = &rsv_blocks.back();
546 if(last->block->get_sensor_id())
553 // Unreserve blocks that were not good
554 while(!rsv_blocks.empty() && last!=good)
556 last->block->reserve(0);
557 rsv_blocks.erase(--rsv_blocks.end());
558 if(!rsv_blocks.empty())
559 last = &rsv_blocks.back();
568 void Train::update_speed()
570 Driver &driver = layout.get_driver();
576 set_status("Stopped");
581 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
582 if(i->block->get_sensor_id())
585 unsigned slow_speed = find_speed(0.1); // 31.3 km/h
590 set_status("Blocked");
592 else if(nsens==1 && target_speed>slow_speed)
600 speed = target_speed;
601 set_status(format("Traveling %d kmh", travel_speed));
605 driver.set_loco_speed(address, speed);
608 float Train::get_real_speed(unsigned i) const
610 if(real_speed[i].weight)
611 return real_speed[i].speed;
615 for(low=i; low>0; --low)
616 if(real_speed[low].weight)
618 for(high=i; high<14; ++high)
619 if(real_speed[high].weight)
622 if(real_speed[high].weight)
624 if(real_speed[low].weight)
626 float f = float(i-low)/(high-low);
627 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
630 return real_speed[high].speed*float(i)/high;
632 else if(real_speed[low].weight)
633 return real_speed[low].speed*float(i)/low;
638 unsigned Train::find_speed(float real) const
640 if(real<=real_speed[0].speed)
645 for(unsigned i=0; (!high && i<=14); ++i)
646 if(real_speed[i].weight)
648 if(real_speed[i].speed<real)
657 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
660 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
661 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
664 void Train::set_status(const string &s)
667 signal_status_changed.emit(s);
670 void Train::set_position(const Block::Endpoint &bep)
672 cur_track = bep.track;
673 cur_track_ep = bep.track_ep;
675 pos = cur_track->get_endpoint_position(cur_track_ep);
678 void Train::release_blocks(list<BlockRef> &blocks)
680 release_blocks(blocks, blocks.begin(), blocks.end());
683 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
687 Block *block = begin->block;
688 blocks.erase(begin++);
693 void Train::reverse_blocks(list<BlockRef> &blocks) const
696 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
697 i->entry = i->block->traverse(i->entry);
701 Train::BlockRef::BlockRef(Block *b, unsigned e):
706 Train::BlockRef Train::BlockRef::next() const
708 Block *blk = block->get_endpoints()[block->traverse(entry)].link;
710 throw InvalidState("At end of line");
712 int ep = blk->get_endpoint_by_link(*block);
714 throw LogicError("Block links are inconsistent");
716 return BlockRef(blk, ep);
720 Train::RealSpeed::RealSpeed():
725 void Train::RealSpeed::add(float s, float w)
727 speed = (speed*weight+s*w)/(weight+w);
728 weight = min(weight+w, 300.0f);
732 Train::Loader::Loader(Train &t):
733 DataFile::BasicLoader<Train>(t),
736 add("block", &Loader::block);
737 add("block_hint", &Loader::block_hint);
738 add("name", &Loader::name);
739 add("real_speed", &Loader::real_speed);
740 add("route", &Loader::route);
743 void Train::Loader::block(unsigned id)
745 Block &blk = obj.layout.get_block(id);
748 entry = blk.get_endpoint_by_link(*prev_block);
753 obj.cur_blocks.push_back(BlockRef(&blk, entry));
754 obj.set_status("Stopped");
755 obj.set_position(blk.get_endpoints()[entry]);
760 void Train::Loader::block_hint(unsigned id)
762 prev_block = &obj.layout.get_block(id);
765 void Train::Loader::name(const string &n)
770 void Train::Loader::real_speed(unsigned i, float speed, float weight)
772 obj.real_speed[i].speed = speed;
773 obj.real_speed[i].weight = weight;
776 void Train::Loader::route(const string &n)
778 obj.set_route(&obj.layout.get_route(n));
781 } // namespace Marklin