4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
10 /** @file ship_cmd.cpp Handling of ships. */
14 #include "landscape.h"
15 #include "timetable.h"
16 #include "news_func.h"
17 #include "company_func.h"
18 #include "depot_base.h"
19 #include "station_base.h"
20 #include "newgrf_engine.h"
21 #include "pathfinder/yapf/yapf.h"
22 #include "newgrf_sound.h"
23 #include "spritecache.h"
24 #include "strings_func.h"
25 #include "window_func.h"
26 #include "date_func.h"
27 #include "vehicle_func.h"
28 #include "sound_func.h"
30 #include "pathfinder/opf/opf_ship.h"
31 #include "engine_base.h"
32 #include "company_base.h"
33 #include "zoom_func.h"
34 #include "map/bridge.h"
36 #include "table/strings.h"
39 * Determine the effective #WaterClass for a ship travelling on a tile.
40 * @param tile Tile of interest
41 * @return the waterclass to be used by the ship.
43 WaterClass
GetEffectiveWaterClass(TileIndex tile
)
45 if (HasTileWaterClass(tile
)) return GetWaterClass(tile
);
46 if (IsAqueductTile(tile
)) return WATER_CLASS_CANAL
;
47 if (IsNormalRailTile(tile
)) {
48 assert(GetRailGroundType(tile
) == RAIL_GROUND_WATER
);
49 return WATER_CLASS_SEA
;
54 static const uint16 _ship_sprites
[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
57 bool IsValidImageIndex
<VEH_SHIP
>(uint8 image_index
)
59 return image_index
< lengthof(_ship_sprites
);
62 static inline TrackdirBits
GetAvailShipTrackdirs(TileIndex tile
, DiagDirection enterdir
)
64 return GetTileWaterwayStatus(tile
) & DiagdirReachesTrackdirs(enterdir
);
67 static SpriteID
GetShipIcon(EngineID engine
, EngineImageType image_type
)
69 const Engine
*e
= Engine::Get(engine
);
70 uint8 spritenum
= e
->u
.ship
.image_index
;
72 if (is_custom_sprite(spritenum
)) {
73 SpriteID sprite
= GetCustomVehicleIcon(engine
, DIR_W
, image_type
);
74 if (sprite
!= 0) return sprite
;
76 spritenum
= e
->original_image_index
;
79 assert(IsValidImageIndex
<VEH_SHIP
>(spritenum
));
80 return DIR_W
+ _ship_sprites
[spritenum
];
83 void DrawShipEngine(int left
, int right
, int preferred_x
, int y
, EngineID engine
, PaletteID pal
, EngineImageType image_type
)
85 SpriteID sprite
= GetShipIcon(engine
, image_type
);
86 const Sprite
*real_sprite
= GetSprite(sprite
, ST_NORMAL
);
87 preferred_x
= Clamp(preferred_x
,
88 left
- UnScaleGUI(real_sprite
->x_offs
),
89 right
- UnScaleGUI(real_sprite
->width
) - UnScaleGUI(real_sprite
->x_offs
));
90 DrawSprite(sprite
, pal
, preferred_x
, y
);
94 * Get the size of the sprite of a ship sprite heading west (used for lists).
95 * @param engine The engine to get the sprite from.
96 * @param[out] width The width of the sprite.
97 * @param[out] height The height of the sprite.
98 * @param[out] xoffs Number of pixels to shift the sprite to the right.
99 * @param[out] yoffs Number of pixels to shift the sprite downwards.
100 * @param image_type Context the sprite is used in.
102 void GetShipSpriteSize(EngineID engine
, uint
&width
, uint
&height
, int &xoffs
, int &yoffs
, EngineImageType image_type
)
104 const Sprite
*spr
= GetSprite(GetShipIcon(engine
, image_type
), ST_NORMAL
);
106 width
= UnScaleGUI(spr
->width
);
107 height
= UnScaleGUI(spr
->height
);
108 xoffs
= UnScaleGUI(spr
->x_offs
);
109 yoffs
= UnScaleGUI(spr
->y_offs
);
112 SpriteID
Ship::GetImage(Direction direction
, EngineImageType image_type
) const
114 uint8 spritenum
= this->spritenum
;
116 if (is_custom_sprite(spritenum
)) {
117 SpriteID sprite
= GetCustomVehicleSprite(this, direction
, image_type
);
118 if (sprite
!= 0) return sprite
;
120 spritenum
= this->GetEngine()->original_image_index
;
123 assert(IsValidImageIndex
<VEH_SHIP
>(spritenum
));
124 return _ship_sprites
[spritenum
] + direction
;
127 static const Depot
*FindClosestShipDepot (const Ship
*v
, bool nearby
= false)
129 if (_settings_game
.pf
.pathfinder_for_ships
!= VPF_OPF
) {
130 assert (_settings_game
.pf
.pathfinder_for_ships
== VPF_YAPF
);
132 TileIndex depot
= YapfShipFindNearestDepot (v
, nearby
? _settings_game
.pf
.yapf
.maximum_go_to_depot_penalty
: 0);
133 return depot
== INVALID_TILE
? NULL
: Depot::GetByTile(depot
);
136 /* The original pathfinder cannot look for the nearest depot. */
138 const Depot
*best_depot
= NULL
;
140 /* If we don't have a maximum distance, we want to find any depot
141 * so the best distance of no depot must be more than any correct
142 * distance. On the other hand if we have set a maximum distance,
143 * any depot further away than the maximum allowed distance can
144 * safely be ignored. */
145 uint best_dist
= nearby
? (12 + 1) : UINT_MAX
;
146 FOR_ALL_DEPOTS(depot
) {
147 TileIndex tile
= depot
->xy
;
148 if (IsShipDepotTile(tile
) && IsTileOwner(tile
, v
->owner
)) {
149 uint dist
= DistanceManhattan(tile
, v
->tile
);
150 if (dist
< best_dist
) {
160 static void CheckIfShipNeedsService (Ship
*v
)
162 if (Company::Get(v
->owner
)->settings
.vehicle
.servint_ships
== 0 || !v
->NeedsAutomaticServicing()) return;
163 if (v
->IsChainInDepot()) {
164 VehicleServiceInDepot(v
);
168 const Depot
*depot
= FindClosestShipDepot (v
, true);
171 if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
172 v
->current_order
.MakeDummy();
173 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
178 v
->current_order
.MakeGoToDepot(depot
->index
, ODTFB_SERVICE
);
179 v
->dest_tile
= depot
->xy
;
180 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
184 * Update the caches of this ship.
186 void Ship::UpdateCache()
188 const ShipVehicleInfo
*svi
= ShipVehInfo(this->engine_type
);
190 /* Get speed fraction for the current water type. Aqueducts are always canals. */
191 bool is_ocean
= GetEffectiveWaterClass(this->tile
) == WATER_CLASS_SEA
;
192 uint raw_speed
= GetVehicleProperty(this, PROP_SHIP_SPEED
, svi
->max_speed
);
193 this->vcache
.cached_max_speed
= svi
->ApplyWaterClassSpeedFrac(raw_speed
, is_ocean
);
195 /* Update cargo aging period. */
196 this->vcache
.cached_cargo_age_period
= GetVehicleProperty(this, PROP_SHIP_CARGO_AGE_PERIOD
, EngInfo(this->engine_type
)->cargo_age_period
);
198 this->UpdateVisualEffect();
201 Money
Ship::GetRunningCost() const
203 const Engine
*e
= this->GetEngine();
204 uint cost_factor
= GetVehicleProperty(this, PROP_SHIP_RUNNING_COST_FACTOR
, e
->u
.ship
.running_cost
);
205 return GetPrice(PR_RUNNING_SHIP
, cost_factor
, e
->GetGRF());
208 void Ship::OnNewDay()
210 if ((++this->day_counter
& 7) == 0) {
211 DecreaseVehicleValue(this);
214 CheckVehicleBreakdown(this);
216 CheckIfShipNeedsService(this);
220 if (this->running_ticks
== 0) return;
222 CommandCost
cost(EXPENSES_SHIP_RUN
, this->GetRunningCost() * this->running_ticks
/ (DAYS_IN_YEAR
* DAY_TICKS
));
224 this->profit_this_year
-= cost
.GetCost();
225 this->running_ticks
= 0;
227 SubtractMoneyFromCompanyFract(this->owner
, cost
);
229 SetWindowDirty(WC_VEHICLE_DETAILS
, this->index
);
230 /* we need this for the profit */
231 SetWindowClassesDirty(WC_SHIPS_LIST
);
234 ShipPathPos
Ship::GetPos() const
236 if (this->vehstatus
& VS_CRASHED
) return ShipPathPos();
240 if (this->IsInDepot()) {
241 /* We'll assume the ship is facing outwards */
242 td
= DiagDirToDiagTrackdir(GetShipDepotDirection(this->tile
));
243 } else if (this->trackdir
== TRACKDIR_WORMHOLE
) {
244 /* ship on aqueduct, so just use his direction and assume a diagonal track */
245 td
= DiagDirToDiagTrackdir(DirToDiagDir(this->direction
));
250 return ShipPathPos(this->tile
, td
);
253 void Ship::MarkDirty()
255 this->colourmap
= PAL_NONE
;
256 this->UpdateViewport(true, false);
260 static void PlayShipSound(const Vehicle
*v
)
262 if (!PlayVehicleSound(v
, VSE_START
)) {
263 SndPlayVehicleFx(ShipVehInfo(v
->engine_type
)->sfx
, v
);
267 void Ship::PlayLeaveStationSound() const
272 TileIndex
Ship::GetOrderStationLocation(StationID station
)
274 if (station
== this->last_station_visited
) this->last_station_visited
= INVALID_STATION
;
276 const Station
*st
= Station::Get(station
);
277 if (!(st
->facilities
& FACIL_DOCK
)) {
278 this->IncrementRealOrderIndex();
285 void Ship::UpdateDeltaXY(Direction direction
)
287 static const int8 _delta_xy_table
[8][4] = {
288 /* y_extent, x_extent, y_offs, x_offs */
289 { 6, 6, -3, -3}, // N
290 { 6, 32, -3, -16}, // NE
291 { 6, 6, -3, -3}, // E
292 {32, 6, -16, -3}, // SE
293 { 6, 6, -3, -3}, // S
294 { 6, 32, -3, -16}, // SW
295 { 6, 6, -3, -3}, // W
296 {32, 6, -16, -3}, // NW
299 const int8
*bb
= _delta_xy_table
[direction
];
300 this->x_offs
= bb
[3];
301 this->y_offs
= bb
[2];
302 this->x_extent
= bb
[1];
303 this->y_extent
= bb
[0];
308 * Ship entirely entered the depot, update its status, orders, vehicle windows, service it, etc.
309 * @param v Ship that entered a depot.
311 static void ShipEnterDepot (Ship
*v
)
313 SetWindowClassesDirty (WC_SHIPS_LIST
);
315 v
->trackdir
= TRACKDIR_DEPOT
;
317 v
->UpdateViewport (true, true);
318 SetWindowDirty (WC_VEHICLE_DEPOT
, v
->tile
);
320 VehicleEnterDepot (v
);
323 static bool CheckShipLeaveDepot(Ship
*v
)
325 if (!v
->IsChainInDepot()) return false;
327 /* We are leaving a depot, but have to go to the exact same one; re-enter */
328 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) &&
329 IsShipDepotTile(v
->tile
) && GetDepotIndex(v
->tile
) == v
->current_order
.GetDestination()) {
334 TileIndex tile
= v
->tile
;
336 DiagDirection north_dir
= GetShipDepotDirection(tile
);
337 TileIndex north_neighbour
= TILE_ADD(tile
, TileOffsByDiagDir(north_dir
));
338 DiagDirection south_dir
= ReverseDiagDir(north_dir
);
339 TileIndex south_neighbour
= TILE_ADD(tile
, 2 * TileOffsByDiagDir(south_dir
));
341 TrackdirBits north_trackdirs
= GetAvailShipTrackdirs(north_neighbour
, north_dir
);
342 TrackdirBits south_trackdirs
= GetAvailShipTrackdirs(south_neighbour
, south_dir
);
343 if (north_trackdirs
&& south_trackdirs
) {
344 /* Ask pathfinder for best direction */
345 bool reverse
= false;
347 switch (_settings_game
.pf
.pathfinder_for_ships
) {
348 case VPF_OPF
: reverse
= OPFShipChooseTrack(v
, north_neighbour
, north_dir
, north_trackdirs
, path_found
) == INVALID_TRACKDIR
; break; // OPF always allows reversing
349 case VPF_YAPF
: reverse
= YapfShipCheckReverse(v
); break;
350 default: NOT_REACHED();
352 if (reverse
) north_trackdirs
= TRACKDIR_BIT_NONE
;
355 if (north_trackdirs
) {
356 /* Leave towards north */
357 v
->direction
= DiagDirToDir(north_dir
);
358 v
->trackdir
= DiagDirToDiagTrackdir(north_dir
);
359 } else if (south_trackdirs
) {
360 /* Leave towards south */
361 v
->direction
= DiagDirToDir(south_dir
);
362 v
->trackdir
= DiagDirToDiagTrackdir(south_dir
);
364 /* Both ways blocked */
368 v
->vehstatus
&= ~VS_HIDDEN
;
371 v
->UpdateViewport(true, true);
372 SetWindowDirty(WC_VEHICLE_DEPOT
, v
->tile
);
375 VehicleServiceInDepot(v
);
376 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
377 SetWindowClassesDirty(WC_SHIPS_LIST
);
382 static bool ShipAccelerate(Vehicle
*v
)
387 spd
= min(v
->cur_speed
+ 1, v
->vcache
.cached_max_speed
);
388 spd
= min(spd
, v
->current_order
.GetMaxSpeed() * 2);
390 /* updates statusbar only if speed have changed to save CPU time */
391 if (spd
!= v
->cur_speed
) {
393 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
396 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
397 spd
= v
->GetOldAdvanceSpeed(spd
);
399 if (spd
== 0) return false;
400 if ((byte
)++spd
== 0) return true;
402 v
->progress
= (t
= v
->progress
) - (byte
)spd
;
404 return (t
< v
->progress
);
408 * Ship arrives at a dock. If it is the first time, send out a news item.
409 * @param v Ship that arrived.
410 * @param st Station being visited.
412 static void ShipArrivesAt(const Vehicle
*v
, Station
*st
)
414 /* Check if station was ever visited before */
415 if (!(st
->had_vehicle_of_type
& HVOT_SHIP
)) {
416 st
->had_vehicle_of_type
|= HVOT_SHIP
;
418 AddNewsItem
<ArrivalNewsItem
> (STR_NEWS_FIRST_SHIP_ARRIVAL
, v
, st
);
419 AI::NewEvent(v
->owner
, new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
425 * Runs the pathfinder to choose a trackdir to continue along.
427 * @param v Ship to navigate
428 * @param tile Tile the ship is about to enter
429 * @param enterdir Direction of entering
430 * @param trackdirs Available trackdir choices on \a tile
431 * @return Trackdir to choose, or INVALID_TRACKDIR when to reverse.
433 static Trackdir
ChooseShipTrack(Ship
*v
, TileIndex tile
, DiagDirection enterdir
, TrackdirBits trackdirs
)
435 assert(IsValidDiagDirection(enterdir
));
437 bool path_found
= true;
439 switch (_settings_game
.pf
.pathfinder_for_ships
) {
440 case VPF_OPF
: trackdir
= OPFShipChooseTrack(v
, tile
, enterdir
, trackdirs
, path_found
); break;
441 case VPF_YAPF
: trackdir
= YapfShipChooseTrack(v
, tile
, enterdir
, trackdirs
, path_found
); break;
442 default: NOT_REACHED();
445 v
->HandlePathfindingResult(path_found
);
449 static void ShipController(Ship
*v
)
452 v
->current_order_time
++;
454 if (v
->HandleBreakdown()) return;
456 if (v
->vehstatus
& VS_STOPPED
) return;
461 if (v
->current_order
.IsType(OT_LOADING
)) return;
463 if (CheckShipLeaveDepot(v
)) return;
465 v
->ShowVisualEffect();
467 if (!ShipAccelerate(v
)) return;
469 FullPosTile gp
= GetNewVehiclePos(v
);
470 if (v
->trackdir
== TRACKDIR_WORMHOLE
) {
472 if (gp
.tile
!= v
->tile
) {
473 /* Still on the bridge */
476 v
->UpdatePositionAndViewport();
479 v
->trackdir
= DiagDirToDiagTrackdir(ReverseDiagDir(GetTunnelBridgeDirection(v
->tile
)));
481 } else if (v
->trackdir
== TRACKDIR_DEPOT
) {
483 assert(gp
.tile
== v
->tile
);
484 gp
.set (v
->x_pos
, v
->y_pos
, gp
.tile
);
485 } else if (gp
.tile
== v
->tile
) {
486 /* Not on a bridge or in a depot, staying in the old tile */
488 /* A leave station order only needs one tick to get processed, so we can
489 * always skip ahead. */
490 if (v
->current_order
.IsType(OT_LEAVESTATION
)) {
491 v
->current_order
.Clear();
492 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
493 } else if (v
->dest_tile
!= 0) {
494 /* We have a target, let's see if we reached it... */
495 if (v
->current_order
.IsType(OT_GOTO_WAYPOINT
) &&
496 DistanceManhattan(v
->dest_tile
, gp
.tile
) <= 3) {
497 /* We got within 3 tiles of our target buoy, so let's skip to our
499 UpdateVehicleTimetable(v
, true);
500 v
->IncrementRealOrderIndex();
501 v
->current_order
.MakeDummy();
502 } else if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
503 if (v
->dest_tile
== gp
.tile
&& (gp
.xx
& 0xF) == 8 && (gp
.yy
& 0xF) == 8) {
507 } else if (v
->current_order
.IsType(OT_GOTO_STATION
)) {
508 StationID sid
= v
->current_order
.GetDestination();
509 Station
*st
= Station::Get(sid
);
510 if (st
->IsDockingTile(gp
.tile
)) {
511 assert(st
->facilities
& FACIL_DOCK
);
512 v
->last_station_visited
= sid
;
513 /* Process station in the orderlist. */
514 ShipArrivesAt(v
, st
);
520 /* Not on a bridge or in a depot, about to enter a new tile */
522 if (!IsValidTile(gp
.tile
)) goto reverse_direction
;
524 DiagDirection diagdir
= DiagdirBetweenTiles(v
->tile
, gp
.tile
);
525 assert(diagdir
!= INVALID_DIAGDIR
);
527 if (IsAqueductTile(v
->tile
) && GetTunnelBridgeDirection(v
->tile
) == diagdir
) {
528 TileIndex end_tile
= GetOtherBridgeEnd(v
->tile
);
529 if (end_tile
!= gp
.tile
) {
530 /* Entering an aqueduct */
532 v
->trackdir
= TRACKDIR_WORMHOLE
;
535 v
->UpdatePositionAndViewport();
540 TrackdirBits trackdirs
= GetAvailShipTrackdirs(gp
.tile
, diagdir
);
541 if (trackdirs
== TRACKDIR_BIT_NONE
) goto reverse_direction
;
543 /* Choose a direction, and continue if we find one */
544 Trackdir trackdir
= ChooseShipTrack(v
, gp
.tile
, diagdir
, trackdirs
);
545 if (trackdir
== INVALID_TRACKDIR
) goto reverse_direction
;
547 const InitialSubcoords
*b
= get_initial_subcoords (trackdir
);
548 gp
.adjust_subcoords (b
);
550 WaterClass old_wc
= GetEffectiveWaterClass(v
->tile
);
553 v
->trackdir
= trackdir
;
555 /* Update ship cache when the water class changes. Aqueducts are always canals. */
556 WaterClass new_wc
= GetEffectiveWaterClass(gp
.tile
);
557 if (old_wc
!= new_wc
) v
->UpdateCache();
559 v
->direction
= b
->dir
;
562 /* update image of ship, as well as delta XY */
565 v
->z_pos
= GetSlopePixelZ(gp
.xx
, gp
.yy
);
569 v
->UpdateViewport(true, true);
573 v
->direction
= ReverseDir(v
->direction
);
574 v
->trackdir
= ReverseTrackdir(v
->trackdir
);
580 if (!(this->vehstatus
& VS_STOPPED
)) this->running_ticks
++;
582 ShipController(this);
589 * @param tile tile of the depot where ship is built.
590 * @param flags type of operation.
591 * @param e the engine to build.
592 * @param data unused.
593 * @param ret[out] the vehicle that has been built.
594 * @return the cost of this operation or an error.
596 CommandCost
CmdBuildShip(TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**ret
)
598 tile
= GetShipDepotNorthTile(tile
);
599 if (flags
& DC_EXEC
) {
603 const ShipVehicleInfo
*svi
= &e
->u
.ship
;
605 Ship
*v
= new Ship();
608 v
->owner
= _current_company
;
610 x
= TileX(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
611 y
= TileY(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
614 v
->z_pos
= GetSlopePixelZ(x
, y
);
616 v
->UpdateDeltaXY(v
->direction
);
617 v
->vehstatus
= VS_HIDDEN
| VS_STOPPED
| VS_DEFPAL
;
619 v
->spritenum
= svi
->image_index
;
620 v
->cargo_type
= e
->GetDefaultCargoType();
621 v
->cargo_cap
= svi
->capacity
;
624 v
->last_station_visited
= INVALID_STATION
;
625 v
->last_loading_station
= INVALID_STATION
;
626 v
->engine_type
= e
->index
;
628 v
->reliability
= e
->reliability
;
629 v
->reliability_spd_dec
= e
->reliability_spd_dec
;
630 v
->max_age
= e
->GetLifeLengthInDays();
631 _new_vehicle_id
= v
->index
;
633 v
->trackdir
= TRACKDIR_DEPOT
;
635 v
->SetServiceInterval(Company::Get(_current_company
)->settings
.vehicle
.servint_ships
);
636 v
->date_of_last_service
= _date
;
637 v
->build_year
= _cur_year
;
638 v
->cur_image
= SPR_IMG_QUERY
;
639 v
->random_bits
= VehicleRandomBits();
643 if (e
->flags
& ENGINE_EXCLUSIVE_PREVIEW
) SetBit(v
->vehicle_flags
, VF_BUILT_AS_PROTOTYPE
);
644 v
->SetServiceIntervalIsPercent(Company::Get(_current_company
)->settings
.vehicle
.servint_ispercent
);
646 v
->InvalidateNewGRFCacheOfChain();
648 v
->cargo_cap
= e
->DetermineCapacity(v
);
650 v
->InvalidateNewGRFCacheOfChain();
655 return CommandCost();
658 bool Ship::FindClosestDepot(TileIndex
*location
, DestinationID
*destination
, bool *reverse
)
660 const Depot
*depot
= FindClosestShipDepot(this);
662 if (depot
== NULL
) return false;
664 if (location
!= NULL
) *location
= depot
->xy
;
665 if (destination
!= NULL
) *destination
= depot
->index
;