ship_cmd.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "ship.h"
00014 #include "landscape.h"
00015 #include "timetable.h"
00016 #include "news_func.h"
00017 #include "company_func.h"
00018 #include "pathfinder/npf/npf_func.h"
00019 #include "depot_base.h"
00020 #include "station_base.h"
00021 #include "newgrf_engine.h"
00022 #include "pathfinder/yapf/yapf.h"
00023 #include "newgrf_sound.h"
00024 #include "spritecache.h"
00025 #include "strings_func.h"
00026 #include "window_func.h"
00027 #include "date_func.h"
00028 #include "vehicle_func.h"
00029 #include "sound_func.h"
00030 #include "ai/ai.hpp"
00031 #include "pathfinder/opf/opf_ship.h"
00032 #include "engine_base.h"
00033 #include "company_base.h"
00034 #include "tunnelbridge_map.h"
00035 #include "zoom_func.h"
00036 
00037 #include "table/strings.h"
00038 
00044 WaterClass GetEffectiveWaterClass(TileIndex tile)
00045 {
00046   if (HasTileWaterClass(tile)) return GetWaterClass(tile);
00047   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
00048     assert(GetTunnelBridgeTransportType(tile) == TRANSPORT_WATER);
00049     return WATER_CLASS_CANAL;
00050   }
00051   if (IsTileType(tile, MP_RAILWAY)) {
00052     assert(GetRailGroundType(tile) == RAIL_GROUND_WATER);
00053     return WATER_CLASS_SEA;
00054   }
00055   NOT_REACHED();
00056 }
00057 
00058 static const uint16 _ship_sprites[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
00059 
00060 static inline TrackBits GetTileShipTrackStatus(TileIndex tile)
00061 {
00062   return TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_WATER, 0));
00063 }
00064 
00065 static SpriteID GetShipIcon(EngineID engine, EngineImageType image_type)
00066 {
00067   const Engine *e = Engine::Get(engine);
00068   uint8 spritenum = e->u.ship.image_index;
00069 
00070   if (is_custom_sprite(spritenum)) {
00071     SpriteID sprite = GetCustomVehicleIcon(engine, DIR_W, image_type);
00072     if (sprite != 0) return sprite;
00073 
00074     spritenum = e->original_image_index;
00075   }
00076 
00077   return DIR_W + _ship_sprites[spritenum];
00078 }
00079 
00080 void DrawShipEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
00081 {
00082   SpriteID sprite = GetShipIcon(engine, image_type);
00083   const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
00084   preferred_x = Clamp(preferred_x, left - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI), right - UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI) - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI));
00085   DrawSprite(sprite, pal, preferred_x, y);
00086 }
00087 
00094 void GetShipSpriteSize(EngineID engine, uint &width, uint &height, EngineImageType image_type)
00095 {
00096   const Sprite *spr = GetSprite(GetShipIcon(engine, image_type), ST_NORMAL);
00097 
00098   width  = UnScaleByZoom(spr->width, ZOOM_LVL_GUI);
00099   height = UnScaleByZoom(spr->height, ZOOM_LVL_GUI);
00100 }
00101 
00102 SpriteID Ship::GetImage(Direction direction, EngineImageType image_type) const
00103 {
00104   uint8 spritenum = this->spritenum;
00105 
00106   if (is_custom_sprite(spritenum)) {
00107     SpriteID sprite = GetCustomVehicleSprite(this, direction, image_type);
00108     if (sprite != 0) return sprite;
00109 
00110     spritenum = this->GetEngine()->original_image_index;
00111   }
00112 
00113   return _ship_sprites[spritenum] + direction;
00114 }
00115 
00116 static const Depot *FindClosestShipDepot(const Vehicle *v, uint max_distance)
00117 {
00118   /* Find the closest depot */
00119   const Depot *depot;
00120   const Depot *best_depot = NULL;
00121   /* If we don't have a maximum distance, i.e. distance = 0,
00122    * we want to find any depot so the best distance of no
00123    * depot must be more than any correct distance. On the
00124    * other hand if we have set a maximum distance, any depot
00125    * further away than max_distance can safely be ignored. */
00126   uint best_dist = max_distance == 0 ? UINT_MAX : max_distance + 1;
00127 
00128   FOR_ALL_DEPOTS(depot) {
00129     TileIndex tile = depot->xy;
00130     if (IsShipDepotTile(tile) && IsTileOwner(tile, v->owner)) {
00131       uint dist = DistanceManhattan(tile, v->tile);
00132       if (dist < best_dist) {
00133         best_dist = dist;
00134         best_depot = depot;
00135       }
00136     }
00137   }
00138 
00139   return best_depot;
00140 }
00141 
00142 static void CheckIfShipNeedsService(Vehicle *v)
00143 {
00144   if (Company::Get(v->owner)->settings.vehicle.servint_ships == 0 || !v->NeedsAutomaticServicing()) return;
00145   if (v->IsChainInDepot()) {
00146     VehicleServiceInDepot(v);
00147     return;
00148   }
00149 
00150   uint max_distance;
00151   switch (_settings_game.pf.pathfinder_for_ships) {
00152     case VPF_OPF:  max_distance = 12; break;
00153     case VPF_NPF:  max_distance = _settings_game.pf.npf.maximum_go_to_depot_penalty  / NPF_TILE_LENGTH;  break;
00154     case VPF_YAPF: max_distance = _settings_game.pf.yapf.maximum_go_to_depot_penalty / YAPF_TILE_LENGTH; break;
00155     default: NOT_REACHED();
00156   }
00157 
00158   const Depot *depot = FindClosestShipDepot(v, max_distance);
00159 
00160   if (depot == NULL) {
00161     if (v->current_order.IsType(OT_GOTO_DEPOT)) {
00162       v->current_order.MakeDummy();
00163       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
00164     }
00165     return;
00166   }
00167 
00168   v->current_order.MakeGoToDepot(depot->index, ODTFB_SERVICE);
00169   v->dest_tile = depot->xy;
00170   SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
00171 }
00172 
00176 void Ship::UpdateCache()
00177 {
00178   const ShipVehicleInfo *svi = ShipVehInfo(this->engine_type);
00179 
00180   /* Get speed fraction for the current water type. Aqueducts are always canals. */
00181   bool is_ocean = GetEffectiveWaterClass(this->tile) == WATER_CLASS_SEA;
00182   uint raw_speed = GetVehicleProperty(this, PROP_SHIP_SPEED, svi->max_speed);
00183   this->vcache.cached_max_speed = svi->ApplyWaterClassSpeedFrac(raw_speed, is_ocean);
00184 
00185   /* Update cargo aging period. */
00186   this->vcache.cached_cargo_age_period = GetVehicleProperty(this, PROP_SHIP_CARGO_AGE_PERIOD, EngInfo(this->engine_type)->cargo_age_period);
00187 
00188   this->UpdateVisualEffect();
00189 }
00190 
00191 Money Ship::GetRunningCost() const
00192 {
00193   const Engine *e = this->GetEngine();
00194   uint cost_factor = GetVehicleProperty(this, PROP_SHIP_RUNNING_COST_FACTOR, e->u.ship.running_cost);
00195   return GetPrice(PR_RUNNING_SHIP, cost_factor, e->GetGRF());
00196 }
00197 
00198 void Ship::OnNewDay()
00199 {
00200   if ((++this->day_counter & 7) == 0) {
00201     DecreaseVehicleValue(this);
00202   }
00203 
00204   CheckVehicleBreakdown(this);
00205   AgeVehicle(this);
00206   CheckIfShipNeedsService(this);
00207 
00208   CheckOrders(this);
00209 
00210   if (this->running_ticks == 0) return;
00211 
00212   CommandCost cost(EXPENSES_SHIP_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
00213 
00214   this->profit_this_year -= cost.GetCost();
00215   this->running_ticks = 0;
00216 
00217   SubtractMoneyFromCompanyFract(this->owner, cost);
00218 
00219   SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
00220   /* we need this for the profit */
00221   SetWindowClassesDirty(WC_SHIPS_LIST);
00222 }
00223 
00224 Trackdir Ship::GetVehicleTrackdir() const
00225 {
00226   if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
00227 
00228   if (this->IsInDepot()) {
00229     /* We'll assume the ship is facing outwards */
00230     return DiagDirToDiagTrackdir(GetShipDepotDirection(this->tile));
00231   }
00232 
00233   if (this->state == TRACK_BIT_WORMHOLE) {
00234     /* ship on aqueduct, so just use his direction and assume a diagonal track */
00235     return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
00236   }
00237 
00238   return TrackDirectionToTrackdir(FindFirstTrack(this->state), this->direction);
00239 }
00240 
00241 void Ship::MarkDirty()
00242 {
00243   this->UpdateViewport(false, false);
00244   this->UpdateCache();
00245 }
00246 
00247 static void PlayShipSound(const Vehicle *v)
00248 {
00249   if (!PlayVehicleSound(v, VSE_START)) {
00250     SndPlayVehicleFx(ShipVehInfo(v->engine_type)->sfx, v);
00251   }
00252 }
00253 
00254 void Ship::PlayLeaveStationSound() const
00255 {
00256   PlayShipSound(this);
00257 }
00258 
00259 TileIndex Ship::GetOrderStationLocation(StationID station)
00260 {
00261   if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
00262 
00263   const Station *st = Station::Get(station);
00264   if (st->dock_tile != INVALID_TILE) {
00265     return TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
00266   } else {
00267     this->IncrementRealOrderIndex();
00268     return 0;
00269   }
00270 }
00271 
00272 void Ship::UpdateDeltaXY(Direction direction)
00273 {
00274   static const int8 _delta_xy_table[8][4] = {
00275     /* y_extent, x_extent, y_offs, x_offs */
00276     { 6,  6,  -3,  -3}, // N
00277     { 6, 32,  -3, -16}, // NE
00278     { 6,  6,  -3,  -3}, // E
00279     {32,  6, -16,  -3}, // SE
00280     { 6,  6,  -3,  -3}, // S
00281     { 6, 32,  -3, -16}, // SW
00282     { 6,  6,  -3,  -3}, // W
00283     {32,  6, -16,  -3}, // NW
00284   };
00285 
00286   const int8 *bb = _delta_xy_table[direction];
00287   this->x_offs        = bb[3];
00288   this->y_offs        = bb[2];
00289   this->x_extent      = bb[1];
00290   this->y_extent      = bb[0];
00291   this->z_extent      = 6;
00292 }
00293 
00294 static const TileIndexDiffC _ship_leave_depot_offs[] = {
00295   {-1,  0},
00296   { 0, -1}
00297 };
00298 
00299 static bool CheckShipLeaveDepot(Ship *v)
00300 {
00301   if (!v->IsChainInDepot()) return false;
00302 
00303   /* We are leaving a depot, but have to go to the exact same one; re-enter */
00304   if (v->current_order.IsType(OT_GOTO_DEPOT) &&
00305       IsShipDepotTile(v->tile) && GetDepotIndex(v->tile) == v->current_order.GetDestination()) {
00306     VehicleEnterDepot(v);
00307     return true;
00308   }
00309 
00310   TileIndex tile = v->tile;
00311   Axis axis = GetShipDepotAxis(tile);
00312 
00313   DiagDirection north_dir = ReverseDiagDir(AxisToDiagDir(axis));
00314   TileIndex north_neighbour = TILE_ADD(tile, ToTileIndexDiff(_ship_leave_depot_offs[axis]));
00315   DiagDirection south_dir = AxisToDiagDir(axis);
00316   TileIndex south_neighbour = TILE_ADD(tile, -2 * ToTileIndexDiff(_ship_leave_depot_offs[axis]));
00317 
00318   TrackBits north_tracks = DiagdirReachesTracks(north_dir) & GetTileShipTrackStatus(north_neighbour);
00319   TrackBits south_tracks = DiagdirReachesTracks(south_dir) & GetTileShipTrackStatus(south_neighbour);
00320   if (north_tracks && south_tracks) {
00321     /* Ask pathfinder for best direction */
00322     bool reverse = false;
00323     bool path_found;
00324     switch (_settings_game.pf.pathfinder_for_ships) {
00325       case VPF_OPF: reverse = OPFShipChooseTrack(v, north_neighbour, north_dir, north_tracks, path_found) == INVALID_TRACK; break; // OPF always allows reversing
00326       case VPF_NPF: reverse = NPFShipCheckReverse(v); break;
00327       case VPF_YAPF: reverse = YapfShipCheckReverse(v); break;
00328       default: NOT_REACHED();
00329     }
00330     if (reverse) north_tracks = TRACK_BIT_NONE;
00331   }
00332 
00333   if (north_tracks) {
00334     /* Leave towards north */
00335     v->direction = DiagDirToDir(north_dir);
00336   } else if (south_tracks) {
00337     /* Leave towards south */
00338     v->direction = DiagDirToDir(south_dir);
00339   } else {
00340     /* Both ways blocked */
00341     return false;
00342   }
00343 
00344   v->state = AxisToTrackBits(axis);
00345   v->vehstatus &= ~VS_HIDDEN;
00346 
00347   v->cur_speed = 0;
00348   v->UpdateViewport(true, true);
00349   SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
00350 
00351   PlayShipSound(v);
00352   VehicleServiceInDepot(v);
00353   InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00354   SetWindowClassesDirty(WC_SHIPS_LIST);
00355 
00356   return false;
00357 }
00358 
00359 static bool ShipAccelerate(Vehicle *v)
00360 {
00361   uint spd;
00362   byte t;
00363 
00364   spd = min(v->cur_speed + 1, v->vcache.cached_max_speed);
00365   spd = min(spd, v->current_order.max_speed * 2);
00366 
00367   /* updates statusbar only if speed have changed to save CPU time */
00368   if (spd != v->cur_speed) {
00369     v->cur_speed = spd;
00370     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
00371   }
00372 
00373   /* Convert direction-indepenent speed into direction-dependent speed. (old movement method) */
00374   spd = v->GetOldAdvanceSpeed(spd);
00375 
00376   if (spd == 0) return false;
00377   if ((byte)++spd == 0) return true;
00378 
00379   v->progress = (t = v->progress) - (byte)spd;
00380 
00381   return (t < v->progress);
00382 }
00383 
00389 static void ShipArrivesAt(const Vehicle *v, Station *st)
00390 {
00391   /* Check if station was ever visited before */
00392   if (!(st->had_vehicle_of_type & HVOT_SHIP)) {
00393     st->had_vehicle_of_type |= HVOT_SHIP;
00394 
00395     SetDParam(0, st->index);
00396     AddVehicleNewsItem(
00397       STR_NEWS_FIRST_SHIP_ARRIVAL,
00398       (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
00399       v->index,
00400       st->index
00401     );
00402     AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
00403   }
00404 }
00405 
00406 
00416 static Track ChooseShipTrack(Ship *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks)
00417 {
00418   assert(IsValidDiagDirection(enterdir));
00419 
00420   bool path_found = true;
00421   Track track;
00422   switch (_settings_game.pf.pathfinder_for_ships) {
00423     case VPF_OPF: track = OPFShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
00424     case VPF_NPF: track = NPFShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
00425     case VPF_YAPF: track = YapfShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
00426     default: NOT_REACHED();
00427   }
00428 
00429   v->HandlePathfindingResult(path_found);
00430   return track;
00431 }
00432 
00433 static const Direction _new_vehicle_direction_table[] = {
00434   DIR_N , DIR_NW, DIR_W , INVALID_DIR,
00435   DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
00436   DIR_E , DIR_SE, DIR_S
00437 };
00438 
00439 static Direction ShipGetNewDirectionFromTiles(TileIndex new_tile, TileIndex old_tile)
00440 {
00441   uint offs = (TileY(new_tile) - TileY(old_tile) + 1) * 4 +
00442               TileX(new_tile) - TileX(old_tile) + 1;
00443   assert(offs < 11 && offs != 3 && offs != 7);
00444   return _new_vehicle_direction_table[offs];
00445 }
00446 
00447 static Direction ShipGetNewDirection(Vehicle *v, int x, int y)
00448 {
00449   uint offs = (y - v->y_pos + 1) * 4 + (x - v->x_pos + 1);
00450   assert(offs < 11 && offs != 3 && offs != 7);
00451   return _new_vehicle_direction_table[offs];
00452 }
00453 
00454 static inline TrackBits GetAvailShipTracks(TileIndex tile, DiagDirection dir)
00455 {
00456   return GetTileShipTrackStatus(tile) & DiagdirReachesTracks(dir);
00457 }
00458 
00459 static const byte _ship_subcoord[4][6][3] = {
00460   {
00461     {15, 8, 1},
00462     { 0, 0, 0},
00463     { 0, 0, 0},
00464     {15, 8, 2},
00465     {15, 7, 0},
00466     { 0, 0, 0},
00467   },
00468   {
00469     { 0, 0, 0},
00470     { 8, 0, 3},
00471     { 7, 0, 2},
00472     { 0, 0, 0},
00473     { 8, 0, 4},
00474     { 0, 0, 0},
00475   },
00476   {
00477     { 0, 8, 5},
00478     { 0, 0, 0},
00479     { 0, 7, 6},
00480     { 0, 0, 0},
00481     { 0, 0, 0},
00482     { 0, 8, 4},
00483   },
00484   {
00485     { 0, 0, 0},
00486     { 8, 15, 7},
00487     { 0, 0, 0},
00488     { 8, 15, 6},
00489     { 0, 0, 0},
00490     { 7, 15, 0},
00491   }
00492 };
00493 
00494 static void ShipController(Ship *v)
00495 {
00496   uint32 r;
00497   const byte *b;
00498   Direction dir;
00499   Track track;
00500   TrackBits tracks;
00501 
00502   v->tick_counter++;
00503   v->current_order_time++;
00504 
00505   if (v->HandleBreakdown()) return;
00506 
00507   if (v->vehstatus & VS_STOPPED) return;
00508 
00509   ProcessOrders(v);
00510   v->HandleLoading();
00511 
00512   if (v->current_order.IsType(OT_LOADING)) return;
00513 
00514   if (CheckShipLeaveDepot(v)) return;
00515 
00516   v->ShowVisualEffect();
00517 
00518   if (!ShipAccelerate(v)) return;
00519 
00520   GetNewVehiclePosResult gp = GetNewVehiclePos(v);
00521   if (v->state != TRACK_BIT_WORMHOLE) {
00522     /* Not on a bridge */
00523     if (gp.old_tile == gp.new_tile) {
00524       /* Staying in tile */
00525       if (v->IsInDepot()) {
00526         gp.x = v->x_pos;
00527         gp.y = v->y_pos;
00528       } else {
00529         /* Not inside depot */
00530         r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
00531         if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
00532 
00533         /* A leave station order only needs one tick to get processed, so we can
00534          * always skip ahead. */
00535         if (v->current_order.IsType(OT_LEAVESTATION)) {
00536           v->current_order.Free();
00537           SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
00538         } else if (v->dest_tile != 0) {
00539           /* We have a target, let's see if we reached it... */
00540           if (v->current_order.IsType(OT_GOTO_WAYPOINT) &&
00541               DistanceManhattan(v->dest_tile, gp.new_tile) <= 3) {
00542             /* We got within 3 tiles of our target buoy, so let's skip to our
00543              * next order */
00544             UpdateVehicleTimetable(v, true);
00545             v->IncrementRealOrderIndex();
00546             v->current_order.MakeDummy();
00547           } else {
00548             /* Non-buoy orders really need to reach the tile */
00549             if (v->dest_tile == gp.new_tile) {
00550               if (v->current_order.IsType(OT_GOTO_DEPOT)) {
00551                 if ((gp.x & 0xF) == 8 && (gp.y & 0xF) == 8) {
00552                   VehicleEnterDepot(v);
00553                   return;
00554                 }
00555               } else if (v->current_order.IsType(OT_GOTO_STATION)) {
00556                 v->last_station_visited = v->current_order.GetDestination();
00557 
00558                 /* Process station in the orderlist. */
00559                 Station *st = Station::Get(v->current_order.GetDestination());
00560                 if (st->facilities & FACIL_DOCK) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
00561                   ShipArrivesAt(v, st);
00562                   v->BeginLoading();
00563                 } else { // leave stations without docks right aways
00564                   v->current_order.MakeLeaveStation();
00565                   v->IncrementRealOrderIndex();
00566                 }
00567               }
00568             }
00569           }
00570         }
00571       }
00572     } else {
00573       DiagDirection diagdir;
00574       /* New tile */
00575       if (TileX(gp.new_tile) >= MapMaxX() || TileY(gp.new_tile) >= MapMaxY()) {
00576         goto reverse_direction;
00577       }
00578 
00579       dir = ShipGetNewDirectionFromTiles(gp.new_tile, gp.old_tile);
00580       assert(dir == DIR_NE || dir == DIR_SE || dir == DIR_SW || dir == DIR_NW);
00581       diagdir = DirToDiagDir(dir);
00582       tracks = GetAvailShipTracks(gp.new_tile, diagdir);
00583       if (tracks == TRACK_BIT_NONE) goto reverse_direction;
00584 
00585       /* Choose a direction, and continue if we find one */
00586       track = ChooseShipTrack(v, gp.new_tile, diagdir, tracks);
00587       if (track == INVALID_TRACK) goto reverse_direction;
00588 
00589       b = _ship_subcoord[diagdir][track];
00590 
00591       gp.x = (gp.x & ~0xF) | b[0];
00592       gp.y = (gp.y & ~0xF) | b[1];
00593 
00594       /* Call the landscape function and tell it that the vehicle entered the tile */
00595       r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
00596       if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
00597 
00598       if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
00599         v->tile = gp.new_tile;
00600         v->state = TrackToTrackBits(track);
00601 
00602         /* Update ship cache when the water class changes. Aqueducts are always canals. */
00603         WaterClass old_wc = GetEffectiveWaterClass(gp.old_tile);
00604         WaterClass new_wc = GetEffectiveWaterClass(gp.new_tile);
00605         if (old_wc != new_wc) v->UpdateCache();
00606       }
00607 
00608       v->direction = (Direction)b[2];
00609     }
00610   } else {
00611     /* On a bridge */
00612     if (!IsTileType(gp.new_tile, MP_TUNNELBRIDGE) || !HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
00613       v->x_pos = gp.x;
00614       v->y_pos = gp.y;
00615       VehicleUpdatePosition(v);
00616       if ((v->vehstatus & VS_HIDDEN) == 0) VehicleUpdateViewport(v, true);
00617       return;
00618     }
00619   }
00620 
00621   /* update image of ship, as well as delta XY */
00622   dir = ShipGetNewDirection(v, gp.x, gp.y);
00623   v->x_pos = gp.x;
00624   v->y_pos = gp.y;
00625   v->z_pos = GetSlopePixelZ(gp.x, gp.y);
00626 
00627 getout:
00628   VehicleUpdatePosition(v);
00629   v->UpdateViewport(true, true);
00630   return;
00631 
00632 reverse_direction:
00633   dir = ReverseDir(v->direction);
00634   v->direction = dir;
00635   goto getout;
00636 }
00637 
00638 bool Ship::Tick()
00639 {
00640   if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
00641 
00642   ShipController(this);
00643 
00644   return true;
00645 }
00646 
00656 CommandCost CmdBuildShip(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
00657 {
00658   tile = GetShipDepotNorthTile(tile);
00659   if (flags & DC_EXEC) {
00660     int x;
00661     int y;
00662 
00663     const ShipVehicleInfo *svi = &e->u.ship;
00664 
00665     Ship *v = new Ship();
00666     *ret = v;
00667 
00668     v->owner = _current_company;
00669     v->tile = tile;
00670     x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
00671     y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
00672     v->x_pos = x;
00673     v->y_pos = y;
00674     v->z_pos = GetSlopePixelZ(x, y);
00675 
00676     v->UpdateDeltaXY(v->direction);
00677     v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
00678 
00679     v->spritenum = svi->image_index;
00680     v->cargo_type = e->GetDefaultCargoType();
00681     v->cargo_cap = svi->capacity;
00682 
00683     v->last_station_visited = INVALID_STATION;
00684     v->engine_type = e->index;
00685 
00686     v->reliability = e->reliability;
00687     v->reliability_spd_dec = e->reliability_spd_dec;
00688     v->max_age = e->GetLifeLengthInDays();
00689     _new_vehicle_id = v->index;
00690 
00691     v->state = TRACK_BIT_DEPOT;
00692 
00693     v->service_interval = Company::Get(_current_company)->settings.vehicle.servint_ships;
00694     v->date_of_last_service = _date;
00695     v->build_year = _cur_year;
00696     v->cur_image = SPR_IMG_QUERY;
00697     v->random_bits = VehicleRandomBits();
00698 
00699     v->UpdateCache();
00700 
00701     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
00702 
00703     v->InvalidateNewGRFCacheOfChain();
00704 
00705     v->cargo_cap = e->DetermineCapacity(v);
00706 
00707     v->InvalidateNewGRFCacheOfChain();
00708 
00709     VehicleUpdatePosition(v);
00710   }
00711 
00712   return CommandCost();
00713 }
00714 
00715 bool Ship::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
00716 {
00717   const Depot *depot = FindClosestShipDepot(this, 0);
00718 
00719   if (depot == NULL) return false;
00720 
00721   if (location    != NULL) *location    = depot->xy;
00722   if (destination != NULL) *destination = depot->index;
00723 
00724   return true;
00725 }