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 "tracktype.h"
28 Train::Train(Layout &l, const LocoType &t, unsigned a):
33 control(new AIControl(*this, new SimplePhysics)),
36 speed_changing(false),
47 vehicles.push_back(new Vehicle(layout, loco_type));
49 layout.add_train(*this);
51 layout.get_driver().add_loco(address);
52 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
53 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
55 layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
56 layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
57 layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
62 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
64 layout.remove_train(*this);
67 void Train::set_name(const string &n)
71 signal_name_changed.emit(name);
74 Vehicle &Train::get_vehicle(unsigned i)
76 if(i>=vehicles.size())
77 throw InvalidParameterValue("Vehicle index out of range");
81 const Vehicle &Train::get_vehicle(unsigned i) const
83 if(i>=vehicles.size())
84 throw InvalidParameterValue("Vehicle index out of range");
88 void Train::set_control(const string &n, float v)
90 control->set_control(n, v);
91 signal_control_changed.emit(n, control->get_control(n).value);
94 void Train::set_active(bool a)
98 if(!a && control->get_speed())
99 throw InvalidState("Can't deactivate while moving");
104 stop_timeout = Time::TimeStamp();
109 stop_timeout = Time::now()+2*Time::sec;
110 set_status("Stopped");
114 void Train::set_function(unsigned func, bool state)
116 if(!loco_type.get_functions().count(func))
117 throw InvalidParameterValue("Invalid function");
119 layout.get_driver().set_loco_function(address, func, state);
121 layout.get_driver().set_loco_function(address+1, func-4, state);
124 bool Train::get_function(unsigned func) const
126 return (functions>>func)&1;
129 void Train::set_route(const Route *r)
131 if(!rsv_blocks.empty())
133 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
134 if(i->block->get_sensor_id())
136 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
143 end_of_route = false;
147 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
148 BlockRef next = last.next();
149 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
150 if(!route->get_tracks().count(ep.track))
153 route = Route::find(*ep.track, ep.track_ep, *next_route);
160 signal_route_changed.emit(route);
163 void Train::go_to(const Track &to)
165 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
166 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
168 signal_arrived.emit();
174 if(rsv_blocks.empty())
175 last = &cur_blocks.back();
178 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
179 if(i->block->get_sensor_id())
183 BlockRef next = last->next();
184 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
186 set_route(Route::find(*ep.track, ep.track_ep, to));
189 void Train::place(Block &block, unsigned entry)
191 if(control->get_speed())
192 throw InvalidState("Must be stopped before placing");
194 release_blocks(rsv_blocks);
195 release_blocks(cur_blocks);
199 if(!block.reserve(this))
201 set_status("Unplaced");
205 cur_blocks.push_back(BlockRef(&block, entry));
208 unsigned exit = block.traverse(entry);
209 const Block::Endpoint &bep = block.get_endpoints()[exit];
210 Track *track = bep.track->get_link(bep.track_ep);
211 unsigned ep = track->get_endpoint_by_link(*bep.track);
212 vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
216 const Block::Endpoint &bep = block.get_endpoints()[entry];
217 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
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());
233 else if(i->block->get_sensor_id())
240 int Train::get_entry_to_block(Block &block) const
242 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
245 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
251 float Train::get_reserved_distance() const
253 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
254 const VehicleType &vtype = veh.get_type();
256 Track *track = veh.get_track();
257 unsigned entry = veh.get_entry();
259 float result = -vtype.get_length()/2;
262 entry = track->traverse(entry);
263 result += veh.get_offset();
266 result -= veh.get_offset();
269 list<BlockRef>::const_iterator block = cur_blocks.begin();
272 if(!first || !reverse)
273 result += track->get_type().get_path_length(track->get_active_path());
276 unsigned exit = track->traverse(entry);
277 Track *next = track->get_link(exit);
279 while(!block->block->get_tracks().count(next))
282 if(block==cur_blocks.end())
283 block = rsv_blocks.begin();
284 if(block==rsv_blocks.end())
288 entry = next->get_endpoint_by_link(*track);
293 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
295 if(!active && stop_timeout && t>=stop_timeout)
297 release_blocks(rsv_blocks);
298 end_of_route = false;
299 stop_timeout = Time::TimeStamp();
303 float speed = control->get_speed();
304 unsigned speed_notch = find_speed(abs(speed));
306 if(speed && (speed<0)!=reverse)
308 layout.get_driver().set_loco_reverse(address, speed<0);
311 release_blocks(rsv_blocks);
312 reverse_blocks(cur_blocks);
316 if(speed_notch!=current_speed && !speed_changing)
318 speed_changing = true;
319 layout.get_driver().set_loco_speed(address, speed_notch);
324 set_status(format("Traveling %d kmh", get_travel_speed()));
326 set_status("Waiting");
334 Track *track = vehicles[0]->get_track();
337 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
338 ok = i->block->get_tracks().count(track);
342 float d = get_real_speed(current_speed)*(dt/Time::sec);
343 vehicles[0]->advance(reverse ? -d : d);
348 void Train::save(list<DataFile::Statement> &st) const
350 st.push_back((DataFile::Statement("name"), name));
351 for(unsigned i=0; i<=14; ++i)
352 if(real_speed[i].weight)
353 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
355 if(!cur_blocks.empty())
357 list<BlockRef> blocks = cur_blocks;
359 reverse_blocks(blocks);
361 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
362 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
364 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
365 st.push_back((DataFile::Statement("block"), i->block->get_id()));
369 st.push_back((DataFile::Statement("route"), route->get_name()));
372 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
376 current_speed = speed;
377 speed_changing = false;
381 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
383 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
388 functions |= 1<<func;
390 functions &= ~(1<<func);
392 signal_function_changed.emit(func, state);
396 void Train::sensor_event(unsigned addr, bool state)
400 // Find the first sensor block from our reserved blocks that isn't this sensor
401 list<BlockRef>::iterator i;
402 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
403 if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
406 if(i!=rsv_blocks.begin())
408 // Compute speed and update related state
409 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
413 RealSpeed &rs = real_speed[current_speed];
414 rs.add(travel_dist/travel_time_secs, travel_time_secs);
415 set_status(format("Traveling %d kmh", get_travel_speed()));
420 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
422 j->block->traverse(j->entry, &block_len);
423 travel_dist += block_len;
425 if(j->block->get_sensor_id()==addr)
427 const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
430 Track *track = bep.track->get_link(bep.track_ep);
431 unsigned ep = track->get_endpoint_by_link(*bep.track);
432 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
435 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
438 last_entry_time = Time::now();
441 // Check if we've reached the next route
444 const set<const Track *> &rtracks = next_route->get_tracks();
445 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
446 if(rtracks.count(j->block->get_endpoints()[j->entry].track))
451 signal_route_changed.emit(route);
456 // Move blocks up to the next sensor to our current blocks
457 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
459 // Try to get more blocks if we're moving
462 unsigned nsens = reserve_more();
463 if(!nsens && end_of_route)
465 signal_arrived.emit();
473 // Find the first sensor in our current blocks that's still active
474 list<BlockRef>::iterator end = cur_blocks.begin();
475 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
476 if(i->block->get_sensor_id())
478 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
484 if(end!=cur_blocks.begin())
486 // Free blocks up to the last inactive sensor
488 release_blocks(cur_blocks, cur_blocks.begin(), end);
493 void Train::turnout_event(unsigned addr, bool)
497 unsigned pending_addr = pending_block->get_turnout_id();
498 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
499 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
504 void Train::block_reserved(const Block &block, const Train *train)
506 if(&block==pending_block && !train)
510 unsigned Train::reserve_more()
513 if(!rsv_blocks.empty())
514 last = &rsv_blocks.back();
515 else if(!cur_blocks.empty())
516 last = &cur_blocks.back();
522 // See how many sensor blocks we already have
524 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
525 if(i->block->get_sensor_id())
528 const Route *cur_route = 0;
531 unsigned exit = last->block->traverse(last->entry);
532 Track *track = last->block->get_endpoints()[exit].track;
533 if(route->get_tracks().count(track))
535 else if(next_route && next_route->get_tracks().count(track))
536 cur_route = next_route;
539 bool got_more = false;
540 BlockRef *good = last;
541 unsigned good_sens = nsens;
544 // Traverse to the next block
545 unsigned exit = last->block->traverse(last->entry);
546 Block *link = last->block->get_link(exit);
550 int entry = link->get_endpoint_by_link(*last->block);
552 throw LogicError("Block links are inconsistent!");
554 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
558 if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
559 cur_route = next_route;
560 else if(!cur_route->get_tracks().count(entry_ep.track))
562 // Keep the blocks if we arrived at the end of the route
569 else if(route && route->get_tracks().count(entry_ep.track))
572 if(!link->reserve(this))
574 // If we found another train and it's not headed straight for us, we can keep the blocks we got
575 int other_entry = link->get_train()->get_entry_to_block(*link);
577 throw LogicError("Block reservation inconsistency");
578 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
583 pending_block = link;
587 if(link->get_turnout_id())
589 const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
591 // Keep the blocks reserved so far, as either us or the other train can diverge
595 // Figure out what path we'd like to take on the turnout
598 path = cur_route->get_turnout(link->get_turnout_id());
600 path = entry_ep.track->get_active_path();
601 if(!((track_ep.paths>>path)&1))
603 for(unsigned i=0; track_ep.paths>>i; ++i)
604 if((track_ep.paths>>i)&1)
608 if(path!=static_cast<int>(entry_ep.track->get_active_path()))
610 // The turnout is set to wrong path - switch and wait for it
612 pending_block = link;
613 entry_ep.track->set_active_path(path);
618 rsv_blocks.push_back(BlockRef(link, entry));
619 last = &rsv_blocks.back();
620 if(last->block->get_sensor_id())
627 // Unreserve blocks that were not good
628 while(!rsv_blocks.empty() && last!=good)
630 last->block->reserve(0);
631 rsv_blocks.erase(--rsv_blocks.end());
632 if(!rsv_blocks.empty())
633 last = &rsv_blocks.back();
639 float Train::get_real_speed(unsigned i) const
641 if(real_speed[i].weight)
642 return real_speed[i].speed;
646 for(low=i; low>0; --low)
647 if(real_speed[low].weight)
649 for(high=i; high<14; ++high)
650 if(real_speed[high].weight)
653 if(real_speed[high].weight)
655 if(real_speed[low].weight)
657 float f = float(i-low)/(high-low);
658 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
661 return real_speed[high].speed*float(i)/high;
663 else if(real_speed[low].weight)
664 return real_speed[low].speed*float(i)/low;
669 unsigned Train::find_speed(float real) const
671 if(real<=real_speed[0].speed)
676 for(unsigned i=0; (!high && i<=14); ++i)
677 if(real_speed[i].weight)
679 if(real_speed[i].speed<real)
688 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
691 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
692 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
695 float Train::get_travel_speed() const
697 float speed = get_real_speed(current_speed);
698 float scale = layout.get_catalogue().get_scale();
699 return static_cast<int>(round(speed/scale*3.6/5))*5;
702 void Train::set_status(const string &s)
705 signal_status_changed.emit(s);
708 void Train::release_blocks(list<BlockRef> &blocks)
710 release_blocks(blocks, blocks.begin(), blocks.end());
713 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
717 Block *block = begin->block;
718 blocks.erase(begin++);
723 void Train::reverse_blocks(list<BlockRef> &blocks) const
726 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
727 i->entry = i->block->traverse(i->entry);
731 Train::BlockRef::BlockRef(Block *b, unsigned e):
736 Train::BlockRef Train::BlockRef::next() const
738 Block *blk = block->get_endpoints()[block->traverse(entry)].link;
740 throw InvalidState("At end of line");
742 int ep = blk->get_endpoint_by_link(*block);
744 throw LogicError("Block links are inconsistent");
746 return BlockRef(blk, ep);
750 Train::RealSpeed::RealSpeed():
755 void Train::RealSpeed::add(float s, float w)
757 speed = (speed*weight+s*w)/(weight+w);
758 weight = min(weight+w, 300.0f);
762 Train::Loader::Loader(Train &t):
763 DataFile::BasicLoader<Train>(t),
766 add("block", &Loader::block);
767 add("block_hint", &Loader::block_hint);
768 add("name", &Loader::name);
769 add("real_speed", &Loader::real_speed);
770 add("route", &Loader::route);
773 void Train::Loader::block(unsigned id)
775 Block &blk = obj.layout.get_block(id);
778 entry = blk.get_endpoint_by_link(*prev_block);
783 obj.cur_blocks.push_back(BlockRef(&blk, entry));
784 obj.set_status("Stopped");
785 const Block::Endpoint &bep = blk.get_endpoints()[entry];
786 obj.vehicles.back()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
788 if(blk.get_sensor_id())
789 obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
794 void Train::Loader::block_hint(unsigned id)
796 prev_block = &obj.layout.get_block(id);
799 void Train::Loader::name(const string &n)
804 void Train::Loader::real_speed(unsigned i, float speed, float weight)
806 obj.real_speed[i].speed = speed;
807 obj.real_speed[i].weight = weight;
810 void Train::Loader::route(const string &n)
812 obj.set_route(&obj.layout.get_route(n));
815 } // namespace Marklin