+void Route::set_turnout(unsigned addr, unsigned path)
+{
+ if(!addr)
+ throw InvalidParameterValue("Invalid turnout address");
+ map<unsigned, int>::iterator i = turnouts.find(addr);
+ if(i==turnouts.end())
+ throw KeyError("Turnout is not in this route");
+ if(i->second>=0 && path!=static_cast<unsigned>(i->second))
+ throw InvalidState("Setting conflicts with route");
+ i->second = path;
+}
+
+void Route::update_turnouts()
+{
+ set<unsigned> found;
+ for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
+ if(unsigned tid = (*i)->get_turnout_id())
+ {
+ found.insert(tid);
+
+ const vector<TrackType::Endpoint> &endpoints = (*i)->get_type().get_endpoints();
+ const vector<Track *> &links = (*i)->get_links();
+
+ // Build a combined path mask from linked endpoints
+ unsigned mask = 15;
+ for(unsigned j=0; j<endpoints.size(); ++j)
+ {
+ if(!tracks.count(links[j]))
+ continue;
+
+ if(unsigned tid2 = links[j]->get_turnout_id())
+ {
+ const TrackType::Endpoint &ep = links[j]->get_type().get_endpoints()[links[j]->get_endpoint_by_link(**i)];
+ int p = get_turnout(tid2);
+ if(p>=0 && !(ep.paths&(1<<p)))
+ {
+ // The linked track is a turnout and has a path which is incompatible with this endpoint
+ mask &= ~endpoints[j].paths;
+ continue;
+ }
+ }
+ mask &= endpoints[j].paths;
+ }
+
+ if(mask && !(mask&(mask-1)))
+ {
+ // Exactly one possible choice, set the path accordingly
+ unsigned path = 0;
+ for(; (mask && !(mask&1)); mask>>=1, ++path) ;
+ turnouts[tid] = path;
+ }
+ else if(!turnouts.count(tid))
+ // More than one possible choice, and no existing entry - set as undecided
+ turnouts[tid] = -1;
+ }
+
+ // Remove any turnouts that do not exist in the route
+ for(map<unsigned, int>::iterator i=turnouts.begin(); i!=turnouts.end();)
+ {
+ if(!found.count(i->first))
+ turnouts.erase(i++);
+ else
+ ++i;
+ }
+}
+