ship_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: ship_cmd.cpp 15718 2009-03-15 00:32:18Z rubidium $ */
00002 
00005 #include "stdafx.h"
00006 #include "ship.h"
00007 #include "landscape.h"
00008 #include "timetable.h"
00009 #include "command_func.h"
00010 #include "station_map.h"
00011 #include "news_func.h"
00012 #include "company_func.h"
00013 #include "npf.h"
00014 #include "depot_base.h"
00015 #include "vehicle_gui.h"
00016 #include "newgrf_engine.h"
00017 #include "yapf/yapf.h"
00018 #include "newgrf_sound.h"
00019 #include "spritecache.h"
00020 #include "strings_func.h"
00021 #include "functions.h"
00022 #include "window_func.h"
00023 #include "date_func.h"
00024 #include "vehicle_func.h"
00025 #include "sound_func.h"
00026 #include "variables.h"
00027 #include "autoreplace_gui.h"
00028 #include "gfx_func.h"
00029 #include "effectvehicle_func.h"
00030 #include "settings_type.h"
00031 #include "ai/ai.hpp"
00032 #include "pathfind.h"
00033 
00034 #include "table/strings.h"
00035 #include "table/sprites.h"
00036 
00037 static const uint16 _ship_sprites[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
00038 
00039 static const TrackBits _ship_sometracks[4] = {
00040   TRACK_BIT_X | TRACK_BIT_LOWER | TRACK_BIT_LEFT,  // 0x19, // DIAGDIR_NE
00041   TRACK_BIT_Y | TRACK_BIT_UPPER | TRACK_BIT_LEFT,  // 0x16, // DIAGDIR_SE
00042   TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT, // 0x25, // DIAGDIR_SW
00043   TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_RIGHT, // 0x2A, // DIAGDIR_NW
00044 };
00045 
00046 static inline TrackBits GetTileShipTrackStatus(TileIndex tile)
00047 {
00048   return TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_WATER, 0));
00049 }
00050 
00051 static SpriteID GetShipIcon(EngineID engine)
00052 {
00053   uint8 spritenum = ShipVehInfo(engine)->image_index;
00054 
00055   if (is_custom_sprite(spritenum)) {
00056     SpriteID sprite = GetCustomVehicleIcon(engine, DIR_W);
00057     if (sprite != 0) return sprite;
00058 
00059     spritenum = GetEngine(engine)->image_index;
00060   }
00061 
00062   return 6 + _ship_sprites[spritenum];
00063 }
00064 
00065 void DrawShipEngine(int x, int y, EngineID engine, SpriteID pal)
00066 {
00067   DrawSprite(GetShipIcon(engine), pal, x, y);
00068 }
00069 
00075 void GetShipSpriteSize(EngineID engine, uint &width, uint &height)
00076 {
00077   const Sprite *spr = GetSprite(GetShipIcon(engine), ST_NORMAL);
00078 
00079   width  = spr->width;
00080   height = spr->height;
00081 }
00082 
00083 SpriteID Ship::GetImage(Direction direction) const
00084 {
00085   uint8 spritenum = this->spritenum;
00086 
00087   if (is_custom_sprite(spritenum)) {
00088     SpriteID sprite = GetCustomVehicleSprite(this, direction);
00089     if (sprite != 0) return sprite;
00090 
00091     spritenum = GetEngine(this->engine_type)->image_index;
00092   }
00093 
00094   return _ship_sprites[spritenum] + direction;
00095 }
00096 
00097 static const Depot *FindClosestShipDepot(const Vehicle *v)
00098 {
00099   if (_settings_game.pf.pathfinder_for_ships == VPF_NPF) { // NPF is used
00100     Trackdir trackdir = GetVehicleTrackdir(v);
00101     NPFFoundTargetData ftd = NPFRouteToDepotTrialError(v->tile, trackdir, false, TRANSPORT_WATER, 0, v->owner, INVALID_RAILTYPES);
00102 
00103     if (ftd.best_bird_dist == 0) return GetDepotByTile(ftd.node.tile); // Found target
00104 
00105     return NULL; // Did not find target
00106   }
00107 
00108   /* OPF or YAPF - find the closest depot */
00109 
00110   const Depot *depot;
00111   const Depot *best_depot = NULL;
00112   uint best_dist = UINT_MAX;
00113 
00114   FOR_ALL_DEPOTS(depot) {
00115     TileIndex tile = depot->xy;
00116     if (IsShipDepotTile(tile) && IsTileOwner(tile, v->owner)) {
00117       uint dist = DistanceManhattan(tile, v->tile);
00118       if (dist < best_dist) {
00119         best_dist = dist;
00120         best_depot = depot;
00121       }
00122     }
00123   }
00124 
00125   return best_depot;
00126 }
00127 
00128 static void CheckIfShipNeedsService(Vehicle *v)
00129 {
00130   if (_settings_game.vehicle.servint_ships == 0 || !v->NeedsAutomaticServicing()) return;
00131   if (v->IsInDepot()) {
00132     VehicleServiceInDepot(v);
00133     return;
00134   }
00135 
00136   const Depot *depot = FindClosestShipDepot(v);
00137 
00138   if (depot == NULL || DistanceManhattan(v->tile, depot->xy) > 12) {
00139     if (v->current_order.IsType(OT_GOTO_DEPOT)) {
00140       v->current_order.MakeDummy();
00141       InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
00142     }
00143     return;
00144   }
00145 
00146   v->current_order.MakeGoToDepot(depot->index, ODTFB_SERVICE);
00147   v->dest_tile = depot->xy;
00148   InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
00149 }
00150 
00151 Money Ship::GetRunningCost() const
00152 {
00153   return GetVehicleProperty(this, 0x0F, ShipVehInfo(this->engine_type)->running_cost) * _price.ship_running;
00154 }
00155 
00156 void Ship::OnNewDay()
00157 {
00158   if ((++this->day_counter & 7) == 0)
00159     DecreaseVehicleValue(this);
00160 
00161   CheckVehicleBreakdown(this);
00162   AgeVehicle(this);
00163   CheckIfShipNeedsService(this);
00164 
00165   CheckOrders(this);
00166 
00167   if (this->running_ticks == 0) return;
00168 
00169   CommandCost cost(EXPENSES_SHIP_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
00170 
00171   this->profit_this_year -= cost.GetCost();
00172   this->running_ticks = 0;
00173 
00174   SubtractMoneyFromCompanyFract(this->owner, cost);
00175 
00176   InvalidateWindow(WC_VEHICLE_DETAILS, this->index);
00177   /* we need this for the profit */
00178   InvalidateWindowClasses(WC_SHIPS_LIST);
00179 }
00180 
00181 static void HandleBrokenShip(Vehicle *v)
00182 {
00183   if (v->breakdown_ctr != 1) {
00184     v->breakdown_ctr = 1;
00185     v->cur_speed = 0;
00186 
00187     if (v->breakdowns_since_last_service != 255)
00188       v->breakdowns_since_last_service++;
00189 
00190     InvalidateWindow(WC_VEHICLE_VIEW, v->index);
00191     InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
00192 
00193     if (!PlayVehicleSound(v, VSE_BREAKDOWN)) {
00194       SndPlayVehicleFx((_settings_game.game_creation.landscape != LT_TOYLAND) ?
00195         SND_10_TRAIN_BREAKDOWN : SND_3A_COMEDY_BREAKDOWN_2, v);
00196     }
00197 
00198     if (!(v->vehstatus & VS_HIDDEN)) {
00199       Vehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
00200       if (u != NULL) u->u.effect.animation_state = v->breakdown_delay * 2;
00201     }
00202   }
00203 
00204   if (!(v->tick_counter & 1)) {
00205     if (!--v->breakdown_delay) {
00206       v->breakdown_ctr = 0;
00207       InvalidateWindow(WC_VEHICLE_VIEW, v->index);
00208     }
00209   }
00210 }
00211 
00212 void Ship::MarkDirty()
00213 {
00214   this->cur_image = this->GetImage(this->direction);
00215   MarkSingleVehicleDirty(this);
00216 }
00217 
00218 static void PlayShipSound(const Vehicle *v)
00219 {
00220   if (!PlayVehicleSound(v, VSE_START)) {
00221     SndPlayVehicleFx(ShipVehInfo(v->engine_type)->sfx, v);
00222   }
00223 }
00224 
00225 void Ship::PlayLeaveStationSound() const
00226 {
00227   PlayShipSound(this);
00228 }
00229 
00230 TileIndex Ship::GetOrderStationLocation(StationID station)
00231 {
00232   if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
00233 
00234   const Station *st = GetStation(station);
00235   if (st->dock_tile != INVALID_TILE) {
00236     return TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
00237   } else {
00238     this->cur_order_index++;
00239     return 0;
00240   }
00241 }
00242 
00243 void Ship::UpdateDeltaXY(Direction direction)
00244 {
00245 #define MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)
00246   static const uint32 _delta_xy_table[8] = {
00247     MKIT( 6,  6,  -3,  -3),
00248     MKIT( 6, 32,  -3, -16),
00249     MKIT( 6,  6,  -3,  -3),
00250     MKIT(32,  6, -16,  -3),
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   };
00256 #undef MKIT
00257 
00258   uint32 x = _delta_xy_table[direction];
00259   this->x_offs        = GB(x,  0, 8);
00260   this->y_offs        = GB(x,  8, 8);
00261   this->x_extent      = GB(x, 16, 8);
00262   this->y_extent      = GB(x, 24, 8);
00263   this->z_extent      = 6;
00264 }
00265 
00266 void RecalcShipStuff(Vehicle *v)
00267 {
00268   v->UpdateDeltaXY(v->direction);
00269   v->cur_image = v->GetImage(v->direction);
00270   v->MarkDirty();
00271   InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
00272 }
00273 
00274 static const TileIndexDiffC _ship_leave_depot_offs[] = {
00275   {-1,  0},
00276   { 0, -1}
00277 };
00278 
00279 static void CheckShipLeaveDepot(Vehicle *v)
00280 {
00281   if (!v->IsInDepot()) return;
00282 
00283   TileIndex tile = v->tile;
00284   Axis axis = GetShipDepotAxis(tile);
00285 
00286   /* Check first (north) side */
00287   if (_ship_sometracks[axis] & GetTileShipTrackStatus(TILE_ADD(tile, ToTileIndexDiff(_ship_leave_depot_offs[axis])))) {
00288     v->direction = ReverseDir(AxisToDirection(axis));
00289   /* Check second (south) side */
00290   } else if (_ship_sometracks[axis + 2] & GetTileShipTrackStatus(TILE_ADD(tile, -2 * ToTileIndexDiff(_ship_leave_depot_offs[axis])))) {
00291     v->direction = AxisToDirection(axis);
00292   } else {
00293     return;
00294   }
00295 
00296   v->u.ship.state = AxisToTrackBits(axis);
00297   v->vehstatus &= ~VS_HIDDEN;
00298 
00299   v->cur_speed = 0;
00300   RecalcShipStuff(v);
00301 
00302   PlayShipSound(v);
00303   VehicleServiceInDepot(v);
00304   InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00305   InvalidateWindowClasses(WC_SHIPS_LIST);
00306 }
00307 
00308 static bool ShipAccelerate(Vehicle *v)
00309 {
00310   uint spd;
00311   byte t;
00312 
00313   spd = min(v->cur_speed + 1, GetVehicleProperty(v, 0x0B, v->max_speed));
00314 
00315   /* updates statusbar only if speed have changed to save CPU time */
00316   if (spd != v->cur_speed) {
00317     v->cur_speed = spd;
00318     if (_settings_client.gui.vehicle_speed)
00319       InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
00320   }
00321 
00322   /* Decrease somewhat when turning */
00323   if (!(v->direction & 1)) spd = spd * 3 / 4;
00324 
00325   if (spd == 0) return false;
00326   if ((byte)++spd == 0) return true;
00327 
00328   v->progress = (t = v->progress) - (byte)spd;
00329 
00330   return (t < v->progress);
00331 }
00332 
00333 static void ShipArrivesAt(const Vehicle *v, Station *st)
00334 {
00335   /* Check if station was ever visited before */
00336   if (!(st->had_vehicle_of_type & HVOT_SHIP)) {
00337     st->had_vehicle_of_type |= HVOT_SHIP;
00338 
00339     SetDParam(0, st->index);
00340     AddNewsItem(
00341       STR_9833_CITIZENS_CELEBRATE_FIRST,
00342       (v->owner == _local_company) ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
00343       v->index,
00344       st->index
00345     );
00346     AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
00347   }
00348 }
00349 
00350 struct PathFindShip {
00351   TileIndex skiptile;
00352   TileIndex dest_coords;
00353   uint best_bird_dist;
00354   uint best_length;
00355 };
00356 
00357 static bool ShipTrackFollower(TileIndex tile, PathFindShip *pfs, int track, uint length)
00358 {
00359   /* Found dest? */
00360   if (tile == pfs->dest_coords) {
00361     pfs->best_bird_dist = 0;
00362 
00363     pfs->best_length = minu(pfs->best_length, length);
00364     return true;
00365   }
00366 
00367   /* Skip this tile in the calculation */
00368   if (tile != pfs->skiptile) {
00369     pfs->best_bird_dist = minu(pfs->best_bird_dist, DistanceMaxPlusManhattan(pfs->dest_coords, tile));
00370   }
00371 
00372   return false;
00373 }
00374 
00375 static const byte _ship_search_directions[6][4] = {
00376   { 0, 9, 2, 9 },
00377   { 9, 1, 9, 3 },
00378   { 9, 0, 3, 9 },
00379   { 1, 9, 9, 2 },
00380   { 3, 2, 9, 9 },
00381   { 9, 9, 1, 0 },
00382 };
00383 
00384 static const byte _pick_shiptrack_table[6] = {1, 3, 2, 2, 0, 0};
00385 
00386 static uint FindShipTrack(Vehicle *v, TileIndex tile, DiagDirection dir, TrackBits bits, TileIndex skiptile, Track *track)
00387 {
00388   PathFindShip pfs;
00389   Track i, best_track;
00390   uint best_bird_dist = 0;
00391   uint best_length    = 0;
00392   uint r;
00393   byte ship_dir = v->direction & 3;
00394 
00395   pfs.dest_coords = v->dest_tile;
00396   pfs.skiptile = skiptile;
00397 
00398   best_track = INVALID_TRACK;
00399 
00400   do {
00401     i = RemoveFirstTrack(&bits);
00402 
00403     pfs.best_bird_dist = UINT_MAX;
00404     pfs.best_length = UINT_MAX;
00405 
00406     FollowTrack(tile, PATHFIND_FLAGS_SHIP_MODE | PATHFIND_FLAGS_DISABLE_TILE_HASH, TRANSPORT_WATER, 0, (DiagDirection)_ship_search_directions[i][dir], (TPFEnumProc*)ShipTrackFollower, NULL, &pfs);
00407 
00408     if (best_track != INVALID_TRACK) {
00409       if (pfs.best_bird_dist != 0) {
00410         /* neither reached the destination, pick the one with the smallest bird dist */
00411         if (pfs.best_bird_dist > best_bird_dist) goto bad;
00412         if (pfs.best_bird_dist < best_bird_dist) goto good;
00413       } else {
00414         if (pfs.best_length > best_length) goto bad;
00415         if (pfs.best_length < best_length) goto good;
00416       }
00417 
00418       /* if we reach this position, there's two paths of equal value so far.
00419        * pick one randomly. */
00420       r = GB(Random(), 0, 8);
00421       if (_pick_shiptrack_table[i] == ship_dir) r += 80;
00422       if (_pick_shiptrack_table[best_track] == ship_dir) r -= 80;
00423       if (r <= 127) goto bad;
00424     }
00425 good:;
00426     best_track = i;
00427     best_bird_dist = pfs.best_bird_dist;
00428     best_length = pfs.best_length;
00429 bad:;
00430 
00431   } while (bits != 0);
00432 
00433   *track = best_track;
00434   return best_bird_dist;
00435 }
00436 
00437 static inline NPFFoundTargetData PerfNPFRouteToStationOrTile(TileIndex tile, Trackdir trackdir, bool ignore_start_tile, NPFFindStationOrTileData *target, TransportType type, Owner owner, RailTypes railtypes)
00438 {
00439 
00440   void *perf = NpfBeginInterval();
00441   NPFFoundTargetData ret = NPFRouteToStationOrTile(tile, trackdir, ignore_start_tile, target, type, 0, owner, railtypes);
00442   int t = NpfEndInterval(perf);
00443   DEBUG(yapf, 4, "[NPFW] %d us - %d rounds - %d open - %d closed -- ", t, 0, _aystar_stats_open_size, _aystar_stats_closed_size);
00444   return ret;
00445 }
00446 
00450 static Track ChooseShipTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks)
00451 {
00452   assert(IsValidDiagDirection(enterdir));
00453 
00454   switch (_settings_game.pf.pathfinder_for_ships) {
00455     case VPF_YAPF: { // YAPF
00456       Trackdir trackdir = YapfChooseShipTrack(v, tile, enterdir, tracks);
00457       if (trackdir != INVALID_TRACKDIR) return TrackdirToTrack(trackdir);
00458     } break;
00459 
00460     case VPF_NPF: { // NPF
00461       NPFFindStationOrTileData fstd;
00462       Trackdir trackdir = GetVehicleTrackdir(v);
00463       assert(trackdir != INVALID_TRACKDIR); // Check that we are not in a depot
00464 
00465       NPFFillWithOrderData(&fstd, v);
00466 
00467       NPFFoundTargetData ftd = PerfNPFRouteToStationOrTile(tile - TileOffsByDiagDir(enterdir), trackdir, true, &fstd, TRANSPORT_WATER, v->owner, INVALID_RAILTYPES);
00468 
00469       /* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains
00470        * the direction we need to take to get there, if ftd.best_bird_dist is not 0,
00471        * we did not find our target, but ftd.best_trackdir contains the direction leading
00472        * to the tile closest to our target. */
00473       if (ftd.best_trackdir != 0xff) return TrackdirToTrack(ftd.best_trackdir); // TODO: Wrapper function?
00474     } break;
00475 
00476     default:
00477     case VPF_OPF: { // OPF
00478       TileIndex tile2 = TILE_ADD(tile, -TileOffsByDiagDir(enterdir));
00479       Track track;
00480 
00481       /* Let's find out how far it would be if we would reverse first */
00482       TrackBits b = GetTileShipTrackStatus(tile2) & _ship_sometracks[ReverseDiagDir(enterdir)] & v->u.ship.state;
00483 
00484       uint distr = UINT_MAX; // distance if we reversed
00485       if (b != 0) {
00486         distr = FindShipTrack(v, tile2, ReverseDiagDir(enterdir), b, tile, &track);
00487         if (distr != UINT_MAX) distr++; // penalty for reversing
00488       }
00489 
00490       /* And if we would not reverse? */
00491       uint dist = FindShipTrack(v, tile, enterdir, tracks, 0, &track);
00492 
00493       if (dist <= distr) return track;
00494     } break;
00495   }
00496 
00497   return INVALID_TRACK; // We could better reverse
00498 }
00499 
00500 static const Direction _new_vehicle_direction_table[] = {
00501   DIR_N , DIR_NW, DIR_W , INVALID_DIR,
00502   DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
00503   DIR_E , DIR_SE, DIR_S
00504 };
00505 
00506 static Direction ShipGetNewDirectionFromTiles(TileIndex new_tile, TileIndex old_tile)
00507 {
00508   uint offs = (TileY(new_tile) - TileY(old_tile) + 1) * 4 +
00509               TileX(new_tile) - TileX(old_tile) + 1;
00510   assert(offs < 11 && offs != 3 && offs != 7);
00511   return _new_vehicle_direction_table[offs];
00512 }
00513 
00514 static Direction ShipGetNewDirection(Vehicle *v, int x, int y)
00515 {
00516   uint offs = (y - v->y_pos + 1) * 4 + (x - v->x_pos + 1);
00517   assert(offs < 11 && offs != 3 && offs != 7);
00518   return _new_vehicle_direction_table[offs];
00519 }
00520 
00521 static inline TrackBits GetAvailShipTracks(TileIndex tile, int dir)
00522 {
00523   return GetTileShipTrackStatus(tile) & _ship_sometracks[dir];
00524 }
00525 
00526 static const byte _ship_subcoord[4][6][3] = {
00527   {
00528     {15, 8, 1},
00529     { 0, 0, 0},
00530     { 0, 0, 0},
00531     {15, 8, 2},
00532     {15, 7, 0},
00533     { 0, 0, 0},
00534   },
00535   {
00536     { 0, 0, 0},
00537     { 8, 0, 3},
00538     { 7, 0, 2},
00539     { 0, 0, 0},
00540     { 8, 0, 4},
00541     { 0, 0, 0},
00542   },
00543   {
00544     { 0, 8, 5},
00545     { 0, 0, 0},
00546     { 0, 7, 6},
00547     { 0, 0, 0},
00548     { 0, 0, 0},
00549     { 0, 8, 4},
00550   },
00551   {
00552     { 0, 0, 0},
00553     { 8, 15, 7},
00554     { 0, 0, 0},
00555     { 8, 15, 6},
00556     { 0, 0, 0},
00557     { 7, 15, 0},
00558   }
00559 };
00560 
00561 static void ShipController(Vehicle *v)
00562 {
00563   uint32 r;
00564   const byte *b;
00565   Direction dir;
00566   Track track;
00567   TrackBits tracks;
00568 
00569   v->tick_counter++;
00570   v->current_order_time++;
00571 
00572   if (v->breakdown_ctr != 0) {
00573     if (v->breakdown_ctr <= 2) {
00574       HandleBrokenShip(v);
00575       return;
00576     }
00577     if (!v->current_order.IsType(OT_LOADING)) v->breakdown_ctr--;
00578   }
00579 
00580   if (v->vehstatus & VS_STOPPED) return;
00581 
00582   ProcessOrders(v);
00583   v->HandleLoading();
00584 
00585   if (v->current_order.IsType(OT_LOADING)) return;
00586 
00587   CheckShipLeaveDepot(v);
00588 
00589   if (!ShipAccelerate(v)) return;
00590 
00591   GetNewVehiclePosResult gp = GetNewVehiclePos(v);
00592   if (v->u.ship.state != TRACK_BIT_WORMHOLE) {
00593     /* Not on a bridge */
00594     if (gp.old_tile == gp.new_tile) {
00595       /* Staying in tile */
00596       if (v->IsInDepot()) {
00597         gp.x = v->x_pos;
00598         gp.y = v->y_pos;
00599       } else {
00600         /* Not inside depot */
00601         r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
00602         if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
00603 
00604         /* A leave station order only needs one tick to get processed, so we can
00605          * always skip ahead. */
00606         if (v->current_order.IsType(OT_LEAVESTATION)) {
00607           v->current_order.Free();
00608           InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
00609         } else if (v->dest_tile != 0) {
00610           /* We have a target, let's see if we reached it... */
00611           if (v->current_order.IsType(OT_GOTO_STATION) &&
00612               GetStation(v->current_order.GetDestination())->IsBuoy() &&
00613               DistanceManhattan(v->dest_tile, gp.new_tile) <= 3) {
00614             /* We got within 3 tiles of our target buoy, so let's skip to our
00615              * next order */
00616             UpdateVehicleTimetable(v, true);
00617             v->cur_order_index++;
00618             v->current_order.MakeDummy();
00619             InvalidateVehicleOrder(v, 0);
00620           } else {
00621             /* Non-buoy orders really need to reach the tile */
00622             if (v->dest_tile == gp.new_tile) {
00623               if (v->current_order.IsType(OT_GOTO_DEPOT)) {
00624                 if ((gp.x & 0xF) == 8 && (gp.y & 0xF) == 8) {
00625                   VehicleEnterDepot(v);
00626                   return;
00627                 }
00628               } else if (v->current_order.IsType(OT_GOTO_STATION)) {
00629                 v->last_station_visited = v->current_order.GetDestination();
00630 
00631                 /* Process station in the orderlist. */
00632                 Station *st = GetStation(v->current_order.GetDestination());
00633                 if (st->facilities & FACIL_DOCK) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
00634                   ShipArrivesAt(v, st);
00635                   v->BeginLoading();
00636                 } else { // leave stations without docks right aways
00637                   v->current_order.MakeLeaveStation();
00638                   v->cur_order_index++;
00639                   InvalidateVehicleOrder(v, 0);
00640                 }
00641               }
00642             }
00643           }
00644         }
00645       }
00646     } else {
00647       DiagDirection diagdir;
00648       /* New tile */
00649       if (TileX(gp.new_tile) >= MapMaxX() || TileY(gp.new_tile) >= MapMaxY()) {
00650         goto reverse_direction;
00651       }
00652 
00653       dir = ShipGetNewDirectionFromTiles(gp.new_tile, gp.old_tile);
00654       assert(dir == DIR_NE || dir == DIR_SE || dir == DIR_SW || dir == DIR_NW);
00655       diagdir = DirToDiagDir(dir);
00656       tracks = GetAvailShipTracks(gp.new_tile, diagdir);
00657       if (tracks == TRACK_BIT_NONE) goto reverse_direction;
00658 
00659       /* Choose a direction, and continue if we find one */
00660       track = ChooseShipTrack(v, gp.new_tile, diagdir, tracks);
00661       if (track == INVALID_TRACK) goto reverse_direction;
00662 
00663       b = _ship_subcoord[diagdir][track];
00664 
00665       gp.x = (gp.x & ~0xF) | b[0];
00666       gp.y = (gp.y & ~0xF) | b[1];
00667 
00668       /* Call the landscape function and tell it that the vehicle entered the tile */
00669       r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
00670       if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
00671 
00672       if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
00673         v->tile = gp.new_tile;
00674         v->u.ship.state = TrackToTrackBits(track);
00675       }
00676 
00677       v->direction = (Direction)b[2];
00678     }
00679   } else {
00680     /* On a bridge */
00681     if (!IsTileType(gp.new_tile, MP_TUNNELBRIDGE) || !HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
00682       v->x_pos = gp.x;
00683       v->y_pos = gp.y;
00684       VehicleMove(v, !(v->vehstatus & VS_HIDDEN));
00685       return;
00686     }
00687   }
00688 
00689   /* update image of ship, as well as delta XY */
00690   dir = ShipGetNewDirection(v, gp.x, gp.y);
00691   v->x_pos = gp.x;
00692   v->y_pos = gp.y;
00693   v->z_pos = GetSlopeZ(gp.x, gp.y);
00694 
00695 getout:
00696   v->UpdateDeltaXY(dir);
00697   v->cur_image = v->GetImage(dir);
00698   VehicleMove(v, true);
00699   return;
00700 
00701 reverse_direction:
00702   dir = ReverseDir(v->direction);
00703   v->direction = dir;
00704   goto getout;
00705 }
00706 
00707 static void AgeShipCargo(Vehicle *v)
00708 {
00709   if (_age_cargo_skip_counter != 0) return;
00710   v->cargo.AgeCargo();
00711 }
00712 
00713 void Ship::Tick()
00714 {
00715   if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
00716 
00717   AgeShipCargo(this);
00718   ShipController(this);
00719 }
00720 
00727 CommandCost CmdBuildShip(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00728 {
00729   UnitID unit_num;
00730 
00731   if (!IsEngineBuildable(p1, VEH_SHIP, _current_company)) return_cmd_error(STR_SHIP_NOT_AVAILABLE);
00732 
00733   const Engine *e = GetEngine(p1);
00734   CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
00735 
00736   /* Engines without valid cargo should not be available */
00737   if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
00738 
00739   if (flags & DC_QUERY_COST) return value;
00740 
00741   /* The ai_new queries the vehicle cost before building the route,
00742    * so we must check against cheaters no sooner than now. --pasky */
00743   if (!IsShipDepotTile(tile)) return CMD_ERROR;
00744   if (!IsTileOwner(tile, _current_company)) return CMD_ERROR;
00745 
00746   unit_num = (flags & DC_AUTOREPLACE) ? 0 : GetFreeUnitNumber(VEH_SHIP);
00747 
00748   if (!Vehicle::CanAllocateItem() || unit_num > _settings_game.vehicle.max_ships)
00749     return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
00750 
00751   if (flags & DC_EXEC) {
00752     int x;
00753     int y;
00754 
00755     const ShipVehicleInfo *svi = ShipVehInfo(p1);
00756 
00757     Vehicle *v = new Ship();
00758     v->unitnumber = unit_num;
00759 
00760     v->owner = _current_company;
00761     v->tile = tile;
00762     x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
00763     y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
00764     v->x_pos = x;
00765     v->y_pos = y;
00766     v->z_pos = GetSlopeZ(x, y);
00767 
00768     v->running_ticks = 0;
00769 
00770     v->UpdateDeltaXY(v->direction);
00771     v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
00772 
00773     v->spritenum = svi->image_index;
00774     v->cargo_type = e->GetDefaultCargoType();
00775     v->cargo_subtype = 0;
00776     v->cargo_cap = svi->capacity;
00777     v->value = value.GetCost();
00778 
00779     v->last_station_visited = INVALID_STATION;
00780     v->max_speed = svi->max_speed;
00781     v->engine_type = p1;
00782 
00783     v->reliability = e->reliability;
00784     v->reliability_spd_dec = e->reliability_spd_dec;
00785     v->max_age = e->lifelength * DAYS_IN_LEAP_YEAR;
00786     _new_vehicle_id = v->index;
00787 
00788     v->name = NULL;
00789     v->u.ship.state = TRACK_BIT_DEPOT;
00790 
00791     v->service_interval = _settings_game.vehicle.servint_ships;
00792     v->date_of_last_service = _date;
00793     v->build_year = _cur_year;
00794     v->cur_image = 0x0E5E;
00795     v->random_bits = VehicleRandomBits();
00796 
00797     v->vehicle_flags = 0;
00798     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
00799 
00800     v->cargo_cap = GetVehicleProperty(v, 0x0D, svi->capacity);
00801 
00802     VehicleMove(v, false);
00803 
00804     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00805     InvalidateWindowClassesData(WC_SHIPS_LIST, 0);
00806     InvalidateWindow(WC_COMPANY, v->owner);
00807     if (IsLocalCompany())
00808       InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Ship window
00809 
00810     GetCompany(_current_company)->num_engines[p1]++;
00811   }
00812 
00813   return value;
00814 }
00815 
00822 CommandCost CmdSellShip(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00823 {
00824   Vehicle *v;
00825 
00826   if (!IsValidVehicleID(p1)) return CMD_ERROR;
00827 
00828   v = GetVehicle(p1);
00829 
00830   if (v->type != VEH_SHIP || !CheckOwnership(v->owner)) return CMD_ERROR;
00831 
00832   if (HASBITS(v->vehstatus, VS_CRASHED)) return_cmd_error(STR_CAN_T_SELL_DESTROYED_VEHICLE);
00833 
00834   if (!v->IsStoppedInDepot()) {
00835     return_cmd_error(STR_980B_SHIP_MUST_BE_STOPPED_IN);
00836   }
00837 
00838   CommandCost ret(EXPENSES_NEW_VEHICLES, -v->value);
00839 
00840   if (flags & DC_EXEC) {
00841     delete v;
00842   }
00843 
00844   return ret;
00845 }
00846 
00847 bool Ship::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
00848 {
00849   const Depot *depot = FindClosestShipDepot(this);
00850 
00851   if (depot == NULL) return false;
00852 
00853   if (location    != NULL) *location    = depot->xy;
00854   if (destination != NULL) *destination = depot->index;
00855 
00856   return true;
00857 }
00858 
00867 CommandCost CmdSendShipToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00868 {
00869   if (p2 & DEPOT_MASS_SEND) {
00870     /* Mass goto depot requested */
00871     if (!ValidVLWFlags(p2 & VLW_MASK)) return CMD_ERROR;
00872     return SendAllVehiclesToDepot(VEH_SHIP, flags, p2 & DEPOT_SERVICE, _current_company, (p2 & VLW_MASK), p1);
00873   }
00874 
00875   if (!IsValidVehicleID(p1)) return CMD_ERROR;
00876 
00877   Vehicle *v = GetVehicle(p1);
00878 
00879   if (v->type != VEH_SHIP) return CMD_ERROR;
00880 
00881   return v->SendToDepot(flags, (DepotCommand)(p2 & DEPOT_COMMAND_MASK));
00882 }
00883 
00884 
00895 CommandCost CmdRefitShip(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00896 {
00897   Vehicle *v;
00898   CommandCost cost(EXPENSES_SHIP_RUN);
00899   CargoID new_cid = GB(p2, 0, 8); // gets the cargo number
00900   byte new_subtype = GB(p2, 8, 8);
00901   uint16 capacity = CALLBACK_FAILED;
00902 
00903   if (!IsValidVehicleID(p1)) return CMD_ERROR;
00904 
00905   v = GetVehicle(p1);
00906 
00907   if (v->type != VEH_SHIP || !CheckOwnership(v->owner)) return CMD_ERROR;
00908   if (!v->IsStoppedInDepot()) return_cmd_error(STR_980B_SHIP_MUST_BE_STOPPED_IN);
00909   if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_CAN_T_REFIT_DESTROYED_VEHICLE);
00910 
00911   /* Check cargo */
00912   if (!ShipVehInfo(v->engine_type)->refittable) return CMD_ERROR;
00913   if (new_cid >= NUM_CARGO || !CanRefitTo(v->engine_type, new_cid)) return CMD_ERROR;
00914 
00915   /* Check the refit capacity callback */
00916   if (HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_REFIT_CAPACITY)) {
00917     /* Back up the existing cargo type */
00918     CargoID temp_cid = v->cargo_type;
00919     byte temp_subtype = v->cargo_subtype;
00920     v->cargo_type = new_cid;
00921     v->cargo_subtype = new_subtype;
00922 
00923     capacity = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, v->engine_type, v);
00924 
00925     /* Restore the cargo type */
00926     v->cargo_type = temp_cid;
00927     v->cargo_subtype = temp_subtype;
00928   }
00929 
00930   if (capacity == CALLBACK_FAILED) {
00931     capacity = GetVehicleProperty(v, 0x0D, ShipVehInfo(v->engine_type)->capacity);
00932   }
00933   _returned_refit_capacity = capacity;
00934 
00935   if (new_cid != v->cargo_type) {
00936     cost = GetRefitCost(v->engine_type);
00937   }
00938 
00939   if (flags & DC_EXEC) {
00940     v->cargo_cap = capacity;
00941     v->cargo.Truncate((v->cargo_type == new_cid) ? capacity : 0);
00942     v->cargo_type = new_cid;
00943     v->cargo_subtype = new_subtype;
00944     v->colourmap = PAL_NONE; // invalidate vehicle colour map
00945     InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
00946     InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
00947     InvalidateWindowClassesData(WC_SHIPS_LIST, 0);
00948   }
00949 
00950   return cost;
00951 
00952 }

Generated on Sun Mar 15 22:49:50 2009 for openttd by  doxygen 1.5.6