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];
307 static bool CheckShipLeaveDepot(Ship
*v
)
309 if (!v
->IsChainInDepot()) return false;
311 /* We are leaving a depot, but have to go to the exact same one; re-enter */
312 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) &&
313 IsShipDepotTile(v
->tile
) && GetDepotIndex(v
->tile
) == v
->current_order
.GetDestination()) {
314 VehicleEnterDepot(v
);
318 TileIndex tile
= v
->tile
;
320 DiagDirection north_dir
= GetShipDepotDirection(tile
);
321 TileIndex north_neighbour
= TILE_ADD(tile
, TileOffsByDiagDir(north_dir
));
322 DiagDirection south_dir
= ReverseDiagDir(north_dir
);
323 TileIndex south_neighbour
= TILE_ADD(tile
, 2 * TileOffsByDiagDir(south_dir
));
325 TrackdirBits north_trackdirs
= GetAvailShipTrackdirs(north_neighbour
, north_dir
);
326 TrackdirBits south_trackdirs
= GetAvailShipTrackdirs(south_neighbour
, south_dir
);
327 if (north_trackdirs
&& south_trackdirs
) {
328 /* Ask pathfinder for best direction */
329 bool reverse
= false;
331 switch (_settings_game
.pf
.pathfinder_for_ships
) {
332 case VPF_OPF
: reverse
= OPFShipChooseTrack(v
, north_neighbour
, north_dir
, north_trackdirs
, path_found
) == INVALID_TRACKDIR
; break; // OPF always allows reversing
333 case VPF_YAPF
: reverse
= YapfShipCheckReverse(v
); break;
334 default: NOT_REACHED();
336 if (reverse
) north_trackdirs
= TRACKDIR_BIT_NONE
;
339 if (north_trackdirs
) {
340 /* Leave towards north */
341 v
->direction
= DiagDirToDir(north_dir
);
342 v
->trackdir
= DiagDirToDiagTrackdir(north_dir
);
343 } else if (south_trackdirs
) {
344 /* Leave towards south */
345 v
->direction
= DiagDirToDir(south_dir
);
346 v
->trackdir
= DiagDirToDiagTrackdir(south_dir
);
348 /* Both ways blocked */
352 v
->vehstatus
&= ~VS_HIDDEN
;
355 v
->UpdateViewport(true, true);
356 SetWindowDirty(WC_VEHICLE_DEPOT
, v
->tile
);
359 VehicleServiceInDepot(v
);
360 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
361 SetWindowClassesDirty(WC_SHIPS_LIST
);
366 static bool ShipAccelerate(Vehicle
*v
)
371 spd
= min(v
->cur_speed
+ 1, v
->vcache
.cached_max_speed
);
372 spd
= min(spd
, v
->current_order
.GetMaxSpeed() * 2);
374 /* updates statusbar only if speed have changed to save CPU time */
375 if (spd
!= v
->cur_speed
) {
377 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
380 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
381 spd
= v
->GetOldAdvanceSpeed(spd
);
383 if (spd
== 0) return false;
384 if ((byte
)++spd
== 0) return true;
386 v
->progress
= (t
= v
->progress
) - (byte
)spd
;
388 return (t
< v
->progress
);
392 * Ship arrives at a dock. If it is the first time, send out a news item.
393 * @param v Ship that arrived.
394 * @param st Station being visited.
396 static void ShipArrivesAt(const Vehicle
*v
, Station
*st
)
398 /* Check if station was ever visited before */
399 if (!(st
->had_vehicle_of_type
& HVOT_SHIP
)) {
400 st
->had_vehicle_of_type
|= HVOT_SHIP
;
402 SetDParam(0, st
->index
);
404 STR_NEWS_FIRST_SHIP_ARRIVAL
,
405 (v
->owner
== _local_company
) ? NT_ARRIVAL_COMPANY
: NT_ARRIVAL_OTHER
,
409 AI::NewEvent(v
->owner
, new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
415 * Runs the pathfinder to choose a trackdir to continue along.
417 * @param v Ship to navigate
418 * @param tile Tile the ship is about to enter
419 * @param enterdir Direction of entering
420 * @param trackdirs Available trackdir choices on \a tile
421 * @return Trackdir to choose, or INVALID_TRACKDIR when to reverse.
423 static Trackdir
ChooseShipTrack(Ship
*v
, TileIndex tile
, DiagDirection enterdir
, TrackdirBits trackdirs
)
425 assert(IsValidDiagDirection(enterdir
));
427 bool path_found
= true;
429 switch (_settings_game
.pf
.pathfinder_for_ships
) {
430 case VPF_OPF
: trackdir
= OPFShipChooseTrack(v
, tile
, enterdir
, trackdirs
, path_found
); break;
431 case VPF_YAPF
: trackdir
= YapfShipChooseTrack(v
, tile
, enterdir
, trackdirs
, path_found
); break;
432 default: NOT_REACHED();
435 v
->HandlePathfindingResult(path_found
);
439 static void ShipController(Ship
*v
)
442 v
->current_order_time
++;
444 if (v
->HandleBreakdown()) return;
446 if (v
->vehstatus
& VS_STOPPED
) return;
451 if (v
->current_order
.IsType(OT_LOADING
)) return;
453 if (CheckShipLeaveDepot(v
)) return;
455 v
->ShowVisualEffect();
457 if (!ShipAccelerate(v
)) return;
459 FullPosTile gp
= GetNewVehiclePos(v
);
460 if (v
->trackdir
== TRACKDIR_WORMHOLE
) {
462 if (gp
.tile
!= v
->tile
) {
463 /* Still on the bridge */
466 v
->UpdatePositionAndViewport();
469 v
->trackdir
= DiagDirToDiagTrackdir(ReverseDiagDir(GetTunnelBridgeDirection(v
->tile
)));
471 } else if (v
->trackdir
== TRACKDIR_DEPOT
) {
473 assert(gp
.tile
== v
->tile
);
474 gp
.set (v
->x_pos
, v
->y_pos
, gp
.tile
);
475 } else if (gp
.tile
== v
->tile
) {
476 /* Not on a bridge or in a depot, staying in the old tile */
478 /* A leave station order only needs one tick to get processed, so we can
479 * always skip ahead. */
480 if (v
->current_order
.IsType(OT_LEAVESTATION
)) {
481 v
->current_order
.Clear();
482 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
483 } else if (v
->dest_tile
!= 0) {
484 /* We have a target, let's see if we reached it... */
485 if (v
->current_order
.IsType(OT_GOTO_WAYPOINT
) &&
486 DistanceManhattan(v
->dest_tile
, gp
.tile
) <= 3) {
487 /* We got within 3 tiles of our target buoy, so let's skip to our
489 UpdateVehicleTimetable(v
, true);
490 v
->IncrementRealOrderIndex();
491 v
->current_order
.MakeDummy();
492 } else if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
493 if (v
->dest_tile
== gp
.tile
&& (gp
.xx
& 0xF) == 8 && (gp
.yy
& 0xF) == 8) {
494 VehicleEnterDepot(v
);
497 } else if (v
->current_order
.IsType(OT_GOTO_STATION
)) {
498 StationID sid
= v
->current_order
.GetDestination();
499 Station
*st
= Station::Get(sid
);
500 if (st
->IsDockingTile(gp
.tile
)) {
501 assert(st
->facilities
& FACIL_DOCK
);
502 v
->last_station_visited
= sid
;
503 /* Process station in the orderlist. */
504 ShipArrivesAt(v
, st
);
510 /* Not on a bridge or in a depot, about to enter a new tile */
512 if (!IsValidTile(gp
.tile
)) goto reverse_direction
;
514 DiagDirection diagdir
= DiagdirBetweenTiles(v
->tile
, gp
.tile
);
515 assert(diagdir
!= INVALID_DIAGDIR
);
517 if (IsAqueductTile(v
->tile
) && GetTunnelBridgeDirection(v
->tile
) == diagdir
) {
518 TileIndex end_tile
= GetOtherBridgeEnd(v
->tile
);
519 if (end_tile
!= gp
.tile
) {
520 /* Entering an aqueduct */
522 v
->trackdir
= TRACKDIR_WORMHOLE
;
525 v
->UpdatePositionAndViewport();
530 TrackdirBits trackdirs
= GetAvailShipTrackdirs(gp
.tile
, diagdir
);
531 if (trackdirs
== TRACKDIR_BIT_NONE
) goto reverse_direction
;
533 /* Choose a direction, and continue if we find one */
534 Trackdir trackdir
= ChooseShipTrack(v
, gp
.tile
, diagdir
, trackdirs
);
535 if (trackdir
== INVALID_TRACKDIR
) goto reverse_direction
;
537 const InitialSubcoords
*b
= get_initial_subcoords (trackdir
);
538 gp
.adjust_subcoords (b
);
540 WaterClass old_wc
= GetEffectiveWaterClass(v
->tile
);
543 v
->trackdir
= trackdir
;
545 /* Update ship cache when the water class changes. Aqueducts are always canals. */
546 WaterClass new_wc
= GetEffectiveWaterClass(gp
.tile
);
547 if (old_wc
!= new_wc
) v
->UpdateCache();
549 v
->direction
= b
->dir
;
552 /* update image of ship, as well as delta XY */
555 v
->z_pos
= GetSlopePixelZ(gp
.xx
, gp
.yy
);
559 v
->UpdateViewport(true, true);
563 v
->direction
= ReverseDir(v
->direction
);
564 v
->trackdir
= ReverseTrackdir(v
->trackdir
);
570 if (!(this->vehstatus
& VS_STOPPED
)) this->running_ticks
++;
572 ShipController(this);
579 * @param tile tile of the depot where ship is built.
580 * @param flags type of operation.
581 * @param e the engine to build.
582 * @param data unused.
583 * @param ret[out] the vehicle that has been built.
584 * @return the cost of this operation or an error.
586 CommandCost
CmdBuildShip(TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**ret
)
588 tile
= GetShipDepotNorthTile(tile
);
589 if (flags
& DC_EXEC
) {
593 const ShipVehicleInfo
*svi
= &e
->u
.ship
;
595 Ship
*v
= new Ship();
598 v
->owner
= _current_company
;
600 x
= TileX(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
601 y
= TileY(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
604 v
->z_pos
= GetSlopePixelZ(x
, y
);
606 v
->UpdateDeltaXY(v
->direction
);
607 v
->vehstatus
= VS_HIDDEN
| VS_STOPPED
| VS_DEFPAL
;
609 v
->spritenum
= svi
->image_index
;
610 v
->cargo_type
= e
->GetDefaultCargoType();
611 v
->cargo_cap
= svi
->capacity
;
614 v
->last_station_visited
= INVALID_STATION
;
615 v
->last_loading_station
= INVALID_STATION
;
616 v
->engine_type
= e
->index
;
618 v
->reliability
= e
->reliability
;
619 v
->reliability_spd_dec
= e
->reliability_spd_dec
;
620 v
->max_age
= e
->GetLifeLengthInDays();
621 _new_vehicle_id
= v
->index
;
623 v
->trackdir
= TRACKDIR_DEPOT
;
625 v
->SetServiceInterval(Company::Get(_current_company
)->settings
.vehicle
.servint_ships
);
626 v
->date_of_last_service
= _date
;
627 v
->build_year
= _cur_year
;
628 v
->cur_image
= SPR_IMG_QUERY
;
629 v
->random_bits
= VehicleRandomBits();
633 if (e
->flags
& ENGINE_EXCLUSIVE_PREVIEW
) SetBit(v
->vehicle_flags
, VF_BUILT_AS_PROTOTYPE
);
634 v
->SetServiceIntervalIsPercent(Company::Get(_current_company
)->settings
.vehicle
.servint_ispercent
);
636 v
->InvalidateNewGRFCacheOfChain();
638 v
->cargo_cap
= e
->DetermineCapacity(v
);
640 v
->InvalidateNewGRFCacheOfChain();
645 return CommandCost();
648 bool Ship::FindClosestDepot(TileIndex
*location
, DestinationID
*destination
, bool *reverse
)
650 const Depot
*depot
= FindClosestShipDepot(this);
652 if (depot
== NULL
) return false;
654 if (location
!= NULL
) *location
= depot
->xy
;
655 if (destination
!= NULL
) *destination
= depot
->index
;