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"
25 Train::Train(Layout &l, const LocoType &t, unsigned a):
43 vehicles.push_back(new Vehicle(layout, loco_type));
45 layout.add_train(*this);
47 layout.get_driver().add_loco(address);
48 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
49 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
51 layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
52 layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
53 layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
58 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
60 layout.remove_train(*this);
63 void Train::set_name(const string &n)
67 signal_name_changed.emit(name);
70 Vehicle &Train::get_vehicle(unsigned i)
72 if(i>=vehicles.size())
73 throw InvalidParameterValue("Vehicle index out of range");
77 const Vehicle &Train::get_vehicle(unsigned i) const
79 if(i>=vehicles.size())
80 throw InvalidParameterValue("Vehicle index out of range");
84 void Train::set_speed(unsigned speed)
86 if(speed==target_speed)
88 travel_speed = static_cast<int>(round(get_real_speed(speed)*87*3.6/5))*5;
94 stop_timeout = Time::now()+(800+current_speed*150)*Time::msec;
99 signal_target_speed_changed.emit(target_speed);
105 void Train::set_reverse(bool rev)
115 else if(stop_timeout)
118 layout.get_driver().set_loco_reverse(address, rev);
120 release_blocks(rsv_blocks);
121 reverse_blocks(cur_blocks);
123 // XXX Do something about the vehicles
126 void Train::set_function(unsigned func, bool state)
128 if(!loco_type.get_functions().count(func))
129 throw InvalidParameterValue("Invalid function");
131 layout.get_driver().set_loco_function(address, func, state);
133 layout.get_driver().set_loco_function(address+1, func-4, state);
136 bool Train::get_function(unsigned func) const
138 return (functions>>func)&1;
141 void Train::set_route(const Route *r)
143 if(!rsv_blocks.empty())
145 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
146 if(i->block->get_sensor_id())
148 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
155 end_of_route = false;
159 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
160 BlockRef next = last.next();
161 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
162 if(!route->get_tracks().count(ep.track))
165 route = Route::find(*ep.track, ep.track_ep, *next_route);
169 if(target_speed && reserve_more()<2)
172 signal_route_changed.emit(route);
175 void Train::go_to(const Track &to)
177 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
178 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
186 if(rsv_blocks.empty())
187 last = &cur_blocks.back();
190 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
191 if(i->block->get_sensor_id())
195 BlockRef next = last->next();
196 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
198 set_route(Route::find(*ep.track, ep.track_ep, to));
201 void Train::place(Block &block, unsigned entry)
206 release_blocks(rsv_blocks);
207 release_blocks(cur_blocks);
209 if(!block.reserve(this))
211 set_status("Unplaced");
215 cur_blocks.push_back(BlockRef(&block, entry));
216 set_position(block.get_endpoints()[entry]);
218 set_status("Stopped");
221 bool Train::free_block(Block &block)
224 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
230 release_blocks(rsv_blocks, i, rsv_blocks.end());
234 else if(i->block->get_sensor_id())
241 int Train::get_entry_to_block(Block &block) const
243 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
246 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
252 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
254 if(stop_timeout && t>=stop_timeout)
256 release_blocks(rsv_blocks);
257 end_of_route = false;
258 stop_timeout = Time::TimeStamp();
263 Track *track = vehicles[0]->get_track();
266 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
267 ok = i->block->get_tracks().count(track);
270 vehicles[0]->advance(get_real_speed(current_speed)*(dt/Time::sec));
274 void Train::save(list<DataFile::Statement> &st) const
276 st.push_back((DataFile::Statement("name"), name));
277 for(unsigned i=0; i<=14; ++i)
278 if(real_speed[i].weight)
279 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
281 if(!cur_blocks.empty())
283 list<BlockRef> blocks = cur_blocks;
285 reverse_blocks(blocks);
287 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
288 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
290 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
291 st.push_back((DataFile::Statement("block"), i->block->get_id()));
295 st.push_back((DataFile::Statement("route"), route->get_name()));
298 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
302 current_speed = speed;
305 signal_speed_changed.emit(current_speed);
306 signal_reverse_changed.emit(reverse);
310 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
312 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
317 functions |= 1<<func;
319 functions &= ~(1<<func);
321 signal_function_changed.emit(func, state);
325 void Train::sensor_event(unsigned addr, bool state)
329 // Find the first sensor block from our reserved blocks that isn't this sensor
330 list<BlockRef>::iterator i;
331 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
332 if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
335 if(i!=rsv_blocks.begin())
337 // Compute speed and update related state
338 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
339 travel_speed = static_cast<int>(round(travel_dist/travel_time_secs*87*3.6/5))*5;
343 RealSpeed &rs = real_speed[current_speed];
344 rs.add(travel_dist/travel_time_secs, travel_time_secs);
349 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
351 j->block->traverse(j->entry, &block_len);
352 travel_dist += block_len;
354 if(j->block->get_sensor_id()==addr)
355 set_position(j->block->get_endpoints()[j->entry]);
357 last_entry_time = Time::now();
360 // Check if we've reached the next route
363 const set<const Track *> &rtracks = next_route->get_tracks();
364 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
365 if(rtracks.count(j->block->get_endpoints()[j->entry].track))
370 signal_route_changed.emit(route);
375 // Move blocks up to the next sensor to our current blocks
376 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
378 // Try to get more blocks if we're moving
381 unsigned nsens = reserve_more();
382 if(!nsens && end_of_route)
394 // Find the first sensor in our current blocks that's still active
395 list<BlockRef>::iterator end = cur_blocks.begin();
396 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
397 if(i->block->get_sensor_id())
399 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
405 if(end!=cur_blocks.begin())
407 // Free blocks up to the last inactive sensor
409 release_blocks(cur_blocks, cur_blocks.begin(), end);
414 void Train::turnout_event(unsigned addr, bool)
418 unsigned pending_addr = pending_block->get_turnout_id();
419 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
420 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
425 void Train::block_reserved(const Block &block, const Train *train)
427 if(&block==pending_block && !train)
431 unsigned Train::reserve_more()
434 if(!rsv_blocks.empty())
435 last = &rsv_blocks.back();
436 else if(!cur_blocks.empty())
437 last = &cur_blocks.back();
443 // See how many sensor blocks we already have
445 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
446 if(i->block->get_sensor_id())
449 const Route *cur_route = 0;
452 unsigned exit = last->block->traverse(last->entry);
453 Track *track = last->block->get_endpoints()[exit].track;
454 if(route->get_tracks().count(track))
456 else if(next_route && next_route->get_tracks().count(track))
457 cur_route = next_route;
460 bool got_more = false;
461 BlockRef *good = last;
462 unsigned good_sens = nsens;
465 // Traverse to the next block
466 unsigned exit = last->block->traverse(last->entry);
467 Block *link = last->block->get_link(exit);
471 int entry = link->get_endpoint_by_link(*last->block);
473 throw LogicError("Block links are inconsistent!");
475 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
479 if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
480 cur_route = next_route;
481 else if(!cur_route->get_tracks().count(entry_ep.track))
483 // Keep the blocks if we arrived at the end of the route
490 else if(route && route->get_tracks().count(entry_ep.track))
493 if(!link->reserve(this))
495 // If we found another train and it's not headed straight for us, we can keep the blocks we got
496 int other_entry = link->get_train()->get_entry_to_block(*link);
498 throw LogicError("Block reservation inconsistency");
499 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
504 pending_block = link;
508 if(link->get_turnout_id())
510 const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
512 // Keep the blocks reserved so far, as either us or the other train can diverge
516 // Figure out what path we'd like to take on the turnout
519 path = cur_route->get_turnout(link->get_turnout_id());
521 path = entry_ep.track->get_active_path();
522 if(!((track_ep.paths>>path)&1))
524 for(unsigned i=0; track_ep.paths>>i; ++i)
525 if((track_ep.paths>>i)&1)
529 if(path!=static_cast<int>(entry_ep.track->get_active_path()))
531 // The turnout is set to wrong path - switch and wait for it
533 pending_block = link;
534 entry_ep.track->set_active_path(path);
539 rsv_blocks.push_back(BlockRef(link, entry));
540 last = &rsv_blocks.back();
541 if(last->block->get_sensor_id())
548 // Unreserve blocks that were not good
549 while(!rsv_blocks.empty() && last!=good)
551 last->block->reserve(0);
552 rsv_blocks.erase(--rsv_blocks.end());
553 if(!rsv_blocks.empty())
554 last = &rsv_blocks.back();
563 void Train::update_speed()
565 Driver &driver = layout.get_driver();
571 set_status("Stopped");
576 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
577 if(i->block->get_sensor_id())
580 unsigned slow_speed = find_speed(0.1); // 31.3 km/h
585 set_status("Blocked");
587 else if(nsens==1 && target_speed>slow_speed)
595 speed = target_speed;
596 set_status(format("Traveling %d kmh", travel_speed));
600 driver.set_loco_speed(address, speed);
603 float Train::get_real_speed(unsigned i) const
605 if(real_speed[i].weight)
606 return real_speed[i].speed;
610 for(low=i; low>0; --low)
611 if(real_speed[low].weight)
613 for(high=i; high<14; ++high)
614 if(real_speed[high].weight)
617 if(real_speed[high].weight)
619 if(real_speed[low].weight)
621 float f = float(i-low)/(high-low);
622 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
625 return real_speed[high].speed*float(i)/high;
627 else if(real_speed[low].weight)
628 return real_speed[low].speed*float(i)/low;
633 unsigned Train::find_speed(float real) const
635 if(real<=real_speed[0].speed)
640 for(unsigned i=0; (!high && i<=14); ++i)
641 if(real_speed[i].weight)
643 if(real_speed[i].speed<real)
652 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
655 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
656 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
659 void Train::set_status(const string &s)
662 signal_status_changed.emit(s);
665 void Train::set_position(const Block::Endpoint &bep)
667 vehicles[0]->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
670 void Train::release_blocks(list<BlockRef> &blocks)
672 release_blocks(blocks, blocks.begin(), blocks.end());
675 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
679 Block *block = begin->block;
680 blocks.erase(begin++);
685 void Train::reverse_blocks(list<BlockRef> &blocks) const
688 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
689 i->entry = i->block->traverse(i->entry);
693 Train::BlockRef::BlockRef(Block *b, unsigned e):
698 Train::BlockRef Train::BlockRef::next() const
700 Block *blk = block->get_endpoints()[block->traverse(entry)].link;
702 throw InvalidState("At end of line");
704 int ep = blk->get_endpoint_by_link(*block);
706 throw LogicError("Block links are inconsistent");
708 return BlockRef(blk, ep);
712 Train::RealSpeed::RealSpeed():
717 void Train::RealSpeed::add(float s, float w)
719 speed = (speed*weight+s*w)/(weight+w);
720 weight = min(weight+w, 300.0f);
724 Train::Loader::Loader(Train &t):
725 DataFile::BasicLoader<Train>(t),
728 add("block", &Loader::block);
729 add("block_hint", &Loader::block_hint);
730 add("name", &Loader::name);
731 add("real_speed", &Loader::real_speed);
732 add("route", &Loader::route);
735 void Train::Loader::block(unsigned id)
737 Block &blk = obj.layout.get_block(id);
740 entry = blk.get_endpoint_by_link(*prev_block);
745 obj.cur_blocks.push_back(BlockRef(&blk, entry));
746 obj.set_status("Stopped");
747 obj.set_position(blk.get_endpoints()[entry]);
752 void Train::Loader::block_hint(unsigned id)
754 prev_block = &obj.layout.get_block(id);
757 void Train::Loader::name(const string &n)
762 void Train::Loader::real_speed(unsigned i, float speed, float weight)
764 obj.real_speed[i].speed = speed;
765 obj.real_speed[i].weight = weight;
768 void Train::Loader::route(const string &n)
770 obj.set_route(&obj.layout.get_route(n));
773 } // namespace Marklin