FindDepotData OPFShipFindNearestDepot(const Ship *v, int max_distance) // todo
{
TileIndex tile = v->tile;
Trackdir trackdir = v->GetVehicleTrackdir();
DiagDirection enterdir = TrackdirToExitdir(trackdir);
TrackBits tracks = TrackdirBitsToTrackBits(DiagdirReachesTrackdirs(enterdir));
TileIndex tile_rev = TILE_ADD(tile, -TileOffsByDiagDir(enterdir));
TrackBits tracks_rev = TrackStatusToTrackBits(GetTileTrackStatus(tile_rev, TRANSPORT_WATER, 0)) & DiagdirReachesTracks(ReverseDiagDir(enterdir)) & TrackdirBitsToTrackBits(TrackdirToTrackdirBits(trackdir));
FindDepotData fdd;
Depot *depot;
Track track;
uint best_dist = UINT_MAX;
FOR_ALL_DEPOTS(depot) {
TileIndex depottile = depot->xy;
if (IsShipDepotTile(depottile) && IsTileOwner(depottile, v->owner)) {
/* Let's find out how far it would be if we would reverse first */
uint fst_dist_rev = UINT_MAX;
if (tracks_rev != 0) {
fst_dist_rev = FindShipTrack(v, tile_rev, ReverseDiagDir(enterdir), tracks_rev, tile, &track, depottile);
if (fst_dist_rev != UINT_MAX) fst_dist_rev++; // penalty for reversing
}
/* And if we would not reverse? */
uint fst_dist = FindShipTrack(v, tile, enterdir, tracks, 0, &track, depottile);
/* Get the shortest distance */
uint dist = minu(fst_dist_rev, fst_dist);
if (dist < best_dist) {
best_dist = dist;
uint distdepot = DistanceManhattan(tile, depottile);
fdd.best_length = distdepot;
fdd.tile = depottile;
}
}
}
return fdd;
}