+#include "layout.h"
+#include "route.h"
+#include "trackiter.h"
+#include "train.h"
+#include "trainrouter.h"
+#include "zone.h"
+
+using namespace std;
+using namespace Msp;
+
+namespace R2C2 {
+
+TrainRouter::TrainRouter(Train &t):
+ TrainAI(t),
+ priority(0),
+ arriving(false),
+ yielding_to(0)
+{
+ train.get_layout().signal_block_reserved.connect(sigc::mem_fun(this, &TrainRouter::block_reserved));
+ train.signal_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_advanced));
+}
+
+void TrainRouter::set_priority(int p)
+{
+ priority = p;
+}
+
+void TrainRouter::yield_to(const Train &t)
+{
+ yielding_to = &t;
+}
+
+bool TrainRouter::set_route(const Route *r)
+{
+ train.free_noncritical_blocks();
+
+ Route *lead = 0;
+ if(r && train.is_placed())
+ {
+ TrackIter first = train.get_tail_block().track_iter();
+ TrackIter next = train.get_head_block().next().track_iter();
+ if(!r->has_track(*next))
+ {
+ lead = Route::find(next, *r);
+ if(!lead)
+ return false;
+ create_lead_route(lead, lead);
+ }
+ else if(!r->has_track(*first))
+ lead = create_lead_route(0, r);
+ }
+
+ routes.clear();
+ if(lead)
+ routes.push_back(lead);
+ if(r)
+ routes.push_back(r);
+ train.stop_at(0);
+ arriving = false;
+
+ train.reserve_more();
+
+ const Route *route = get_route();
+ signal_route_changed.emit(route);
+ signal_event.emit(Message("route-changed", route));
+
+ return true;
+}
+
+bool TrainRouter::go_to(Track &to)
+{
+ if(!train.get_speed())
+ {
+ for(BlockIter i=train.get_tail_block(); (i && i->get_train()==&train); i=i.next())
+ if(i->has_track(to))
+ {
+ signal_arrived.emit();
+ signal_event.emit(Message("arrived"));
+ return set_route(0);
+ }
+ }
+
+ train.free_noncritical_blocks();
+
+ TrackIter next = train.get_head_block().next().track_iter();
+
+ Route *route = Route::find(next, to);
+ if(!route)
+ return false;
+ create_lead_route(route, route);
+ return set_route(route);
+}
+
+bool TrainRouter::go_to(const Zone &to)
+{
+ set<Track *> tracks;
+ for(BlockIter i=train.get_tail_block(); (i && i->get_train()==&train); i=i.next())
+ tracks.insert(i->get_tracks().begin(), i->get_tracks().end());
+
+ const Zone::TrackSet &ztracks = to.get_tracks();
+ unsigned union_size = 0;
+ for(Zone::TrackSet::const_iterator i=ztracks.begin(); i!=ztracks.end(); ++i)
+ union_size += tracks.count(*i);
+
+ if(union_size==tracks.size() || union_size==ztracks.size())
+ {
+ signal_arrived.emit();
+ signal_event.emit(Message("arrived"));
+ return set_route(0);
+ }
+
+ train.free_noncritical_blocks();
+
+ TrackIter next = train.get_head_block().next().track_iter();
+
+ Route *route = Route::find(next, to);
+ if(!route)
+ return false;
+ create_lead_route(route, route);
+ route->add_tracks(ztracks);
+ return set_route(route);
+}
+
+const Route *TrainRouter::get_route() const
+{
+ if(routes.empty())
+ return 0;
+ return routes.front();
+}
+
+void TrainRouter::message(const Message &msg)
+{
+ if(msg.type=="set-route")
+ {
+ if(msg.value.check_type<Route *>())
+ set_route(msg.value.value<Route *>());
+ else
+ set_route(msg.value.value<const Route *>());
+ }
+ else if(msg.type=="clear-route")
+ set_route(0);
+ else if(msg.type=="go-to-track")
+ go_to(*msg.value.value<Track *>());
+ else if(msg.type=="go-to-zone")
+ {
+ if(msg.value.check_type<Zone *>())
+ go_to(*msg.value.value<Zone *>());
+ else
+ go_to(*msg.value.value<const Zone *>());
+ }
+}
+
+void TrainRouter::tick(const Time::TimeStamp &, const Time::TimeDelta &)
+{
+ if(arriving && !train.get_speed())
+ {
+ train.set_active(false);
+ signal_arrived.emit();
+ signal_event.emit(Message("arrived"));
+ set_route(0);
+ }
+}
+
+void TrainRouter::save(list<DataFile::Statement> &st) const
+{
+ if(!tag.empty())
+ st.push_back((DataFile::Statement("tag"), tag));
+
+ st.push_back((DataFile::Statement("priority"), priority));
+
+ if(!routes.empty())
+ {
+ RouteList::const_iterator i = routes.begin();
+ for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
+ if(i!=routes.end())
+ st.push_back((DataFile::Statement("route"), (*i)->get_name()));
+ }
+}
+
+void TrainRouter::block_reserved(Block &block, Train *t)
+{
+ if(t!=&train)
+ return;
+
+ yielding_to = 0;
+
+ BlockIter b_iter(&block, t->get_entry_to_block(block));
+ BlockIter b_iter_next;
+
+ RouteList::iterator route = routes.begin();
+ if(advance_route(route, block))
+ {
+ // Check if the block is a turnout and set it to proper path
+ if(unsigned tid = block.get_turnout_id())
+ {
+ int path = (*route)->get_turnout(tid);
+ if(path>=0)
+ b_iter.track_iter()->set_active_path(path);
+ }
+
+ // Check if the next block is still part of the designated route
+ b_iter_next = b_iter.next(*route);
+
+ RouteList::iterator next_route = route;
+ if(!advance_route(next_route, *b_iter_next))
+ {
+ train.stop_at(&block);
+ return;
+ }
+
+ }
+ else
+ b_iter_next = b_iter.next();
+
+ // Check if there's another train and ask it to free the block if appropriate
+ if(b_iter_next)
+ {
+ if(Train *other_train = b_iter_next->get_train())
+ {
+ /* There's another train ahead of us. If it wants to exit the block
+ from the same endpoint we're trying to enter from or the other way
+ around, treat it as coming towards us. Otherwise treat it as going
+ in the same direction. */
+ int other_entry = other_train->get_entry_to_block(*b_iter_next);
+ if(other_entry<0)
+ throw logic_error("block reservation inconsistency");
+
+ unsigned exit = b_iter_next.reverse().entry();
+ unsigned other_exit = BlockIter(b_iter_next.block(), other_entry).reverse().entry();
+ bool entry_conflict = (b_iter_next.entry()==other_exit);
+ bool exit_conflict = (exit==static_cast<unsigned>(other_entry));
+ // TODO: speed matching with preceding train
+
+ // XXX Should invent a better way to get our counterpart from the other train
+ TrainRouter *other_router = dynamic_cast<TrainRouter *>(other_train->get_tagged_ai("router"));
+ int other_prio = (other_router ? other_router->get_priority() : 0);
+
+ if(!entry_conflict && !exit_conflict && other_prio<priority)
+ {
+ /* Ask a lesser priority train going to the same direction to free
+ the block for us */
+ other_train->free_block(*b_iter_next);
+ }
+ else if(other_train!=yielding_to && (other_prio<priority || (other_prio==priority && entry_conflict)))
+ {
+ /* A lesser priority train is coming at us, we must ask it to free
+ enough blocks to get clear of it to avoid a potential deadlock */
+ BlockIter last_contested;
+ RouteList::iterator j = route;
+ for(BlockIter i=b_iter_next; (i && i->get_train()==other_train);)
+ {
+ if(!advance_route(j, *i))
+ break;
+ last_contested = i;
+ i = i.next(*j);
+ }
+
+ if(last_contested)
+ {
+ if(other_train->free_block(*last_contested))
+ other_router->yield_to(train);
+ else
+ yield_to(*other_train);
+ }
+ }
+ }
+ }
+}
+
+void TrainRouter::train_advanced(Block &block)
+{
+ // Check if we've reached the next route
+ if(routes.size()>1)
+ {
+ unsigned entry = train.get_entry_to_block(block);
+ Track &track = *block.get_endpoint(entry).track;
+ const Route &route = **++routes.begin();
+ if(route.has_track(track))
+ {
+ routes.pop_front();
+ // XXX Exceptions?
+ signal_event.emit(Message("route-changed", get_route()));
+ }
+ }
+
+ BlockIter iter(&block, train.get_entry_to_block(block));
+ iter = iter.next();
+ if(iter && !is_on_route(*iter))
+ arriving = true;
+}
+
+const Route *TrainRouter::get_route_for_block(const Block &block) const
+{
+ const set<Track *> &tracks = block.get_tracks();
+ for(RouteList::const_iterator i=routes.begin(); i!=routes.end(); ++i)
+ for(set<Track *>::const_iterator j=tracks.begin(); j!=tracks.end(); ++j)
+ if((*i)->has_track(**j))
+ return *i;
+
+ return 0;
+}
+
+Route *TrainRouter::create_lead_route(Route *lead, const Route *target)
+{
+ if(!lead)
+ {
+ lead = new Route(train.get_layout());
+ lead->set_name("Lead");
+ lead->set_temporary(true);
+ }
+
+ set<Track *> tracks;
+ for(BlockIter i=train.get_tail_block(); (i && i->get_train()==&train); i=i.next())
+ {
+ const set<Track *> &btracks = i->get_tracks();
+ for(set<Track *>::const_iterator j=btracks.begin(); j!=btracks.end(); ++j)
+ if(!target || !target->has_track(**j))
+ tracks.insert(*j);
+ }
+
+ lead->add_tracks(tracks);
+
+ return lead;
+}
+
+bool TrainRouter::advance_route(RouteList::iterator &iter, const Block &block)
+{
+ const set<Track *> &tracks = block.get_tracks();
+ for(; iter!=routes.end(); ++iter)
+ for(set<Track *>::const_iterator j=tracks.begin(); j!=tracks.end(); ++j)
+ if((*iter)->has_track(**j))
+ return true;
+
+ return false;
+}
+
+bool TrainRouter::is_on_route(const Block &block)
+{
+ RouteList::iterator iter = routes.begin();
+ return advance_route(iter, block);
+}
+
+
+TrainRouter::Loader::Loader(TrainRouter &r):
+ DataFile::ObjectLoader<TrainRouter>(r)
+{
+ add("priority", &TrainRouter::priority);
+ add("route", &Loader::route);
+ add("tag", &Loader::tag);
+}
+
+void TrainRouter::Loader::route(const string &n)
+{
+ obj.set_route(&obj.train.get_layout().get_route(n));
+}
+
+void TrainRouter::Loader::tag(const string &t)
+{
+ obj.set_tag(t);
+}
+
+} // namespace R2C2