+#include <msp/core/maputils.h>
#include "catalogue.h"
#include "layout.h"
#include "route.h"
namespace R2C2 {
-TrainRoutePlanner::TrainRoutePlanner(Layout &layout)
+TrainRoutePlanner::TrainRoutePlanner(Layout &layout):
+ goal(0),
+ result(PENDING),
+ thread(0)
{
const map<unsigned, Train *> &trains = layout.get_trains();
for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
{
TrainRoutingInfo info(*i->second);
- if(info.router && info.router->get_destination())
+ if(info.destination)
routed_trains.push_back(info);
}
+}
+
+TrainRoutePlanner::~TrainRoutePlanner()
+{
+ if(thread)
+ {
+ thread->join();
+ delete thread;
+ }
+}
+
+TrainRoutePlanner::Result TrainRoutePlanner::plan()
+{
+ prepare_plan();
+ create_plan();
+ if(result==PENDING)
+ finalize_plan();
+
+ return result;
+}
+
+void TrainRoutePlanner::plan_async()
+{
+ if(thread)
+ throw logic_error("already planning");
+
+ prepare_plan();
+ thread = new PlanningThread(*this);
+}
+
+TrainRoutePlanner::Result TrainRoutePlanner::check()
+{
+ if(result==PENDING && goal)
+ {
+ if(thread)
+ {
+ thread->join();
+ delete thread;
+ thread = 0;
+ }
+ finalize_plan();
+ }
+
+ return result;
+}
+
+const list<Route *> &TrainRoutePlanner::get_routes_for(const Train &train) const
+{
+ return get_train_info(train).routes;
+}
+
+const list<TrainRouter::SequencePoint> &TrainRoutePlanner::get_sequence_for(const Train &train) const
+{
+ return get_train_info(train).sequence;
+}
+
+const TrainRoutePlanner::TrainRoutingInfo &TrainRoutePlanner::get_train_info(const Train &train) const
+{
+ for(vector<TrainRoutingInfo>::const_iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
+ if(i->train==&train)
+ return *i;
+
+ throw key_error(train.get_name());
+}
+
+const TrainRoutePlanner::RoutingStep &TrainRoutePlanner::get_step()
+{
+ steps.splice(steps.end(), queue, queue.begin());
+ return steps.back();
+}
+
+void TrainRoutePlanner::prepare_plan()
+{
+ steps.clear();
+ queue.clear();
+ goal = 0;
+ result = PENDING;
queue.push_back(RoutingStep());
RoutingStep &start = queue.back();
start.update_estimate();
}
-void TrainRoutePlanner::plan()
+void TrainRoutePlanner::create_plan()
{
- const RoutingStep *goal = 0;
while(!queue.empty())
{
const RoutingStep &step = get_step();
if(step.is_goal())
{
goal = &step;
- break;
+ return;
}
add_steps(step);
}
- if(goal)
- create_routes(*goal);
-}
-
-const TrainRoutePlanner::RoutingStep &TrainRoutePlanner::get_step()
-{
- steps.splice(steps.end(), queue, queue.begin());
- return steps.back();
+ result = FAILED;
}
void TrainRoutePlanner::add_steps(const RoutingStep &step)
queue.merge(new_steps);
}
-void TrainRoutePlanner::create_routes(const RoutingStep &goal)
+void TrainRoutePlanner::finalize_plan()
{
for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
{
- Route *route = new Route(i->train->get_layout());
- route->set_name("Router");
- route->set_temporary(true);
- i->routes.push_front(route);
-
- for(unsigned j=0; j<3; ++j)
+ i->routes.clear();
+ i->sequence.clear();
+ for(unsigned j=0; j<2; ++j)
i->track_history[j] = 0;
}
- for(const RoutingStep *i=&goal; i; i=i->prev)
- {
+ map<Track *, TrainRouter::SequencePoint *> sequenced_tracks;
+ unsigned sequence = steps.size();
+ for(const RoutingStep *i=goal; i; i=i->prev)
for(vector<TrainRoutingState>::const_iterator j=i->trains.begin(); j!=i->trains.end(); ++j)
{
Track **history = j->info->track_history;
if(j->track.track()==history[0])
continue;
- if(j->state==WAITING || j->state==BLOCKED)
- j->info->waits.push_front(&*j);
+ Route *route = 0;
+ bool start_new_route = true;
+ if(!j->info->routes.empty())
+ {
+ route = j->info->routes.front();
+ start_new_route = route->has_track(*j->track);
+ if(!start_new_route)
+ {
+ unsigned nls = j->track->get_n_link_slots();
+ for(unsigned k=0; (!start_new_route && k<nls); ++k)
+ {
+ Track *link = j->track->get_link(k);
+ start_new_route = (link && link!=history[0] && route->has_track(*link));
+ }
+ }
+ }
- Route *route = j->info->routes.front();
- if(route->has_track(*j->track))
+ if(start_new_route)
{
route = new Route(j->info->train->get_layout());
route->set_name("Router");
route->set_temporary(true);
- for(unsigned k=2; k>0; --k)
+ for(unsigned k=0; (k<2 && history[k]); ++k)
route->add_track(*history[k]);
j->info->routes.push_front(route);
}
- if(history[0])
- route->add_track(*history[0]);
- for(unsigned k=2; k>0; --k)
- history[k] = history[k-1];
+ route->add_track(*j->track.track());
+ history[1] = history[0];
history[0] = j->track.track();
- }
- }
- for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
- {
- for(list<Route *>::iterator j=i->routes.begin(); j!=i->routes.end(); ++j)
- i->router->add_route(**j);
- const TrainRoutingState *current_wait = 0;
- for(list<const TrainRoutingState *>::const_iterator j=i->waits.begin(); j!=i->waits.end(); ++j)
- if(!current_wait || (*j)->track.track()!=current_wait->track.track())
+ bool waitable = j->track.endpoint().paths!=j->track->get_type().get_paths();
+ map<Track *, TrainRouter::SequencePoint *>::iterator k = sequenced_tracks.find(j->track.track());
+ if(k!=sequenced_tracks.end())
{
- Block &block = (*j)->track.next()->get_block();
- i->router->add_wait(block, 0);
- current_wait = *j;
+ if(!k->second->preceding_train)
+ {
+ k->second->preceding_train = j->info->train;
+ k->second->sequence_in = sequence;
+ }
+ j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
+ if(waitable)
+ k->second = &j->info->sequence.front();
+ --sequence;
}
- }
+ else if(waitable)
+ {
+ j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
+ sequenced_tracks[j->track.track()] = &j->info->sequence.front();
+ --sequence;
+ }
+ }
+
+ result = COMPLETE;
}
TrainRoutePlanner::TrainRoutingInfo::TrainRoutingInfo(Train &t):
train(&t),
speed(train->get_maximum_speed()),
- router(train->get_ai_of_type<TrainRouter>())
+ first_noncritical(train->get_first_noncritical_block().block()),
+ router(train->get_ai_of_type<TrainRouter>()),
+ destination(0),
+ has_duration(false)
{
+ if(router)
+ {
+ destination = router->get_destination();
+ if(destination)
+ {
+ waypoints.resize(router->get_n_waypoints());
+ metrics.resize(waypoints.size()+1);
+ metrics[0] = &router->get_metric(-1);
+ for(unsigned i=0; i<waypoints.size(); ++i)
+ {
+ waypoints[i] = &router->get_waypoint(i);
+ metrics[i+1] = &router->get_metric(i);
+ }
+ has_duration = router->get_trip_duration();
+ }
+ }
+
// If no maximum speed is specified, use a sensible default
if(!speed)
speed = 20*train->get_layout().get_catalogue().get_scale();
TrainRoutePlanner::TrainRoutingState::TrainRoutingState(TrainRoutingInfo &inf):
info(&inf),
+ critical(true),
occupied_tracks(0),
state(MOVING),
delay(info->router->get_departure_delay()),
- waypoint(info->router->get_n_waypoints() ? 0 : -1),
+ duration(info->router->get_trip_duration()),
+ waypoint(info->waypoints.empty() ? -1 : 0),
blocked_by(-1)
{
const Vehicle *veh = &info->train->get_vehicle(0);
info(other.info),
track(other.track),
path(other.path),
+ critical(other.critical),
occupied_tracks(other.occupied_tracks),
offset(other.offset),
back_offset(other.back_offset),
state(other.state),
delay(other.delay),
+ duration(other.duration),
waypoint(other.waypoint),
distance_traveled(other.distance_traveled),
remaining_estimate(other.remaining_estimate),
bool TrainRoutePlanner::TrainRoutingState::is_occupying(Track &trk) const
{
+ if(state==ARRIVED && !duration && info->has_duration)
+ return false;
+
OccupiedTrack *occ = occupied_tracks;
for(unsigned n=occ->n_tracks; n>0; --n, occ=occ->next)
if(occ->track==&trk)
bool TrainRoutePlanner::TrainRoutingState::check_arrival()
{
- TrainRouter &router = *info->router;
TrackIter next_track = track.next(path);
- if(waypoint<0 && router.is_destination(*track) && !router.is_destination(*next_track))
+ if(waypoint<0 && info->destination->has_track(*track) && !info->destination->has_track(*next_track))
{
state = ARRIVED;
return true;
}
- else if(waypoint>=0 && router.is_waypoint(waypoint, *track) && !router.is_waypoint(waypoint, *next_track))
+ else if(waypoint>=0 && info->waypoints[waypoint]->has_track(*track) && !info->waypoints[waypoint]->has_track(*next_track))
{
++waypoint;
- if(waypoint>=static_cast<int>(router.get_n_waypoints()))
+ if(waypoint>=static_cast<int>(info->waypoints.size()))
waypoint = -1;
}
+ if(info->first_noncritical->has_track(*track))
+ critical = false;
+
return false;
}
offset += distance;
back_offset += distance;
- OccupiedTrack *last_occ = occupied_tracks;
- for(unsigned n=occupied_tracks->n_tracks; n>1; --n)
- last_occ = last_occ->next;
+ unsigned count_to_free = 0;
+ unsigned last_sensor_addr = 0;
+ float distance_after_sensor = 0;
+ OccupiedTrack *occ = occupied_tracks;
+ for(unsigned n=occupied_tracks->n_tracks; n>0; --n)
+ {
+ if(unsigned saddr = occ->track->get_sensor_address())
+ {
+ if(saddr!=last_sensor_addr)
+ {
+ count_to_free = 0;
+ distance_after_sensor = 0;
+ }
+ last_sensor_addr = saddr;
+ }
+
+ ++count_to_free;
+ distance_after_sensor += occ->path_length;
+
+ occ = occ->next;
+ }
- // XXX What if there's multiple tracks to remove?
- if(back_offset>last_occ->path_length)
+ if(count_to_free && back_offset>distance_after_sensor)
{
- back_offset -= last_occ->path_length;
+ back_offset -= distance_after_sensor;
if(occupied_tracks->refcount>1)
{
--occupied_tracks->refcount;
occupied_tracks = new OccupiedTrack(*occupied_tracks);
}
- --occupied_tracks->n_tracks;
+ occupied_tracks->n_tracks -= count_to_free;
}
distance_traveled += distance;
delay = Time::zero;
}
+ if(duration)
+ duration = max(duration-secs*Time::sec, Time::zero);
+
if(state==MOVING)
advance(info->speed*secs);
else if(state!=ARRIVED)
void TrainRoutePlanner::TrainRoutingState::update_estimate()
{
TrackIter iter = track.reverse(path);
- float distance = info->router->get_metric(waypoint).get_distance_from(*iter.track(), iter.entry());
+ float distance = info->metrics[waypoint+1]->get_distance_from(*iter.track(), iter.entry());
distance += track->get_type().get_path_length(path)-offset;
remaining_estimate = distance;
}
TrainRoutePlanner::RoutingStep::RoutingStep(const RoutingStep *p):
time(p->time),
+ penalty(p->penalty),
cost_estimate(p->cost_estimate),
trains(p->trains),
prev(p)
train.advance_track(0);
const TrackType::Endpoint &next_entry_ep = next_track.endpoint();
- for(unsigned i=0; next_entry_ep.paths>>i; ++i)
- if(next_entry_ep.has_path(i))
- {
- train.path = i;
- train.update_estimate();
- next.update_estimate();
- if(next.is_viable())
- new_steps.push_back(next);
- }
+ if(train.critical)
+ {
+ train.path = train.track->get_type().coerce_path(train.track.entry(), train.track->get_active_path());
+ train.update_estimate();
+ next.update_estimate();
+ if(next.is_viable())
+ new_steps.push_back(next);
+ }
+ else
+ {
+ for(unsigned i=0; next_entry_ep.paths>>i; ++i)
+ if(next_entry_ep.has_path(i))
+ {
+ train.path = i;
+ train.update_estimate();
+ next.update_estimate();
+ if(next.is_viable())
+ new_steps.push_back(next);
+ }
+ }
+
+ new_steps.sort();
+ for(list<RoutingStep>::iterator i=new_steps.begin(); ++i!=new_steps.end(); )
+ {
+ i->penalty += 5*Time::sec;
+ i->update_estimate();
+ }
- if(next_entry_ep.paths!=next_track->get_type().get_paths())
+ if(next_entry_ep.paths!=next_track->get_type().get_paths() && !train.critical)
{
RoutingStep wait(this);
wait.advance(dt);
wait.trains[train_index].state = WAITING;
+ wait.penalty += 15*Time::sec;
+ wait.update_estimate();
if(wait.is_viable())
new_steps.push_back(wait);
}
void TrainRoutePlanner::RoutingStep::update_estimate()
{
- cost_estimate = Time::zero;
+ cost_estimate = penalty;
for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
if(i->remaining_estimate>=0)
cost_estimate += i->wait_time+((i->distance_traveled+i->remaining_estimate)/i->info->speed)*Time::sec;
return cost_estimate<other.cost_estimate;
}
+
+TrainRoutePlanner::PlanningThread::PlanningThread(TrainRoutePlanner &p):
+ planner(p)
+{
+ launch();
+}
+
+void TrainRoutePlanner::PlanningThread::main()
+{
+ planner.create_plan();
+}
+
} // namespace R2C2