2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
9 * @file aircraft_cmd.cpp
10 * This file deals with aircraft and airport movements functionalities
15 #include "landscape.h"
16 #include "news_func.h"
17 #include "newgrf_engine.h"
18 #include "newgrf_sound.h"
19 #include "spritecache.h"
20 #include "strings_func.h"
21 #include "command_func.h"
22 #include "window_func.h"
23 #include "date_func.h"
24 #include "vehicle_func.h"
25 #include "sound_func.h"
26 #include "cheat_type.h"
27 #include "company_base.h"
29 #include "game/game.hpp"
30 #include "company_func.h"
31 #include "effectvehicle_func.h"
32 #include "station_base.h"
33 #include "engine_base.h"
34 #include "core/random_func.hpp"
35 #include "core/backup_type.hpp"
36 #include "zoom_func.h"
37 #include "disaster_vehicle.h"
38 #include "newgrf_airporttiles.h"
39 #include "framerate_type.h"
41 #include "table/strings.h"
43 #include "safeguards.h"
45 void Aircraft::UpdateDeltaXY()
52 switch (this->subtype
) {
53 default: NOT_REACHED();
57 switch (this->state
) {
82 static bool AirportMove(Aircraft
*v
, const AirportFTAClass
*apc
);
83 static bool AirportSetBlocks(Aircraft
*v
, const AirportFTA
*current_pos
, const AirportFTAClass
*apc
);
84 static bool AirportHasBlock(Aircraft
*v
, const AirportFTA
*current_pos
, const AirportFTAClass
*apc
);
85 static bool AirportFindFreeTerminal(Aircraft
*v
, const AirportFTAClass
*apc
);
86 static bool AirportFindFreeHelipad(Aircraft
*v
, const AirportFTAClass
*apc
);
87 static void CrashAirplane(Aircraft
*v
);
89 static const SpriteID _aircraft_sprite
[] = {
90 0x0EB5, 0x0EBD, 0x0EC5, 0x0ECD,
91 0x0ED5, 0x0EDD, 0x0E9D, 0x0EA5,
92 0x0EAD, 0x0EE5, 0x0F05, 0x0F0D,
93 0x0F15, 0x0F1D, 0x0F25, 0x0F2D,
94 0x0EED, 0x0EF5, 0x0EFD, 0x0F35,
95 0x0E9D, 0x0EA5, 0x0EAD, 0x0EB5,
100 bool IsValidImageIndex
<VEH_AIRCRAFT
>(uint8 image_index
)
102 return image_index
< lengthof(_aircraft_sprite
);
105 /** Helicopter rotor animation states */
106 enum HelicopterRotorStates
{
114 * Find the nearest hangar to v
115 * INVALID_STATION is returned, if the company does not have any suitable
116 * airports (like helipads only)
117 * @param v vehicle looking for a hangar
118 * @return the StationID if one is found, otherwise, INVALID_STATION
120 static StationID
FindNearestHangar(const Aircraft
*v
)
123 StationID index
= INVALID_STATION
;
124 TileIndex vtile
= TileVirtXY(v
->x_pos
, v
->y_pos
);
125 const AircraftVehicleInfo
*avi
= AircraftVehInfo(v
->engine_type
);
126 uint max_range
= v
->acache
.cached_max_range_sqr
;
128 /* Determine destinations where it's coming from and where it's heading to */
129 const Station
*last_dest
= nullptr;
130 const Station
*next_dest
= nullptr;
131 if (max_range
!= 0) {
132 if (v
->current_order
.IsType(OT_GOTO_STATION
) ||
133 (v
->current_order
.IsType(OT_GOTO_DEPOT
) && v
->current_order
.GetDepotActionType() != ODATFB_NEAREST_DEPOT
)) {
134 last_dest
= Station::GetIfValid(v
->last_station_visited
);
135 next_dest
= Station::GetIfValid(v
->current_order
.GetDestination());
137 last_dest
= GetTargetAirportIfValid(v
);
138 next_dest
= Station::GetIfValid(v
->GetNextStoppingStation().value
);
142 for (const Station
*st
: Station::Iterate()) {
143 if (st
->owner
!= v
->owner
|| !(st
->facilities
& FACIL_AIRPORT
) || !st
->airport
.HasHangar()) continue;
145 const AirportFTAClass
*afc
= st
->airport
.GetFTA();
147 /* don't crash the plane if we know it can't land at the airport */
148 if ((afc
->flags
& AirportFTAClass::SHORT_STRIP
) && (avi
->subtype
& AIR_FAST
) && !_cheats
.no_jetcrash
.value
) continue;
150 /* the plane won't land at any helicopter station */
151 if (!(afc
->flags
& AirportFTAClass::AIRPLANES
) && (avi
->subtype
& AIR_CTOL
)) continue;
153 /* Check if our last and next destinations can be reached from the depot airport. */
154 if (max_range
!= 0) {
155 uint last_dist
= (last_dest
!= nullptr && last_dest
->airport
.tile
!= INVALID_TILE
) ? DistanceSquare(st
->airport
.tile
, last_dest
->airport
.tile
) : 0;
156 uint next_dist
= (next_dest
!= nullptr && next_dest
->airport
.tile
!= INVALID_TILE
) ? DistanceSquare(st
->airport
.tile
, next_dest
->airport
.tile
) : 0;
157 if (last_dist
> max_range
|| next_dist
> max_range
) continue;
160 /* v->tile can't be used here, when aircraft is flying v->tile is set to 0 */
161 uint distance
= DistanceSquare(vtile
, st
->airport
.tile
);
162 if (distance
< best
|| index
== INVALID_STATION
) {
170 void Aircraft::GetImage(Direction direction
, EngineImageType image_type
, VehicleSpriteSeq
*result
) const
172 uint8 spritenum
= this->spritenum
;
174 if (is_custom_sprite(spritenum
)) {
175 GetCustomVehicleSprite(this, direction
, image_type
, result
);
176 if (result
->IsValid()) return;
178 spritenum
= this->GetEngine()->original_image_index
;
181 assert(IsValidImageIndex
<VEH_AIRCRAFT
>(spritenum
));
182 result
->Set(direction
+ _aircraft_sprite
[spritenum
]);
185 void GetRotorImage(const Aircraft
*v
, EngineImageType image_type
, VehicleSpriteSeq
*result
)
187 assert(v
->subtype
== AIR_HELICOPTER
);
189 const Aircraft
*w
= v
->Next()->Next();
190 if (is_custom_sprite(v
->spritenum
)) {
191 GetCustomRotorSprite(v
, false, image_type
, result
);
192 if (result
->IsValid()) return;
195 /* Return standard rotor sprites if there are no custom sprites for this helicopter */
196 result
->Set(SPR_ROTOR_STOPPED
+ w
->state
);
199 static void GetAircraftIcon(EngineID engine
, EngineImageType image_type
, VehicleSpriteSeq
*result
)
201 const Engine
*e
= Engine::Get(engine
);
202 uint8 spritenum
= e
->u
.air
.image_index
;
204 if (is_custom_sprite(spritenum
)) {
205 GetCustomVehicleIcon(engine
, DIR_W
, image_type
, result
);
206 if (result
->IsValid()) return;
208 spritenum
= e
->original_image_index
;
211 assert(IsValidImageIndex
<VEH_AIRCRAFT
>(spritenum
));
212 result
->Set(DIR_W
+ _aircraft_sprite
[spritenum
]);
215 void DrawAircraftEngine(int left
, int right
, int preferred_x
, int y
, EngineID engine
, PaletteID pal
, EngineImageType image_type
)
217 VehicleSpriteSeq seq
;
218 GetAircraftIcon(engine
, image_type
, &seq
);
221 seq
.GetBounds(&rect
);
222 preferred_x
= Clamp(preferred_x
,
223 left
- UnScaleGUI(rect
.left
),
224 right
- UnScaleGUI(rect
.right
));
226 seq
.Draw(preferred_x
, y
, pal
, pal
== PALETTE_CRASH
);
228 if (!(AircraftVehInfo(engine
)->subtype
& AIR_CTOL
)) {
229 VehicleSpriteSeq rotor_seq
;
230 GetCustomRotorIcon(engine
, image_type
, &rotor_seq
);
231 if (!rotor_seq
.IsValid()) rotor_seq
.Set(SPR_ROTOR_STOPPED
);
232 rotor_seq
.Draw(preferred_x
, y
- ScaleGUITrad(5), PAL_NONE
, false);
237 * Get the size of the sprite of an aircraft sprite heading west (used for lists).
238 * @param engine The engine to get the sprite from.
239 * @param[out] width The width of the sprite.
240 * @param[out] height The height of the sprite.
241 * @param[out] xoffs Number of pixels to shift the sprite to the right.
242 * @param[out] yoffs Number of pixels to shift the sprite downwards.
243 * @param image_type Context the sprite is used in.
245 void GetAircraftSpriteSize(EngineID engine
, uint
&width
, uint
&height
, int &xoffs
, int &yoffs
, EngineImageType image_type
)
247 VehicleSpriteSeq seq
;
248 GetAircraftIcon(engine
, image_type
, &seq
);
251 seq
.GetBounds(&rect
);
253 width
= UnScaleGUI(rect
.right
- rect
.left
+ 1);
254 height
= UnScaleGUI(rect
.bottom
- rect
.top
+ 1);
255 xoffs
= UnScaleGUI(rect
.left
);
256 yoffs
= UnScaleGUI(rect
.top
);
261 * @param tile tile of the depot where aircraft is built.
262 * @param flags type of operation.
263 * @param e the engine to build.
264 * @param data unused.
265 * @param[out] ret the vehicle that has been built.
266 * @return the cost of this operation or an error.
268 CommandCost
CmdBuildAircraft(TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**ret
)
270 const AircraftVehicleInfo
*avi
= &e
->u
.air
;
271 const Station
*st
= Station::GetByTile(tile
);
273 /* Prevent building aircraft types at places which can't handle them */
274 if (!CanVehicleUseStation(e
->index
, st
)) return CMD_ERROR
;
276 /* Make sure all aircraft end up in the first tile of the hangar. */
277 tile
= st
->airport
.GetHangarTile(st
->airport
.GetHangarNum(tile
));
279 if (flags
& DC_EXEC
) {
280 Aircraft
*v
= new Aircraft(); // aircraft
281 Aircraft
*u
= new Aircraft(); // shadow
284 v
->direction
= DIR_SE
;
286 v
->owner
= u
->owner
= _current_company
;
290 uint x
= TileX(tile
) * TILE_SIZE
+ 5;
291 uint y
= TileY(tile
) * TILE_SIZE
+ 3;
293 v
->x_pos
= u
->x_pos
= x
;
294 v
->y_pos
= u
->y_pos
= y
;
296 u
->z_pos
= GetSlopePixelZ(x
, y
);
297 v
->z_pos
= u
->z_pos
+ 1;
299 v
->vehstatus
= VS_HIDDEN
| VS_STOPPED
| VS_DEFPAL
;
300 u
->vehstatus
= VS_HIDDEN
| VS_UNCLICKABLE
| VS_SHADOW
;
302 v
->spritenum
= avi
->image_index
;
304 v
->cargo_cap
= avi
->passenger_capacity
;
306 u
->cargo_cap
= avi
->mail_capacity
;
309 v
->cargo_type
= e
->GetDefaultCargoType();
310 u
->cargo_type
= CT_MAIL
;
313 v
->last_station_visited
= INVALID_STATION
;
314 v
->last_loading_station
= INVALID_STATION
;
316 v
->acceleration
= avi
->acceleration
;
317 v
->engine_type
= e
->index
;
318 u
->engine_type
= e
->index
;
320 v
->subtype
= (avi
->subtype
& AIR_CTOL
? AIR_AIRCRAFT
: AIR_HELICOPTER
);
323 u
->subtype
= AIR_SHADOW
;
326 v
->reliability
= e
->reliability
;
327 v
->reliability_spd_dec
= e
->reliability_spd_dec
;
328 v
->max_age
= e
->GetLifeLengthInDays();
330 _new_vehicle_id
= v
->index
;
332 v
->pos
= GetVehiclePosOnBuild(tile
);
335 v
->previous_pos
= v
->pos
;
336 v
->targetairport
= GetStationIndex(tile
);
339 v
->SetServiceInterval(Company::Get(_current_company
)->settings
.vehicle
.servint_aircraft
);
341 v
->date_of_last_service
= _date
;
342 v
->build_year
= u
->build_year
= _cur_year
;
344 v
->sprite_cache
.sprite_seq
.Set(SPR_IMG_QUERY
);
345 u
->sprite_cache
.sprite_seq
.Set(SPR_IMG_QUERY
);
347 v
->random_bits
= VehicleRandomBits();
348 u
->random_bits
= VehicleRandomBits();
350 v
->vehicle_flags
= 0;
351 if (e
->flags
& ENGINE_EXCLUSIVE_PREVIEW
) SetBit(v
->vehicle_flags
, VF_BUILT_AS_PROTOTYPE
);
352 v
->SetServiceIntervalIsPercent(Company::Get(_current_company
)->settings
.vehicle
.servint_ispercent
);
354 v
->InvalidateNewGRFCacheOfChain();
356 v
->cargo_cap
= e
->DetermineCapacity(v
, &u
->cargo_cap
);
358 v
->InvalidateNewGRFCacheOfChain();
360 UpdateAircraftCache(v
, true);
365 /* Aircraft with 3 vehicles (chopper)? */
366 if (v
->subtype
== AIR_HELICOPTER
) {
367 Aircraft
*w
= new Aircraft();
368 w
->engine_type
= e
->index
;
369 w
->direction
= DIR_N
;
370 w
->owner
= _current_company
;
373 w
->z_pos
= v
->z_pos
+ ROTOR_Z_OFFSET
;
374 w
->vehstatus
= VS_HIDDEN
| VS_UNCLICKABLE
;
376 w
->subtype
= AIR_ROTOR
;
377 w
->sprite_cache
.sprite_seq
.Set(SPR_ROTOR_STOPPED
);
378 w
->random_bits
= VehicleRandomBits();
379 /* Use rotor's air.state to store the rotor animation frame */
380 w
->state
= HRS_ROTOR_STOPPED
;
388 return CommandCost();
392 bool Aircraft::FindClosestDepot(TileIndex
*location
, DestinationID
*destination
, bool *reverse
)
394 const Station
*st
= GetTargetAirportIfValid(this);
395 /* If the station is not a valid airport or if it has no hangars */
396 if (st
== nullptr || !CanVehicleUseStation(this, st
) || !st
->airport
.HasHangar()) {
397 /* the aircraft has to search for a hangar on its own */
398 StationID station
= FindNearestHangar(this);
400 if (station
== INVALID_STATION
) return false;
402 st
= Station::Get(station
);
405 if (location
!= nullptr) *location
= st
->xy
;
406 if (destination
!= nullptr) *destination
= st
->index
;
411 static void CheckIfAircraftNeedsService(Aircraft
*v
)
413 if (Company::Get(v
->owner
)->settings
.vehicle
.servint_aircraft
== 0 || !v
->NeedsAutomaticServicing()) return;
414 if (v
->IsChainInDepot()) {
415 VehicleServiceInDepot(v
);
419 /* When we're parsing conditional orders and the like
420 * we don't want to consider going to a depot too. */
421 if (!v
->current_order
.IsType(OT_GOTO_DEPOT
) && !v
->current_order
.IsType(OT_GOTO_STATION
)) return;
423 const Station
*st
= Station::Get(v
->current_order
.GetDestination());
425 assert(st
!= nullptr);
427 /* only goto depot if the target airport has a depot */
428 if (st
->airport
.HasHangar() && CanVehicleUseStation(v
, st
)) {
429 v
->current_order
.MakeGoToDepot(st
->index
, ODTFB_SERVICE
);
430 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
431 } else if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
432 v
->current_order
.MakeDummy();
433 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
437 Money
Aircraft::GetRunningCost() const
439 const Engine
*e
= this->GetEngine();
440 uint cost_factor
= GetVehicleProperty(this, PROP_AIRCRAFT_RUNNING_COST_FACTOR
, e
->u
.air
.running_cost
);
441 return GetPrice(PR_RUNNING_AIRCRAFT
, cost_factor
, e
->GetGRF());
444 void Aircraft::OnNewDay()
446 if (!this->IsNormalAircraft()) return;
448 if ((++this->day_counter
& 7) == 0) DecreaseVehicleValue(this);
452 CheckVehicleBreakdown(this);
454 CheckIfAircraftNeedsService(this);
456 if (this->running_ticks
== 0) return;
458 CommandCost
cost(EXPENSES_AIRCRAFT_RUN
, this->GetRunningCost() * this->running_ticks
/ (DAYS_IN_YEAR
* DAY_TICKS
));
460 this->profit_this_year
-= cost
.GetCost();
461 this->running_ticks
= 0;
463 SubtractMoneyFromCompanyFract(this->owner
, cost
);
465 SetWindowDirty(WC_VEHICLE_DETAILS
, this->index
);
466 SetWindowClassesDirty(WC_AIRCRAFT_LIST
);
469 static void HelicopterTickHandler(Aircraft
*v
)
471 Aircraft
*u
= v
->Next()->Next();
473 if (u
->vehstatus
& VS_HIDDEN
) return;
475 /* if true, helicopter rotors do not rotate. This should only be the case if a helicopter is
476 * loading/unloading at a terminal or stopped */
477 if (v
->current_order
.IsType(OT_LOADING
) || (v
->vehstatus
& VS_STOPPED
)) {
478 if (u
->cur_speed
!= 0) {
480 if (u
->cur_speed
>= 0x80 && u
->state
== HRS_ROTOR_MOVING_3
) {
485 if (u
->cur_speed
== 0) {
488 if (u
->cur_speed
>= 0x50) {
493 int tick
= ++u
->tick_counter
;
494 int spd
= u
->cur_speed
>> 4;
496 VehicleSpriteSeq seq
;
498 u
->state
= HRS_ROTOR_STOPPED
;
499 GetRotorImage(v
, EIT_ON_MAP
, &seq
);
500 if (u
->sprite_cache
.sprite_seq
== seq
) return;
501 } else if (tick
>= spd
) {
504 if (u
->state
> HRS_ROTOR_MOVING_3
) u
->state
= HRS_ROTOR_MOVING_1
;
505 GetRotorImage(v
, EIT_ON_MAP
, &seq
);
510 u
->sprite_cache
.sprite_seq
= seq
;
512 u
->UpdatePositionAndViewport();
516 * Set aircraft position.
517 * @param v Aircraft to position.
518 * @param x New X position.
519 * @param y New y position.
520 * @param z New z position.
522 void SetAircraftPosition(Aircraft
*v
, int x
, int y
, int z
)
529 v
->UpdateViewport(true, false);
530 if (v
->subtype
== AIR_HELICOPTER
) {
531 GetRotorImage(v
, EIT_ON_MAP
, &v
->Next()->Next()->sprite_cache
.sprite_seq
);
534 Aircraft
*u
= v
->Next();
536 int safe_x
= Clamp(x
, 0, MapMaxX() * TILE_SIZE
);
537 int safe_y
= Clamp(y
- 1, 0, MapMaxY() * TILE_SIZE
);
539 u
->y_pos
= y
- ((v
->z_pos
- GetSlopePixelZ(safe_x
, safe_y
)) >> 3);
541 safe_y
= Clamp(u
->y_pos
, 0, MapMaxY() * TILE_SIZE
);
542 u
->z_pos
= GetSlopePixelZ(safe_x
, safe_y
);
543 u
->sprite_cache
.sprite_seq
.CopyWithoutPalette(v
->sprite_cache
.sprite_seq
); // the shadow is never coloured
545 u
->UpdatePositionAndViewport();
551 u
->z_pos
= z
+ ROTOR_Z_OFFSET
;
553 u
->UpdatePositionAndViewport();
558 * Handle Aircraft specific tasks when an Aircraft enters a hangar
559 * @param *v Vehicle that enters the hangar
561 void HandleAircraftEnterHangar(Aircraft
*v
)
566 Aircraft
*u
= v
->Next();
567 u
->vehstatus
|= VS_HIDDEN
;
570 u
->vehstatus
|= VS_HIDDEN
;
574 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, v
->z_pos
);
577 static void PlayAircraftSound(const Vehicle
*v
)
579 if (!PlayVehicleSound(v
, VSE_START
)) {
580 SndPlayVehicleFx(AircraftVehInfo(v
->engine_type
)->sfx
, v
);
586 * Update cached values of an aircraft.
587 * Currently caches callback 36 max speed.
589 * @param update_range Update the aircraft range.
591 void UpdateAircraftCache(Aircraft
*v
, bool update_range
)
593 uint max_speed
= GetVehicleProperty(v
, PROP_AIRCRAFT_SPEED
, 0);
594 if (max_speed
!= 0) {
595 /* Convert from original units to km-ish/h */
596 max_speed
= (max_speed
* 128) / 10;
598 v
->vcache
.cached_max_speed
= max_speed
;
600 /* Use the default max speed of the vehicle. */
601 v
->vcache
.cached_max_speed
= AircraftVehInfo(v
->engine_type
)->max_speed
;
604 /* Update cargo aging period. */
605 v
->vcache
.cached_cargo_age_period
= GetVehicleProperty(v
, PROP_AIRCRAFT_CARGO_AGE_PERIOD
, EngInfo(v
->engine_type
)->cargo_age_period
);
606 Aircraft
*u
= v
->Next(); // Shadow for mail
607 u
->vcache
.cached_cargo_age_period
= GetVehicleProperty(u
, PROP_AIRCRAFT_CARGO_AGE_PERIOD
, EngInfo(u
->engine_type
)->cargo_age_period
);
609 /* Update aircraft range. */
611 v
->acache
.cached_max_range
= GetVehicleProperty(v
, PROP_AIRCRAFT_RANGE
, AircraftVehInfo(v
->engine_type
)->max_range
);
612 /* Squared it now so we don't have to do it later all the time. */
613 v
->acache
.cached_max_range_sqr
= v
->acache
.cached_max_range
* v
->acache
.cached_max_range
;
619 * Special velocities for aircraft
621 enum AircraftSpeedLimits
{
622 SPEED_LIMIT_TAXI
= 50, ///< Maximum speed of an aircraft while taxiing
623 SPEED_LIMIT_APPROACH
= 230, ///< Maximum speed of an aircraft on finals
624 SPEED_LIMIT_BROKEN
= 320, ///< Maximum speed of an aircraft that is broken
625 SPEED_LIMIT_HOLD
= 425, ///< Maximum speed of an aircraft that flies the holding pattern
626 SPEED_LIMIT_NONE
= 0xFFFF, ///< No environmental speed limit. Speed limit is type dependent
630 * Sets the new speed for an aircraft
631 * @param v The vehicle for which the speed should be obtained
632 * @param speed_limit The maximum speed the vehicle may have.
633 * @param hard_limit If true, the limit is directly enforced, otherwise the plane is slowed down gradually
634 * @return The number of position updates needed within the tick
636 static int UpdateAircraftSpeed(Aircraft
*v
, uint speed_limit
= SPEED_LIMIT_NONE
, bool hard_limit
= true)
639 * 'acceleration' has the unit 3/8 mph/tick. This function is called twice per tick.
640 * So the speed amount we need to accelerate is:
641 * acceleration * 3 / 16 mph = acceleration * 3 / 16 * 16 / 10 km-ish/h
642 * = acceleration * 3 / 10 * 256 * (km-ish/h / 256)
643 * ~ acceleration * 77 (km-ish/h / 256)
645 uint spd
= v
->acceleration
* 77;
648 /* Adjust speed limits by plane speed factor to prevent taxiing
649 * and take-off speeds being too low. */
650 speed_limit
*= _settings_game
.vehicle
.plane_speed
;
652 /* adjust speed for broken vehicles */
653 if (v
->vehstatus
& VS_AIRCRAFT_BROKEN
) {
654 if (SPEED_LIMIT_BROKEN
< speed_limit
) hard_limit
= false;
655 speed_limit
= std::min
<uint
>(speed_limit
, SPEED_LIMIT_BROKEN
);
658 if (v
->vcache
.cached_max_speed
< speed_limit
) {
659 if (v
->cur_speed
< speed_limit
) hard_limit
= false;
660 speed_limit
= v
->vcache
.cached_max_speed
;
663 v
->subspeed
= (t
= v
->subspeed
) + (byte
)spd
;
665 /* Aircraft's current speed is used twice so that very fast planes are
666 * forced to slow down rapidly in the short distance needed. The magic
667 * value 16384 was determined to give similar results to the old speed/48
668 * method at slower speeds. This also results in less reduction at slow
669 * speeds to that aircraft do not get to taxi speed straight after
671 if (!hard_limit
&& v
->cur_speed
> speed_limit
) {
672 speed_limit
= v
->cur_speed
- std::max(1, ((v
->cur_speed
* v
->cur_speed
) / 16384) / _settings_game
.vehicle
.plane_speed
);
675 spd
= std::min(v
->cur_speed
+ (spd
>> 8) + (v
->subspeed
< t
), speed_limit
);
677 /* updates statusbar only if speed have changed to save CPU time */
678 if (spd
!= v
->cur_speed
) {
680 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
683 /* Adjust distance moved by plane speed setting */
684 if (_settings_game
.vehicle
.plane_speed
> 1) spd
/= _settings_game
.vehicle
.plane_speed
;
686 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
687 spd
= v
->GetOldAdvanceSpeed(spd
);
690 v
->progress
= (byte
)spd
;
695 * Get the tile height below the aircraft.
696 * This function is needed because aircraft can leave the mapborders.
698 * @param v The vehicle to get the height for.
699 * @return The height in pixels from 'z_pos' 0.
701 int GetTileHeightBelowAircraft(const Vehicle
*v
)
703 int safe_x
= Clamp(v
->x_pos
, 0, MapMaxX() * TILE_SIZE
);
704 int safe_y
= Clamp(v
->y_pos
, 0, MapMaxY() * TILE_SIZE
);
705 return TileHeight(TileVirtXY(safe_x
, safe_y
)) * TILE_HEIGHT
;
709 * Get the 'flight level' bounds, in pixels from 'z_pos' 0 for a particular
710 * vehicle for normal flight situation.
711 * When the maximum is reached the vehicle should consider descending.
712 * When the minimum is reached the vehicle should consider ascending.
714 * @param v The vehicle to get the flight levels for.
715 * @param[out] min_level The minimum bounds for flight level.
716 * @param[out] max_level The maximum bounds for flight level.
718 void GetAircraftFlightLevelBounds(const Vehicle
*v
, int *min_level
, int *max_level
)
720 int base_altitude
= GetTileHeightBelowAircraft(v
);
721 if (v
->type
== VEH_AIRCRAFT
&& Aircraft::From(v
)->subtype
== AIR_HELICOPTER
) {
722 base_altitude
+= HELICOPTER_HOLD_MAX_FLYING_ALTITUDE
- PLANE_HOLD_MAX_FLYING_ALTITUDE
;
725 /* Make sure eastbound and westbound planes do not "crash" into each
726 * other by providing them with vertical separation
728 switch (v
->direction
) {
739 /* Make faster planes fly higher so that they can overtake slower ones */
740 base_altitude
+= std::min(20 * (v
->vcache
.cached_max_speed
/ 200) - 90, 0);
742 if (min_level
!= nullptr) *min_level
= base_altitude
+ AIRCRAFT_MIN_FLYING_ALTITUDE
;
743 if (max_level
!= nullptr) *max_level
= base_altitude
+ AIRCRAFT_MAX_FLYING_ALTITUDE
;
747 * Gets the maximum 'flight level' for the holding pattern of the aircraft,
748 * in pixels 'z_pos' 0, depending on terrain below.
750 * @param v The aircraft that may or may not need to decrease its altitude.
751 * @return Maximal aircraft holding altitude, while in normal flight, in pixels.
753 int GetAircraftHoldMaxAltitude(const Aircraft
*v
)
755 int tile_height
= GetTileHeightBelowAircraft(v
);
757 return tile_height
+ ((v
->subtype
== AIR_HELICOPTER
) ? HELICOPTER_HOLD_MAX_FLYING_ALTITUDE
: PLANE_HOLD_MAX_FLYING_ALTITUDE
);
761 int GetAircraftFlightLevel(T
*v
, bool takeoff
)
763 /* Aircraft is in flight. We want to enforce it being somewhere
764 * between the minimum and the maximum allowed altitude. */
765 int aircraft_min_altitude
;
766 int aircraft_max_altitude
;
767 GetAircraftFlightLevelBounds(v
, &aircraft_min_altitude
, &aircraft_max_altitude
);
768 int aircraft_middle_altitude
= (aircraft_min_altitude
+ aircraft_max_altitude
) / 2;
770 /* If those assumptions would be violated, aircraft would behave fairly strange. */
771 assert(aircraft_min_altitude
< aircraft_middle_altitude
);
772 assert(aircraft_middle_altitude
< aircraft_max_altitude
);
775 if (z
< aircraft_min_altitude
||
776 (HasBit(v
->flags
, VAF_IN_MIN_HEIGHT_CORRECTION
) && z
< aircraft_middle_altitude
)) {
777 /* Ascend. And don't fly into that mountain right ahead.
778 * And avoid our aircraft become a stairclimber, so if we start
779 * correcting altitude, then we stop correction not too early. */
780 SetBit(v
->flags
, VAF_IN_MIN_HEIGHT_CORRECTION
);
781 z
+= takeoff
? 2 : 1;
782 } else if (!takeoff
&& (z
> aircraft_max_altitude
||
783 (HasBit(v
->flags
, VAF_IN_MAX_HEIGHT_CORRECTION
) && z
> aircraft_middle_altitude
))) {
784 /* Descend lower. You are an aircraft, not an space ship.
785 * And again, don't stop correcting altitude too early. */
786 SetBit(v
->flags
, VAF_IN_MAX_HEIGHT_CORRECTION
);
788 } else if (HasBit(v
->flags
, VAF_IN_MIN_HEIGHT_CORRECTION
) && z
>= aircraft_middle_altitude
) {
789 /* Now, we have corrected altitude enough. */
790 ClrBit(v
->flags
, VAF_IN_MIN_HEIGHT_CORRECTION
);
791 } else if (HasBit(v
->flags
, VAF_IN_MAX_HEIGHT_CORRECTION
) && z
<= aircraft_middle_altitude
) {
792 /* Now, we have corrected altitude enough. */
793 ClrBit(v
->flags
, VAF_IN_MAX_HEIGHT_CORRECTION
);
799 template int GetAircraftFlightLevel(DisasterVehicle
*v
, bool takeoff
);
800 template int GetAircraftFlightLevel(Aircraft
*v
, bool takeoff
);
803 * Find the entry point to an airport depending on direction which
804 * the airport is being approached from. Each airport can have up to
805 * four entry points for its approach system so that approaching
806 * aircraft do not fly through each other or are forced to do 180
807 * degree turns during the approach. The arrivals are grouped into
808 * four sectors dependent on the DiagDirection from which the airport
811 * @param v The vehicle that is approaching the airport
812 * @param apc The Airport Class being approached.
813 * @param rotation The rotation of the airport.
814 * @return The index of the entry point
816 static byte
AircraftGetEntryPoint(const Aircraft
*v
, const AirportFTAClass
*apc
, Direction rotation
)
818 assert(v
!= nullptr);
819 assert(apc
!= nullptr);
821 /* In the case the station doesn't exit anymore, set target tile 0.
822 * It doesn't hurt much, aircraft will go to next order, nearest hangar
823 * or it will simply crash in next tick */
826 const Station
*st
= Station::GetIfValid(v
->targetairport
);
828 /* Make sure we don't go to INVALID_TILE if the airport has been removed. */
829 tile
= (st
->airport
.tile
!= INVALID_TILE
) ? st
->airport
.tile
: st
->xy
;
832 int delta_x
= v
->x_pos
- TileX(tile
) * TILE_SIZE
;
833 int delta_y
= v
->y_pos
- TileY(tile
) * TILE_SIZE
;
836 if (abs(delta_y
) < abs(delta_x
)) {
837 /* We are northeast or southwest of the airport */
838 dir
= delta_x
< 0 ? DIAGDIR_NE
: DIAGDIR_SW
;
840 /* We are northwest or southeast of the airport */
841 dir
= delta_y
< 0 ? DIAGDIR_NW
: DIAGDIR_SE
;
843 dir
= ChangeDiagDir(dir
, DiagDirDifference(DIAGDIR_NE
, DirToDiagDir(rotation
)));
844 return apc
->entry_points
[dir
];
848 static void MaybeCrashAirplane(Aircraft
*v
);
851 * Controls the movement of an aircraft. This function actually moves the vehicle
852 * on the map and takes care of minor things like sound playback.
853 * @todo De-mystify the cur_speed values for helicopter rotors.
854 * @param v The vehicle that is moved. Must be the first vehicle of the chain
855 * @return Whether the position requested by the State Machine has been reached
857 static bool AircraftController(Aircraft
*v
)
859 /* nullptr if station is invalid */
860 const Station
*st
= Station::GetIfValid(v
->targetairport
);
861 /* INVALID_TILE if there is no station */
862 TileIndex tile
= INVALID_TILE
;
863 Direction rotation
= DIR_N
;
864 uint size_x
= 1, size_y
= 1;
866 if (st
->airport
.tile
!= INVALID_TILE
) {
867 tile
= st
->airport
.tile
;
868 rotation
= st
->airport
.rotation
;
869 size_x
= st
->airport
.w
;
870 size_y
= st
->airport
.h
;
875 /* DUMMY if there is no station or no airport */
876 const AirportFTAClass
*afc
= tile
== INVALID_TILE
? GetAirport(AT_DUMMY
) : st
->airport
.GetFTA();
878 /* prevent going to INVALID_TILE if airport is deleted. */
879 if (st
== nullptr || st
->airport
.tile
== INVALID_TILE
) {
880 /* Jump into our "holding pattern" state machine if possible */
881 if (v
->pos
>= afc
->nofelements
) {
882 v
->pos
= v
->previous_pos
= AircraftGetEntryPoint(v
, afc
, DIR_N
);
883 } else if (v
->targetairport
!= v
->current_order
.GetDestination()) {
884 /* If not possible, just get out of here fast */
886 UpdateAircraftCache(v
);
887 AircraftNextAirportPos_and_Order(v
);
888 /* get aircraft back on running altitude */
889 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, GetAircraftFlightLevel(v
));
894 /* get airport moving data */
895 const AirportMovingData amd
= RotateAirportMovingData(afc
->MovingData(v
->pos
), rotation
, size_x
, size_y
);
897 int x
= TileX(tile
) * TILE_SIZE
;
898 int y
= TileY(tile
) * TILE_SIZE
;
900 /* Helicopter raise */
901 if (amd
.flag
& AMED_HELI_RAISE
) {
902 Aircraft
*u
= v
->Next()->Next();
904 /* Make sure the rotors don't rotate too fast */
905 if (u
->cur_speed
> 32) {
907 if (--u
->cur_speed
== 32) {
908 if (!PlayVehicleSound(v
, VSE_START
)) {
909 SoundID sfx
= AircraftVehInfo(v
->engine_type
)->sfx
;
910 /* For compatibility with old NewGRF we ignore the sfx property, unless a NewGRF-defined sound is used.
911 * The baseset has only one helicopter sound, so this only limits using plane or cow sounds. */
912 if (sfx
< ORIGINAL_SAMPLE_COUNT
) sfx
= SND_18_HELICOPTER
;
913 SndPlayVehicleFx(sfx
, v
);
918 int count
= UpdateAircraftSpeed(v
);
923 GetAircraftFlightLevelBounds(v
, &z_dest
, nullptr);
925 /* Reached altitude? */
926 if (v
->z_pos
>= z_dest
) {
930 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, std::min(v
->z_pos
+ count
, z_dest
));
936 /* Helicopter landing. */
937 if (amd
.flag
& AMED_HELI_LOWER
) {
938 SetBit(v
->flags
, VAF_HELI_DIRECT_DESCENT
);
941 /* FIXME - AircraftController -> if station no longer exists, do not land
942 * helicopter will circle until sign disappears, then go to next order
943 * what to do when it is the only order left, right now it just stays in 1 place */
945 UpdateAircraftCache(v
);
946 AircraftNextAirportPos_and_Order(v
);
950 /* Vehicle is now at the airport.
951 * Helicopter has arrived at the target landing pad, so the current position is also where it should land.
952 * Except for Oilrigs which are special due to being a 1x1 station, and helicopters land outside it. */
953 if (st
->airport
.type
!= AT_OILRIG
) {
956 tile
= TileVirtXY(x
, y
);
960 /* Find altitude of landing position. */
961 int z
= GetSlopePixelZ(x
, y
) + 1 + afc
->delta_z
;
964 Vehicle
*u
= v
->Next()->Next();
966 /* Increase speed of rotors. When speed is 80, we've landed. */
967 if (u
->cur_speed
>= 80) {
968 ClrBit(v
->flags
, VAF_HELI_DIRECT_DESCENT
);
973 int count
= UpdateAircraftSpeed(v
);
976 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, std::max(v
->z_pos
- count
, z
));
978 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, std::min(v
->z_pos
+ count
, z
));
985 /* Get distance from destination pos to current pos. */
986 uint dist
= abs(x
+ amd
.x
- v
->x_pos
) + abs(y
+ amd
.y
- v
->y_pos
);
988 /* Need exact position? */
989 if (!(amd
.flag
& AMED_EXACTPOS
) && dist
<= (amd
.flag
& AMED_SLOWTURN
? 8U : 4U)) return true;
993 /* Change direction smoothly to final direction. */
994 DirDiff dirdiff
= DirDifference(amd
.direction
, v
->direction
);
995 /* if distance is 0, and plane points in right direction, no point in calling
996 * UpdateAircraftSpeed(). So do it only afterwards */
997 if (dirdiff
== DIRDIFF_SAME
) {
1002 if (!UpdateAircraftSpeed(v
, SPEED_LIMIT_TAXI
)) return false;
1004 v
->direction
= ChangeDir(v
->direction
, dirdiff
> DIRDIFF_REVERSE
? DIRDIFF_45LEFT
: DIRDIFF_45RIGHT
);
1007 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, v
->z_pos
);
1011 if (amd
.flag
& AMED_BRAKE
&& v
->cur_speed
> SPEED_LIMIT_TAXI
* _settings_game
.vehicle
.plane_speed
) {
1012 MaybeCrashAirplane(v
);
1013 if ((v
->vehstatus
& VS_CRASHED
) != 0) return false;
1016 uint speed_limit
= SPEED_LIMIT_TAXI
;
1017 bool hard_limit
= true;
1019 if (amd
.flag
& AMED_NOSPDCLAMP
) speed_limit
= SPEED_LIMIT_NONE
;
1020 if (amd
.flag
& AMED_HOLD
) { speed_limit
= SPEED_LIMIT_HOLD
; hard_limit
= false; }
1021 if (amd
.flag
& AMED_LAND
) { speed_limit
= SPEED_LIMIT_APPROACH
; hard_limit
= false; }
1022 if (amd
.flag
& AMED_BRAKE
) { speed_limit
= SPEED_LIMIT_TAXI
; hard_limit
= false; }
1024 int count
= UpdateAircraftSpeed(v
, speed_limit
, hard_limit
);
1025 if (count
== 0) return false;
1027 /* If the plane will be a few subpixels away from the destination after
1028 * this movement loop, start nudging him towards the exact position for
1029 * the whole loop. Otherwise, heavily depending on the speed of the plane,
1030 * it is possible we totally overshoot the target, causing the plane to
1031 * make a loop, and trying again, and again, and again .. */
1032 bool nudge_towards_target
= static_cast<uint
>(count
) + 3 > dist
;
1034 if (v
->turn_counter
!= 0) v
->turn_counter
--;
1038 GetNewVehiclePosResult gp
;
1040 if (nudge_towards_target
|| (amd
.flag
& AMED_LAND
)) {
1041 /* move vehicle one pixel towards target */
1042 gp
.x
= (v
->x_pos
!= (x
+ amd
.x
)) ?
1043 v
->x_pos
+ ((x
+ amd
.x
> v
->x_pos
) ? 1 : -1) :
1045 gp
.y
= (v
->y_pos
!= (y
+ amd
.y
)) ?
1046 v
->y_pos
+ ((y
+ amd
.y
> v
->y_pos
) ? 1 : -1) :
1049 /* Oilrigs must keep v->tile as st->airport.tile, since the landing pad is in a non-airport tile */
1050 gp
.new_tile
= (st
->airport
.type
== AT_OILRIG
) ? st
->airport
.tile
: TileVirtXY(gp
.x
, gp
.y
);
1054 /* Turn. Do it slowly if in the air. */
1055 Direction newdir
= GetDirectionTowards(v
, x
+ amd
.x
, y
+ amd
.y
);
1056 if (newdir
!= v
->direction
) {
1057 if (amd
.flag
& AMED_SLOWTURN
&& v
->number_consecutive_turns
< 8 && v
->subtype
== AIR_AIRCRAFT
) {
1058 if (v
->turn_counter
== 0 || newdir
== v
->last_direction
) {
1059 if (newdir
== v
->last_direction
) {
1060 v
->number_consecutive_turns
= 0;
1062 v
->number_consecutive_turns
++;
1064 v
->turn_counter
= 2 * _settings_game
.vehicle
.plane_speed
;
1065 v
->last_direction
= v
->direction
;
1066 v
->direction
= newdir
;
1070 gp
= GetNewVehiclePos(v
);
1073 v
->direction
= newdir
;
1075 /* When leaving a terminal an aircraft often goes to a position
1076 * directly in front of it. If it would move while turning it
1077 * would need an two extra turns to end up at the correct position.
1078 * To make it easier just disallow all moving while turning as
1079 * long as an aircraft is on the ground. */
1082 gp
.new_tile
= gp
.old_tile
= v
->tile
;
1085 v
->number_consecutive_turns
= 0;
1087 gp
= GetNewVehiclePos(v
);
1091 v
->tile
= gp
.new_tile
;
1092 /* If vehicle is in the air, use tile coordinate 0. */
1093 if (amd
.flag
& (AMED_TAKEOFF
| AMED_SLOWTURN
| AMED_LAND
)) v
->tile
= 0;
1095 /* Adjust Z for land or takeoff? */
1098 if (amd
.flag
& AMED_TAKEOFF
) {
1099 z
= GetAircraftFlightLevel(v
, true);
1100 } else if (amd
.flag
& AMED_HOLD
) {
1101 /* Let the plane drop from normal flight altitude to holding pattern altitude */
1102 if (z
> GetAircraftHoldMaxAltitude(v
)) z
--;
1103 } else if ((amd
.flag
& AMED_SLOWTURN
) && (amd
.flag
& AMED_NOSPDCLAMP
)) {
1104 z
= GetAircraftFlightLevel(v
);
1107 /* NewGRF airports (like a rotated intercontinental from OpenGFX+Airports) can be non-rectangular
1108 * and their primary (north-most) tile does not have to be part of the airport.
1109 * As such, the height of the primary tile can be different from the rest of the airport.
1110 * Given we are landing/breaking, and as such are not a helicopter, we know that there has to be a hangar.
1111 * We also know that the airport itself has to be completely flat (otherwise it is not a valid airport).
1112 * Therefore, use the height of this hangar to calculate our z-value. */
1113 int airport_z
= v
->z_pos
;
1114 if ((amd
.flag
& (AMED_LAND
| AMED_BRAKE
)) && st
!= nullptr) {
1115 assert(st
->airport
.HasHangar());
1116 TileIndex hangar_tile
= st
->airport
.GetHangarTile(0);
1117 airport_z
= GetTileMaxPixelZ(hangar_tile
) + 1; // To avoid clashing with the shadow
1120 if (amd
.flag
& AMED_LAND
) {
1121 if (st
->airport
.tile
== INVALID_TILE
) {
1122 /* Airport has been removed, abort the landing procedure */
1124 UpdateAircraftCache(v
);
1125 AircraftNextAirportPos_and_Order(v
);
1126 /* get aircraft back on running altitude */
1127 SetAircraftPosition(v
, gp
.x
, gp
.y
, GetAircraftFlightLevel(v
));
1131 /* We're not flying below our destination, right? */
1132 assert(airport_z
<= z
);
1133 int t
= std::max(1U, dist
- 4);
1134 int delta
= z
- airport_z
;
1136 /* Only start lowering when we're sufficiently close for a 1:1 glide */
1138 z
-= CeilDiv(z
- airport_z
, t
);
1140 if (z
< airport_z
) z
= airport_z
;
1143 /* We've landed. Decrease speed when we're reaching end of runway. */
1144 if (amd
.flag
& AMED_BRAKE
) {
1146 if (z
> airport_z
) {
1148 } else if (z
< airport_z
) {
1154 SetAircraftPosition(v
, gp
.x
, gp
.y
, z
);
1155 } while (--count
!= 0);
1160 * Handle crashed aircraft \a v.
1161 * @param v Crashed aircraft.
1163 static bool HandleCrashedAircraft(Aircraft
*v
)
1165 v
->crashed_counter
+= 3;
1167 Station
*st
= GetTargetAirportIfValid(v
);
1169 /* make aircraft crash down to the ground */
1170 if (v
->crashed_counter
< 500 && st
== nullptr && ((v
->crashed_counter
% 3) == 0) ) {
1171 int z
= GetSlopePixelZ(Clamp(v
->x_pos
, 0, MapMaxX() * TILE_SIZE
), Clamp(v
->y_pos
, 0, MapMaxY() * TILE_SIZE
));
1173 if (v
->z_pos
== z
) {
1174 v
->crashed_counter
= 500;
1179 if (v
->crashed_counter
< 650) {
1181 if (Chance16R(1, 32, r
)) {
1182 static const DirDiff delta
[] = {
1183 DIRDIFF_45LEFT
, DIRDIFF_SAME
, DIRDIFF_SAME
, DIRDIFF_45RIGHT
1186 v
->direction
= ChangeDir(v
->direction
, delta
[GB(r
, 16, 2)]);
1187 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, v
->z_pos
);
1189 CreateEffectVehicleRel(v
,
1193 EV_EXPLOSION_SMALL
);
1195 } else if (v
->crashed_counter
>= 10000) {
1196 /* remove rubble of crashed airplane */
1198 /* clear runway-in on all airports, set by crashing plane
1199 * small airports use AIRPORT_BUSY, city airports use RUNWAY_IN_OUT_block, etc.
1200 * but they all share the same number */
1201 if (st
!= nullptr) {
1202 CLRBITS(st
->airport
.flags
, RUNWAY_IN_block
);
1203 CLRBITS(st
->airport
.flags
, RUNWAY_IN_OUT_block
); // commuter airport
1204 CLRBITS(st
->airport
.flags
, RUNWAY_IN2_block
); // intercontinental
1217 * Handle smoke of broken aircraft.
1219 * @param mode Is this the non-first call for this vehicle in this tick?
1221 static void HandleAircraftSmoke(Aircraft
*v
, bool mode
)
1223 static const struct {
1237 if (!(v
->vehstatus
& VS_AIRCRAFT_BROKEN
)) return;
1239 /* Stop smoking when landed */
1240 if (v
->cur_speed
< 10) {
1241 v
->vehstatus
&= ~VS_AIRCRAFT_BROKEN
;
1242 v
->breakdown_ctr
= 0;
1246 /* Spawn effect et most once per Tick, i.e. !mode */
1247 if (!mode
&& (v
->tick_counter
& 0x0F) == 0) {
1248 CreateEffectVehicleRel(v
,
1249 smoke_pos
[v
->direction
].x
,
1250 smoke_pos
[v
->direction
].y
,
1252 EV_BREAKDOWN_SMOKE_AIRCRAFT
1257 void HandleMissingAircraftOrders(Aircraft
*v
)
1260 * We do not have an order. This can be divided into two cases:
1261 * 1) we are heading to an invalid station. In this case we must
1262 * find another airport to go to. If there is nowhere to go,
1263 * we will destroy the aircraft as it otherwise will enter
1264 * the holding pattern for the first airport, which can cause
1265 * the plane to go into an undefined state when building an
1266 * airport with the same StationID.
1267 * 2) we are (still) heading to a (still) valid airport, then we
1268 * can continue going there. This can happen when you are
1269 * changing the aircraft's orders while in-flight or in for
1270 * example a depot. However, when we have a current order to
1271 * go to a depot, we have to keep that order so the aircraft
1274 const Station
*st
= GetTargetAirportIfValid(v
);
1275 if (st
== nullptr) {
1276 Backup
<CompanyID
> cur_company(_current_company
, v
->owner
, FILE_LINE
);
1277 CommandCost ret
= DoCommand(v
->tile
, v
->index
, 0, DC_EXEC
, CMD_SEND_VEHICLE_TO_DEPOT
);
1278 cur_company
.Restore();
1280 if (ret
.Failed()) CrashAirplane(v
);
1281 } else if (!v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
1282 v
->current_order
.Free();
1287 TileIndex
Aircraft::GetOrderStationLocation(StationID station
)
1289 /* Orders are changed in flight, ensure going to the right station. */
1290 if (this->state
== FLYING
) {
1291 AircraftNextAirportPos_and_Order(this);
1294 /* Aircraft do not use dest-tile */
1298 void Aircraft::MarkDirty()
1300 this->colourmap
= PAL_NONE
;
1301 this->UpdateViewport(true, false);
1302 if (this->subtype
== AIR_HELICOPTER
) {
1303 GetRotorImage(this, EIT_ON_MAP
, &this->Next()->Next()->sprite_cache
.sprite_seq
);
1308 uint
Aircraft::Crash(bool flooded
)
1310 uint pass
= Vehicle::Crash(flooded
) + 2; // pilots
1311 this->crashed_counter
= flooded
? 9000 : 0; // max 10000, disappear pretty fast when flooded
1317 * Bring the aircraft in a crashed state, create the explosion animation, and create a news item about the crash.
1318 * @param v Aircraft that crashed.
1320 static void CrashAirplane(Aircraft
*v
)
1322 CreateEffectVehicleRel(v
, 4, 4, 8, EV_EXPLOSION_LARGE
);
1324 uint pass
= v
->Crash();
1327 v
->cargo
.Truncate();
1328 v
->Next()->cargo
.Truncate();
1329 const Station
*st
= GetTargetAirportIfValid(v
);
1331 if (st
== nullptr) {
1332 newsitem
= STR_NEWS_PLANE_CRASH_OUT_OF_FUEL
;
1334 SetDParam(1, st
->index
);
1335 newsitem
= STR_NEWS_AIRCRAFT_CRASH
;
1338 AI::NewEvent(v
->owner
, new ScriptEventVehicleCrashed(v
->index
, v
->tile
, st
== nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT
: ScriptEventVehicleCrashed::CRASH_PLANE_LANDING
));
1339 Game::NewEvent(new ScriptEventVehicleCrashed(v
->index
, v
->tile
, st
== nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT
: ScriptEventVehicleCrashed::CRASH_PLANE_LANDING
));
1341 AddTileNewsItem(newsitem
, NT_ACCIDENT
, v
->tile
, nullptr, st
!= nullptr ? st
->index
: INVALID_STATION
);
1343 ModifyStationRatingAround(v
->tile
, v
->owner
, -160, 30);
1344 if (_settings_client
.sound
.disaster
) SndPlayVehicleFx(SND_12_EXPLOSION
, v
);
1348 * Decide whether aircraft \a v should crash.
1349 * @param v Aircraft to test.
1351 static void MaybeCrashAirplane(Aircraft
*v
)
1354 Station
*st
= Station::Get(v
->targetairport
);
1357 if ((st
->airport
.GetFTA()->flags
& AirportFTAClass::SHORT_STRIP
) &&
1358 (AircraftVehInfo(v
->engine_type
)->subtype
& AIR_FAST
) &&
1359 !_cheats
.no_jetcrash
.value
) {
1362 if (_settings_game
.vehicle
.plane_crashes
== 0) return;
1363 prob
= (0x4000 << _settings_game
.vehicle
.plane_crashes
) / 1500;
1366 if (GB(Random(), 0, 22) > prob
) return;
1368 /* Crash the airplane. Remove all goods stored at the station. */
1369 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
1370 st
->goods
[i
].rating
= 1;
1371 st
->goods
[i
].cargo
.Truncate();
1378 * Aircraft arrives at a terminal. If it is the first aircraft, throw a party.
1379 * Start loading cargo.
1380 * @param v Aircraft that arrived.
1382 static void AircraftEntersTerminal(Aircraft
*v
)
1384 if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) return;
1386 Station
*st
= Station::Get(v
->targetairport
);
1387 v
->last_station_visited
= v
->targetairport
;
1389 /* Check if station was ever visited before */
1390 if (!(st
->had_vehicle_of_type
& HVOT_AIRCRAFT
)) {
1391 st
->had_vehicle_of_type
|= HVOT_AIRCRAFT
;
1392 SetDParam(0, st
->index
);
1393 /* show newsitem of celebrating citizens */
1395 STR_NEWS_FIRST_AIRCRAFT_ARRIVAL
,
1396 (v
->owner
== _local_company
) ? NT_ARRIVAL_COMPANY
: NT_ARRIVAL_OTHER
,
1400 AI::NewEvent(v
->owner
, new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
1401 Game::NewEvent(new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
1408 * Aircraft touched down at the landing strip.
1409 * @param v Aircraft that landed.
1411 static void AircraftLandAirplane(Aircraft
*v
)
1413 Station
*st
= Station::Get(v
->targetairport
);
1415 TileIndex vt
= TileVirtXY(v
->x_pos
, v
->y_pos
);
1419 AirportTileAnimationTrigger(st
, vt
, AAT_STATION_AIRPLANE_LAND
);
1421 if (!PlayVehicleSound(v
, VSE_TOUCHDOWN
)) {
1422 SndPlayVehicleFx(SND_17_SKID_PLANE
, v
);
1427 /** set the right pos when heading to other airports after takeoff */
1428 void AircraftNextAirportPos_and_Order(Aircraft
*v
)
1430 if (v
->current_order
.IsType(OT_GOTO_STATION
) || v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
1431 v
->targetairport
= v
->current_order
.GetDestination();
1434 const Station
*st
= GetTargetAirportIfValid(v
);
1435 const AirportFTAClass
*apc
= st
== nullptr ? GetAirport(AT_DUMMY
) : st
->airport
.GetFTA();
1436 Direction rotation
= st
== nullptr ? DIR_N
: st
->airport
.rotation
;
1437 v
->pos
= v
->previous_pos
= AircraftGetEntryPoint(v
, apc
, rotation
);
1441 * Aircraft is about to leave the hangar.
1442 * @param v Aircraft leaving.
1443 * @param exit_dir The direction the vehicle leaves the hangar.
1444 * @note This function is called in AfterLoadGame for old savegames, so don't rely
1445 * on any data to be valid, especially don't rely on the fact that the vehicle
1446 * is actually on the ground inside a depot.
1448 void AircraftLeaveHangar(Aircraft
*v
, Direction exit_dir
)
1453 v
->direction
= exit_dir
;
1454 v
->vehstatus
&= ~VS_HIDDEN
;
1456 Vehicle
*u
= v
->Next();
1457 u
->vehstatus
&= ~VS_HIDDEN
;
1462 u
->vehstatus
&= ~VS_HIDDEN
;
1467 VehicleServiceInDepot(v
);
1468 SetAircraftPosition(v
, v
->x_pos
, v
->y_pos
, v
->z_pos
);
1469 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
1470 SetWindowClassesDirty(WC_AIRCRAFT_LIST
);
1473 ////////////////////////////////////////////////////////////////////////////////
1474 /////////////////// AIRCRAFT MOVEMENT SCHEME ////////////////////////////////
1475 ////////////////////////////////////////////////////////////////////////////////
1476 static void AircraftEventHandler_EnterTerminal(Aircraft
*v
, const AirportFTAClass
*apc
)
1478 AircraftEntersTerminal(v
);
1479 v
->state
= apc
->layout
[v
->pos
].heading
;
1483 * Aircraft arrived in an airport hangar.
1484 * @param v Aircraft in the hangar.
1485 * @param apc Airport description containing the hangar.
1487 static void AircraftEventHandler_EnterHangar(Aircraft
*v
, const AirportFTAClass
*apc
)
1489 VehicleEnterDepot(v
);
1490 v
->state
= apc
->layout
[v
->pos
].heading
;
1494 * Handle aircraft movement/decision making in an airport hangar.
1495 * @param v Aircraft in the hangar.
1496 * @param apc Airport description containing the hangar.
1498 static void AircraftEventHandler_InHangar(Aircraft
*v
, const AirportFTAClass
*apc
)
1500 /* if we just arrived, execute EnterHangar first */
1501 if (v
->previous_pos
!= v
->pos
) {
1502 AircraftEventHandler_EnterHangar(v
, apc
);
1506 /* if we were sent to the depot, stay there */
1507 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) && (v
->vehstatus
& VS_STOPPED
)) {
1508 v
->current_order
.Free();
1512 if (!v
->current_order
.IsType(OT_GOTO_STATION
) &&
1513 !v
->current_order
.IsType(OT_GOTO_DEPOT
))
1516 /* We are leaving a hangar, but have to go to the exact same one; re-enter */
1517 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) && v
->current_order
.GetDestination() == v
->targetairport
) {
1518 VehicleEnterDepot(v
);
1522 /* if the block of the next position is busy, stay put */
1523 if (AirportHasBlock(v
, &apc
->layout
[v
->pos
], apc
)) return;
1525 /* We are already at the target airport, we need to find a terminal */
1526 if (v
->current_order
.GetDestination() == v
->targetairport
) {
1527 /* FindFreeTerminal:
1528 * 1. Find a free terminal, 2. Occupy it, 3. Set the vehicle's state to that terminal */
1529 if (v
->subtype
== AIR_HELICOPTER
) {
1530 if (!AirportFindFreeHelipad(v
, apc
)) return; // helicopter
1532 if (!AirportFindFreeTerminal(v
, apc
)) return; // airplane
1534 } else { // Else prepare for launch.
1535 /* airplane goto state takeoff, helicopter to helitakeoff */
1536 v
->state
= (v
->subtype
== AIR_HELICOPTER
) ? HELITAKEOFF
: TAKEOFF
;
1538 const Station
*st
= Station::GetByTile(v
->tile
);
1539 AircraftLeaveHangar(v
, st
->airport
.GetHangarExitDirection(v
->tile
));
1540 AirportMove(v
, apc
);
1543 /** At one of the Airport's Terminals */
1544 static void AircraftEventHandler_AtTerminal(Aircraft
*v
, const AirportFTAClass
*apc
)
1546 /* if we just arrived, execute EnterTerminal first */
1547 if (v
->previous_pos
!= v
->pos
) {
1548 AircraftEventHandler_EnterTerminal(v
, apc
);
1549 /* on an airport with helipads, a helicopter will always land there
1550 * and get serviced at the same time - setting */
1551 if (_settings_game
.order
.serviceathelipad
) {
1552 if (v
->subtype
== AIR_HELICOPTER
&& apc
->num_helipads
> 0) {
1553 /* an excerpt of ServiceAircraft, without the invisibility stuff */
1554 v
->date_of_last_service
= _date
;
1555 v
->breakdowns_since_last_service
= 0;
1556 v
->reliability
= v
->GetEngine()->reliability
;
1557 SetWindowDirty(WC_VEHICLE_DETAILS
, v
->index
);
1563 if (v
->current_order
.IsType(OT_NOTHING
)) return;
1565 /* if the block of the next position is busy, stay put */
1566 if (AirportHasBlock(v
, &apc
->layout
[v
->pos
], apc
)) return;
1568 /* airport-road is free. We either have to go to another airport, or to the hangar
1569 * ---> start moving */
1571 bool go_to_hangar
= false;
1572 switch (v
->current_order
.GetType()) {
1573 case OT_GOTO_STATION
: // ready to fly to another airport
1575 case OT_GOTO_DEPOT
: // visit hangar for servicing, sale, etc.
1576 go_to_hangar
= v
->current_order
.GetDestination() == v
->targetairport
;
1578 case OT_CONDITIONAL
:
1579 /* In case of a conditional order we just have to wait a tick
1580 * longer, so the conditional order can actually be processed;
1581 * we should not clear the order as that makes us go nowhere. */
1583 default: // orders have been deleted (no orders), goto depot and don't bother us
1584 v
->current_order
.Free();
1585 go_to_hangar
= Station::Get(v
->targetairport
)->airport
.HasHangar();
1588 if (go_to_hangar
&& Station::Get(v
->targetairport
)->airport
.HasHangar()) {
1591 /* airplane goto state takeoff, helicopter to helitakeoff */
1592 v
->state
= (v
->subtype
== AIR_HELICOPTER
) ? HELITAKEOFF
: TAKEOFF
;
1594 AirportMove(v
, apc
);
1597 static void AircraftEventHandler_General(Aircraft
*v
, const AirportFTAClass
*apc
)
1599 error("OK, you shouldn't be here, check your Airport Scheme!");
1602 static void AircraftEventHandler_TakeOff(Aircraft
*v
, const AirportFTAClass
*apc
)
1604 PlayAircraftSound(v
); // play takeoffsound for airplanes
1605 v
->state
= STARTTAKEOFF
;
1608 static void AircraftEventHandler_StartTakeOff(Aircraft
*v
, const AirportFTAClass
*apc
)
1610 v
->state
= ENDTAKEOFF
;
1614 static void AircraftEventHandler_EndTakeOff(Aircraft
*v
, const AirportFTAClass
*apc
)
1617 /* get the next position to go to, differs per airport */
1618 AircraftNextAirportPos_and_Order(v
);
1621 static void AircraftEventHandler_HeliTakeOff(Aircraft
*v
, const AirportFTAClass
*apc
)
1626 /* get the next position to go to, differs per airport */
1627 AircraftNextAirportPos_and_Order(v
);
1629 /* Send the helicopter to a hangar if needed for replacement */
1630 if (v
->NeedsAutomaticServicing()) {
1631 Backup
<CompanyID
> cur_company(_current_company
, v
->owner
, FILE_LINE
);
1632 DoCommand(v
->tile
, v
->index
| DEPOT_SERVICE
| DEPOT_LOCATE_HANGAR
, 0, DC_EXEC
, CMD_SEND_VEHICLE_TO_DEPOT
);
1633 cur_company
.Restore();
1637 static void AircraftEventHandler_Flying(Aircraft
*v
, const AirportFTAClass
*apc
)
1639 Station
*st
= Station::Get(v
->targetairport
);
1641 /* Runway busy, not allowed to use this airstation or closed, circle. */
1642 if (CanVehicleUseStation(v
, st
) && (st
->owner
== OWNER_NONE
|| st
->owner
== v
->owner
) && !(st
->airport
.flags
& AIRPORT_CLOSED_block
)) {
1643 /* {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
1644 * if it is an airplane, look for LANDING, for helicopter HELILANDING
1645 * it is possible to choose from multiple landing runways, so loop until a free one is found */
1646 byte landingtype
= (v
->subtype
== AIR_HELICOPTER
) ? HELILANDING
: LANDING
;
1647 const AirportFTA
*current
= apc
->layout
[v
->pos
].next
;
1648 while (current
!= nullptr) {
1649 if (current
->heading
== landingtype
) {
1650 /* save speed before, since if AirportHasBlock is false, it resets them to 0
1651 * we don't want that for plane in air
1652 * hack for speed thingie */
1653 uint16 tcur_speed
= v
->cur_speed
;
1654 uint16 tsubspeed
= v
->subspeed
;
1655 if (!AirportHasBlock(v
, current
, apc
)) {
1656 v
->state
= landingtype
; // LANDING / HELILANDING
1657 if (v
->state
== HELILANDING
) SetBit(v
->flags
, VAF_HELI_DIRECT_DESCENT
);
1658 /* it's a bit dirty, but I need to set position to next position, otherwise
1659 * if there are multiple runways, plane won't know which one it took (because
1660 * they all have heading LANDING). And also occupy that block! */
1661 v
->pos
= current
->next_position
;
1662 SETBITS(st
->airport
.flags
, apc
->layout
[v
->pos
].block
);
1665 v
->cur_speed
= tcur_speed
;
1666 v
->subspeed
= tsubspeed
;
1668 current
= current
->next
;
1672 v
->pos
= apc
->layout
[v
->pos
].next_position
;
1675 static void AircraftEventHandler_Landing(Aircraft
*v
, const AirportFTAClass
*apc
)
1677 v
->state
= ENDLANDING
;
1678 AircraftLandAirplane(v
); // maybe crash airplane
1680 /* check if the aircraft needs to be replaced or renewed and send it to a hangar if needed */
1681 if (v
->NeedsAutomaticServicing()) {
1682 Backup
<CompanyID
> cur_company(_current_company
, v
->owner
, FILE_LINE
);
1683 DoCommand(v
->tile
, v
->index
| DEPOT_SERVICE
, 0, DC_EXEC
, CMD_SEND_VEHICLE_TO_DEPOT
);
1684 cur_company
.Restore();
1688 static void AircraftEventHandler_HeliLanding(Aircraft
*v
, const AirportFTAClass
*apc
)
1690 v
->state
= HELIENDLANDING
;
1694 static void AircraftEventHandler_EndLanding(Aircraft
*v
, const AirportFTAClass
*apc
)
1696 /* next block busy, don't do a thing, just wait */
1697 if (AirportHasBlock(v
, &apc
->layout
[v
->pos
], apc
)) return;
1699 /* if going to terminal (OT_GOTO_STATION) choose one
1700 * 1. in case all terminals are busy AirportFindFreeTerminal() returns false or
1701 * 2. not going for terminal (but depot, no order),
1702 * --> get out of the way to the hangar. */
1703 if (v
->current_order
.IsType(OT_GOTO_STATION
)) {
1704 if (AirportFindFreeTerminal(v
, apc
)) return;
1710 static void AircraftEventHandler_HeliEndLanding(Aircraft
*v
, const AirportFTAClass
*apc
)
1712 /* next block busy, don't do a thing, just wait */
1713 if (AirportHasBlock(v
, &apc
->layout
[v
->pos
], apc
)) return;
1715 /* if going to helipad (OT_GOTO_STATION) choose one. If airport doesn't have helipads, choose terminal
1716 * 1. in case all terminals/helipads are busy (AirportFindFreeHelipad() returns false) or
1717 * 2. not going for terminal (but depot, no order),
1718 * --> get out of the way to the hangar IF there are terminals on the airport.
1720 * the reason behind this is that if an airport has a terminal, it also has a hangar. Airplanes
1721 * must go to a hangar. */
1722 if (v
->current_order
.IsType(OT_GOTO_STATION
)) {
1723 if (AirportFindFreeHelipad(v
, apc
)) return;
1725 v
->state
= Station::Get(v
->targetairport
)->airport
.HasHangar() ? HANGAR
: HELITAKEOFF
;
1729 * Signature of the aircraft handler function.
1730 * @param v Aircraft to handle.
1731 * @param apc Airport state machine.
1733 typedef void AircraftStateHandler(Aircraft
*v
, const AirportFTAClass
*apc
);
1734 /** Array of handler functions for each target of the aircraft. */
1735 static AircraftStateHandler
* const _aircraft_state_handlers
[] = {
1736 AircraftEventHandler_General
, // TO_ALL = 0
1737 AircraftEventHandler_InHangar
, // HANGAR = 1
1738 AircraftEventHandler_AtTerminal
, // TERM1 = 2
1739 AircraftEventHandler_AtTerminal
, // TERM2 = 3
1740 AircraftEventHandler_AtTerminal
, // TERM3 = 4
1741 AircraftEventHandler_AtTerminal
, // TERM4 = 5
1742 AircraftEventHandler_AtTerminal
, // TERM5 = 6
1743 AircraftEventHandler_AtTerminal
, // TERM6 = 7
1744 AircraftEventHandler_AtTerminal
, // HELIPAD1 = 8
1745 AircraftEventHandler_AtTerminal
, // HELIPAD2 = 9
1746 AircraftEventHandler_TakeOff
, // TAKEOFF = 10
1747 AircraftEventHandler_StartTakeOff
, // STARTTAKEOFF = 11
1748 AircraftEventHandler_EndTakeOff
, // ENDTAKEOFF = 12
1749 AircraftEventHandler_HeliTakeOff
, // HELITAKEOFF = 13
1750 AircraftEventHandler_Flying
, // FLYING = 14
1751 AircraftEventHandler_Landing
, // LANDING = 15
1752 AircraftEventHandler_EndLanding
, // ENDLANDING = 16
1753 AircraftEventHandler_HeliLanding
, // HELILANDING = 17
1754 AircraftEventHandler_HeliEndLanding
, // HELIENDLANDING = 18
1755 AircraftEventHandler_AtTerminal
, // TERM7 = 19
1756 AircraftEventHandler_AtTerminal
, // TERM8 = 20
1757 AircraftEventHandler_AtTerminal
, // HELIPAD3 = 21
1760 static void AirportClearBlock(const Aircraft
*v
, const AirportFTAClass
*apc
)
1762 /* we have left the previous block, and entered the new one. Free the previous block */
1763 if (apc
->layout
[v
->previous_pos
].block
!= apc
->layout
[v
->pos
].block
) {
1764 Station
*st
= Station::Get(v
->targetairport
);
1766 CLRBITS(st
->airport
.flags
, apc
->layout
[v
->previous_pos
].block
);
1770 static void AirportGoToNextPosition(Aircraft
*v
)
1772 /* if aircraft is not in position, wait until it is */
1773 if (!AircraftController(v
)) return;
1775 const AirportFTAClass
*apc
= Station::Get(v
->targetairport
)->airport
.GetFTA();
1777 AirportClearBlock(v
, apc
);
1778 AirportMove(v
, apc
); // move aircraft to next position
1781 /* gets pos from vehicle and next orders */
1782 static bool AirportMove(Aircraft
*v
, const AirportFTAClass
*apc
)
1784 /* error handling */
1785 if (v
->pos
>= apc
->nofelements
) {
1786 DEBUG(misc
, 0, "[Ap] position %d is not valid for current airport. Max position is %d", v
->pos
, apc
->nofelements
-1);
1787 assert(v
->pos
< apc
->nofelements
);
1790 const AirportFTA
*current
= &apc
->layout
[v
->pos
];
1791 /* we have arrived in an important state (eg terminal, hangar, etc.) */
1792 if (current
->heading
== v
->state
) {
1793 byte prev_pos
= v
->pos
; // location could be changed in state, so save it before-hand
1794 byte prev_state
= v
->state
;
1795 _aircraft_state_handlers
[v
->state
](v
, apc
);
1796 if (v
->state
!= FLYING
) v
->previous_pos
= prev_pos
;
1797 if (v
->state
!= prev_state
|| v
->pos
!= prev_pos
) UpdateAircraftCache(v
);
1801 v
->previous_pos
= v
->pos
; // save previous location
1803 /* there is only one choice to move to */
1804 if (current
->next
== nullptr) {
1805 if (AirportSetBlocks(v
, current
, apc
)) {
1806 v
->pos
= current
->next_position
;
1807 UpdateAircraftCache(v
);
1808 } // move to next position
1812 /* there are more choices to choose from, choose the one that
1813 * matches our heading */
1815 if (v
->state
== current
->heading
|| current
->heading
== TO_ALL
) {
1816 if (AirportSetBlocks(v
, current
, apc
)) {
1817 v
->pos
= current
->next_position
;
1818 UpdateAircraftCache(v
);
1819 } // move to next position
1822 current
= current
->next
;
1823 } while (current
!= nullptr);
1825 DEBUG(misc
, 0, "[Ap] cannot move further on Airport! (pos %d state %d) for vehicle %d", v
->pos
, v
->state
, v
->index
);
1829 /** returns true if the road ahead is busy, eg. you must wait before proceeding. */
1830 static bool AirportHasBlock(Aircraft
*v
, const AirportFTA
*current_pos
, const AirportFTAClass
*apc
)
1832 const AirportFTA
*reference
= &apc
->layout
[v
->pos
];
1833 const AirportFTA
*next
= &apc
->layout
[current_pos
->next_position
];
1835 /* same block, then of course we can move */
1836 if (apc
->layout
[current_pos
->position
].block
!= next
->block
) {
1837 const Station
*st
= Station::Get(v
->targetairport
);
1838 uint64 airport_flags
= next
->block
;
1840 /* check additional possible extra blocks */
1841 if (current_pos
!= reference
&& current_pos
->block
!= NOTHING_block
) {
1842 airport_flags
|= current_pos
->block
;
1845 if (st
->airport
.flags
& airport_flags
) {
1855 * "reserve" a block for the plane
1856 * @param v airplane that requires the operation
1857 * @param current_pos of the vehicle in the list of blocks
1858 * @param apc airport on which block is requested to be set
1859 * @returns true on success. Eg, next block was free and we have occupied it
1861 static bool AirportSetBlocks(Aircraft
*v
, const AirportFTA
*current_pos
, const AirportFTAClass
*apc
)
1863 const AirportFTA
*next
= &apc
->layout
[current_pos
->next_position
];
1864 const AirportFTA
*reference
= &apc
->layout
[v
->pos
];
1866 /* if the next position is in another block, check it and wait until it is free */
1867 if ((apc
->layout
[current_pos
->position
].block
& next
->block
) != next
->block
) {
1868 uint64 airport_flags
= next
->block
;
1869 /* search for all all elements in the list with the same state, and blocks != N
1870 * this means more blocks should be checked/set */
1871 const AirportFTA
*current
= current_pos
;
1872 if (current
== reference
) current
= current
->next
;
1873 while (current
!= nullptr) {
1874 if (current
->heading
== current_pos
->heading
&& current
->block
!= 0) {
1875 airport_flags
|= current
->block
;
1878 current
= current
->next
;
1881 /* if the block to be checked is in the next position, then exclude that from
1882 * checking, because it has been set by the airplane before */
1883 if (current_pos
->block
== next
->block
) airport_flags
^= next
->block
;
1885 Station
*st
= Station::Get(v
->targetairport
);
1886 if (st
->airport
.flags
& airport_flags
) {
1892 if (next
->block
!= NOTHING_block
) {
1893 SETBITS(st
->airport
.flags
, airport_flags
); // occupy next block
1900 * Combination of aircraft state for going to a certain terminal and the
1901 * airport flag for that terminal block.
1903 struct MovementTerminalMapping
{
1904 AirportMovementStates state
; ///< Aircraft movement state when going to this terminal.
1905 uint64 airport_flag
; ///< Bitmask in the airport flags that need to be free for this terminal.
1908 /** A list of all valid terminals and their associated blocks. */
1909 static const MovementTerminalMapping _airport_terminal_mapping
[] = {
1910 {TERM1
, TERM1_block
},
1911 {TERM2
, TERM2_block
},
1912 {TERM3
, TERM3_block
},
1913 {TERM4
, TERM4_block
},
1914 {TERM5
, TERM5_block
},
1915 {TERM6
, TERM6_block
},
1916 {TERM7
, TERM7_block
},
1917 {TERM8
, TERM8_block
},
1918 {HELIPAD1
, HELIPAD1_block
},
1919 {HELIPAD2
, HELIPAD2_block
},
1920 {HELIPAD3
, HELIPAD3_block
},
1924 * Find a free terminal or helipad, and if available, assign it.
1925 * @param v Aircraft looking for a free terminal or helipad.
1926 * @param i First terminal to examine.
1927 * @param last_terminal Terminal number to stop examining.
1928 * @return A terminal or helipad has been found, and has been assigned to the aircraft.
1930 static bool FreeTerminal(Aircraft
*v
, byte i
, byte last_terminal
)
1932 assert(last_terminal
<= lengthof(_airport_terminal_mapping
));
1933 Station
*st
= Station::Get(v
->targetairport
);
1934 for (; i
< last_terminal
; i
++) {
1935 if ((st
->airport
.flags
& _airport_terminal_mapping
[i
].airport_flag
) == 0) {
1936 /* TERMINAL# HELIPAD# */
1937 v
->state
= _airport_terminal_mapping
[i
].state
; // start moving to that terminal/helipad
1938 SETBITS(st
->airport
.flags
, _airport_terminal_mapping
[i
].airport_flag
); // occupy terminal/helipad
1946 * Get the number of terminals at the airport.
1947 * @param apc Airport description.
1948 * @return Number of terminals.
1950 static uint
GetNumTerminals(const AirportFTAClass
*apc
)
1954 for (uint i
= apc
->terminals
[0]; i
> 0; i
--) num
+= apc
->terminals
[i
];
1960 * Find a free terminal, and assign it if available.
1961 * @param v Aircraft to handle.
1962 * @param apc Airport state machine.
1963 * @return Found a free terminal and assigned it.
1965 static bool AirportFindFreeTerminal(Aircraft
*v
, const AirportFTAClass
*apc
)
1967 /* example of more terminalgroups
1968 * {0,HANGAR,NOTHING_block,1}, {0,TERMGROUP,TERM_GROUP1_block,0}, {0,TERMGROUP,TERM_GROUP2_ENTER_block,1}, {0,0,N,1},
1969 * Heading TERMGROUP denotes a group. We see 2 groups here:
1970 * 1. group 0 -- TERM_GROUP1_block (check block)
1971 * 2. group 1 -- TERM_GROUP2_ENTER_block (check block)
1972 * First in line is checked first, group 0. If the block (TERM_GROUP1_block) is free, it
1973 * looks at the corresponding terminals of that group. If no free ones are found, other
1974 * possible groups are checked (in this case group 1, since that is after group 0). If that
1975 * fails, then attempt fails and plane waits
1977 if (apc
->terminals
[0] > 1) {
1978 const Station
*st
= Station::Get(v
->targetairport
);
1979 const AirportFTA
*temp
= apc
->layout
[v
->pos
].next
;
1981 while (temp
!= nullptr) {
1982 if (temp
->heading
== TERMGROUP
) {
1983 if (!(st
->airport
.flags
& temp
->block
)) {
1984 /* read which group do we want to go to?
1985 * (the first free group) */
1986 uint target_group
= temp
->next_position
+ 1;
1988 /* at what terminal does the group start?
1989 * that means, sum up all terminals of
1990 * groups with lower number */
1991 uint group_start
= 0;
1992 for (uint i
= 1; i
< target_group
; i
++) {
1993 group_start
+= apc
->terminals
[i
];
1996 uint group_end
= group_start
+ apc
->terminals
[target_group
];
1997 if (FreeTerminal(v
, group_start
, group_end
)) return true;
2000 /* once the heading isn't 255, we've exhausted the possible blocks.
2001 * So we cannot move */
2008 /* if there is only 1 terminalgroup, all terminals are checked (starting from 0 to max) */
2009 return FreeTerminal(v
, 0, GetNumTerminals(apc
));
2013 * Find a free helipad, and assign it if available.
2014 * @param v Aircraft to handle.
2015 * @param apc Airport state machine.
2016 * @return Found a free helipad and assigned it.
2018 static bool AirportFindFreeHelipad(Aircraft
*v
, const AirportFTAClass
*apc
)
2020 /* if an airport doesn't have helipads, use terminals */
2021 if (apc
->num_helipads
== 0) return AirportFindFreeTerminal(v
, apc
);
2023 /* only 1 helicoptergroup, check all helipads
2024 * The blocks for helipads start after the last terminal (MAX_TERMINALS) */
2025 return FreeTerminal(v
, MAX_TERMINALS
, apc
->num_helipads
+ MAX_TERMINALS
);
2029 * Handle the 'dest too far' flag and the corresponding news message for aircraft.
2030 * @param v The aircraft.
2031 * @param too_far True if the current destination is too far away.
2033 static void AircraftHandleDestTooFar(Aircraft
*v
, bool too_far
)
2036 if (!HasBit(v
->flags
, VAF_DEST_TOO_FAR
)) {
2037 SetBit(v
->flags
, VAF_DEST_TOO_FAR
);
2038 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
2039 AI::NewEvent(v
->owner
, new ScriptEventAircraftDestTooFar(v
->index
));
2040 if (v
->owner
== _local_company
) {
2041 /* Post a news message. */
2042 SetDParam(0, v
->index
);
2043 AddVehicleAdviceNewsItem(STR_NEWS_AIRCRAFT_DEST_TOO_FAR
, v
->index
);
2049 if (HasBit(v
->flags
, VAF_DEST_TOO_FAR
)) {
2050 /* Not too far anymore, clear flag and message. */
2051 ClrBit(v
->flags
, VAF_DEST_TOO_FAR
);
2052 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
2053 DeleteVehicleNews(v
->index
, STR_NEWS_AIRCRAFT_DEST_TOO_FAR
);
2057 static bool AircraftEventHandler(Aircraft
*v
, int loop
)
2059 if (v
->vehstatus
& VS_CRASHED
) {
2060 return HandleCrashedAircraft(v
);
2063 if (v
->vehstatus
& VS_STOPPED
) return true;
2065 v
->HandleBreakdown();
2067 HandleAircraftSmoke(v
, loop
!= 0);
2069 v
->HandleLoading(loop
!= 0);
2071 if (v
->current_order
.IsType(OT_LOADING
) || v
->current_order
.IsType(OT_LEAVESTATION
)) return true;
2073 if (v
->state
>= ENDTAKEOFF
&& v
->state
<= HELIENDLANDING
) {
2074 /* If we are flying, unconditionally clear the 'dest too far' state. */
2075 AircraftHandleDestTooFar(v
, false);
2076 } else if (v
->acache
.cached_max_range_sqr
!= 0) {
2077 /* Check the distance to the next destination. This code works because the target
2078 * airport is only updated after take off and not on the ground. */
2079 Station
*cur_st
= Station::GetIfValid(v
->targetairport
);
2080 Station
*next_st
= v
->current_order
.IsType(OT_GOTO_STATION
) || v
->current_order
.IsType(OT_GOTO_DEPOT
) ? Station::GetIfValid(v
->current_order
.GetDestination()) : nullptr;
2082 if (cur_st
!= nullptr && cur_st
->airport
.tile
!= INVALID_TILE
&& next_st
!= nullptr && next_st
->airport
.tile
!= INVALID_TILE
) {
2083 uint dist
= DistanceSquare(cur_st
->airport
.tile
, next_st
->airport
.tile
);
2084 AircraftHandleDestTooFar(v
, dist
> v
->acache
.cached_max_range_sqr
);
2088 if (!HasBit(v
->flags
, VAF_DEST_TOO_FAR
)) AirportGoToNextPosition(v
);
2093 bool Aircraft::Tick()
2095 if (!this->IsNormalAircraft()) return true;
2097 PerformanceAccumulator
framerate(PFE_GL_AIRCRAFT
);
2099 this->tick_counter
++;
2101 if (!(this->vehstatus
& VS_STOPPED
)) this->running_ticks
++;
2103 if (this->subtype
== AIR_HELICOPTER
) HelicopterTickHandler(this);
2105 this->current_order_time
++;
2107 for (uint i
= 0; i
!= 2; i
++) {
2108 /* stop if the aircraft was deleted */
2109 if (!AircraftEventHandler(this, i
)) return false;
2117 * Returns aircraft's target station if v->target_airport
2118 * is a valid station with airport.
2119 * @param v vehicle to get target airport for
2120 * @return pointer to target station, nullptr if invalid
2122 Station
*GetTargetAirportIfValid(const Aircraft
*v
)
2124 assert(v
->type
== VEH_AIRCRAFT
);
2126 Station
*st
= Station::GetIfValid(v
->targetairport
);
2127 if (st
== nullptr) return nullptr;
2129 return st
->airport
.tile
== INVALID_TILE
? nullptr : st
;
2133 * Updates the status of the Aircraft heading or in the station
2134 * @param st Station been updated
2136 void UpdateAirplanesOnNewStation(const Station
*st
)
2138 /* only 1 station is updated per function call, so it is enough to get entry_point once */
2139 const AirportFTAClass
*ap
= st
->airport
.GetFTA();
2140 Direction rotation
= st
->airport
.tile
== INVALID_TILE
? DIR_N
: st
->airport
.rotation
;
2142 for (Aircraft
*v
: Aircraft::Iterate()) {
2143 if (!v
->IsNormalAircraft() || v
->targetairport
!= st
->index
) continue;
2144 assert(v
->state
== FLYING
);
2146 Order
*o
= &v
->current_order
;
2147 /* The aircraft is heading to a hangar, but the new station doesn't have one,
2148 * or the aircraft can't land on the new station. Cancel current order. */
2149 if (o
->IsType(OT_GOTO_DEPOT
) && !(o
->GetDepotOrderType() & ODTFB_PART_OF_ORDERS
) && o
->GetDestination() == st
->index
&&
2150 (!st
->airport
.HasHangar() || !CanVehicleUseStation(v
, st
))) {
2152 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
2154 v
->pos
= v
->previous_pos
= AircraftGetEntryPoint(v
, ap
, rotation
);
2155 UpdateAircraftCache(v
);
2158 /* Heliports don't have a hangar. Invalidate all go to hangar orders from all aircraft. */
2159 if (!st
->airport
.HasHangar()) RemoveOrderFromAllVehicles(OT_GOTO_DEPOT
, st
->index
, true);