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):
40 layout.add_train(*this);
42 layout.get_driver().add_loco(address);
43 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
44 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
46 layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
47 layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
48 layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
53 layout.remove_train(*this);
56 void Train::set_name(const string &n)
60 signal_name_changed.emit(name);
63 void Train::set_speed(unsigned speed)
65 if(speed==target_speed)
67 travel_speed = static_cast<int>(round(get_real_speed(speed)*87*3.6/5))*5;
73 stop_timeout = Time::now()+(800+current_speed*150)*Time::msec;
78 signal_target_speed_changed.emit(target_speed);
84 void Train::set_reverse(bool rev)
97 layout.get_driver().set_loco_reverse(address, rev);
99 release_blocks(rsv_blocks);
100 reverse_blocks(cur_blocks);
104 unsigned path = cur_track->get_active_path();
105 cur_track_ep = cur_track->traverse(cur_track_ep, path);
106 offset = cur_track->get_type().get_path_length(path)-offset;
110 void Train::set_function(unsigned func, bool state)
112 if(!loco_type.get_functions().count(func))
113 throw InvalidParameterValue("Invalid function");
115 layout.get_driver().set_loco_function(address, func, state);
117 layout.get_driver().set_loco_function(address+1, func-4, state);
120 bool Train::get_function(unsigned func) const
122 return (functions>>func)&1;
125 void Train::set_route(const Route *r)
128 signal_route_changed.emit(route);
131 void Train::place(Block &block, unsigned entry)
136 release_blocks(rsv_blocks);
137 release_blocks(cur_blocks);
139 if(!block.reserve(this))
141 set_status("Unplaced");
145 cur_blocks.push_back(BlockRef(&block, entry));
146 set_position(block.get_endpoints()[entry]);
148 set_status("Stopped");
151 bool Train::free_block(Block &block)
154 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
160 release_blocks(rsv_blocks, i, rsv_blocks.end());
164 else if(i->block->get_sensor_id())
171 int Train::get_entry_to_block(Block &block) const
173 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
176 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
182 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
184 if(stop_timeout && t>=stop_timeout)
186 release_blocks(rsv_blocks);
187 stop_timeout = Time::TimeStamp();
192 unsigned path = cur_track->get_active_path();
194 offset += get_real_speed(current_speed)*(dt/Time::sec);
195 float path_len = cur_track->get_type().get_path_length(path);
198 unsigned out = cur_track->traverse(cur_track_ep, path);
199 Track *next = cur_track->get_link(out);
202 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
203 ok = i->block->get_tracks().count(next);
208 cur_track_ep = next->get_endpoint_by_link(*cur_track);
213 offset = path_len-0.001;
217 pos = cur_track->get_point(cur_track_ep, path, offset).pos;
221 void Train::save(list<DataFile::Statement> &st) const
223 st.push_back((DataFile::Statement("name"), name));
224 for(unsigned i=0; i<=14; ++i)
225 if(real_speed[i].weight)
226 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
228 st.push_back((DataFile::Statement("route"), route->get_name()));
230 if(!cur_blocks.empty())
232 list<BlockRef> blocks = cur_blocks;
234 reverse_blocks(blocks);
236 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
237 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
239 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
240 st.push_back((DataFile::Statement("block"), i->block->get_id()));
244 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
248 current_speed = speed;
251 signal_speed_changed.emit(current_speed);
252 signal_reverse_changed.emit(reverse);
256 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
258 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
263 functions |= 1<<func;
265 functions &= ~(1<<func);
267 signal_function_changed.emit(func, state);
271 void Train::sensor_event(unsigned addr, bool state)
275 // Find the first sensor block from our reserved blocks that isn't this sensor
276 list<BlockRef>::iterator i;
277 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
278 if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
281 if(i!=rsv_blocks.begin())
283 // Compute speed and update related state
284 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
285 travel_speed = static_cast<int>(round(travel_dist/travel_time_secs*87*3.6/5))*5;
289 RealSpeed &rs = real_speed[current_speed];
290 rs.add(travel_dist/travel_time_secs, travel_time_secs);
295 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
297 j->block->traverse(j->entry, &block_len);
298 travel_dist += block_len;
300 if(j->block->get_sensor_id()==addr)
301 set_position(j->block->get_endpoints()[j->entry]);
303 last_entry_time = Time::now();
306 // Move blocks up to the next sensor to our current blocks
307 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
309 // Try to get more blocks if we're moving
310 if(target_speed && reserve_more()<2)
316 // Find the first sensor in our current blocks that's still active
317 list<BlockRef>::iterator end = cur_blocks.begin();
318 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
319 if(i->block->get_sensor_id())
321 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
327 if(end!=cur_blocks.begin())
329 // Free blocks up to the last inactive sensor
331 release_blocks(cur_blocks, cur_blocks.begin(), end);
336 void Train::turnout_event(unsigned addr, bool)
338 if(pending_block && addr==pending_block->get_turnout_id())
342 void Train::block_reserved(const Block &block, const Train *train)
344 if(&block==pending_block && !train)
348 unsigned Train::reserve_more()
351 if(!rsv_blocks.empty())
352 last = &rsv_blocks.back();
353 else if(!cur_blocks.empty())
354 last = &cur_blocks.back();
360 // See how many blocks we already have
362 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
363 if(i->block->get_sensor_id())
366 bool got_more = false;
367 BlockRef *good = last;
368 unsigned good_sens = nsens;
371 // Traverse to the next block
372 unsigned exit = last->block->traverse(last->entry);
373 Block *link = last->block->get_link(exit);
377 int entry = link->get_endpoint_by_link(*last->block);
379 throw LogicError("Block links are inconsistent!");
380 if(!link->reserve(this))
382 // If we found another train and it's not headed straight for us, we can keep the blocks we got
383 int other_entry = link->get_train()->get_entry_to_block(*link);
385 throw LogicError("Block reservation inconsistency");
386 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
391 pending_block = link;
395 if(link->get_turnout_id())
397 const Block::Endpoint &ep = link->get_endpoints()[entry];
398 const Endpoint &track_ep = ep.track->get_type().get_endpoints()[ep.track_ep];
400 // Keep the blocks reserved so far, as either us or the other train can diverge
404 // Figure out what path we'd like to take on the turnout
407 path = route->get_turnout(link->get_turnout_id());
409 path = ep.track->get_active_path();
410 if(!((track_ep.paths>>path)&1))
412 for(unsigned i=0; track_ep.paths>>i; ++i)
413 if((track_ep.paths>>i)&1)
417 if(path!=static_cast<int>(ep.track->get_active_path()))
419 // The turnout is set to wrong path - switch and wait for it
421 pending_block = link;
422 ep.track->set_active_path(path);
427 rsv_blocks.push_back(BlockRef(link, entry));
428 last = &rsv_blocks.back();
429 if(last->block->get_sensor_id())
436 // Unreserve blocks that were not good
437 while(!rsv_blocks.empty() && last!=good)
439 last->block->reserve(0);
440 rsv_blocks.erase(--rsv_blocks.end());
441 if(!rsv_blocks.empty())
442 last = &rsv_blocks.back();
451 void Train::update_speed()
453 Driver &driver = layout.get_driver();
459 set_status("Stopped");
464 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
465 if(i->block->get_sensor_id())
468 unsigned slow_speed = find_speed(0.1); // 31.3 km/h
473 set_status("Blocked");
475 else if(nsens==1 && target_speed>slow_speed)
483 speed = target_speed;
484 set_status(format("Traveling %d kmh", travel_speed));
488 driver.set_loco_speed(address, speed);
491 float Train::get_real_speed(unsigned i) const
493 if(real_speed[i].weight)
494 return real_speed[i].speed;
498 for(low=i; low>0; --low)
499 if(real_speed[low].weight)
501 for(high=i; high<14; ++high)
502 if(real_speed[high].weight)
505 if(real_speed[high].weight)
507 if(real_speed[low].weight)
509 float f = float(i-low)/(high-low);
510 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
513 return real_speed[high].speed*float(i)/high;
515 else if(real_speed[low].weight)
516 return real_speed[low].speed*float(i)/low;
521 unsigned Train::find_speed(float real) const
523 if(real<=real_speed[0].speed)
528 for(unsigned i=0; (!high && i<=14); ++i)
529 if(real_speed[i].weight)
531 if(real_speed[i].speed<real)
540 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
543 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
544 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
547 void Train::set_status(const string &s)
550 signal_status_changed.emit(s);
553 void Train::set_position(const Block::Endpoint &bep)
555 cur_track = bep.track;
556 cur_track_ep = bep.track_ep;
558 pos = cur_track->get_endpoint_position(cur_track_ep);
561 void Train::release_blocks(list<BlockRef> &blocks)
563 release_blocks(blocks, blocks.begin(), blocks.end());
566 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
570 Block *block = begin->block;
571 blocks.erase(begin++);
576 void Train::reverse_blocks(list<BlockRef> &blocks) const
579 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
580 i->entry = i->block->traverse(i->entry);
584 Train::RealSpeed::RealSpeed():
589 void Train::RealSpeed::add(float s, float w)
591 speed = (speed*weight+s*w)/(weight+w);
592 weight = min(weight+w, 300.0f);
596 Train::Loader::Loader(Train &t):
597 DataFile::BasicLoader<Train>(t),
600 add("block", &Loader::block);
601 add("block_hint", &Loader::block_hint);
602 add("name", &Loader::name);
603 add("real_speed", &Loader::real_speed);
604 add("route", &Loader::route);
607 void Train::Loader::block(unsigned id)
609 Block &blk = obj.layout.get_block(id);
612 entry = blk.get_endpoint_by_link(*prev_block);
617 obj.cur_blocks.push_back(BlockRef(&blk, entry));
618 obj.set_status("Stopped");
619 obj.set_position(blk.get_endpoints()[entry]);
624 void Train::Loader::block_hint(unsigned id)
626 prev_block = &obj.layout.get_block(id);
629 void Train::Loader::name(const string &n)
634 void Train::Loader::real_speed(unsigned i, float speed, float weight)
636 obj.real_speed[i].speed = speed;
637 obj.real_speed[i].weight = weight;
640 void Train::Loader::route(const string &n)
642 obj.set_route(&obj.layout.get_route(n));
645 } // namespace Marklin