ship_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: ship_cmd.cpp 24424 2012-07-20 19:45:31Z rubidium $ */
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 #define MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)
00275   static const uint32 _delta_xy_table[8] = {
00276     MKIT( 6,  6,  -3,  -3),
00277     MKIT( 6, 32,  -3, -16),
00278     MKIT( 6,  6,  -3,  -3),
00279     MKIT(32,  6, -16,  -3),
00280     MKIT( 6,  6,  -3,  -3),
00281     MKIT( 6, 32,  -3, -16),
00282     MKIT( 6,  6,  -3,  -3),
00283     MKIT(32,  6, -16,  -3),
00284   };
00285 #undef MKIT
00286 
00287   uint32 x = _delta_xy_table[direction];
00288   this->x_offs        = GB(x,  0, 8);
00289   this->y_offs        = GB(x,  8, 8);
00290   this->x_extent      = GB(x, 16, 8);
00291   this->y_extent      = GB(x, 24, 8);
00292   this->z_extent      = 6;
00293 }
00294 
00295 static const TileIndexDiffC _ship_leave_depot_offs[] = {
00296   {-1,  0},
00297   { 0, -1}
00298 };
00299 
00300 static bool CheckShipLeaveDepot(Ship *v)
00301 {
00302   if (!v->IsChainInDepot()) return false;
00303 
00304   /* We are leaving a depot, but have to go to the exact same one; re-enter */
00305   if (v->current_order.IsType(OT_GOTO_DEPOT) &&
00306       IsShipDepotTile(v->tile) && GetDepotIndex(v->tile) == v->current_order.GetDestination()) {
00307     VehicleEnterDepot(v);
00308     return true;
00309   }
00310 
00311   TileIndex tile = v->tile;
00312   Axis axis = GetShipDepotAxis(tile);
00313 
00314   /* Check first (north) side */
00315   if (DiagdirReachesTracks((DiagDirection)axis) & GetTileShipTrackStatus(TILE_ADD(tile, ToTileIndexDiff(_ship_leave_depot_offs[axis])))) {
00316     v->direction = ReverseDir(AxisToDirection(axis));
00317   /* Check second (south) side */
00318   } else if (DiagdirReachesTracks((DiagDirection)(axis + 2)) & GetTileShipTrackStatus(TILE_ADD(tile, -2 * ToTileIndexDiff(_ship_leave_depot_offs[axis])))) {
00319     v->direction = AxisToDirection(axis);
00320   } else {
00321     return false;
00322   }
00323 
00324   v->state = AxisToTrackBits(axis);
00325   v->vehstatus &= ~VS_HIDDEN;
00326 
00327   v->cur_speed = 0;
00328   v->UpdateViewport(true, true);
00329   SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
00330 
00331   PlayShipSound(v);
00332   VehicleServiceInDepot(v);
00333   InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00334   SetWindowClassesDirty(WC_SHIPS_LIST);
00335 
00336   return false;
00337 }
00338 
00339 static bool ShipAccelerate(Vehicle *v)
00340 {
00341   uint spd;
00342   byte t;
00343 
00344   spd = min(v->cur_speed + 1, v->vcache.cached_max_speed);
00345   spd = min(spd, v->current_order.max_speed * 2);
00346 
00347   /* updates statusbar only if speed have changed to save CPU time */
00348   if (spd != v->cur_speed) {
00349     v->cur_speed = spd;
00350     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
00351   }
00352 
00353   /* Convert direction-indepenent speed into direction-dependent speed. (old movement method) */
00354   spd = v->GetOldAdvanceSpeed(spd);
00355 
00356   if (spd == 0) return false;
00357   if ((byte)++spd == 0) return true;
00358 
00359   v->progress = (t = v->progress) - (byte)spd;
00360 
00361   return (t < v->progress);
00362 }
00363 
00369 static void ShipArrivesAt(const Vehicle *v, Station *st)
00370 {
00371   /* Check if station was ever visited before */
00372   if (!(st->had_vehicle_of_type & HVOT_SHIP)) {
00373     st->had_vehicle_of_type |= HVOT_SHIP;
00374 
00375     SetDParam(0, st->index);
00376     AddVehicleNewsItem(
00377       STR_NEWS_FIRST_SHIP_ARRIVAL,
00378       (v->owner == _local_company) ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
00379       v->index,
00380       st->index
00381     );
00382     AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
00383   }
00384 }
00385 
00386 
00392 static Track ChooseShipTrack(Ship *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks)
00393 {
00394   assert(IsValidDiagDirection(enterdir));
00395 
00396   bool path_found = true;
00397   Track track;
00398   switch (_settings_game.pf.pathfinder_for_ships) {
00399     case VPF_OPF: track = OPFShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
00400     case VPF_NPF: track = NPFShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
00401     case VPF_YAPF: track = YapfShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
00402     default: NOT_REACHED();
00403   }
00404 
00405   v->HandlePathfindingResult(path_found);
00406   return track;
00407 }
00408 
00409 static const Direction _new_vehicle_direction_table[] = {
00410   DIR_N , DIR_NW, DIR_W , INVALID_DIR,
00411   DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
00412   DIR_E , DIR_SE, DIR_S
00413 };
00414 
00415 static Direction ShipGetNewDirectionFromTiles(TileIndex new_tile, TileIndex old_tile)
00416 {
00417   uint offs = (TileY(new_tile) - TileY(old_tile) + 1) * 4 +
00418               TileX(new_tile) - TileX(old_tile) + 1;
00419   assert(offs < 11 && offs != 3 && offs != 7);
00420   return _new_vehicle_direction_table[offs];
00421 }
00422 
00423 static Direction ShipGetNewDirection(Vehicle *v, int x, int y)
00424 {
00425   uint offs = (y - v->y_pos + 1) * 4 + (x - v->x_pos + 1);
00426   assert(offs < 11 && offs != 3 && offs != 7);
00427   return _new_vehicle_direction_table[offs];
00428 }
00429 
00430 static inline TrackBits GetAvailShipTracks(TileIndex tile, DiagDirection dir)
00431 {
00432   return GetTileShipTrackStatus(tile) & DiagdirReachesTracks(dir);
00433 }
00434 
00435 static const byte _ship_subcoord[4][6][3] = {
00436   {
00437     {15, 8, 1},
00438     { 0, 0, 0},
00439     { 0, 0, 0},
00440     {15, 8, 2},
00441     {15, 7, 0},
00442     { 0, 0, 0},
00443   },
00444   {
00445     { 0, 0, 0},
00446     { 8, 0, 3},
00447     { 7, 0, 2},
00448     { 0, 0, 0},
00449     { 8, 0, 4},
00450     { 0, 0, 0},
00451   },
00452   {
00453     { 0, 8, 5},
00454     { 0, 0, 0},
00455     { 0, 7, 6},
00456     { 0, 0, 0},
00457     { 0, 0, 0},
00458     { 0, 8, 4},
00459   },
00460   {
00461     { 0, 0, 0},
00462     { 8, 15, 7},
00463     { 0, 0, 0},
00464     { 8, 15, 6},
00465     { 0, 0, 0},
00466     { 7, 15, 0},
00467   }
00468 };
00469 
00470 static void ShipController(Ship *v)
00471 {
00472   uint32 r;
00473   const byte *b;
00474   Direction dir;
00475   Track track;
00476   TrackBits tracks;
00477 
00478   v->tick_counter++;
00479   v->current_order_time++;
00480 
00481   if (v->HandleBreakdown()) return;
00482 
00483   if (v->vehstatus & VS_STOPPED) return;
00484 
00485   ProcessOrders(v);
00486   v->HandleLoading();
00487 
00488   if (v->current_order.IsType(OT_LOADING)) return;
00489 
00490   if (CheckShipLeaveDepot(v)) return;
00491 
00492   v->ShowVisualEffect();
00493 
00494   if (!ShipAccelerate(v)) return;
00495 
00496   GetNewVehiclePosResult gp = GetNewVehiclePos(v);
00497   if (v->state != TRACK_BIT_WORMHOLE) {
00498     /* Not on a bridge */
00499     if (gp.old_tile == gp.new_tile) {
00500       /* Staying in tile */
00501       if (v->IsInDepot()) {
00502         gp.x = v->x_pos;
00503         gp.y = v->y_pos;
00504       } else {
00505         /* Not inside depot */
00506         r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
00507         if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
00508 
00509         /* A leave station order only needs one tick to get processed, so we can
00510          * always skip ahead. */
00511         if (v->current_order.IsType(OT_LEAVESTATION)) {
00512           v->current_order.Free();
00513           SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
00514         } else if (v->dest_tile != 0) {
00515           /* We have a target, let's see if we reached it... */
00516           if (v->current_order.IsType(OT_GOTO_WAYPOINT) &&
00517               DistanceManhattan(v->dest_tile, gp.new_tile) <= 3) {
00518             /* We got within 3 tiles of our target buoy, so let's skip to our
00519              * next order */
00520             UpdateVehicleTimetable(v, true);
00521             v->IncrementRealOrderIndex();
00522             v->current_order.MakeDummy();
00523           } else {
00524             /* Non-buoy orders really need to reach the tile */
00525             if (v->dest_tile == gp.new_tile) {
00526               if (v->current_order.IsType(OT_GOTO_DEPOT)) {
00527                 if ((gp.x & 0xF) == 8 && (gp.y & 0xF) == 8) {
00528                   VehicleEnterDepot(v);
00529                   return;
00530                 }
00531               } else if (v->current_order.IsType(OT_GOTO_STATION)) {
00532                 v->last_station_visited = v->current_order.GetDestination();
00533 
00534                 /* Process station in the orderlist. */
00535                 Station *st = Station::Get(v->current_order.GetDestination());
00536                 if (st->facilities & FACIL_DOCK) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
00537                   ShipArrivesAt(v, st);
00538                   v->BeginLoading();
00539                 } else { // leave stations without docks right aways
00540                   v->current_order.MakeLeaveStation();
00541                   v->IncrementRealOrderIndex();
00542                 }
00543               }
00544             }
00545           }
00546         }
00547       }
00548     } else {
00549       DiagDirection diagdir;
00550       /* New tile */
00551       if (TileX(gp.new_tile) >= MapMaxX() || TileY(gp.new_tile) >= MapMaxY()) {
00552         goto reverse_direction;
00553       }
00554 
00555       dir = ShipGetNewDirectionFromTiles(gp.new_tile, gp.old_tile);
00556       assert(dir == DIR_NE || dir == DIR_SE || dir == DIR_SW || dir == DIR_NW);
00557       diagdir = DirToDiagDir(dir);
00558       tracks = GetAvailShipTracks(gp.new_tile, diagdir);
00559       if (tracks == TRACK_BIT_NONE) goto reverse_direction;
00560 
00561       /* Choose a direction, and continue if we find one */
00562       track = ChooseShipTrack(v, gp.new_tile, diagdir, tracks);
00563       if (track == INVALID_TRACK) goto reverse_direction;
00564 
00565       b = _ship_subcoord[diagdir][track];
00566 
00567       gp.x = (gp.x & ~0xF) | b[0];
00568       gp.y = (gp.y & ~0xF) | b[1];
00569 
00570       /* Call the landscape function and tell it that the vehicle entered the tile */
00571       r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
00572       if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
00573 
00574       if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
00575         v->tile = gp.new_tile;
00576         v->state = TrackToTrackBits(track);
00577 
00578         /* Update ship cache when the water class changes. Aqueducts are always canals. */
00579         WaterClass old_wc = GetEffectiveWaterClass(gp.old_tile);
00580         WaterClass new_wc = GetEffectiveWaterClass(gp.new_tile);
00581         if (old_wc != new_wc) v->UpdateCache();
00582       }
00583 
00584       v->direction = (Direction)b[2];
00585     }
00586   } else {
00587     /* On a bridge */
00588     if (!IsTileType(gp.new_tile, MP_TUNNELBRIDGE) || !HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
00589       v->x_pos = gp.x;
00590       v->y_pos = gp.y;
00591       VehicleUpdatePosition(v);
00592       if ((v->vehstatus & VS_HIDDEN) == 0) VehicleUpdateViewport(v, true);
00593       return;
00594     }
00595   }
00596 
00597   /* update image of ship, as well as delta XY */
00598   dir = ShipGetNewDirection(v, gp.x, gp.y);
00599   v->x_pos = gp.x;
00600   v->y_pos = gp.y;
00601   v->z_pos = GetSlopePixelZ(gp.x, gp.y);
00602 
00603 getout:
00604   VehicleUpdatePosition(v);
00605   v->UpdateViewport(true, true);
00606   return;
00607 
00608 reverse_direction:
00609   dir = ReverseDir(v->direction);
00610   v->direction = dir;
00611   goto getout;
00612 }
00613 
00614 bool Ship::Tick()
00615 {
00616   if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
00617 
00618   ShipController(this);
00619 
00620   return true;
00621 }
00622 
00632 CommandCost CmdBuildShip(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
00633 {
00634   tile = GetShipDepotNorthTile(tile);
00635   if (flags & DC_EXEC) {
00636     int x;
00637     int y;
00638 
00639     const ShipVehicleInfo *svi = &e->u.ship;
00640 
00641     Ship *v = new Ship();
00642     *ret = v;
00643 
00644     v->owner = _current_company;
00645     v->tile = tile;
00646     x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
00647     y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
00648     v->x_pos = x;
00649     v->y_pos = y;
00650     v->z_pos = GetSlopePixelZ(x, y);
00651 
00652     v->UpdateDeltaXY(v->direction);
00653     v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
00654 
00655     v->spritenum = svi->image_index;
00656     v->cargo_type = e->GetDefaultCargoType();
00657     v->cargo_cap = svi->capacity;
00658 
00659     v->last_station_visited = INVALID_STATION;
00660     v->engine_type = e->index;
00661 
00662     v->reliability = e->reliability;
00663     v->reliability_spd_dec = e->reliability_spd_dec;
00664     v->max_age = e->GetLifeLengthInDays();
00665     _new_vehicle_id = v->index;
00666 
00667     v->state = TRACK_BIT_DEPOT;
00668 
00669     v->service_interval = Company::Get(_current_company)->settings.vehicle.servint_ships;
00670     v->date_of_last_service = _date;
00671     v->build_year = _cur_year;
00672     v->cur_image = SPR_IMG_QUERY;
00673     v->random_bits = VehicleRandomBits();
00674 
00675     v->UpdateCache();
00676 
00677     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
00678 
00679     v->InvalidateNewGRFCacheOfChain();
00680 
00681     v->cargo_cap = e->DetermineCapacity(v);
00682 
00683     v->InvalidateNewGRFCacheOfChain();
00684 
00685     VehicleUpdatePosition(v);
00686   }
00687 
00688   return CommandCost();
00689 }
00690 
00691 bool Ship::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
00692 {
00693   const Depot *depot = FindClosestShipDepot(this, 0);
00694 
00695   if (depot == NULL) return false;
00696 
00697   if (location    != NULL) *location    = depot->xy;
00698   if (destination != NULL) *destination = depot->index;
00699 
00700   return true;
00701 }