# 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 "vehicle_gui.h"
    00022 #include "newgrf_engine.h"
    00023 #include "pathfinder/yapf/yapf.h"
    00024 #include "newgrf_sound.h"
    00025 #include "spritecache.h"
    00026 #include "strings_func.h"
    00027 #include "window_func.h"
    00028 #include "date_func.h"
    00029 #include "vehicle_func.h"
    00030 #include "sound_func.h"
    00031 #include "ai/ai.hpp"
    00032 #include "pathfinder/opf/opf_ship.h"
    00033 #include "engine_base.h"
    00034 #include "engine_func.h"
    00035 #include "company_base.h"
    00036 #include "infrastructure_func.h"
    00037 #include "command_func.h"
    00038
    00039 #include "table/strings.h"
    00040
    00041 static const uint16 _ship_sprites[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
    00042
    00043 static inline TrackBits GetTileShipTrackStatus(TileIndex tile)
    00044 {
    00045   return TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_WATER, 0));
    00046 }
    00047
    00048 static SpriteID GetShipIcon(EngineID engine)
    00049 {
    00050   const Engine *e = Engine::Get(engine);
    00051   uint8 spritenum = e->u.ship.image_index;
    00052
    00053   if (is_custom_sprite(spritenum)) {
    00054     SpriteID sprite = GetCustomVehicleIcon(engine, DIR_W);
    00055     if (sprite != 0) return sprite;
    00056
    00057     spritenum = e->original_image_index;
    00058   }
    00059
    00060   return DIR_W + _ship_sprites[spritenum];
    00061 }
    00062
    00063 void DrawShipEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal)
    00064 {
    00065   SpriteID sprite = GetShipIcon(engine);
    00066   const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
    00067   preferred_x = Clamp(preferred_x, left - real_sprite->x_offs, right - real_sprite->width - real_sprite->x_offs);
    00068   DrawSprite(sprite, pal, preferred_x, y);
    00069 }
    00070
    00077 void GetShipSpriteSize(EngineID engine, uint &width, uint &height)
    00078 {
    00079   const Sprite *spr = GetSprite(GetShipIcon(engine), ST_NORMAL);
    00080
    00081   width  = spr->width;
    00082   height = spr->height;
    00083 }
    00084
    00085 SpriteID Ship::GetImage(Direction direction) const
    00086 {
    00087   uint8 spritenum = this->spritenum;
    00088
    00089   if (is_custom_sprite(spritenum)) {
    00090     SpriteID sprite = GetCustomVehicleSprite(this, direction);
    00091     if (sprite != 0) return sprite;
    00092
    00093     spritenum = Engine::Get(this->engine_type)->original_image_index;
    00094   }
    00095
    00096   return _ship_sprites[spritenum] + direction;
    00097 }
    00098
    00099 static const Depot *FindClosestShipDepot(const Vehicle *v, uint max_distance)
    00100 {
    00101   /* Find the closest depot */
    00102   const Depot *depot;
    00103   const Depot *best_depot = NULL;
    00104   /* If we don't have a maximum distance, i.e. distance = 0,
    00105    * we want to find any depot so the best distance of no
    00106    * depot must be more than any correct distance. On the
    00107    * other hand if we have set a maximum distance, any depot
    00108    * further away than max_distance can safely be ignored. */
    00109   uint best_dist = max_distance == 0 ? UINT_MAX : max_distance + 1;
    00110
    00111   FOR_ALL_DEPOTS(depot) {
    00112     TileIndex tile = depot->xy;
    00113     if (IsShipDepotTile(tile) && IsInfraTileUsageAllowed(VEH_SHIP, v->owner, tile)) {
    00114       uint dist = DistanceManhattan(tile, v->tile);
    00115       if (dist < best_dist) {
    00116         best_dist = dist;
    00117         best_depot = depot;
    00118       }
    00119     }
    00120   }
    00121
    00122   return best_depot;
    00123 }
    00124
    00125 static void CheckIfShipNeedsService(Vehicle *v)
    00126 {
    00127   if (Company::Get(v->owner)->settings.vehicle.servint_ships == 0 || !v->NeedsAutomaticServicing()) return;
    00128   if (v->IsInDepot()) {
    00129     VehicleServiceInDepot(v);
    00130     return;
    00131   }
    00132
    00133   uint max_distance;
    00134   switch (_settings_game.pf.pathfinder_for_ships) {
    00135     case VPF_OPF:  max_distance = 12; break;
    00136     case VPF_NPF:  max_distance = _settings_game.pf.npf.maximum_go_to_depot_penalty  / NPF_TILE_LENGTH;  break;
    00137     case VPF_YAPF: max_distance = _settings_game.pf.yapf.maximum_go_to_depot_penalty / YAPF_TILE_LENGTH; break;
    00138     default: NOT_REACHED();
    00139   }
    00140
    00141   const Depot *depot = FindClosestShipDepot(v, max_distance);
    00142
    00143   if (depot == NULL) {
    00144     if (v->current_order.IsType(OT_GOTO_DEPOT)) {
    00145       v->current_order.MakeDummy();
    00146       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    00147     }
    00148     return;
    00149   }
    00150
    00151   v->current_order.MakeGoToDepot(depot->index, ODTFB_SERVICE);
    00152   v->dest_tile = depot->xy;
    00153   SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    00154 }
    00155
    00159 void Ship::UpdateCache()
    00160 {
    00161   this->vcache.cached_max_speed = GetVehicleProperty(this, PROP_SHIP_SPEED, ShipVehInfo(this->engine_type)->max_speed);
    00162
    00163   this->UpdateVisualEffect();
    00164 }
    00165
    00166 Money Ship::GetRunningCost() const
    00167 {
    00168   const Engine *e = Engine::Get(this->engine_type);
    00169   uint cost_factor = GetVehicleProperty(this, PROP_SHIP_RUNNING_COST_FACTOR, e->u.ship.running_cost);
    00170   return GetPrice(PR_RUNNING_SHIP, cost_factor, e->grf_prop.grffile);
    00171 }
    00172
    00173 void Ship::OnNewDay()
    00174 {
    00175   if ((++this->day_counter & 7) == 0) {
    00176     DecreaseVehicleValue(this);
    00177   }
    00178
    00179   CheckVehicleBreakdown(this);
    00180   AgeVehicle(this);
    00181   CheckIfShipNeedsService(this);
    00182
    00183   CheckOrders(this);
    00184
    00185   if (this->running_ticks == 0) return;
    00186
    00187   CommandCost cost(EXPENSES_SHIP_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
    00188
    00189   this->profit_this_year -= cost.GetCost();
    00190   this->running_ticks = 0;
    00191
    00192   SubtractMoneyFromCompanyFract(this->owner, cost);
    00193
    00194   SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
    00195   /* we need this for the profit */
    00196   SetWindowClassesDirty(WC_SHIPS_LIST);
    00197 }
    00198
    00199 Trackdir Ship::GetVehicleTrackdir() const
    00200 {
    00201   if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
    00202
    00203   if (this->IsInDepot()) {
    00204     /* We'll assume the ship is facing outwards */
    00205     return DiagDirToDiagTrackdir(GetShipDepotDirection(this->tile));
    00206   }
    00207
    00208   if (this->state == TRACK_BIT_WORMHOLE) {
    00209     /* ship on aqueduct, so just use his direction and assume a diagonal track */
    00210     return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
    00211   }
    00212
    00213   return TrackDirectionToTrackdir(FindFirstTrack(this->state), this->direction);
    00214 }
    00215
    00216 void Ship::MarkDirty()
    00217 {
    00218   this->UpdateViewport(false, false);
    00219   this->UpdateCache();
    00220 }
    00221
    00222 static void PlayShipSound(const Vehicle *v)
    00223 {
    00224   if (!PlayVehicleSound(v, VSE_START)) {
    00225     SndPlayVehicleFx(ShipVehInfo(v->engine_type)->sfx, v);
    00226   }
    00227 }
    00228
    00229 void Ship::PlayLeaveStationSound() const
    00230 {
    00231   PlayShipSound(this);
    00232 }
    00233
    00234 TileIndex Ship::GetOrderStationLocation(StationID station)
    00235 {
    00236   if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
    00237
    00238   const Station *st = Station::Get(station);
    00239   if (st->dock_tile != INVALID_TILE) {
    00240     return TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
    00241   } else {
    00242     this->IncrementRealOrderIndex();
    00243     return 0;
    00244   }
    00245 }
    00246
    00247 void Ship::UpdateDeltaXY(Direction direction)
    00248 {
    00249 #define MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)
    00250   static const uint32 _delta_xy_table[8] = {
    00251     MKIT( 6,  6,  -3,  -3),
    00252     MKIT( 6, 32,  -3, -16),
    00253     MKIT( 6,  6,  -3,  -3),
    00254     MKIT(32,  6, -16,  -3),
    00255     MKIT( 6,  6,  -3,  -3),
    00256     MKIT( 6, 32,  -3, -16),
    00257     MKIT( 6,  6,  -3,  -3),
    00258     MKIT(32,  6, -16,  -3),
    00259   };
    00260 #undef MKIT
    00261
    00262   uint32 x = _delta_xy_table[direction];
    00263   this->x_offs        = GB(x,  0, 8);
    00264   this->y_offs        = GB(x,  8, 8);
    00265   this->x_extent      = GB(x, 16, 8);
    00266   this->y_extent      = GB(x, 24, 8);
    00267   this->z_extent      = 6;
    00268 }
    00269
    00270 static const TileIndexDiffC _ship_leave_depot_offs[] = {
    00271   {-1,  0},
    00272   { 0, -1}
    00273 };
    00274
    00275 static bool CheckShipLeaveDepot(Ship *v)
    00276 {
    00277   if (!v->IsInDepot()) return false;
    00278
    00279   /* We are leaving a depot, but have to go to the exact same one; re-enter */
    00280   if (v->current_order.IsType(OT_GOTO_DEPOT) &&
    00281       IsShipDepotTile(v->tile) && GetDepotIndex(v->tile) == v->current_order.GetDestination()) {
    00282     VehicleEnterDepot(v);
    00283     return true;
    00284   }
    00285
    00286   TileIndex tile = v->tile;
    00287   Axis axis = GetShipDepotAxis(tile);
    00288
    00289   /* Check first (north) side */
    00290   if (DiagdirReachesTracks((DiagDirection)axis) & GetTileShipTrackStatus(TILE_ADD(tile, ToTileIndexDiff(_ship_leave_depot_offs[axis])))) {
    00291     v->direction = ReverseDir(AxisToDirection(axis));
    00292   /* Check second (south) side */
    00293   } else if (DiagdirReachesTracks((DiagDirection)(axis + 2)) & GetTileShipTrackStatus(TILE_ADD(tile, -2 * ToTileIndexDiff(_ship_leave_depot_offs[axis])))) {
    00294     v->direction = AxisToDirection(axis);
    00295   } else {
    00296     return false;
    00297   }
    00298
    00299   v->state = AxisToTrackBits(axis);
    00300   v->vehstatus &= ~VS_HIDDEN;
    00301
    00302   v->cur_speed = 0;
    00303   v->UpdateViewport(false, true);
    00304   SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
    00305
    00306   PlayShipSound(v);
    00307   VehicleServiceInDepot(v);
    00308   InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    00309   SetWindowClassesDirty(WC_SHIPS_LIST);
    00310
    00311   return false;
    00312 }
    00313
    00314 static bool ShipAccelerate(Vehicle *v)
    00315 {
    00316   uint spd;
    00317   byte t;
    00318
    00319   spd = min(v->cur_speed + 1, v->vcache.cached_max_speed);
    00320
    00321   if(v->breakdown_ctr == 1 && v->breakdown_type == BREAKDOWN_LOW_POWER && v->cur_speed > (v->breakdown_severity * ShipVehInfo(v->engine_type)->max_speed) >> 8) {
    00322     if((v->tick_counter & 0x7) == 0 && v->cur_speed > 0) {
    00323       spd = v->cur_speed - 1;
    00324     } else {
    00325       spd = v->cur_speed;
    00326     }
    00327   }
    00328
    00329   if(v->breakdown_ctr == 1 && v->breakdown_type == BREAKDOWN_LOW_SPEED) {
    00330     spd = min(spd, v->breakdown_severity);
    00331   }
    00332
    00333   /* updates statusbar only if speed have changed to save CPU time */
    00334   if (spd != v->cur_speed) {
    00335     v->cur_speed = spd;
    00336     if (_settings_client.gui.vehicle_speed) {
    00337       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    00338     }
    00339   }
    00340
    00341   /* Convert direction-indepenent speed into direction-dependent speed. (old movement method) */
    00342   spd = v->GetOldAdvanceSpeed(spd);
    00343
    00344   if (spd == 0) return false;
    00345   if ((byte)++spd == 0) return true;
    00346
    00347   v->progress = (t = v->progress) - (byte)spd;
    00348
    00349   return (t < v->progress);
    00350 }
    00351
    00357 static void ShipArrivesAt(const Vehicle *v, Station *st)
    00358 {
    00359   /* Check if station was ever visited before */
    00360   if (!(st->had_vehicle_of_type & HVOT_SHIP)) {
    00361     st->had_vehicle_of_type |= HVOT_SHIP;
    00362
    00363     SetDParam(0, st->index);
    00364     AddVehicleNewsItem(
    00365       STR_NEWS_FIRST_SHIP_ARRIVAL,
    00366       (v->owner == _local_company) ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
    00367       v->index,
    00368       st->index
    00369     );
    00370     AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
    00371   }
    00372 }
    00373
    00374
    00380 static Track ChooseShipTrack(Ship *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks)
    00381 {
    00382   assert(IsValidDiagDirection(enterdir));
    00383
    00384   bool path_found = true;
    00385   Track track;
    00386   switch (_settings_game.pf.pathfinder_for_ships) {
    00387     case VPF_OPF: track = OPFShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
    00388     case VPF_NPF: track = NPFShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
    00389     case VPF_YAPF: track = YapfShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
    00390     default: NOT_REACHED();
    00391   }
    00392
    00393   v->HandlePathfindingResult(path_found);
    00394   return track;
    00395 }
    00396
    00397 static const Direction _new_vehicle_direction_table[] = {
    00398   DIR_N , DIR_NW, DIR_W , INVALID_DIR,
    00399   DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
    00400   DIR_E , DIR_SE, DIR_S
    00401 };
    00402
    00403 static Direction ShipGetNewDirectionFromTiles(TileIndex new_tile, TileIndex old_tile)
    00404 {
    00405   uint offs = (TileY(new_tile) - TileY(old_tile) + 1) * 4 +
    00406               TileX(new_tile) - TileX(old_tile) + 1;
    00407   assert(offs < 11 && offs != 3 && offs != 7);
    00408   return _new_vehicle_direction_table[offs];
    00409 }
    00410
    00411 static Direction ShipGetNewDirection(Vehicle *v, int x, int y)
    00412 {
    00413   uint offs = (y - v->y_pos + 1) * 4 + (x - v->x_pos + 1);
    00414   assert(offs < 11 && offs != 3 && offs != 7);
    00415   return _new_vehicle_direction_table[offs];
    00416 }
    00417
    00418 static inline TrackBits GetAvailShipTracks(TileIndex tile, DiagDirection dir)
    00419 {
    00420   return GetTileShipTrackStatus(tile) & DiagdirReachesTracks(dir);
    00421 }
    00422
    00423 static const byte _ship_subcoord[4][6][3] = {
    00424   {
    00425     {15, 8, 1},
    00426     { 0, 0, 0},
    00427     { 0, 0, 0},
    00428     {15, 8, 2},
    00429     {15, 7, 0},
    00430     { 0, 0, 0},
    00431   },
    00432   {
    00433     { 0, 0, 0},
    00434     { 8, 0, 3},
    00435     { 7, 0, 2},
    00436     { 0, 0, 0},
    00437     { 8, 0, 4},
    00438     { 0, 0, 0},
    00439   },
    00440   {
    00441     { 0, 8, 5},
    00442     { 0, 0, 0},
    00443     { 0, 7, 6},
    00444     { 0, 0, 0},
    00445     { 0, 0, 0},
    00446     { 0, 8, 4},
    00447   },
    00448   {
    00449     { 0, 0, 0},
    00450     { 8, 15, 7},
    00451     { 0, 0, 0},
    00452     { 8, 15, 6},
    00453     { 0, 0, 0},
    00454     { 7, 15, 0},
    00455   }
    00456 };
    00457
    00458 static void ShipController(Ship *v)
    00459 {
    00460   uint32 r;
    00461   const byte *b;
    00462   Direction dir;
    00463   Track track;
    00464   TrackBits tracks;
    00465
    00466   v->tick_counter++;
    00467   v->current_order_time++;
    00468
    00469   if (v->HandleBreakdown()) return;
    00470
    00471   if (v->vehstatus & VS_STOPPED) return;
    00472
    00473   ProcessOrders(v);
    00474   v->HandleLoading();
    00475
    00476   if (v->current_order.IsType(OT_LOADING)) return;
    00477
    00478   if (CheckShipLeaveDepot(v)) return;
    00479
    00480   v->ShowVisualEffect();
    00481
    00482   if (!ShipAccelerate(v)) return;
    00483
    00484   GetNewVehiclePosResult gp = GetNewVehiclePos(v);
    00485   if (v->state != TRACK_BIT_WORMHOLE) {
    00486     /* Not on a bridge */
    00487     if (gp.old_tile == gp.new_tile) {
    00488       /* Staying in tile */
    00489       if (v->IsInDepot()) {
    00490         gp.x = v->x_pos;
    00491         gp.y = v->y_pos;
    00492       } else {
    00493         /* Not inside depot */
    00494         r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
    00495         if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
    00496
    00497         /* A leave station order only needs one tick to get processed, so we can
    00498          * always skip ahead. */
    00499         if (v->current_order.IsType(OT_LEAVESTATION)) {
    00500           v->current_order.Free();
    00501           SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    00502         } else if (v->dest_tile != 0) {
    00503           /* We have a target, let's see if we reached it... */
    00504           if (v->current_order.IsType(OT_GOTO_WAYPOINT) &&
    00505               DistanceManhattan(v->dest_tile, gp.new_tile) <= 3) {
    00506             /* We got within 3 tiles of our target buoy, so let's skip to our
    00507              * next order */
    00508             UpdateVehicleTimetable(v, true);
    00509             v->IncrementRealOrderIndex();
    00510             v->current_order.MakeDummy();
    00511           } else {
    00512             /* Non-buoy orders really need to reach the tile */
    00513             if (v->dest_tile == gp.new_tile) {
    00514               if (v->current_order.IsType(OT_GOTO_DEPOT)) {
    00515                 if ((gp.x & 0xF) == 8 && (gp.y & 0xF) == 8) {
    00516                   VehicleEnterDepot(v);
    00517                   return;
    00518                 }
    00519               } else if (v->current_order.IsType(OT_GOTO_STATION)) {
    00520                 v->last_station_visited = v->current_order.GetDestination();
    00521
    00522                 /* Process station in the orderlist. */
    00523                 Station *st = Station::Get(v->current_order.GetDestination());
    00524                 if (st->facilities & FACIL_DOCK) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
    00525                   ShipArrivesAt(v, st);
    00526                   v->BeginLoading();
    00527                 } else { // leave stations without docks right aways
    00528                   v->current_order.MakeLeaveStation();
    00529                   v->IncrementRealOrderIndex();
    00530                 }
    00531               }
    00532             }
    00533           }
    00534         }
    00535       }
    00536     } else {
    00537       DiagDirection diagdir;
    00538       /* New tile */
    00539       if (TileX(gp.new_tile) >= MapMaxX() || TileY(gp.new_tile) >= MapMaxY()) {
    00540         goto reverse_direction;
    00541       }
    00542
    00543       dir = ShipGetNewDirectionFromTiles(gp.new_tile, gp.old_tile);
    00544       assert(dir == DIR_NE || dir == DIR_SE || dir == DIR_SW || dir == DIR_NW);
    00545       diagdir = DirToDiagDir(dir);
    00546       tracks = GetAvailShipTracks(gp.new_tile, diagdir);
    00547       if (tracks == TRACK_BIT_NONE) goto reverse_direction;
    00548
    00549       /* Choose a direction, and continue if we find one */
    00550       track = ChooseShipTrack(v, gp.new_tile, diagdir, tracks);
    00551       if (track == INVALID_TRACK) goto reverse_direction;
    00552
    00553       b = _ship_subcoord[diagdir][track];
    00554
    00555       gp.x = (gp.x & ~0xF) | b[0];
    00556       gp.y = (gp.y & ~0xF) | b[1];
    00557
    00558       /* Call the landscape function and tell it that the vehicle entered the tile */
    00559       r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
    00560       if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
    00561
    00562       if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
    00563         v->tile = gp.new_tile;
    00564         v->state = TrackToTrackBits(track);
    00565       }
    00566
    00567       v->direction = (Direction)b[2];
    00568     }
    00569   } else {
    00570     /* On a bridge */
    00571     if (!IsTileType(gp.new_tile, MP_TUNNELBRIDGE) || !HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
    00572       v->x_pos = gp.x;
    00573       v->y_pos = gp.y;
    00574       VehicleMove(v, !(v->vehstatus & VS_HIDDEN));
    00575       return;
    00576     }
    00577   }
    00578
    00579   /* update image of ship, as well as delta XY */
    00580   dir = ShipGetNewDirection(v, gp.x, gp.y);
    00581   v->x_pos = gp.x;
    00582   v->y_pos = gp.y;
    00583   v->z_pos = GetSlopeZ(gp.x, gp.y);
    00584
    00585 getout:
    00586   v->UpdateViewport(true, true);
    00587   return;
    00588
    00589 reverse_direction:
    00590   dir = ReverseDir(v->direction);
    00591   v->direction = dir;
    00592   goto getout;
    00593 }
    00594
    00595 bool Ship::Tick()
    00596 {
    00597   if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
    00598
    00599   ShipController(this);
    00600
    00601   return true;
    00602 }
    00603
    00613 CommandCost CmdBuildShip(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
    00614 {
    00615   tile = GetShipDepotNorthTile(tile);
    00616   UnitID unit_num;
    00617
    00618   if (!IsEngineBuildable(e->index, VEH_SHIP, _current_company)) return_cmd_error(STR_ERROR_SHIP_NOT_AVAILABLE);
    00619
    00620   CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
    00621
    00622   /* Engines without valid cargo should not be available */
    00623   if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
    00624
    00625   if (flags & DC_QUERY_COST) return value;
    00626
    00627   /* The ai_new queries the vehicle cost before building the route,
    00628    * so we must check against cheaters no sooner than now. --pasky */
    00629   if (!IsShipDepotTile(tile)) return CMD_ERROR;
    00630   if (!IsInfraUsageAllowed(VEH_SHIP, _current_company, GetTileOwner(tile))) return CMD_ERROR;
    00631
    00632   unit_num = (flags & DC_AUTOREPLACE) ? 0 : GetFreeUnitNumber(VEH_SHIP);
    00633
    00634   if (!Vehicle::CanAllocateItem() || unit_num > _settings_game.vehicle.max_ships)
    00635     return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
    00636
    00637   if (flags & DC_EXEC) {
    00638     int x;
    00639     int y;
    00640
    00641     const ShipVehicleInfo *svi = &e->u.ship;
    00642
    00643     Ship *v = new Ship();
    00644     *ret = v;
    00645
    00646     v->owner = _current_company;
    00647     v->tile = tile;
    00648     x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
    00649     y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
    00650     v->x_pos = x;
    00651     v->y_pos = y;
    00652     v->z_pos = GetSlopeZ(x, y);
    00653
    00654     v->UpdateDeltaXY(v->direction);
    00655     v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
    00656
    00657     v->spritenum = svi->image_index;
    00658     v->cargo_type = e->GetDefaultCargoType();
    00659     v->cargo_cap = svi->capacity;
    00660
    00661     v->last_station_visited = INVALID_STATION;
    00662     v->last_loading_station = INVALID_STATION;
    00663
    00664     v->engine_type = e->index;
    00665
    00666     v->reliability = e->reliability;
    00667     v->reliability_spd_dec = e->reliability_spd_dec;
    00668     v->breakdown_chance = 64; // Ships have a 50% lower breakdown chance than normal.
    00669     v->max_age = e->GetLifeLengthInDays();
    00670     _new_vehicle_id = v->index;
    00671
    00672     v->state = TRACK_BIT_DEPOT;
    00673
    00674     v->service_interval = Company::Get(_current_company)->settings.vehicle.servint_ships;
    00675     v->date_of_last_service = _date;
    00676     v->build_year = _cur_year;
    00677     v->cur_image = SPR_IMG_QUERY;
    00678     v->random_bits = VehicleRandomBits();
    00679
    00680     v->UpdateCache();
    00681
    00682     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
    00683
    00684     v->InvalidateNewGRFCacheOfChain();
    00685
    00686     v->cargo_cap = GetVehicleCapacity(v);
    00687
    00688     v->InvalidateNewGRFCacheOfChain();
    00689
    00690     VehicleMove(v, false);
    00691   }
    00692
    00693   return CommandCost();
    00694 }
    00695
    00696 bool Ship::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
    00697 {
    00698   const Depot *depot = FindClosestShipDepot(this, 0);
    00699
    00700   if (depot == NULL) return false;
    00701
    00702   if (location    != NULL) *location    = depot->xy;
    00703   if (destination != NULL) *destination = depot->index;
    00704
    00705   return true;
    00706 }