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));
64 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
66 layout.remove_train(*this);
69 void Train::set_name(const string &n)
73 signal_name_changed.emit(name);
76 Vehicle &Train::get_vehicle(unsigned i)
78 if(i>=vehicles.size())
79 throw InvalidParameterValue("Vehicle index out of range");
83 const Vehicle &Train::get_vehicle(unsigned i) const
85 if(i>=vehicles.size())
86 throw InvalidParameterValue("Vehicle index out of range");
90 void Train::set_control(const string &n, float v)
92 control->set_control(n, v);
93 signal_control_changed.emit(n, control->get_control(n).value);
96 void Train::set_active(bool a)
100 if(!a && control->get_speed())
101 throw InvalidState("Can't deactivate while moving");
106 stop_timeout = Time::TimeStamp();
111 stop_timeout = Time::now()+2*Time::sec;
112 set_status("Stopped");
116 void Train::set_function(unsigned func, bool state)
118 if(!loco_type.get_functions().count(func))
119 throw InvalidParameterValue("Invalid function");
121 layout.get_driver().set_loco_function(address, func, state);
123 layout.get_driver().set_loco_function(address+1, func-4, state);
126 bool Train::get_function(unsigned func) const
128 return (functions>>func)&1;
131 void Train::set_route(const Route *r)
133 if(!rsv_blocks.empty())
135 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
136 if(i->block->get_sensor_id())
138 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
145 end_of_route = false;
149 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
150 BlockRef next = last.next();
151 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
152 if(!route->get_tracks().count(ep.track))
155 route = Route::find(*ep.track, ep.track_ep, *next_route);
162 signal_route_changed.emit(route);
165 void Train::go_to(const Track &to)
167 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
168 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
170 signal_arrived.emit();
176 if(rsv_blocks.empty())
177 last = &cur_blocks.back();
180 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
181 if(i->block->get_sensor_id())
185 BlockRef next = last->next();
186 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
188 set_route(Route::find(*ep.track, ep.track_ep, to));
191 void Train::place(Block &block, unsigned entry)
193 if(control->get_speed())
194 throw InvalidState("Must be stopped before placing");
196 release_blocks(rsv_blocks);
197 release_blocks(cur_blocks);
201 if(!block.reserve(this))
203 set_status("Unplaced");
207 cur_blocks.push_back(BlockRef(&block, entry));
210 unsigned exit = block.traverse(entry);
211 const Block::Endpoint &bep = block.get_endpoints()[exit];
212 Track *track = bep.track->get_link(bep.track_ep);
213 unsigned ep = track->get_endpoint_by_link(*bep.track);
214 vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
218 const Block::Endpoint &bep = block.get_endpoints()[entry];
219 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
223 bool Train::free_block(Block &block)
226 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
232 release_blocks(rsv_blocks, i, rsv_blocks.end());
235 else if(i->block->get_sensor_id())
242 int Train::get_entry_to_block(Block &block) const
244 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
247 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
253 float Train::get_reserved_distance() const
255 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
256 const VehicleType &vtype = veh.get_type();
258 Track *track = veh.get_track();
259 unsigned entry = veh.get_entry();
261 float result = -vtype.get_length()/2;
264 entry = track->traverse(entry);
265 result += veh.get_offset();
268 result -= veh.get_offset();
271 list<BlockRef>::const_iterator block = cur_blocks.begin();
274 if(!first || !reverse)
275 result += track->get_type().get_path_length(track->get_active_path());
278 unsigned exit = track->traverse(entry);
279 Track *next = track->get_link(exit);
281 while(!block->block->get_tracks().count(next))
284 if(block==cur_blocks.end())
285 block = rsv_blocks.begin();
286 if(block==rsv_blocks.end())
290 entry = next->get_endpoint_by_link(*track);
295 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
297 if(!active && stop_timeout && t>=stop_timeout)
299 release_blocks(rsv_blocks);
300 end_of_route = false;
301 stop_timeout = Time::TimeStamp();
307 float speed = control->get_speed();
308 unsigned speed_notch = find_speed(abs(speed));
310 if(speed && (speed<0)!=reverse)
312 layout.get_driver().set_loco_reverse(address, speed<0);
315 release_blocks(rsv_blocks);
316 reverse_blocks(cur_blocks);
320 if(speed_notch!=current_speed && !speed_changing)
322 speed_changing = true;
323 layout.get_driver().set_loco_speed(address, speed_notch);
328 set_status(format("Traveling %d kmh", get_travel_speed()));
330 set_status("Waiting");
338 Track *track = vehicles[0]->get_track();
341 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
342 ok = i->block->get_tracks().count(track);
346 float d = get_real_speed(current_speed)*(dt/Time::sec);
347 vehicles[0]->advance(reverse ? -d : d);
350 else if(end_of_route)
354 void Train::save(list<DataFile::Statement> &st) const
356 st.push_back((DataFile::Statement("name"), name));
357 for(unsigned i=0; i<=14; ++i)
358 if(real_speed[i].weight)
359 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
361 if(!cur_blocks.empty())
363 list<BlockRef> blocks = cur_blocks;
365 reverse_blocks(blocks);
367 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
368 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
370 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
371 st.push_back((DataFile::Statement("block"), i->block->get_id()));
375 st.push_back((DataFile::Statement("route"), route->get_name()));
379 DataFile::Statement ss("timetable");
380 timetable->save(ss.sub);
385 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
389 current_speed = speed;
390 speed_changing = false;
394 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
396 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
401 functions |= 1<<func;
403 functions &= ~(1<<func);
405 signal_function_changed.emit(func, state);
409 void Train::sensor_event(unsigned addr, bool state)
413 // Find the first sensor block from our reserved blocks that isn't this sensor
414 list<BlockRef>::iterator i;
415 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
416 if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
419 if(i!=rsv_blocks.begin())
421 // Compute speed and update related state
422 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
426 RealSpeed &rs = real_speed[current_speed];
427 rs.add(travel_dist/travel_time_secs, travel_time_secs);
428 set_status(format("Traveling %d kmh", get_travel_speed()));
433 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
435 j->block->traverse(j->entry, &block_len);
436 travel_dist += block_len;
438 if(j->block->get_sensor_id()==addr)
440 const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
443 Track *track = bep.track->get_link(bep.track_ep);
444 unsigned ep = track->get_endpoint_by_link(*bep.track);
445 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
448 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
451 last_entry_time = Time::now();
454 // Check if we've reached the next route
457 const set<const Track *> &rtracks = next_route->get_tracks();
458 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
459 if(rtracks.count(j->block->get_endpoints()[j->entry].track))
464 signal_route_changed.emit(route);
469 // Move blocks up to the next sensor to our current blocks
470 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
472 // Try to get more blocks if we're moving
475 unsigned nsens = reserve_more();
476 if(!nsens && end_of_route)
477 signal_arrived.emit();
483 // Find the first sensor in our current blocks that's still active
484 list<BlockRef>::iterator end = cur_blocks.begin();
485 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
486 if(i->block->get_sensor_id())
488 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
494 if(end!=cur_blocks.begin())
496 // Free blocks up to the last inactive sensor
498 release_blocks(cur_blocks, cur_blocks.begin(), end);
503 void Train::turnout_event(unsigned addr, bool)
507 unsigned pending_addr = pending_block->get_turnout_id();
508 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
509 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
514 void Train::block_reserved(const Block &block, const Train *train)
516 if(&block==pending_block && !train)
520 unsigned Train::reserve_more()
523 if(!rsv_blocks.empty())
524 last = &rsv_blocks.back();
525 else if(!cur_blocks.empty())
526 last = &cur_blocks.back();
532 // See how many sensor blocks we already have
534 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
535 if(i->block->get_sensor_id())
541 const Route *cur_route = 0;
544 const set<Track *> &tracks = last->block->get_tracks();
545 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
547 if(route->get_tracks().count(*i))
549 else if(next_route && next_route->get_tracks().count(*i))
550 cur_route = next_route;
554 bool got_more = false;
555 BlockRef *good = last;
556 unsigned good_sens = nsens;
559 // Traverse to the next block
560 unsigned exit = last->block->traverse(last->entry);
561 Block *link = last->block->get_link(exit);
565 int entry = link->get_endpoint_by_link(*last->block);
567 throw LogicError("Block links are inconsistent!");
569 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
573 if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
574 cur_route = next_route;
575 else if(!cur_route->get_tracks().count(entry_ep.track))
577 // Keep the blocks if we arrived at the end of the route
584 else if(route && route->get_tracks().count(entry_ep.track))
587 if(!link->reserve(this))
589 // If we found another train and it's not headed straight for us, we can keep the blocks we got
590 int other_entry = link->get_train()->get_entry_to_block(*link);
592 throw LogicError("Block reservation inconsistency");
593 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
598 pending_block = link;
602 if(link->get_turnout_id())
604 const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
606 // Keep the blocks reserved so far, as either us or the other train can diverge
610 // Figure out what path we'd like to take on the turnout
613 path = cur_route->get_turnout(link->get_turnout_id());
615 path = entry_ep.track->get_active_path();
616 if(!((track_ep.paths>>path)&1))
618 for(unsigned i=0; track_ep.paths>>i; ++i)
619 if((track_ep.paths>>i)&1)
623 if(path!=static_cast<int>(entry_ep.track->get_active_path()))
625 // The turnout is set to wrong path - switch and wait for it
627 pending_block = link;
628 entry_ep.track->set_active_path(path);
633 rsv_blocks.push_back(BlockRef(link, entry));
634 last = &rsv_blocks.back();
635 if(last->block->get_sensor_id())
642 // Unreserve blocks that were not good
643 while(!rsv_blocks.empty() && last!=good)
645 last->block->reserve(0);
646 rsv_blocks.erase(--rsv_blocks.end());
647 if(!rsv_blocks.empty())
648 last = &rsv_blocks.back();
654 float Train::get_real_speed(unsigned i) const
656 if(real_speed[i].weight)
657 return real_speed[i].speed;
661 for(low=i; low>0; --low)
662 if(real_speed[low].weight)
664 for(high=i; high<14; ++high)
665 if(real_speed[high].weight)
668 if(real_speed[high].weight)
670 if(real_speed[low].weight)
672 float f = float(i-low)/(high-low);
673 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
676 return real_speed[high].speed*float(i)/high;
678 else if(real_speed[low].weight)
679 return real_speed[low].speed*float(i)/low;
684 unsigned Train::find_speed(float real) const
686 if(real<=real_speed[0].speed)
691 for(unsigned i=0; (!high && i<=14); ++i)
692 if(real_speed[i].weight)
694 if(real_speed[i].speed<real)
703 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
706 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
707 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
710 float Train::get_travel_speed() const
712 float speed = get_real_speed(current_speed);
713 float scale = layout.get_catalogue().get_scale();
714 return static_cast<int>(round(speed/scale*3.6/5))*5;
717 void Train::set_status(const string &s)
720 signal_status_changed.emit(s);
723 void Train::release_blocks(list<BlockRef> &blocks)
725 release_blocks(blocks, blocks.begin(), blocks.end());
728 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
732 Block *block = begin->block;
733 blocks.erase(begin++);
738 void Train::reverse_blocks(list<BlockRef> &blocks) const
741 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
742 i->entry = i->block->traverse(i->entry);
746 Train::BlockRef::BlockRef(Block *b, unsigned e):
751 Train::BlockRef Train::BlockRef::next() const
753 Block *blk = block->get_endpoints()[block->traverse(entry)].link;
755 throw InvalidState("At end of line");
757 int ep = blk->get_endpoint_by_link(*block);
759 throw LogicError("Block links are inconsistent");
761 return BlockRef(blk, ep);
765 Train::RealSpeed::RealSpeed():
770 void Train::RealSpeed::add(float s, float w)
772 speed = (speed*weight+s*w)/(weight+w);
773 weight = min(weight+w, 300.0f);
777 Train::Loader::Loader(Train &t):
778 DataFile::BasicLoader<Train>(t),
781 add("block", &Loader::block);
782 add("block_hint", &Loader::block_hint);
783 add("name", &Loader::name);
784 add("real_speed", &Loader::real_speed);
785 add("route", &Loader::route);
786 add("timetable", &Loader::timetable);
789 void Train::Loader::block(unsigned id)
791 Block &blk = obj.layout.get_block(id);
794 entry = blk.get_endpoint_by_link(*prev_block);
799 obj.cur_blocks.push_back(BlockRef(&blk, entry));
800 obj.set_status("Stopped");
801 const Block::Endpoint &bep = blk.get_endpoints()[entry];
802 obj.vehicles.back()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
804 if(blk.get_sensor_id())
805 obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
810 void Train::Loader::block_hint(unsigned id)
812 prev_block = &obj.layout.get_block(id);
815 void Train::Loader::name(const string &n)
820 void Train::Loader::real_speed(unsigned i, float speed, float weight)
822 obj.real_speed[i].speed = speed;
823 obj.real_speed[i].weight = weight;
826 void Train::Loader::route(const string &n)
828 obj.set_route(&obj.layout.get_route(n));
831 void Train::Loader::timetable()
834 throw InvalidState("A timetable has already been loaded");
836 obj.timetable = new Timetable(obj);
837 load_sub(*obj.timetable);
840 } // namespace Marklin