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 "dock_base.h"
15 #include "landscape.h"
16 #include "timetable.h"
17 #include "news_func.h"
18 #include "company_func.h"
19 #include "pathfinder/npf/npf_func.h"
20 #include "depot_base.h"
21 #include "station_base.h"
22 #include "newgrf_engine.h"
23 #include "pathfinder/yapf/yapf.h"
24 #include "newgrf_sound.h"
25 #include "spritecache.h"
26 #include "strings_func.h"
27 #include "window_func.h"
28 #include "date_func.h"
29 #include "vehicle_func.h"
30 #include "sound_func.h"
32 #include "game/game.hpp"
33 #include "pathfinder/opf/opf_ship.h"
34 #include "engine_base.h"
35 #include "company_base.h"
36 #include "tunnelbridge_map.h"
37 #include "zoom_func.h"
39 #include "table/strings.h"
41 #include "safeguards.h"
44 * Determine the effective #WaterClass for a ship travelling on a tile.
45 * @param tile Tile of interest
46 * @return the waterclass to be used by the ship.
48 WaterClass
GetEffectiveWaterClass(TileIndex tile
)
50 if (HasTileWaterClass(tile
)) return GetWaterClass(tile
);
51 if (IsTileType(tile
, MP_TUNNELBRIDGE
)) {
52 assert(GetTunnelBridgeTransportType(tile
) == TRANSPORT_WATER
);
53 return WATER_CLASS_CANAL
;
55 if (IsTileType(tile
, MP_RAILWAY
)) {
56 assert(GetRailGroundType(tile
) == RAIL_GROUND_WATER
);
57 return WATER_CLASS_SEA
;
62 static const uint16 _ship_sprites
[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
65 bool IsValidImageIndex
<VEH_SHIP
>(uint8 image_index
)
67 return image_index
< lengthof(_ship_sprites
);
70 static inline TrackBits
GetTileShipTrackStatus(TileIndex tile
)
72 return TrackStatusToTrackBits(GetTileTrackStatus(tile
, TRANSPORT_WATER
, 0));
75 static void GetShipIcon(EngineID engine
, EngineImageType image_type
, VehicleSpriteSeq
*result
)
77 const Engine
*e
= Engine::Get(engine
);
78 uint8 spritenum
= e
->u
.ship
.image_index
;
80 if (is_custom_sprite(spritenum
)) {
81 GetCustomVehicleIcon(engine
, DIR_W
, image_type
, result
);
82 if (result
->IsValid()) return;
84 spritenum
= e
->original_image_index
;
87 assert(IsValidImageIndex
<VEH_SHIP
>(spritenum
));
88 result
->Set(DIR_W
+ _ship_sprites
[spritenum
]);
91 void DrawShipEngine(int left
, int right
, int preferred_x
, int y
, EngineID engine
, PaletteID pal
, EngineImageType image_type
)
94 GetShipIcon(engine
, image_type
, &seq
);
96 Rect16 rect
= seq
.GetBounds();
97 preferred_x
= Clamp(preferred_x
,
98 left
- UnScaleGUI(rect
.left
),
99 right
- UnScaleGUI(rect
.right
));
101 seq
.Draw(preferred_x
, y
, pal
, pal
== PALETTE_CRASH
);
105 * Get the size of the sprite of a ship sprite heading west (used for lists).
106 * @param engine The engine to get the sprite from.
107 * @param[out] width The width of the sprite.
108 * @param[out] height The height of the sprite.
109 * @param[out] xoffs Number of pixels to shift the sprite to the right.
110 * @param[out] yoffs Number of pixels to shift the sprite downwards.
111 * @param image_type Context the sprite is used in.
113 void GetShipSpriteSize(EngineID engine
, uint
&width
, uint
&height
, int &xoffs
, int &yoffs
, EngineImageType image_type
)
115 VehicleSpriteSeq seq
;
116 GetShipIcon(engine
, image_type
, &seq
);
118 Rect16 rect
= seq
.GetBounds();
120 width
= UnScaleGUI(rect
.right
- rect
.left
+ 1);
121 height
= UnScaleGUI(rect
.bottom
- rect
.top
+ 1);
122 xoffs
= UnScaleGUI(rect
.left
);
123 yoffs
= UnScaleGUI(rect
.top
);
126 void Ship::GetImage(Direction direction
, EngineImageType image_type
, VehicleSpriteSeq
*result
) const
128 uint8 spritenum
= this->spritenum
;
130 if (is_custom_sprite(spritenum
)) {
131 GetCustomVehicleSprite(this, direction
, image_type
, result
);
132 if (result
->IsValid()) return;
134 spritenum
= this->GetEngine()->original_image_index
;
137 assert(IsValidImageIndex
<VEH_SHIP
>(spritenum
));
138 result
->Set(_ship_sprites
[spritenum
] + direction
);
141 static const Depot
*FindClosestShipDepot(const Vehicle
*v
, uint max_distance
)
143 /* Find the closest depot */
145 const Depot
*best_depot
= NULL
;
146 /* If we don't have a maximum distance, i.e. distance = 0,
147 * we want to find any depot so the best distance of no
148 * depot must be more than any correct distance. On the
149 * other hand if we have set a maximum distance, any depot
150 * further away than max_distance can safely be ignored. */
151 uint best_dist
= max_distance
== 0 ? UINT_MAX
: max_distance
+ 1;
153 FOR_ALL_DEPOTS(depot
) {
154 TileIndex tile
= depot
->xy
;
155 if (IsShipDepotTile(tile
) && IsTileOwner(tile
, v
->owner
)) {
156 uint dist
= DistanceManhattan(tile
, v
->tile
);
157 if (dist
< best_dist
) {
167 static void CheckIfShipNeedsService(Vehicle
*v
)
169 if (Company::Get(v
->owner
)->settings
.vehicle
.servint_ships
== 0 || !v
->NeedsAutomaticServicing()) return;
170 if (v
->IsChainInDepot()) {
171 VehicleServiceInDepot(v
);
176 switch (_settings_game
.pf
.pathfinder_for_ships
) {
177 case VPF_OPF
: max_distance
= 12; break;
178 case VPF_NPF
: max_distance
= _settings_game
.pf
.npf
.maximum_go_to_depot_penalty
/ NPF_TILE_LENGTH
; break;
179 case VPF_YAPF
: max_distance
= _settings_game
.pf
.yapf
.maximum_go_to_depot_penalty
/ YAPF_TILE_LENGTH
; break;
180 default: NOT_REACHED();
183 const Depot
*depot
= FindClosestShipDepot(v
, max_distance
);
186 if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
187 v
->current_order
.MakeDummy();
188 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
193 v
->current_order
.MakeGoToDepot(depot
->index
, ODTFB_SERVICE
);
194 v
->dest_tile
= depot
->xy
;
195 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
199 * Update the caches of this ship.
201 void Ship::UpdateCache()
203 const ShipVehicleInfo
*svi
= ShipVehInfo(this->engine_type
);
205 /* Get speed fraction for the current water type. Aqueducts are always canals. */
206 bool is_ocean
= GetEffectiveWaterClass(this->tile
) == WATER_CLASS_SEA
;
207 uint raw_speed
= GetVehicleProperty(this, PROP_SHIP_SPEED
, svi
->max_speed
);
208 this->vcache
.cached_max_speed
= svi
->ApplyWaterClassSpeedFrac(raw_speed
, is_ocean
);
210 /* Update cargo aging period. */
211 this->vcache
.cached_cargo_age_period
= GetVehicleProperty(this, PROP_SHIP_CARGO_AGE_PERIOD
, EngInfo(this->engine_type
)->cargo_age_period
);
213 this->UpdateVisualEffect();
216 Money
Ship::GetRunningCost() const
218 const Engine
*e
= this->GetEngine();
219 uint cost_factor
= GetVehicleProperty(this, PROP_SHIP_RUNNING_COST_FACTOR
, e
->u
.ship
.running_cost
);
220 return GetPrice(PR_RUNNING_SHIP
, cost_factor
, e
->GetGRF());
223 void Ship::OnNewDay()
225 if ((++this->day_counter
& 7) == 0) {
226 DecreaseVehicleValue(this);
229 CheckVehicleBreakdown(this);
231 CheckIfShipNeedsService(this);
235 if (this->running_ticks
== 0) return;
237 CommandCost
cost(EXPENSES_SHIP_RUN
, this->GetRunningCost() * this->running_ticks
/ (DAYS_IN_YEAR
* DAY_TICKS
));
239 this->profit_this_year
-= cost
.GetCost();
240 this->running_ticks
= 0;
242 SubtractMoneyFromCompanyFract(this->owner
, cost
);
244 SetWindowDirty(WC_VEHICLE_DETAILS
, this->index
);
245 /* we need this for the profit */
246 SetWindowClassesDirty(WC_SHIPS_LIST
);
249 Trackdir
Ship::GetVehicleTrackdir() const
251 if (this->vehstatus
& VS_CRASHED
) return INVALID_TRACKDIR
;
253 if (this->IsInDepot()) {
254 /* We'll assume the ship is facing outwards */
255 return DiagDirToDiagTrackdir(GetShipDepotDirection(this->tile
));
258 if (this->state
== TRACK_BIT_WORMHOLE
) {
259 /* ship on aqueduct, so just use his direction and assume a diagonal track */
260 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction
));
263 return TrackDirectionToTrackdir(FindFirstTrack(this->state
), this->direction
);
266 void Ship::MarkDirty()
268 this->colourmap
= PAL_NONE
;
269 this->UpdateViewport(true, false);
273 static void PlayShipSound(const Vehicle
*v
)
275 if (!PlayVehicleSound(v
, VSE_START
)) {
276 SndPlayVehicleFx(ShipVehInfo(v
->engine_type
)->sfx
, v
);
280 void Ship::PlayLeaveStationSound() const
286 * Of all the docks a station has, return the best destination for a ship.
288 * @param st Station the ship \a v is heading for.
289 * @return The free and closest (if none is free, just closest) dock of station \a st to ship \a v.
291 const Dock
* GetBestDock(const Ship
*v
, const Station
*st
)
293 assert(st
!= NULL
&& st
->HasFacilities(FACIL_DOCK
) && st
->docks
!= NULL
);
294 if (st
->docks
->next
== NULL
) return st
->docks
;
296 Dock
*best_dock
= NULL
;
297 uint best_distance
= UINT_MAX
;
299 for (Dock
*dock
= st
->docks
; dock
!= NULL
; dock
= dock
->next
) {
300 uint new_distance
= DistanceManhattan(v
->tile
, dock
->flat
);
302 if (new_distance
< best_distance
) {
304 best_distance
= new_distance
;
308 assert(best_dock
!= NULL
);
313 TileIndex
Ship::GetOrderStationLocation(StationID station
)
315 if (station
== this->last_station_visited
) this->last_station_visited
= INVALID_STATION
;
317 const Station
*st
= Station::Get(station
);
318 if (st
->HasFacilities(FACIL_DOCK
)) {
319 if (st
->docks
== NULL
) {
320 return st
->xy
; // A buoy
322 const Dock
* dock
= GetBestDock(this, st
);
324 DiagDirection direction
= DiagdirBetweenTiles(dock
->sloped
, dock
->flat
);
325 return dock
->flat
+ TileOffsByDiagDir(direction
);
328 this->IncrementRealOrderIndex();
333 void Ship::UpdateDeltaXY(Direction direction
)
335 static const int8 _delta_xy_table
[8][4] = {
336 /* y_extent, x_extent, y_offs, x_offs */
337 { 6, 6, -3, -3}, // N
338 { 6, 32, -3, -16}, // NE
339 { 6, 6, -3, -3}, // E
340 {32, 6, -16, -3}, // SE
341 { 6, 6, -3, -3}, // S
342 { 6, 32, -3, -16}, // SW
343 { 6, 6, -3, -3}, // W
344 {32, 6, -16, -3}, // NW
347 const int8
*bb
= _delta_xy_table
[direction
];
348 this->x_offs
= bb
[3];
349 this->y_offs
= bb
[2];
350 this->x_extent
= bb
[1];
351 this->y_extent
= bb
[0];
355 static bool CheckShipLeaveDepot(Ship
*v
)
357 if (!v
->IsChainInDepot()) return false;
359 if (v
->current_order
.IsWaitTimetabled())
360 v
->HandleWaiting(false);
361 if (v
->current_order
.IsType(OT_WAITING
))
364 /* We are leaving a depot, but have to go to the exact same one; re-enter */
365 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) &&
366 IsShipDepotTile(v
->tile
) && GetDepotIndex(v
->tile
) == v
->current_order
.GetDestination()) {
367 VehicleEnterDepot(v
);
371 TileIndex tile
= v
->tile
;
372 Axis axis
= GetShipDepotAxis(tile
);
374 DiagDirection north_dir
= ReverseDiagDir(AxisToDiagDir(axis
));
375 TileIndex north_neighbour
= TILE_ADD(tile
, TileOffsByDiagDir(north_dir
));
376 DiagDirection south_dir
= AxisToDiagDir(axis
);
377 TileIndex south_neighbour
= TILE_ADD(tile
, 2 * TileOffsByDiagDir(south_dir
));
379 TrackBits north_tracks
= DiagdirReachesTracks(north_dir
) & GetTileShipTrackStatus(north_neighbour
);
380 TrackBits south_tracks
= DiagdirReachesTracks(south_dir
) & GetTileShipTrackStatus(south_neighbour
);
381 if (north_tracks
&& south_tracks
) {
382 /* Ask pathfinder for best direction */
383 bool reverse
= false;
385 switch (_settings_game
.pf
.pathfinder_for_ships
) {
386 case VPF_OPF
: reverse
= OPFShipChooseTrack(v
, north_neighbour
, north_dir
, north_tracks
, path_found
) == INVALID_TRACK
; break; // OPF always allows reversing
387 case VPF_NPF
: reverse
= NPFShipCheckReverse(v
); break;
388 case VPF_YAPF
: reverse
= YapfShipCheckReverse(v
); break;
389 default: NOT_REACHED();
391 if (reverse
) north_tracks
= TRACK_BIT_NONE
;
395 /* Leave towards north */
396 v
->direction
= DiagDirToDir(north_dir
);
397 } else if (south_tracks
) {
398 /* Leave towards south */
399 v
->direction
= DiagDirToDir(south_dir
);
401 /* Both ways blocked */
405 v
->state
= AxisToTrackBits(axis
);
406 v
->vehstatus
&= ~VS_HIDDEN
;
409 v
->UpdateViewport(true, true);
410 SetWindowDirty(WC_VEHICLE_DEPOT
, v
->tile
);
413 VehicleServiceInDepot(v
);
414 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
415 SetWindowClassesDirty(WC_SHIPS_LIST
);
420 static bool ShipAccelerate(Vehicle
*v
)
425 spd
= min(v
->cur_speed
+ 1, v
->vcache
.cached_max_speed
);
426 spd
= min(spd
, v
->current_order
.GetMaxSpeed() * 2);
428 /* updates statusbar only if speed have changed to save CPU time */
429 if (spd
!= v
->cur_speed
) {
431 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
434 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
435 spd
= v
->GetOldAdvanceSpeed(spd
);
437 if (spd
== 0) return false;
438 if ((byte
)++spd
== 0) return true;
440 v
->progress
= (t
= v
->progress
) - (byte
)spd
;
442 return (t
< v
->progress
);
446 * Ship arrives at a dock. If it is the first time, send out a news item.
447 * @param v Ship that arrived.
448 * @param st Station being visited.
450 static void ShipArrivesAt(const Vehicle
*v
, Station
*st
)
452 /* Check if station was ever visited before */
453 if (!(st
->had_vehicle_of_type
& HVOT_SHIP
)) {
454 st
->had_vehicle_of_type
|= HVOT_SHIP
;
456 SetDParam(0, st
->index
);
458 STR_NEWS_FIRST_SHIP_ARRIVAL
,
459 (v
->owner
== _local_company
) ? NT_ARRIVAL_COMPANY
: NT_ARRIVAL_OTHER
,
463 AI::NewEvent(v
->owner
, new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
464 Game::NewEvent(new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
470 * Runs the pathfinder to choose a track to continue along.
472 * @param v Ship to navigate
473 * @param tile Tile, the ship is about to enter
474 * @param enterdir Direction of entering
475 * @param tracks Available track choices on \a tile
476 * @return Track to choose, or INVALID_TRACK when to reverse.
478 static Track
ChooseShipTrack(Ship
*v
, TileIndex tile
, DiagDirection enterdir
, TrackBits tracks
)
480 assert(IsValidDiagDirection(enterdir
));
482 bool path_found
= true;
484 switch (_settings_game
.pf
.pathfinder_for_ships
) {
485 case VPF_OPF
: track
= OPFShipChooseTrack(v
, tile
, enterdir
, tracks
, path_found
); break;
486 case VPF_NPF
: track
= NPFShipChooseTrack(v
, tile
, enterdir
, tracks
, path_found
); break;
487 case VPF_YAPF
: track
= YapfShipChooseTrack(v
, tile
, enterdir
, tracks
, path_found
); break;
488 default: NOT_REACHED();
491 v
->HandlePathfindingResult(path_found
);
495 static inline TrackBits
GetAvailShipTracks(TileIndex tile
, DiagDirection dir
)
497 return GetTileShipTrackStatus(tile
) & DiagdirReachesTracks(dir
);
500 static const byte _ship_subcoord
[4][6][3] = {
535 /* Used for finding tile exit direction using the enter direction and following track */
536 static const DiagDirection _diagdir_tile_exit
[TRACK_END
][DIAGDIR_END
] = {
537 { DIAGDIR_NE
, INVALID_DIAGDIR
, DIAGDIR_SW
, INVALID_DIAGDIR
}, // TRACK_X = 0
538 { INVALID_DIAGDIR
, DIAGDIR_SE
, INVALID_DIAGDIR
, DIAGDIR_NW
}, // TRACK_Y = 1
539 { INVALID_DIAGDIR
, DIAGDIR_NE
, DIAGDIR_NW
, INVALID_DIAGDIR
}, // TRACK_UPPER = 2
540 { DIAGDIR_SE
, INVALID_DIAGDIR
, INVALID_DIAGDIR
, DIAGDIR_SW
}, // TRACK_LOWER = 3
541 { DIAGDIR_NW
, DIAGDIR_SW
, INVALID_DIAGDIR
, INVALID_DIAGDIR
}, // TRACK_LEFT = 4
542 { INVALID_DIAGDIR
, INVALID_DIAGDIR
, DIAGDIR_SE
, DIAGDIR_NE
} // TRACK_RIGHT = 5
545 struct ShipCollideChecker
{
547 TrackBits track_bits
; ///< Trackbits (track that was chosen by the pathfinder converted in trackbits.) .
548 TileIndex tile
; ///< Tile of where ship was found, used to determine distance between ships.
551 /** Helper function for collision avoidance. */
552 static Vehicle
*FindShipOnTile(Vehicle
*v
, void *data
)
554 if (v
->type
!= VEH_SHIP
|| v
->vehstatus
& VS_STOPPED
) return NULL
;
556 ShipCollideChecker
*scc
= (ShipCollideChecker
*)data
;
559 /* Don't detect vehicles on different parallel tracks. */
560 TrackBits bits
= scc
->track_bits
| Ship::From(v
)->state
;
561 if (bits
== TRACK_BIT_HORZ
|| bits
== TRACK_BIT_VERT
) return NULL
;
567 * If there is imminent collision or worse, direction and speed will be adjusted.
568 * @param tile Tile that the ship is about to enter.
569 * @param v Ship that does the request.
570 * @param tracks The available tracks that could be followed.
571 * @param track The track that the pathfinder assigned.
572 * @param diagdir The DiagDirection that tile will be entered.
573 * @return The new track if found.
575 static void CheckDistanceBetweenShips(TileIndex tile
, Ship
*v
, TrackBits tracks
, Track
*track_old
, DiagDirection diagdir
)
577 if (!_settings_game
.pf
.forbid_90_deg
) return;
578 if (DistanceManhattan(v
->dest_tile
, tile
) <= 3 && !v
->current_order
.IsType(OT_GOTO_WAYPOINT
)) return; // No checking close to docks and depots.
580 Track track
= *track_old
;
582 TileIndex tile_plus_one
= TileAddByDiagDir(tile
, _diagdir_tile_exit
[track
][diagdir
]);
583 if (!IsValidTile(tile_plus_one
)) tile_plus_one
= tile
;
585 ShipCollideChecker scc
;
587 scc
.track_bits
= v
->state
;
588 bool found
= HasVehicleOnPos(tile_plus_one
, &scc
, &FindShipOnTile
);
589 scc
.track_bits
= TrackToTrackBits(track
);
590 if (!found
) found
= HasVehicleOnPos(tile
, &scc
, &FindShipOnTile
);
594 /* Speed adjustment related to distance. */
595 v
->cur_speed
/= scc
.tile
== tile_plus_one
? 2 : 4;
599 case TRACK_BIT_3WAY_NE
: track
== TRACK_RIGHT
? track
= TRACK_X
: track
= TRACK_UPPER
; break;
600 case TRACK_BIT_3WAY_SE
: track
== TRACK_LOWER
? track
= TRACK_Y
: track
= TRACK_RIGHT
; break;
601 case TRACK_BIT_3WAY_SW
: track
== TRACK_LEFT
? track
= TRACK_X
: track
= TRACK_LOWER
; break;
602 case TRACK_BIT_3WAY_NW
: track
== TRACK_UPPER
? track
= TRACK_Y
: track
= TRACK_LEFT
; break;
604 /* Don't bump in coast, don't get stuck. */
605 if (track
!= *track_old
&& !IsWaterTile(TileAddByDiagDir(tile
, _diagdir_tile_exit
[track
][diagdir
]))) return;
610 static void ShipController(Ship
*v
)
619 v
->current_order_time
++;
621 if (v
->HandleBreakdown()) return;
623 if (v
->vehstatus
& VS_STOPPED
) return;
628 if (v
->current_order
.IsType(OT_LOADING
)) return;
630 if (CheckShipLeaveDepot(v
)) return;
632 v
->ShowVisualEffect();
634 if (!ShipAccelerate(v
)) return;
636 GetNewVehiclePosResult gp
= GetNewVehiclePos(v
);
637 if (v
->state
!= TRACK_BIT_WORMHOLE
) {
638 /* Not on a bridge */
639 if (gp
.old_tile
== gp
.new_tile
) {
640 /* Staying in tile */
641 if (v
->IsInDepot()) {
645 /* Not inside depot */
646 r
= VehicleEnterTile(v
, gp
.new_tile
, gp
.x
, gp
.y
);
647 if (HasBit(r
, VETS_CANNOT_ENTER
)) goto reverse_direction
;
649 /* A leave station order only needs one tick to get processed, so we can
650 * always skip ahead. */
651 if (v
->current_order
.IsType(OT_LEAVESTATION
)) {
652 v
->current_order
.Free();
653 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
654 } else if (v
->dest_tile
!= 0) {
655 /* We have a target, let's see if we reached it... */
656 if (v
->current_order
.IsType(OT_GOTO_WAYPOINT
) &&
657 DistanceManhattan(v
->dest_tile
, gp
.new_tile
) <= 3) {
658 /* We got within 3 tiles of our target buoy, so let's skip to our
660 UpdateVehicleTimetable(v
, true);
661 v
->IncrementRealOrderIndex();
662 v
->current_order
.MakeDummy();
664 /* Non-buoy orders really need to reach the tile */
665 if (v
->dest_tile
== gp
.new_tile
) {
666 if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
667 if ((gp
.x
& 0xF) == 8 && (gp
.y
& 0xF) == 8) {
668 VehicleEnterDepot(v
);
671 } else if (v
->current_order
.IsType(OT_GOTO_STATION
)) {
672 v
->last_station_visited
= v
->current_order
.GetDestination();
674 /* Process station in the orderlist. */
675 Station
*st
= Station::Get(v
->current_order
.GetDestination());
676 if (st
->facilities
& FACIL_DOCK
) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
677 ShipArrivesAt(v
, st
);
679 } else { // leave stations without docks right aways
680 v
->current_order
.MakeLeaveStation();
681 v
->IncrementRealOrderIndex();
690 if (!IsValidTile(gp
.new_tile
)) goto reverse_direction
;
692 DiagDirection diagdir
= DiagdirBetweenTiles(gp
.old_tile
, gp
.new_tile
);
693 assert(diagdir
!= INVALID_DIAGDIR
);
694 tracks
= GetAvailShipTracks(gp
.new_tile
, diagdir
);
695 if (tracks
== TRACK_BIT_NONE
) goto reverse_direction
;
697 /* Choose a direction, and continue if we find one */
698 track
= ChooseShipTrack(v
, gp
.new_tile
, diagdir
, tracks
);
699 if (track
== INVALID_TRACK
) goto reverse_direction
;
701 /* Try to avoid collision and keep distance between ships. */
702 CheckDistanceBetweenShips(gp
.new_tile
, v
, tracks
, &track
, diagdir
);
704 b
= _ship_subcoord
[diagdir
][track
];
706 gp
.x
= (gp
.x
& ~0xF) | b
[0];
707 gp
.y
= (gp
.y
& ~0xF) | b
[1];
709 /* Call the landscape function and tell it that the vehicle entered the tile */
710 r
= VehicleEnterTile(v
, gp
.new_tile
, gp
.x
, gp
.y
);
711 if (HasBit(r
, VETS_CANNOT_ENTER
)) goto reverse_direction
;
713 if (!HasBit(r
, VETS_ENTERED_WORMHOLE
)) {
714 v
->tile
= gp
.new_tile
;
715 v
->state
= TrackToTrackBits(track
);
717 /* Update ship cache when the water class changes. Aqueducts are always canals. */
718 WaterClass old_wc
= GetEffectiveWaterClass(gp
.old_tile
);
719 WaterClass new_wc
= GetEffectiveWaterClass(gp
.new_tile
);
720 if (old_wc
!= new_wc
) v
->UpdateCache();
723 v
->direction
= (Direction
)b
[2];
727 if (!IsTileType(gp
.new_tile
, MP_TUNNELBRIDGE
) || !HasBit(VehicleEnterTile(v
, gp
.new_tile
, gp
.x
, gp
.y
), VETS_ENTERED_WORMHOLE
)) {
731 if ((v
->vehstatus
& VS_HIDDEN
) == 0) v
->Vehicle::UpdateViewport(true);
736 /* update image of ship, as well as delta XY */
739 v
->z_pos
= GetSlopePixelZ(gp
.x
, gp
.y
);
743 v
->UpdateViewport(true, true);
747 dir
= ReverseDir(v
->direction
);
754 if (!((this->vehstatus
& VS_STOPPED
) || this->IsChainInDepot())) this->running_ticks
++;
756 ShipController(this);
763 * @param tile tile of the depot where ship is built.
764 * @param flags type of operation.
765 * @param e the engine to build.
766 * @param data unused.
767 * @param ret[out] the vehicle that has been built.
768 * @return the cost of this operation or an error.
770 CommandCost
CmdBuildShip(TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**ret
)
772 tile
= GetShipDepotNorthTile(tile
);
773 if (flags
& DC_EXEC
) {
777 const ShipVehicleInfo
*svi
= &e
->u
.ship
;
779 Ship
*v
= new Ship();
782 v
->owner
= _current_company
;
784 x
= TileX(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
785 y
= TileY(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
788 v
->z_pos
= GetSlopePixelZ(x
, y
);
790 v
->UpdateDeltaXY(v
->direction
);
791 v
->vehstatus
= VS_HIDDEN
| VS_STOPPED
| VS_DEFPAL
;
793 v
->spritenum
= svi
->image_index
;
794 v
->cargo_type
= e
->GetDefaultCargoType();
795 v
->cargo_cap
= svi
->capacity
;
798 v
->last_station_visited
= INVALID_STATION
;
799 v
->last_loading_station
= INVALID_STATION
;
800 v
->engine_type
= e
->index
;
802 v
->reliability
= e
->reliability
;
803 v
->reliability_spd_dec
= e
->reliability_spd_dec
;
804 v
->max_age
= e
->GetLifeLengthInDays();
805 _new_vehicle_id
= v
->index
;
807 v
->state
= TRACK_BIT_DEPOT
;
809 v
->SetServiceInterval(Company::Get(_current_company
)->settings
.vehicle
.servint_ships
);
810 v
->date_of_last_service
= _date
;
811 v
->build_year
= _cur_year
;
812 v
->sprite_seq
.Set(SPR_IMG_QUERY
);
813 v
->random_bits
= VehicleRandomBits();
817 if (e
->flags
& ENGINE_EXCLUSIVE_PREVIEW
) SetBit(v
->vehicle_flags
, VF_BUILT_AS_PROTOTYPE
);
818 v
->SetServiceIntervalIsPercent(Company::Get(_current_company
)->settings
.vehicle
.servint_ispercent
);
820 v
->InvalidateNewGRFCacheOfChain();
822 v
->cargo_cap
= e
->DetermineCapacity(v
);
824 v
->InvalidateNewGRFCacheOfChain();
829 return CommandCost();
832 bool Ship::FindClosestDepot(TileIndex
*location
, DestinationID
*destination
, bool *reverse
)
834 const Depot
*depot
= FindClosestShipDepot(this, 0);
836 if (depot
== NULL
) return false;
838 if (location
!= NULL
) *location
= depot
->xy
;
839 if (destination
!= NULL
) *destination
= depot
->index
;