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 void GetShipIcon(EngineID engine
, EngineImageType image_type
, VehicleSpriteSeq
*result
)
69 const Engine
*e
= Engine::Get(engine
);
70 uint8 spritenum
= e
->u
.ship
.image_index
;
72 if (is_custom_sprite(spritenum
)) {
73 GetCustomVehicleIcon(engine
, DIR_W
, image_type
, result
);
74 if (result
->IsValid()) return;
76 spritenum
= e
->original_image_index
;
79 assert(IsValidImageIndex
<VEH_SHIP
>(spritenum
));
80 result
->Set(DIR_W
+ _ship_sprites
[spritenum
]);
83 void DrawShipEngine (BlitArea
*dpi
, int left
, int right
, int preferred_x
,
84 int y
, EngineID engine
, PaletteID pal
, EngineImageType image_type
)
87 GetShipIcon(engine
, image_type
, &seq
);
91 preferred_x
= Clamp(preferred_x
,
92 left
- UnScaleGUI(rect
.left
),
93 right
- UnScaleGUI(rect
.right
));
95 seq
.Draw (dpi
, preferred_x
, y
, pal
, pal
== PALETTE_CRASH
);
99 * Get the size of the sprite of a ship sprite heading west (used for lists).
100 * @param engine The engine to get the sprite from.
101 * @param[out] width The width of the sprite.
102 * @param[out] height The height of the sprite.
103 * @param[out] xoffs Number of pixels to shift the sprite to the right.
104 * @param[out] yoffs Number of pixels to shift the sprite downwards.
105 * @param image_type Context the sprite is used in.
107 void GetShipSpriteSize(EngineID engine
, uint
&width
, uint
&height
, int &xoffs
, int &yoffs
, EngineImageType image_type
)
109 VehicleSpriteSeq seq
;
110 GetShipIcon(engine
, image_type
, &seq
);
113 seq
.GetBounds(&rect
);
115 width
= UnScaleGUI(rect
.right
- rect
.left
+ 1);
116 height
= UnScaleGUI(rect
.bottom
- rect
.top
+ 1);
117 xoffs
= UnScaleGUI(rect
.left
);
118 yoffs
= UnScaleGUI(rect
.top
);
121 void Ship::GetImage(Direction direction
, EngineImageType image_type
, VehicleSpriteSeq
*result
) const
123 uint8 spritenum
= this->spritenum
;
125 if (is_custom_sprite(spritenum
)) {
126 GetCustomVehicleSprite(this, direction
, image_type
, result
);
127 if (result
->IsValid()) return;
129 spritenum
= this->GetEngine()->original_image_index
;
132 assert(IsValidImageIndex
<VEH_SHIP
>(spritenum
));
133 result
->Set(_ship_sprites
[spritenum
] + direction
);
136 static const Depot
*FindClosestShipDepot (const Ship
*v
, bool nearby
= false)
138 if (_settings_game
.pf
.pathfinder_for_ships
!= VPF_OPF
) {
139 assert (_settings_game
.pf
.pathfinder_for_ships
== VPF_YAPF
);
141 TileIndex depot
= YapfShipFindNearestDepot (v
, nearby
? _settings_game
.pf
.yapf
.maximum_go_to_depot_penalty
: 0);
142 return depot
== INVALID_TILE
? NULL
: Depot::GetByTile(depot
);
145 /* The original pathfinder cannot look for the nearest depot. */
147 const Depot
*best_depot
= NULL
;
149 /* If we don't have a maximum distance, we want to find any depot
150 * so the best distance of no depot must be more than any correct
151 * distance. On the other hand if we have set a maximum distance,
152 * any depot further away than the maximum allowed distance can
153 * safely be ignored. */
154 uint best_dist
= nearby
? (12 + 1) : UINT_MAX
;
155 FOR_ALL_DEPOTS(depot
) {
156 TileIndex tile
= depot
->xy
;
157 if (IsShipDepotTile(tile
) && IsTileOwner(tile
, v
->owner
)) {
158 uint dist
= DistanceManhattan(tile
, v
->tile
);
159 if (dist
< best_dist
) {
169 static void CheckIfShipNeedsService (Ship
*v
)
171 if (Company::Get(v
->owner
)->settings
.vehicle
.servint_ships
== 0 || !v
->NeedsAutomaticServicing()) return;
172 if (v
->IsChainInDepot()) {
173 VehicleServiceInDepot(v
);
177 const Depot
*depot
= FindClosestShipDepot (v
, true);
180 if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
181 v
->current_order
.MakeDummy();
182 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
187 v
->current_order
.MakeGoToDepot(depot
->index
, ODTFB_SERVICE
);
188 v
->dest_tile
= depot
->xy
;
189 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
193 * Update the caches of this ship.
195 void Ship::UpdateCache()
197 const ShipVehicleInfo
*svi
= ShipVehInfo(this->engine_type
);
199 /* Get speed fraction for the current water type. Aqueducts are always canals. */
200 bool is_ocean
= GetEffectiveWaterClass(this->tile
) == WATER_CLASS_SEA
;
201 uint raw_speed
= GetVehicleProperty(this, PROP_SHIP_SPEED
, svi
->max_speed
);
202 this->vcache
.cached_max_speed
= svi
->ApplyWaterClassSpeedFrac(raw_speed
, is_ocean
);
204 /* Update cargo aging period. */
205 this->vcache
.cached_cargo_age_period
= GetVehicleProperty(this, PROP_SHIP_CARGO_AGE_PERIOD
, EngInfo(this->engine_type
)->cargo_age_period
);
207 this->UpdateVisualEffect();
210 Money
Ship::GetRunningCost() const
212 const Engine
*e
= this->GetEngine();
213 uint cost_factor
= GetVehicleProperty(this, PROP_SHIP_RUNNING_COST_FACTOR
, e
->u
.ship
.running_cost
);
214 return GetPrice(PR_RUNNING_SHIP
, cost_factor
, e
->GetGRF());
217 void Ship::OnNewDay()
219 if ((++this->day_counter
& 7) == 0) {
220 DecreaseVehicleValue(this);
223 CheckVehicleBreakdown(this);
225 CheckIfShipNeedsService(this);
229 if (this->running_ticks
== 0) return;
231 CommandCost
cost(EXPENSES_SHIP_RUN
, this->GetRunningCost() * this->running_ticks
/ (DAYS_IN_YEAR
* DAY_TICKS
));
233 this->profit_this_year
-= cost
.GetCost();
234 this->running_ticks
= 0;
236 SubtractMoneyFromCompanyFract(this->owner
, cost
);
238 SetWindowDirty(WC_VEHICLE_DETAILS
, this->index
);
239 /* we need this for the profit */
240 SetWindowClassesDirty(WC_SHIPS_LIST
);
243 ShipPathPos
Ship::GetPos() const
245 if (this->vehstatus
& VS_CRASHED
) return ShipPathPos();
249 if (this->IsInDepot()) {
250 /* We'll assume the ship is facing outwards */
251 td
= DiagDirToDiagTrackdir(GetShipDepotDirection(this->tile
));
252 } else if (this->trackdir
== TRACKDIR_WORMHOLE
) {
253 /* ship on aqueduct, so just use his direction and assume a diagonal track */
254 td
= DiagDirToDiagTrackdir(DirToDiagDir(this->direction
));
259 return ShipPathPos(this->tile
, td
);
262 void Ship::MarkDirty()
264 this->colourmap
= PAL_NONE
;
265 this->UpdateViewport(true, false);
269 static void PlayShipSound(const Vehicle
*v
)
271 if (!PlayVehicleSound(v
, VSE_START
)) {
272 SndPlayVehicleFx(ShipVehInfo(v
->engine_type
)->sfx
, v
);
276 void Ship::PlayLeaveStationSound() const
281 TileIndex
Ship::GetOrderStationLocation(StationID station
)
283 if (station
== this->last_station_visited
) this->last_station_visited
= INVALID_STATION
;
285 const Station
*st
= Station::Get(station
);
286 if (!(st
->facilities
& FACIL_DOCK
)) {
287 this->IncrementRealOrderIndex();
294 void Ship::UpdateDeltaXY(Direction direction
)
296 static const int8 _delta_xy_table
[8][4] = {
297 /* y_extent, x_extent, y_offs, x_offs */
298 { 6, 6, -3, -3}, // N
299 { 6, 32, -3, -16}, // NE
300 { 6, 6, -3, -3}, // E
301 {32, 6, -16, -3}, // SE
302 { 6, 6, -3, -3}, // S
303 { 6, 32, -3, -16}, // SW
304 { 6, 6, -3, -3}, // W
305 {32, 6, -16, -3}, // NW
308 const int8
*bb
= _delta_xy_table
[direction
];
309 this->x_offs
= bb
[3];
310 this->y_offs
= bb
[2];
311 this->x_extent
= bb
[1];
312 this->y_extent
= bb
[0];
317 * Ship entirely entered the depot, update its status, orders, vehicle windows, service it, etc.
318 * @param v Ship that entered a depot.
320 static void ShipEnterDepot (Ship
*v
)
322 SetWindowClassesDirty (WC_SHIPS_LIST
);
324 v
->trackdir
= TRACKDIR_DEPOT
;
326 v
->UpdateViewport (true, true);
327 SetWindowDirty (WC_VEHICLE_DEPOT
, v
->tile
);
329 VehicleEnterDepot (v
);
332 static bool CheckShipLeaveDepot(Ship
*v
)
334 if (!v
->IsChainInDepot()) return false;
336 /* We are leaving a depot, but have to go to the exact same one; re-enter */
337 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) &&
338 IsShipDepotTile(v
->tile
) && GetDepotIndex(v
->tile
) == v
->current_order
.GetDestination()) {
343 TileIndex tile
= v
->tile
;
345 DiagDirection north_dir
= GetShipDepotDirection(tile
);
346 TileIndex north_neighbour
= TILE_ADD(tile
, TileOffsByDiagDir(north_dir
));
347 DiagDirection south_dir
= ReverseDiagDir(north_dir
);
348 TileIndex south_neighbour
= TILE_ADD(tile
, 2 * TileOffsByDiagDir(south_dir
));
350 TrackdirBits north_trackdirs
= GetAvailShipTrackdirs(north_neighbour
, north_dir
);
351 TrackdirBits south_trackdirs
= GetAvailShipTrackdirs(south_neighbour
, south_dir
);
352 if (north_trackdirs
&& south_trackdirs
) {
353 /* Ask pathfinder for best direction */
354 bool reverse
= false;
356 switch (_settings_game
.pf
.pathfinder_for_ships
) {
357 case VPF_OPF
: reverse
= OPFShipChooseTrack(v
, north_neighbour
, north_dir
, north_trackdirs
, path_found
) == INVALID_TRACKDIR
; break; // OPF always allows reversing
358 case VPF_YAPF
: reverse
= YapfShipCheckReverse(v
); break;
359 default: NOT_REACHED();
361 if (reverse
) north_trackdirs
= TRACKDIR_BIT_NONE
;
364 if (north_trackdirs
) {
365 /* Leave towards north */
366 v
->direction
= DiagDirToDir(north_dir
);
367 v
->trackdir
= DiagDirToDiagTrackdir(north_dir
);
368 } else if (south_trackdirs
) {
369 /* Leave towards south */
370 v
->direction
= DiagDirToDir(south_dir
);
371 v
->trackdir
= DiagDirToDiagTrackdir(south_dir
);
373 /* Both ways blocked */
377 v
->vehstatus
&= ~VS_HIDDEN
;
380 v
->UpdateViewport(true, true);
381 SetWindowDirty(WC_VEHICLE_DEPOT
, v
->tile
);
384 VehicleServiceInDepot(v
);
385 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
386 SetWindowClassesDirty(WC_SHIPS_LIST
);
391 static bool ShipAccelerate(Vehicle
*v
)
396 spd
= min(v
->cur_speed
+ 1, v
->vcache
.cached_max_speed
);
397 spd
= min(spd
, v
->current_order
.GetMaxSpeed() * 2);
399 /* updates statusbar only if speed have changed to save CPU time */
400 if (spd
!= v
->cur_speed
) {
402 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
405 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
406 spd
= v
->GetOldAdvanceSpeed(spd
);
408 if (spd
== 0) return false;
409 if ((byte
)++spd
== 0) return true;
411 v
->progress
= (t
= v
->progress
) - (byte
)spd
;
413 return (t
< v
->progress
);
417 * Ship arrives at a dock. If it is the first time, send out a news item.
418 * @param v Ship that arrived.
419 * @param st Station being visited.
421 static void ShipArrivesAt(const Vehicle
*v
, Station
*st
)
423 /* Check if station was ever visited before */
424 if (!(st
->had_vehicle_of_type
& HVOT_SHIP
)) {
425 st
->had_vehicle_of_type
|= HVOT_SHIP
;
427 AddNewsItem
<ArrivalNewsItem
> (STR_NEWS_FIRST_SHIP_ARRIVAL
, v
, st
);
428 AI::NewEvent(v
->owner
, new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
434 * Runs the pathfinder to choose a trackdir to continue along.
436 * @param v Ship to navigate
437 * @param tile Tile the ship is about to enter
438 * @param enterdir Direction of entering
439 * @param trackdirs Available trackdir choices on \a tile
440 * @return Trackdir to choose, or INVALID_TRACKDIR when to reverse.
442 static Trackdir
ChooseShipTrack(Ship
*v
, TileIndex tile
, DiagDirection enterdir
, TrackdirBits trackdirs
)
444 assert(IsValidDiagDirection(enterdir
));
446 bool path_found
= true;
448 switch (_settings_game
.pf
.pathfinder_for_ships
) {
449 case VPF_OPF
: trackdir
= OPFShipChooseTrack(v
, tile
, enterdir
, trackdirs
, path_found
); break;
450 case VPF_YAPF
: trackdir
= YapfShipChooseTrack(v
, tile
, enterdir
, trackdirs
, path_found
); break;
451 default: NOT_REACHED();
454 v
->HandlePathfindingResult(path_found
);
458 static void ShipController(Ship
*v
)
461 v
->current_order_time
++;
463 if (v
->HandleBreakdown()) return;
465 if (v
->vehstatus
& VS_STOPPED
) return;
470 if (v
->current_order
.IsType(OT_LOADING
)) return;
472 if (CheckShipLeaveDepot(v
)) return;
474 v
->ShowVisualEffect();
476 if (!ShipAccelerate(v
)) return;
478 FullPosTile gp
= GetNewVehiclePos(v
);
479 if (v
->trackdir
== TRACKDIR_WORMHOLE
) {
481 if (gp
.tile
!= v
->tile
) {
482 /* Still on the bridge */
485 v
->UpdatePositionAndViewport();
488 v
->trackdir
= DiagDirToDiagTrackdir(ReverseDiagDir(GetTunnelBridgeDirection(v
->tile
)));
490 } else if (v
->trackdir
== TRACKDIR_DEPOT
) {
492 assert(gp
.tile
== v
->tile
);
493 gp
.set (v
->x_pos
, v
->y_pos
, gp
.tile
);
494 } else if (gp
.tile
== v
->tile
) {
495 /* Not on a bridge or in a depot, staying in the old tile */
497 /* A leave station order only needs one tick to get processed, so we can
498 * always skip ahead. */
499 if (v
->current_order
.IsType(OT_LEAVESTATION
)) {
500 v
->current_order
.Clear();
501 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
502 } else if (v
->dest_tile
!= 0) {
503 /* We have a target, let's see if we reached it... */
504 if (v
->current_order
.IsType(OT_GOTO_WAYPOINT
) &&
505 DistanceManhattan(v
->dest_tile
, gp
.tile
) <= 3) {
506 /* We got within 3 tiles of our target buoy, so let's skip to our
508 UpdateVehicleTimetable(v
, true);
509 v
->IncrementRealOrderIndex();
510 v
->current_order
.MakeDummy();
511 } else if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
512 if (v
->dest_tile
== gp
.tile
&& (gp
.xx
& 0xF) == 8 && (gp
.yy
& 0xF) == 8) {
516 } else if (v
->current_order
.IsType(OT_GOTO_STATION
)) {
517 StationID sid
= v
->current_order
.GetDestination();
518 Station
*st
= Station::Get(sid
);
519 if (st
->IsDockingTile(gp
.tile
)) {
520 assert(st
->facilities
& FACIL_DOCK
);
521 v
->last_station_visited
= sid
;
522 /* Process station in the orderlist. */
523 ShipArrivesAt(v
, st
);
529 /* Not on a bridge or in a depot, about to enter a new tile */
531 if (!IsValidTile(gp
.tile
)) goto reverse_direction
;
533 DiagDirection diagdir
= DiagdirBetweenTiles(v
->tile
, gp
.tile
);
534 assert(diagdir
!= INVALID_DIAGDIR
);
536 if (IsAqueductTile(v
->tile
) && GetTunnelBridgeDirection(v
->tile
) == diagdir
) {
537 TileIndex end_tile
= GetOtherBridgeEnd(v
->tile
);
538 if (end_tile
!= gp
.tile
) {
539 /* Entering an aqueduct */
541 v
->trackdir
= TRACKDIR_WORMHOLE
;
544 v
->UpdatePositionAndViewport();
549 TrackdirBits trackdirs
= GetAvailShipTrackdirs(gp
.tile
, diagdir
);
550 if (trackdirs
== TRACKDIR_BIT_NONE
) goto reverse_direction
;
552 /* Choose a direction, and continue if we find one */
553 Trackdir trackdir
= ChooseShipTrack(v
, gp
.tile
, diagdir
, trackdirs
);
554 if (trackdir
== INVALID_TRACKDIR
) goto reverse_direction
;
556 const InitialSubcoords
*b
= get_initial_subcoords (trackdir
);
557 gp
.adjust_subcoords (b
);
559 WaterClass old_wc
= GetEffectiveWaterClass(v
->tile
);
562 v
->trackdir
= trackdir
;
564 /* Update ship cache when the water class changes. Aqueducts are always canals. */
565 WaterClass new_wc
= GetEffectiveWaterClass(gp
.tile
);
566 if (old_wc
!= new_wc
) v
->UpdateCache();
568 v
->direction
= b
->dir
;
571 /* update image of ship, as well as delta XY */
574 v
->z_pos
= GetSlopePixelZ(gp
.xx
, gp
.yy
);
578 v
->UpdateViewport(true, true);
582 v
->direction
= ReverseDir(v
->direction
);
583 v
->trackdir
= ReverseTrackdir(v
->trackdir
);
589 if (!(this->vehstatus
& VS_STOPPED
)) this->running_ticks
++;
591 ShipController(this);
598 * @param tile tile of the depot where ship is built.
599 * @param flags type of operation.
600 * @param e the engine to build.
601 * @param data unused.
602 * @param ret[out] the vehicle that has been built.
603 * @return the cost of this operation or an error.
605 CommandCost
CmdBuildShip(TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**ret
)
607 tile
= GetShipDepotNorthTile(tile
);
608 if (flags
& DC_EXEC
) {
612 const ShipVehicleInfo
*svi
= &e
->u
.ship
;
614 Ship
*v
= new Ship();
617 v
->owner
= _current_company
;
619 x
= TileX(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
620 y
= TileY(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
623 v
->z_pos
= GetSlopePixelZ(x
, y
);
625 v
->UpdateDeltaXY(v
->direction
);
626 v
->vehstatus
= VS_HIDDEN
| VS_STOPPED
| VS_DEFPAL
;
628 v
->spritenum
= svi
->image_index
;
629 v
->cargo_type
= e
->GetDefaultCargoType();
630 v
->cargo_cap
= svi
->capacity
;
633 v
->last_station_visited
= INVALID_STATION
;
634 v
->last_loading_station
= INVALID_STATION
;
635 v
->engine_type
= e
->index
;
637 v
->reliability
= e
->reliability
;
638 v
->reliability_spd_dec
= e
->reliability_spd_dec
;
639 v
->max_age
= e
->GetLifeLengthInDays();
640 _new_vehicle_id
= v
->index
;
642 v
->trackdir
= TRACKDIR_DEPOT
;
644 v
->SetServiceInterval(Company::Get(_current_company
)->settings
.vehicle
.servint_ships
);
645 v
->date_of_last_service
= _date
;
646 v
->build_year
= _cur_year
;
647 v
->sprite_seq
.Set(SPR_IMG_QUERY
);
648 v
->random_bits
= VehicleRandomBits();
652 if (e
->flags
& ENGINE_EXCLUSIVE_PREVIEW
) SetBit(v
->vehicle_flags
, VF_BUILT_AS_PROTOTYPE
);
653 v
->SetServiceIntervalIsPercent(Company::Get(_current_company
)->settings
.vehicle
.servint_ispercent
);
655 v
->InvalidateNewGRFCacheOfChain();
657 v
->cargo_cap
= e
->DetermineCapacity(v
);
659 v
->InvalidateNewGRFCacheOfChain();
664 return CommandCost();
667 bool Ship::FindClosestDepot(TileIndex
*location
, DestinationID
*destination
, bool *reverse
)
669 const Depot
*depot
= FindClosestShipDepot(this);
671 if (depot
== NULL
) return false;
673 if (location
!= NULL
) *location
= depot
->xy
;
674 if (destination
!= NULL
) *destination
= depot
->index
;