ship_cmd.cpp

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

Generated on Thu Oct 1 11:03:16 2009 for OpenTTD by  doxygen 1.5.6