Change: Only resort town directory window on population change if necessary
[openttd-github.git] / src / aircraft_cmd.cpp
blobe13658d6fec5cf28a0518c6673cf9ee307579d99
1 /*
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/>.
6 */
8 /**
9 * @file aircraft_cmd.cpp
10 * This file deals with aircraft and airport movements functionalities
13 #include "stdafx.h"
14 #include "aircraft.h"
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"
28 #include "ai/ai.hpp"
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()
47 this->x_offs = -1;
48 this->y_offs = -1;
49 this->x_extent = 2;
50 this->y_extent = 2;
52 switch (this->subtype) {
53 default: NOT_REACHED();
55 case AIR_AIRCRAFT:
56 case AIR_HELICOPTER:
57 switch (this->state) {
58 default: break;
59 case ENDTAKEOFF:
60 case LANDING:
61 case HELILANDING:
62 case FLYING:
63 this->x_extent = 24;
64 this->y_extent = 24;
65 break;
67 this->z_extent = 5;
68 break;
70 case AIR_SHADOW:
71 this->z_extent = 1;
72 this->x_offs = 0;
73 this->y_offs = 0;
74 break;
76 case AIR_ROTOR:
77 this->z_extent = 1;
78 break;
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,
96 0x0EBD, 0x0EC5
99 template <>
100 bool IsValidImageIndex<VEH_AIRCRAFT>(uint8 image_index)
102 return image_index < lengthof(_aircraft_sprite);
105 /** Helicopter rotor animation states */
106 enum HelicopterRotorStates {
107 HRS_ROTOR_STOPPED,
108 HRS_ROTOR_MOVING_1,
109 HRS_ROTOR_MOVING_2,
110 HRS_ROTOR_MOVING_3,
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)
122 uint best = 0;
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());
136 } else {
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) {
163 best = distance;
164 index = st->index;
167 return index;
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);
220 Rect rect;
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);
250 Rect rect;
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);
260 * Build an aircraft.
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
282 *ret = v;
284 v->direction = DIR_SE;
286 v->owner = u->owner = _current_company;
288 v->tile = tile;
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;
305 v->refit_cap = 0;
306 u->cargo_cap = avi->mail_capacity;
307 u->refit_cap = 0;
309 v->cargo_type = e->GetDefaultCargoType();
310 u->cargo_type = CT_MAIL;
312 v->name = nullptr;
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);
321 v->UpdateDeltaXY();
323 u->subtype = AIR_SHADOW;
324 u->UpdateDeltaXY();
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);
334 v->state = HANGAR;
335 v->previous_pos = v->pos;
336 v->targetairport = GetStationIndex(tile);
337 v->SetNext(u);
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_seq.Set(SPR_IMG_QUERY);
345 u->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);
362 v->UpdatePosition();
363 u->UpdatePosition();
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;
371 w->x_pos = v->x_pos;
372 w->y_pos = v->y_pos;
373 w->z_pos = v->z_pos + ROTOR_Z_OFFSET;
374 w->vehstatus = VS_HIDDEN | VS_UNCLICKABLE;
375 w->spritenum = 0xFF;
376 w->subtype = AIR_ROTOR;
377 w->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;
381 w->UpdateDeltaXY();
383 u->SetNext(w);
384 w->UpdatePosition();
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;
408 return true;
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);
416 return;
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);
450 CheckOrders(this);
452 CheckVehicleBreakdown(this);
453 AgeVehicle(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) {
479 u->cur_speed++;
480 if (u->cur_speed >= 0x80 && u->state == HRS_ROTOR_MOVING_3) {
481 u->cur_speed = 0;
484 } else {
485 if (u->cur_speed == 0) {
486 u->cur_speed = 0x70;
488 if (u->cur_speed >= 0x50) {
489 u->cur_speed--;
493 int tick = ++u->tick_counter;
494 int spd = u->cur_speed >> 4;
496 VehicleSpriteSeq seq;
497 if (spd == 0) {
498 u->state = HRS_ROTOR_STOPPED;
499 GetRotorImage(v, EIT_ON_MAP, &seq);
500 if (u->sprite_seq == seq) return;
501 } else if (tick >= spd) {
502 u->tick_counter = 0;
503 u->state++;
504 if (u->state > HRS_ROTOR_MOVING_3) u->state = HRS_ROTOR_MOVING_1;
505 GetRotorImage(v, EIT_ON_MAP, &seq);
506 } else {
507 return;
510 u->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)
524 v->x_pos = x;
525 v->y_pos = y;
526 v->z_pos = z;
528 v->UpdatePosition();
529 v->UpdateViewport(true, false);
530 if (v->subtype == AIR_HELICOPTER) {
531 GetRotorImage(v, EIT_ON_MAP, &v->Next()->Next()->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);
538 u->x_pos = x;
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_seq.CopyWithoutPalette(v->sprite_seq); // the shadow is never coloured
545 u->UpdatePositionAndViewport();
547 u = u->Next();
548 if (u != nullptr) {
549 u->x_pos = x;
550 u->y_pos = y;
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)
563 v->subspeed = 0;
564 v->progress = 0;
566 Aircraft *u = v->Next();
567 u->vehstatus |= VS_HIDDEN;
568 u = u->Next();
569 if (u != nullptr) {
570 u->vehstatus |= VS_HIDDEN;
571 u->cur_speed = 0;
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.
588 * @param v Vehicle
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;
599 } else {
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. */
610 if (update_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;
646 byte t;
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 = min(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
670 * touchdown. */
671 if (!hard_limit && v->cur_speed > speed_limit) {
672 speed_limit = v->cur_speed - max(1, ((v->cur_speed * v->cur_speed) / 16384) / _settings_game.vehicle.plane_speed);
675 spd = 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) {
679 v->cur_speed = spd;
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);
689 spd += v->progress;
690 v->progress = (byte)spd;
691 return spd >> 8;
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) {
729 case DIR_N:
730 case DIR_NE:
731 case DIR_E:
732 case DIR_SE:
733 base_altitude += 10;
734 break;
736 default: break;
739 /* Make faster planes fly higher so that they can overtake slower ones */
740 base_altitude += 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);
760 template <class T>
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);
774 int z = v->z_pos;
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);
787 z--;
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);
796 return z;
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
809 * is approached.
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 */
824 TileIndex tile = 0;
826 const Station *st = Station::GetIfValid(v->targetairport);
827 if (st != nullptr) {
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;
835 DiagDirection dir;
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;
839 } else {
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 int count;
861 /* nullptr if station is invalid */
862 const Station *st = Station::GetIfValid(v->targetairport);
863 /* INVALID_TILE if there is no station */
864 TileIndex tile = INVALID_TILE;
865 Direction rotation = DIR_N;
866 uint size_x = 1, size_y = 1;
867 if (st != nullptr) {
868 if (st->airport.tile != INVALID_TILE) {
869 tile = st->airport.tile;
870 rotation = st->airport.rotation;
871 size_x = st->airport.w;
872 size_y = st->airport.h;
873 } else {
874 tile = st->xy;
877 /* DUMMY if there is no station or no airport */
878 const AirportFTAClass *afc = tile == INVALID_TILE ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
880 /* prevent going to INVALID_TILE if airport is deleted. */
881 if (st == nullptr || st->airport.tile == INVALID_TILE) {
882 /* Jump into our "holding pattern" state machine if possible */
883 if (v->pos >= afc->nofelements) {
884 v->pos = v->previous_pos = AircraftGetEntryPoint(v, afc, DIR_N);
885 } else if (v->targetairport != v->current_order.GetDestination()) {
886 /* If not possible, just get out of here fast */
887 v->state = FLYING;
888 UpdateAircraftCache(v);
889 AircraftNextAirportPos_and_Order(v);
890 /* get aircraft back on running altitude */
891 SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
892 return false;
896 /* get airport moving data */
897 const AirportMovingData amd = RotateAirportMovingData(afc->MovingData(v->pos), rotation, size_x, size_y);
899 int x = TileX(tile) * TILE_SIZE;
900 int y = TileY(tile) * TILE_SIZE;
902 /* Helicopter raise */
903 if (amd.flag & AMED_HELI_RAISE) {
904 Aircraft *u = v->Next()->Next();
906 /* Make sure the rotors don't rotate too fast */
907 if (u->cur_speed > 32) {
908 v->cur_speed = 0;
909 if (--u->cur_speed == 32) {
910 if (!PlayVehicleSound(v, VSE_START)) {
911 SndPlayVehicleFx(SND_18_HELICOPTER, v);
914 } else {
915 u->cur_speed = 32;
916 count = UpdateAircraftSpeed(v);
917 if (count > 0) {
918 v->tile = 0;
920 int z_dest;
921 GetAircraftFlightLevelBounds(v, &z_dest, nullptr);
923 /* Reached altitude? */
924 if (v->z_pos >= z_dest) {
925 v->cur_speed = 0;
926 return true;
928 SetAircraftPosition(v, v->x_pos, v->y_pos, min(v->z_pos + count, z_dest));
931 return false;
934 /* Helicopter landing. */
935 if (amd.flag & AMED_HELI_LOWER) {
936 SetBit(v->flags, VAF_HELI_DIRECT_DESCENT);
938 if (st == nullptr) {
939 /* FIXME - AircraftController -> if station no longer exists, do not land
940 * helicopter will circle until sign disappears, then go to next order
941 * what to do when it is the only order left, right now it just stays in 1 place */
942 v->state = FLYING;
943 UpdateAircraftCache(v);
944 AircraftNextAirportPos_and_Order(v);
945 return false;
948 /* Vehicle is now at the airport. */
949 v->tile = tile;
951 /* Find altitude of landing position. */
952 int z = GetSlopePixelZ(x, y) + 1 + afc->delta_z;
954 if (z == v->z_pos) {
955 Vehicle *u = v->Next()->Next();
957 /* Increase speed of rotors. When speed is 80, we've landed. */
958 if (u->cur_speed >= 80) {
959 ClrBit(v->flags, VAF_HELI_DIRECT_DESCENT);
960 return true;
962 u->cur_speed += 4;
963 } else {
964 count = UpdateAircraftSpeed(v);
965 if (count > 0) {
966 if (v->z_pos > z) {
967 SetAircraftPosition(v, v->x_pos, v->y_pos, max(v->z_pos - count, z));
968 } else {
969 SetAircraftPosition(v, v->x_pos, v->y_pos, min(v->z_pos + count, z));
973 return false;
976 /* Get distance from destination pos to current pos. */
977 uint dist = abs(x + amd.x - v->x_pos) + abs(y + amd.y - v->y_pos);
979 /* Need exact position? */
980 if (!(amd.flag & AMED_EXACTPOS) && dist <= (amd.flag & AMED_SLOWTURN ? 8U : 4U)) return true;
982 /* At final pos? */
983 if (dist == 0) {
984 /* Change direction smoothly to final direction. */
985 DirDiff dirdiff = DirDifference(amd.direction, v->direction);
986 /* if distance is 0, and plane points in right direction, no point in calling
987 * UpdateAircraftSpeed(). So do it only afterwards */
988 if (dirdiff == DIRDIFF_SAME) {
989 v->cur_speed = 0;
990 return true;
993 if (!UpdateAircraftSpeed(v, SPEED_LIMIT_TAXI)) return false;
995 v->direction = ChangeDir(v->direction, dirdiff > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
996 v->cur_speed >>= 1;
998 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
999 return false;
1002 if (amd.flag & AMED_BRAKE && v->cur_speed > SPEED_LIMIT_TAXI * _settings_game.vehicle.plane_speed) {
1003 MaybeCrashAirplane(v);
1004 if ((v->vehstatus & VS_CRASHED) != 0) return false;
1007 uint speed_limit = SPEED_LIMIT_TAXI;
1008 bool hard_limit = true;
1010 if (amd.flag & AMED_NOSPDCLAMP) speed_limit = SPEED_LIMIT_NONE;
1011 if (amd.flag & AMED_HOLD) { speed_limit = SPEED_LIMIT_HOLD; hard_limit = false; }
1012 if (amd.flag & AMED_LAND) { speed_limit = SPEED_LIMIT_APPROACH; hard_limit = false; }
1013 if (amd.flag & AMED_BRAKE) { speed_limit = SPEED_LIMIT_TAXI; hard_limit = false; }
1015 count = UpdateAircraftSpeed(v, speed_limit, hard_limit);
1016 if (count == 0) return false;
1018 if (v->turn_counter != 0) v->turn_counter--;
1020 do {
1022 GetNewVehiclePosResult gp;
1024 if (dist < 4 || (amd.flag & AMED_LAND)) {
1025 /* move vehicle one pixel towards target */
1026 gp.x = (v->x_pos != (x + amd.x)) ?
1027 v->x_pos + ((x + amd.x > v->x_pos) ? 1 : -1) :
1028 v->x_pos;
1029 gp.y = (v->y_pos != (y + amd.y)) ?
1030 v->y_pos + ((y + amd.y > v->y_pos) ? 1 : -1) :
1031 v->y_pos;
1033 /* Oilrigs must keep v->tile as st->airport.tile, since the landing pad is in a non-airport tile */
1034 gp.new_tile = (st->airport.type == AT_OILRIG) ? st->airport.tile : TileVirtXY(gp.x, gp.y);
1036 } else {
1038 /* Turn. Do it slowly if in the air. */
1039 Direction newdir = GetDirectionTowards(v, x + amd.x, y + amd.y);
1040 if (newdir != v->direction) {
1041 if (amd.flag & AMED_SLOWTURN && v->number_consecutive_turns < 8 && v->subtype == AIR_AIRCRAFT) {
1042 if (v->turn_counter == 0 || newdir == v->last_direction) {
1043 if (newdir == v->last_direction) {
1044 v->number_consecutive_turns = 0;
1045 } else {
1046 v->number_consecutive_turns++;
1048 v->turn_counter = 2 * _settings_game.vehicle.plane_speed;
1049 v->last_direction = v->direction;
1050 v->direction = newdir;
1053 /* Move vehicle. */
1054 gp = GetNewVehiclePos(v);
1055 } else {
1056 v->cur_speed >>= 1;
1057 v->direction = newdir;
1059 /* When leaving a terminal an aircraft often goes to a position
1060 * directly in front of it. If it would move while turning it
1061 * would need an two extra turns to end up at the correct position.
1062 * To make it easier just disallow all moving while turning as
1063 * long as an aircraft is on the ground. */
1064 gp.x = v->x_pos;
1065 gp.y = v->y_pos;
1066 gp.new_tile = gp.old_tile = v->tile;
1068 } else {
1069 v->number_consecutive_turns = 0;
1070 /* Move vehicle. */
1071 gp = GetNewVehiclePos(v);
1075 v->tile = gp.new_tile;
1076 /* If vehicle is in the air, use tile coordinate 0. */
1077 if (amd.flag & (AMED_TAKEOFF | AMED_SLOWTURN | AMED_LAND)) v->tile = 0;
1079 /* Adjust Z for land or takeoff? */
1080 int z = v->z_pos;
1082 if (amd.flag & AMED_TAKEOFF) {
1083 z = GetAircraftFlightLevel(v, true);
1084 } else if (amd.flag & AMED_HOLD) {
1085 /* Let the plane drop from normal flight altitude to holding pattern altitude */
1086 if (z > GetAircraftHoldMaxAltitude(v)) z--;
1087 } else if ((amd.flag & AMED_SLOWTURN) && (amd.flag & AMED_NOSPDCLAMP)) {
1088 z = GetAircraftFlightLevel(v);
1091 if (amd.flag & AMED_LAND) {
1092 if (st->airport.tile == INVALID_TILE) {
1093 /* Airport has been removed, abort the landing procedure */
1094 v->state = FLYING;
1095 UpdateAircraftCache(v);
1096 AircraftNextAirportPos_and_Order(v);
1097 /* get aircraft back on running altitude */
1098 SetAircraftPosition(v, gp.x, gp.y, GetAircraftFlightLevel(v));
1099 continue;
1102 int curz = GetSlopePixelZ(x + amd.x, y + amd.y) + 1;
1104 /* We're not flying below our destination, right? */
1105 assert(curz <= z);
1106 int t = max(1U, dist - 4);
1107 int delta = z - curz;
1109 /* Only start lowering when we're sufficiently close for a 1:1 glide */
1110 if (delta >= t) {
1111 z -= CeilDiv(z - curz, t);
1113 if (z < curz) z = curz;
1116 /* We've landed. Decrease speed when we're reaching end of runway. */
1117 if (amd.flag & AMED_BRAKE) {
1118 int curz = GetSlopePixelZ(x, y) + 1;
1120 if (z > curz) {
1121 z--;
1122 } else if (z < curz) {
1123 z++;
1128 SetAircraftPosition(v, gp.x, gp.y, z);
1129 } while (--count != 0);
1130 return false;
1134 * Handle crashed aircraft \a v.
1135 * @param v Crashed aircraft.
1137 static bool HandleCrashedAircraft(Aircraft *v)
1139 v->crashed_counter += 3;
1141 Station *st = GetTargetAirportIfValid(v);
1143 /* make aircraft crash down to the ground */
1144 if (v->crashed_counter < 500 && st == nullptr && ((v->crashed_counter % 3) == 0) ) {
1145 int z = GetSlopePixelZ(Clamp(v->x_pos, 0, MapMaxX() * TILE_SIZE), Clamp(v->y_pos, 0, MapMaxY() * TILE_SIZE));
1146 v->z_pos -= 1;
1147 if (v->z_pos == z) {
1148 v->crashed_counter = 500;
1149 v->z_pos++;
1153 if (v->crashed_counter < 650) {
1154 uint32 r;
1155 if (Chance16R(1, 32, r)) {
1156 static const DirDiff delta[] = {
1157 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
1160 v->direction = ChangeDir(v->direction, delta[GB(r, 16, 2)]);
1161 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1162 r = Random();
1163 CreateEffectVehicleRel(v,
1164 GB(r, 0, 4) - 4,
1165 GB(r, 4, 4) - 4,
1166 GB(r, 8, 4),
1167 EV_EXPLOSION_SMALL);
1169 } else if (v->crashed_counter >= 10000) {
1170 /* remove rubble of crashed airplane */
1172 /* clear runway-in on all airports, set by crashing plane
1173 * small airports use AIRPORT_BUSY, city airports use RUNWAY_IN_OUT_block, etc.
1174 * but they all share the same number */
1175 if (st != nullptr) {
1176 CLRBITS(st->airport.flags, RUNWAY_IN_block);
1177 CLRBITS(st->airport.flags, RUNWAY_IN_OUT_block); // commuter airport
1178 CLRBITS(st->airport.flags, RUNWAY_IN2_block); // intercontinental
1181 delete v;
1183 return false;
1186 return true;
1191 * Handle smoke of broken aircraft.
1192 * @param v Aircraft
1193 * @param mode Is this the non-first call for this vehicle in this tick?
1195 static void HandleAircraftSmoke(Aircraft *v, bool mode)
1197 static const struct {
1198 int8 x;
1199 int8 y;
1200 } smoke_pos[] = {
1201 { 5, 5 },
1202 { 6, 0 },
1203 { 5, -5 },
1204 { 0, -6 },
1205 { -5, -5 },
1206 { -6, 0 },
1207 { -5, 5 },
1208 { 0, 6 }
1211 if (!(v->vehstatus & VS_AIRCRAFT_BROKEN)) return;
1213 /* Stop smoking when landed */
1214 if (v->cur_speed < 10) {
1215 v->vehstatus &= ~VS_AIRCRAFT_BROKEN;
1216 v->breakdown_ctr = 0;
1217 return;
1220 /* Spawn effect et most once per Tick, i.e. !mode */
1221 if (!mode && (v->tick_counter & 0x0F) == 0) {
1222 CreateEffectVehicleRel(v,
1223 smoke_pos[v->direction].x,
1224 smoke_pos[v->direction].y,
1226 EV_BREAKDOWN_SMOKE_AIRCRAFT
1231 void HandleMissingAircraftOrders(Aircraft *v)
1234 * We do not have an order. This can be divided into two cases:
1235 * 1) we are heading to an invalid station. In this case we must
1236 * find another airport to go to. If there is nowhere to go,
1237 * we will destroy the aircraft as it otherwise will enter
1238 * the holding pattern for the first airport, which can cause
1239 * the plane to go into an undefined state when building an
1240 * airport with the same StationID.
1241 * 2) we are (still) heading to a (still) valid airport, then we
1242 * can continue going there. This can happen when you are
1243 * changing the aircraft's orders while in-flight or in for
1244 * example a depot. However, when we have a current order to
1245 * go to a depot, we have to keep that order so the aircraft
1246 * actually stops.
1248 const Station *st = GetTargetAirportIfValid(v);
1249 if (st == nullptr) {
1250 Backup<CompanyID> cur_company(_current_company, v->owner, FILE_LINE);
1251 CommandCost ret = DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_SEND_VEHICLE_TO_DEPOT);
1252 cur_company.Restore();
1254 if (ret.Failed()) CrashAirplane(v);
1255 } else if (!v->current_order.IsType(OT_GOTO_DEPOT)) {
1256 v->current_order.Free();
1261 TileIndex Aircraft::GetOrderStationLocation(StationID station)
1263 /* Orders are changed in flight, ensure going to the right station. */
1264 if (this->state == FLYING) {
1265 AircraftNextAirportPos_and_Order(this);
1268 /* Aircraft do not use dest-tile */
1269 return 0;
1272 void Aircraft::MarkDirty()
1274 this->colourmap = PAL_NONE;
1275 this->UpdateViewport(true, false);
1276 if (this->subtype == AIR_HELICOPTER) {
1277 GetRotorImage(this, EIT_ON_MAP, &this->Next()->Next()->sprite_seq);
1282 uint Aircraft::Crash(bool flooded)
1284 uint pass = Vehicle::Crash(flooded) + 2; // pilots
1285 this->crashed_counter = flooded ? 9000 : 0; // max 10000, disappear pretty fast when flooded
1287 return pass;
1291 * Bring the aircraft in a crashed state, create the explosion animation, and create a news item about the crash.
1292 * @param v Aircraft that crashed.
1294 static void CrashAirplane(Aircraft *v)
1296 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
1298 uint pass = v->Crash();
1299 SetDParam(0, pass);
1301 v->cargo.Truncate();
1302 v->Next()->cargo.Truncate();
1303 const Station *st = GetTargetAirportIfValid(v);
1304 StringID newsitem;
1305 if (st == nullptr) {
1306 newsitem = STR_NEWS_PLANE_CRASH_OUT_OF_FUEL;
1307 } else {
1308 SetDParam(1, st->index);
1309 newsitem = STR_NEWS_AIRCRAFT_CRASH;
1312 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
1313 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
1315 AddVehicleNewsItem(newsitem, NT_ACCIDENT, v->index, st != nullptr ? st->index : INVALID_STATION);
1317 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
1318 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
1322 * Decide whether aircraft \a v should crash.
1323 * @param v Aircraft to test.
1325 static void MaybeCrashAirplane(Aircraft *v)
1328 Station *st = Station::Get(v->targetairport);
1330 uint32 prob;
1331 if ((st->airport.GetFTA()->flags & AirportFTAClass::SHORT_STRIP) &&
1332 (AircraftVehInfo(v->engine_type)->subtype & AIR_FAST) &&
1333 !_cheats.no_jetcrash.value) {
1334 prob = 3276;
1335 } else {
1336 if (_settings_game.vehicle.plane_crashes == 0) return;
1337 prob = (0x4000 << _settings_game.vehicle.plane_crashes) / 1500;
1340 if (GB(Random(), 0, 22) > prob) return;
1342 /* Crash the airplane. Remove all goods stored at the station. */
1343 for (CargoID i = 0; i < NUM_CARGO; i++) {
1344 st->goods[i].rating = 1;
1345 st->goods[i].cargo.Truncate();
1348 CrashAirplane(v);
1352 * Aircraft arrives at a terminal. If it is the first aircraft, throw a party.
1353 * Start loading cargo.
1354 * @param v Aircraft that arrived.
1356 static void AircraftEntersTerminal(Aircraft *v)
1358 if (v->current_order.IsType(OT_GOTO_DEPOT)) return;
1360 Station *st = Station::Get(v->targetairport);
1361 v->last_station_visited = v->targetairport;
1363 /* Check if station was ever visited before */
1364 if (!(st->had_vehicle_of_type & HVOT_AIRCRAFT)) {
1365 st->had_vehicle_of_type |= HVOT_AIRCRAFT;
1366 SetDParam(0, st->index);
1367 /* show newsitem of celebrating citizens */
1368 AddVehicleNewsItem(
1369 STR_NEWS_FIRST_AIRCRAFT_ARRIVAL,
1370 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
1371 v->index,
1372 st->index
1374 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
1375 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
1378 v->BeginLoading();
1382 * Aircraft touched down at the landing strip.
1383 * @param v Aircraft that landed.
1385 static void AircraftLandAirplane(Aircraft *v)
1387 Station *st = Station::Get(v->targetairport);
1389 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1391 v->UpdateDeltaXY();
1393 AirportTileAnimationTrigger(st, vt, AAT_STATION_AIRPLANE_LAND);
1395 if (!PlayVehicleSound(v, VSE_TOUCHDOWN)) {
1396 SndPlayVehicleFx(SND_17_SKID_PLANE, v);
1401 /** set the right pos when heading to other airports after takeoff */
1402 void AircraftNextAirportPos_and_Order(Aircraft *v)
1404 if (v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT)) {
1405 v->targetairport = v->current_order.GetDestination();
1408 const Station *st = GetTargetAirportIfValid(v);
1409 const AirportFTAClass *apc = st == nullptr ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
1410 Direction rotation = st == nullptr ? DIR_N : st->airport.rotation;
1411 v->pos = v->previous_pos = AircraftGetEntryPoint(v, apc, rotation);
1415 * Aircraft is about to leave the hangar.
1416 * @param v Aircraft leaving.
1417 * @param exit_dir The direction the vehicle leaves the hangar.
1418 * @note This function is called in AfterLoadGame for old savegames, so don't rely
1419 * on any data to be valid, especially don't rely on the fact that the vehicle
1420 * is actually on the ground inside a depot.
1422 void AircraftLeaveHangar(Aircraft *v, Direction exit_dir)
1424 v->cur_speed = 0;
1425 v->subspeed = 0;
1426 v->progress = 0;
1427 v->direction = exit_dir;
1428 v->vehstatus &= ~VS_HIDDEN;
1430 Vehicle *u = v->Next();
1431 u->vehstatus &= ~VS_HIDDEN;
1433 /* Rotor blades */
1434 u = u->Next();
1435 if (u != nullptr) {
1436 u->vehstatus &= ~VS_HIDDEN;
1437 u->cur_speed = 80;
1441 VehicleServiceInDepot(v);
1442 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1443 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1444 SetWindowClassesDirty(WC_AIRCRAFT_LIST);
1447 ////////////////////////////////////////////////////////////////////////////////
1448 /////////////////// AIRCRAFT MOVEMENT SCHEME ////////////////////////////////
1449 ////////////////////////////////////////////////////////////////////////////////
1450 static void AircraftEventHandler_EnterTerminal(Aircraft *v, const AirportFTAClass *apc)
1452 AircraftEntersTerminal(v);
1453 v->state = apc->layout[v->pos].heading;
1457 * Aircraft arrived in an airport hangar.
1458 * @param v Aircraft in the hangar.
1459 * @param apc Airport description containing the hangar.
1461 static void AircraftEventHandler_EnterHangar(Aircraft *v, const AirportFTAClass *apc)
1463 VehicleEnterDepot(v);
1464 v->state = apc->layout[v->pos].heading;
1468 * Handle aircraft movement/decision making in an airport hangar.
1469 * @param v Aircraft in the hangar.
1470 * @param apc Airport description containing the hangar.
1472 static void AircraftEventHandler_InHangar(Aircraft *v, const AirportFTAClass *apc)
1474 /* if we just arrived, execute EnterHangar first */
1475 if (v->previous_pos != v->pos) {
1476 AircraftEventHandler_EnterHangar(v, apc);
1477 return;
1480 /* if we were sent to the depot, stay there */
1481 if (v->current_order.IsType(OT_GOTO_DEPOT) && (v->vehstatus & VS_STOPPED)) {
1482 v->current_order.Free();
1483 return;
1486 if (!v->current_order.IsType(OT_GOTO_STATION) &&
1487 !v->current_order.IsType(OT_GOTO_DEPOT))
1488 return;
1490 /* We are leaving a hangar, but have to go to the exact same one; re-enter */
1491 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->current_order.GetDestination() == v->targetairport) {
1492 VehicleEnterDepot(v);
1493 return;
1496 /* if the block of the next position is busy, stay put */
1497 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1499 /* We are already at the target airport, we need to find a terminal */
1500 if (v->current_order.GetDestination() == v->targetairport) {
1501 /* FindFreeTerminal:
1502 * 1. Find a free terminal, 2. Occupy it, 3. Set the vehicle's state to that terminal */
1503 if (v->subtype == AIR_HELICOPTER) {
1504 if (!AirportFindFreeHelipad(v, apc)) return; // helicopter
1505 } else {
1506 if (!AirportFindFreeTerminal(v, apc)) return; // airplane
1508 } else { // Else prepare for launch.
1509 /* airplane goto state takeoff, helicopter to helitakeoff */
1510 v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1512 const Station *st = Station::GetByTile(v->tile);
1513 AircraftLeaveHangar(v, st->airport.GetHangarExitDirection(v->tile));
1514 AirportMove(v, apc);
1517 /** At one of the Airport's Terminals */
1518 static void AircraftEventHandler_AtTerminal(Aircraft *v, const AirportFTAClass *apc)
1520 /* if we just arrived, execute EnterTerminal first */
1521 if (v->previous_pos != v->pos) {
1522 AircraftEventHandler_EnterTerminal(v, apc);
1523 /* on an airport with helipads, a helicopter will always land there
1524 * and get serviced at the same time - setting */
1525 if (_settings_game.order.serviceathelipad) {
1526 if (v->subtype == AIR_HELICOPTER && apc->num_helipads > 0) {
1527 /* an excerpt of ServiceAircraft, without the invisibility stuff */
1528 v->date_of_last_service = _date;
1529 v->breakdowns_since_last_service = 0;
1530 v->reliability = v->GetEngine()->reliability;
1531 SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
1534 return;
1537 if (v->current_order.IsType(OT_NOTHING)) return;
1539 /* if the block of the next position is busy, stay put */
1540 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1542 /* airport-road is free. We either have to go to another airport, or to the hangar
1543 * ---> start moving */
1545 bool go_to_hangar = false;
1546 switch (v->current_order.GetType()) {
1547 case OT_GOTO_STATION: // ready to fly to another airport
1548 break;
1549 case OT_GOTO_DEPOT: // visit hangar for servicing, sale, etc.
1550 go_to_hangar = v->current_order.GetDestination() == v->targetairport;
1551 break;
1552 case OT_CONDITIONAL:
1553 /* In case of a conditional order we just have to wait a tick
1554 * longer, so the conditional order can actually be processed;
1555 * we should not clear the order as that makes us go nowhere. */
1556 return;
1557 default: // orders have been deleted (no orders), goto depot and don't bother us
1558 v->current_order.Free();
1559 go_to_hangar = Station::Get(v->targetairport)->airport.HasHangar();
1562 if (go_to_hangar && Station::Get(v->targetairport)->airport.HasHangar()) {
1563 v->state = HANGAR;
1564 } else {
1565 /* airplane goto state takeoff, helicopter to helitakeoff */
1566 v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1568 AirportMove(v, apc);
1571 static void AircraftEventHandler_General(Aircraft *v, const AirportFTAClass *apc)
1573 error("OK, you shouldn't be here, check your Airport Scheme!");
1576 static void AircraftEventHandler_TakeOff(Aircraft *v, const AirportFTAClass *apc)
1578 PlayAircraftSound(v); // play takeoffsound for airplanes
1579 v->state = STARTTAKEOFF;
1582 static void AircraftEventHandler_StartTakeOff(Aircraft *v, const AirportFTAClass *apc)
1584 v->state = ENDTAKEOFF;
1585 v->UpdateDeltaXY();
1588 static void AircraftEventHandler_EndTakeOff(Aircraft *v, const AirportFTAClass *apc)
1590 v->state = FLYING;
1591 /* get the next position to go to, differs per airport */
1592 AircraftNextAirportPos_and_Order(v);
1595 static void AircraftEventHandler_HeliTakeOff(Aircraft *v, const AirportFTAClass *apc)
1597 v->state = FLYING;
1598 v->UpdateDeltaXY();
1600 /* get the next position to go to, differs per airport */
1601 AircraftNextAirportPos_and_Order(v);
1603 /* Send the helicopter to a hangar if needed for replacement */
1604 if (v->NeedsAutomaticServicing()) {
1605 Backup<CompanyID> cur_company(_current_company, v->owner, FILE_LINE);
1606 DoCommand(v->tile, v->index | DEPOT_SERVICE | DEPOT_LOCATE_HANGAR, 0, DC_EXEC, CMD_SEND_VEHICLE_TO_DEPOT);
1607 cur_company.Restore();
1611 static void AircraftEventHandler_Flying(Aircraft *v, const AirportFTAClass *apc)
1613 Station *st = Station::Get(v->targetairport);
1615 /* Runway busy, not allowed to use this airstation or closed, circle. */
1616 if (CanVehicleUseStation(v, st) && (st->owner == OWNER_NONE || st->owner == v->owner) && !(st->airport.flags & AIRPORT_CLOSED_block)) {
1617 /* {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
1618 * if it is an airplane, look for LANDING, for helicopter HELILANDING
1619 * it is possible to choose from multiple landing runways, so loop until a free one is found */
1620 byte landingtype = (v->subtype == AIR_HELICOPTER) ? HELILANDING : LANDING;
1621 const AirportFTA *current = apc->layout[v->pos].next;
1622 while (current != nullptr) {
1623 if (current->heading == landingtype) {
1624 /* save speed before, since if AirportHasBlock is false, it resets them to 0
1625 * we don't want that for plane in air
1626 * hack for speed thingie */
1627 uint16 tcur_speed = v->cur_speed;
1628 uint16 tsubspeed = v->subspeed;
1629 if (!AirportHasBlock(v, current, apc)) {
1630 v->state = landingtype; // LANDING / HELILANDING
1631 if (v->state == HELILANDING) SetBit(v->flags, VAF_HELI_DIRECT_DESCENT);
1632 /* it's a bit dirty, but I need to set position to next position, otherwise
1633 * if there are multiple runways, plane won't know which one it took (because
1634 * they all have heading LANDING). And also occupy that block! */
1635 v->pos = current->next_position;
1636 SETBITS(st->airport.flags, apc->layout[v->pos].block);
1637 return;
1639 v->cur_speed = tcur_speed;
1640 v->subspeed = tsubspeed;
1642 current = current->next;
1645 v->state = FLYING;
1646 v->pos = apc->layout[v->pos].next_position;
1649 static void AircraftEventHandler_Landing(Aircraft *v, const AirportFTAClass *apc)
1651 v->state = ENDLANDING;
1652 AircraftLandAirplane(v); // maybe crash airplane
1654 /* check if the aircraft needs to be replaced or renewed and send it to a hangar if needed */
1655 if (v->NeedsAutomaticServicing()) {
1656 Backup<CompanyID> cur_company(_current_company, v->owner, FILE_LINE);
1657 DoCommand(v->tile, v->index | DEPOT_SERVICE, 0, DC_EXEC, CMD_SEND_VEHICLE_TO_DEPOT);
1658 cur_company.Restore();
1662 static void AircraftEventHandler_HeliLanding(Aircraft *v, const AirportFTAClass *apc)
1664 v->state = HELIENDLANDING;
1665 v->UpdateDeltaXY();
1668 static void AircraftEventHandler_EndLanding(Aircraft *v, const AirportFTAClass *apc)
1670 /* next block busy, don't do a thing, just wait */
1671 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1673 /* if going to terminal (OT_GOTO_STATION) choose one
1674 * 1. in case all terminals are busy AirportFindFreeTerminal() returns false or
1675 * 2. not going for terminal (but depot, no order),
1676 * --> get out of the way to the hangar. */
1677 if (v->current_order.IsType(OT_GOTO_STATION)) {
1678 if (AirportFindFreeTerminal(v, apc)) return;
1680 v->state = HANGAR;
1684 static void AircraftEventHandler_HeliEndLanding(Aircraft *v, const AirportFTAClass *apc)
1686 /* next block busy, don't do a thing, just wait */
1687 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1689 /* if going to helipad (OT_GOTO_STATION) choose one. If airport doesn't have helipads, choose terminal
1690 * 1. in case all terminals/helipads are busy (AirportFindFreeHelipad() returns false) or
1691 * 2. not going for terminal (but depot, no order),
1692 * --> get out of the way to the hangar IF there are terminals on the airport.
1693 * --> else TAKEOFF
1694 * the reason behind this is that if an airport has a terminal, it also has a hangar. Airplanes
1695 * must go to a hangar. */
1696 if (v->current_order.IsType(OT_GOTO_STATION)) {
1697 if (AirportFindFreeHelipad(v, apc)) return;
1699 v->state = Station::Get(v->targetairport)->airport.HasHangar() ? HANGAR : HELITAKEOFF;
1703 * Signature of the aircraft handler function.
1704 * @param v Aircraft to handle.
1705 * @param apc Airport state machine.
1707 typedef void AircraftStateHandler(Aircraft *v, const AirportFTAClass *apc);
1708 /** Array of handler functions for each target of the aircraft. */
1709 static AircraftStateHandler * const _aircraft_state_handlers[] = {
1710 AircraftEventHandler_General, // TO_ALL = 0
1711 AircraftEventHandler_InHangar, // HANGAR = 1
1712 AircraftEventHandler_AtTerminal, // TERM1 = 2
1713 AircraftEventHandler_AtTerminal, // TERM2 = 3
1714 AircraftEventHandler_AtTerminal, // TERM3 = 4
1715 AircraftEventHandler_AtTerminal, // TERM4 = 5
1716 AircraftEventHandler_AtTerminal, // TERM5 = 6
1717 AircraftEventHandler_AtTerminal, // TERM6 = 7
1718 AircraftEventHandler_AtTerminal, // HELIPAD1 = 8
1719 AircraftEventHandler_AtTerminal, // HELIPAD2 = 9
1720 AircraftEventHandler_TakeOff, // TAKEOFF = 10
1721 AircraftEventHandler_StartTakeOff, // STARTTAKEOFF = 11
1722 AircraftEventHandler_EndTakeOff, // ENDTAKEOFF = 12
1723 AircraftEventHandler_HeliTakeOff, // HELITAKEOFF = 13
1724 AircraftEventHandler_Flying, // FLYING = 14
1725 AircraftEventHandler_Landing, // LANDING = 15
1726 AircraftEventHandler_EndLanding, // ENDLANDING = 16
1727 AircraftEventHandler_HeliLanding, // HELILANDING = 17
1728 AircraftEventHandler_HeliEndLanding, // HELIENDLANDING = 18
1729 AircraftEventHandler_AtTerminal, // TERM7 = 19
1730 AircraftEventHandler_AtTerminal, // TERM8 = 20
1731 AircraftEventHandler_AtTerminal, // HELIPAD3 = 21
1734 static void AirportClearBlock(const Aircraft *v, const AirportFTAClass *apc)
1736 /* we have left the previous block, and entered the new one. Free the previous block */
1737 if (apc->layout[v->previous_pos].block != apc->layout[v->pos].block) {
1738 Station *st = Station::Get(v->targetairport);
1740 CLRBITS(st->airport.flags, apc->layout[v->previous_pos].block);
1744 static void AirportGoToNextPosition(Aircraft *v)
1746 /* if aircraft is not in position, wait until it is */
1747 if (!AircraftController(v)) return;
1749 const AirportFTAClass *apc = Station::Get(v->targetairport)->airport.GetFTA();
1751 AirportClearBlock(v, apc);
1752 AirportMove(v, apc); // move aircraft to next position
1755 /* gets pos from vehicle and next orders */
1756 static bool AirportMove(Aircraft *v, const AirportFTAClass *apc)
1758 /* error handling */
1759 if (v->pos >= apc->nofelements) {
1760 DEBUG(misc, 0, "[Ap] position %d is not valid for current airport. Max position is %d", v->pos, apc->nofelements-1);
1761 assert(v->pos < apc->nofelements);
1764 const AirportFTA *current = &apc->layout[v->pos];
1765 /* we have arrived in an important state (eg terminal, hangar, etc.) */
1766 if (current->heading == v->state) {
1767 byte prev_pos = v->pos; // location could be changed in state, so save it before-hand
1768 byte prev_state = v->state;
1769 _aircraft_state_handlers[v->state](v, apc);
1770 if (v->state != FLYING) v->previous_pos = prev_pos;
1771 if (v->state != prev_state || v->pos != prev_pos) UpdateAircraftCache(v);
1772 return true;
1775 v->previous_pos = v->pos; // save previous location
1777 /* there is only one choice to move to */
1778 if (current->next == nullptr) {
1779 if (AirportSetBlocks(v, current, apc)) {
1780 v->pos = current->next_position;
1781 UpdateAircraftCache(v);
1782 } // move to next position
1783 return false;
1786 /* there are more choices to choose from, choose the one that
1787 * matches our heading */
1788 do {
1789 if (v->state == current->heading || current->heading == TO_ALL) {
1790 if (AirportSetBlocks(v, current, apc)) {
1791 v->pos = current->next_position;
1792 UpdateAircraftCache(v);
1793 } // move to next position
1794 return false;
1796 current = current->next;
1797 } while (current != nullptr);
1799 DEBUG(misc, 0, "[Ap] cannot move further on Airport! (pos %d state %d) for vehicle %d", v->pos, v->state, v->index);
1800 NOT_REACHED();
1803 /** returns true if the road ahead is busy, eg. you must wait before proceeding. */
1804 static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1806 const AirportFTA *reference = &apc->layout[v->pos];
1807 const AirportFTA *next = &apc->layout[current_pos->next_position];
1809 /* same block, then of course we can move */
1810 if (apc->layout[current_pos->position].block != next->block) {
1811 const Station *st = Station::Get(v->targetairport);
1812 uint64 airport_flags = next->block;
1814 /* check additional possible extra blocks */
1815 if (current_pos != reference && current_pos->block != NOTHING_block) {
1816 airport_flags |= current_pos->block;
1819 if (st->airport.flags & airport_flags) {
1820 v->cur_speed = 0;
1821 v->subspeed = 0;
1822 return true;
1825 return false;
1829 * "reserve" a block for the plane
1830 * @param v airplane that requires the operation
1831 * @param current_pos of the vehicle in the list of blocks
1832 * @param apc airport on which block is requested to be set
1833 * @returns true on success. Eg, next block was free and we have occupied it
1835 static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1837 const AirportFTA *next = &apc->layout[current_pos->next_position];
1838 const AirportFTA *reference = &apc->layout[v->pos];
1840 /* if the next position is in another block, check it and wait until it is free */
1841 if ((apc->layout[current_pos->position].block & next->block) != next->block) {
1842 uint64 airport_flags = next->block;
1843 /* search for all all elements in the list with the same state, and blocks != N
1844 * this means more blocks should be checked/set */
1845 const AirportFTA *current = current_pos;
1846 if (current == reference) current = current->next;
1847 while (current != nullptr) {
1848 if (current->heading == current_pos->heading && current->block != 0) {
1849 airport_flags |= current->block;
1850 break;
1852 current = current->next;
1855 /* if the block to be checked is in the next position, then exclude that from
1856 * checking, because it has been set by the airplane before */
1857 if (current_pos->block == next->block) airport_flags ^= next->block;
1859 Station *st = Station::Get(v->targetairport);
1860 if (st->airport.flags & airport_flags) {
1861 v->cur_speed = 0;
1862 v->subspeed = 0;
1863 return false;
1866 if (next->block != NOTHING_block) {
1867 SETBITS(st->airport.flags, airport_flags); // occupy next block
1870 return true;
1874 * Combination of aircraft state for going to a certain terminal and the
1875 * airport flag for that terminal block.
1877 struct MovementTerminalMapping {
1878 AirportMovementStates state; ///< Aircraft movement state when going to this terminal.
1879 uint64 airport_flag; ///< Bitmask in the airport flags that need to be free for this terminal.
1882 /** A list of all valid terminals and their associated blocks. */
1883 static const MovementTerminalMapping _airport_terminal_mapping[] = {
1884 {TERM1, TERM1_block},
1885 {TERM2, TERM2_block},
1886 {TERM3, TERM3_block},
1887 {TERM4, TERM4_block},
1888 {TERM5, TERM5_block},
1889 {TERM6, TERM6_block},
1890 {TERM7, TERM7_block},
1891 {TERM8, TERM8_block},
1892 {HELIPAD1, HELIPAD1_block},
1893 {HELIPAD2, HELIPAD2_block},
1894 {HELIPAD3, HELIPAD3_block},
1898 * Find a free terminal or helipad, and if available, assign it.
1899 * @param v Aircraft looking for a free terminal or helipad.
1900 * @param i First terminal to examine.
1901 * @param last_terminal Terminal number to stop examining.
1902 * @return A terminal or helipad has been found, and has been assigned to the aircraft.
1904 static bool FreeTerminal(Aircraft *v, byte i, byte last_terminal)
1906 assert(last_terminal <= lengthof(_airport_terminal_mapping));
1907 Station *st = Station::Get(v->targetairport);
1908 for (; i < last_terminal; i++) {
1909 if ((st->airport.flags & _airport_terminal_mapping[i].airport_flag) == 0) {
1910 /* TERMINAL# HELIPAD# */
1911 v->state = _airport_terminal_mapping[i].state; // start moving to that terminal/helipad
1912 SETBITS(st->airport.flags, _airport_terminal_mapping[i].airport_flag); // occupy terminal/helipad
1913 return true;
1916 return false;
1920 * Get the number of terminals at the airport.
1921 * @param apc Airport description.
1922 * @return Number of terminals.
1924 static uint GetNumTerminals(const AirportFTAClass *apc)
1926 uint num = 0;
1928 for (uint i = apc->terminals[0]; i > 0; i--) num += apc->terminals[i];
1930 return num;
1934 * Find a free terminal, and assign it if available.
1935 * @param v Aircraft to handle.
1936 * @param apc Airport state machine.
1937 * @return Found a free terminal and assigned it.
1939 static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc)
1941 /* example of more terminalgroups
1942 * {0,HANGAR,NOTHING_block,1}, {0,TERMGROUP,TERM_GROUP1_block,0}, {0,TERMGROUP,TERM_GROUP2_ENTER_block,1}, {0,0,N,1},
1943 * Heading TERMGROUP denotes a group. We see 2 groups here:
1944 * 1. group 0 -- TERM_GROUP1_block (check block)
1945 * 2. group 1 -- TERM_GROUP2_ENTER_block (check block)
1946 * First in line is checked first, group 0. If the block (TERM_GROUP1_block) is free, it
1947 * looks at the corresponding terminals of that group. If no free ones are found, other
1948 * possible groups are checked (in this case group 1, since that is after group 0). If that
1949 * fails, then attempt fails and plane waits
1951 if (apc->terminals[0] > 1) {
1952 const Station *st = Station::Get(v->targetairport);
1953 const AirportFTA *temp = apc->layout[v->pos].next;
1955 while (temp != nullptr) {
1956 if (temp->heading == TERMGROUP) {
1957 if (!(st->airport.flags & temp->block)) {
1958 /* read which group do we want to go to?
1959 * (the first free group) */
1960 uint target_group = temp->next_position + 1;
1962 /* at what terminal does the group start?
1963 * that means, sum up all terminals of
1964 * groups with lower number */
1965 uint group_start = 0;
1966 for (uint i = 1; i < target_group; i++) {
1967 group_start += apc->terminals[i];
1970 uint group_end = group_start + apc->terminals[target_group];
1971 if (FreeTerminal(v, group_start, group_end)) return true;
1973 } else {
1974 /* once the heading isn't 255, we've exhausted the possible blocks.
1975 * So we cannot move */
1976 return false;
1978 temp = temp->next;
1982 /* if there is only 1 terminalgroup, all terminals are checked (starting from 0 to max) */
1983 return FreeTerminal(v, 0, GetNumTerminals(apc));
1987 * Find a free helipad, and assign it if available.
1988 * @param v Aircraft to handle.
1989 * @param apc Airport state machine.
1990 * @return Found a free helipad and assigned it.
1992 static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc)
1994 /* if an airport doesn't have helipads, use terminals */
1995 if (apc->num_helipads == 0) return AirportFindFreeTerminal(v, apc);
1997 /* only 1 helicoptergroup, check all helipads
1998 * The blocks for helipads start after the last terminal (MAX_TERMINALS) */
1999 return FreeTerminal(v, MAX_TERMINALS, apc->num_helipads + MAX_TERMINALS);
2003 * Handle the 'dest too far' flag and the corresponding news message for aircraft.
2004 * @param v The aircraft.
2005 * @param too_far True if the current destination is too far away.
2007 static void AircraftHandleDestTooFar(Aircraft *v, bool too_far)
2009 if (too_far) {
2010 if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) {
2011 SetBit(v->flags, VAF_DEST_TOO_FAR);
2012 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2013 AI::NewEvent(v->owner, new ScriptEventAircraftDestTooFar(v->index));
2014 if (v->owner == _local_company) {
2015 /* Post a news message. */
2016 SetDParam(0, v->index);
2017 AddVehicleAdviceNewsItem(STR_NEWS_AIRCRAFT_DEST_TOO_FAR, v->index);
2020 return;
2023 if (HasBit(v->flags, VAF_DEST_TOO_FAR)) {
2024 /* Not too far anymore, clear flag and message. */
2025 ClrBit(v->flags, VAF_DEST_TOO_FAR);
2026 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2027 DeleteVehicleNews(v->index, STR_NEWS_AIRCRAFT_DEST_TOO_FAR);
2031 static bool AircraftEventHandler(Aircraft *v, int loop)
2033 if (v->vehstatus & VS_CRASHED) {
2034 return HandleCrashedAircraft(v);
2037 if (v->vehstatus & VS_STOPPED) return true;
2039 v->HandleBreakdown();
2041 HandleAircraftSmoke(v, loop != 0);
2042 ProcessOrders(v);
2043 v->HandleLoading(loop != 0);
2045 if (v->current_order.IsType(OT_LOADING) || v->current_order.IsType(OT_LEAVESTATION)) return true;
2047 if (v->state >= ENDTAKEOFF && v->state <= HELIENDLANDING) {
2048 /* If we are flying, unconditionally clear the 'dest too far' state. */
2049 AircraftHandleDestTooFar(v, false);
2050 } else if (v->acache.cached_max_range_sqr != 0) {
2051 /* Check the distance to the next destination. This code works because the target
2052 * airport is only updated after take off and not on the ground. */
2053 Station *cur_st = Station::GetIfValid(v->targetairport);
2054 Station *next_st = v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT) ? Station::GetIfValid(v->current_order.GetDestination()) : nullptr;
2056 if (cur_st != nullptr && cur_st->airport.tile != INVALID_TILE && next_st != nullptr && next_st->airport.tile != INVALID_TILE) {
2057 uint dist = DistanceSquare(cur_st->airport.tile, next_st->airport.tile);
2058 AircraftHandleDestTooFar(v, dist > v->acache.cached_max_range_sqr);
2062 if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) AirportGoToNextPosition(v);
2064 return true;
2067 bool Aircraft::Tick()
2069 if (!this->IsNormalAircraft()) return true;
2071 PerformanceAccumulator framerate(PFE_GL_AIRCRAFT);
2073 this->tick_counter++;
2075 if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
2077 if (this->subtype == AIR_HELICOPTER) HelicopterTickHandler(this);
2079 this->current_order_time++;
2081 for (uint i = 0; i != 2; i++) {
2082 /* stop if the aircraft was deleted */
2083 if (!AircraftEventHandler(this, i)) return false;
2086 return true;
2091 * Returns aircraft's target station if v->target_airport
2092 * is a valid station with airport.
2093 * @param v vehicle to get target airport for
2094 * @return pointer to target station, nullptr if invalid
2096 Station *GetTargetAirportIfValid(const Aircraft *v)
2098 assert(v->type == VEH_AIRCRAFT);
2100 Station *st = Station::GetIfValid(v->targetairport);
2101 if (st == nullptr) return nullptr;
2103 return st->airport.tile == INVALID_TILE ? nullptr : st;
2107 * Updates the status of the Aircraft heading or in the station
2108 * @param st Station been updated
2110 void UpdateAirplanesOnNewStation(const Station *st)
2112 /* only 1 station is updated per function call, so it is enough to get entry_point once */
2113 const AirportFTAClass *ap = st->airport.GetFTA();
2114 Direction rotation = st->airport.tile == INVALID_TILE ? DIR_N : st->airport.rotation;
2116 for (Aircraft *v : Aircraft::Iterate()) {
2117 if (!v->IsNormalAircraft() || v->targetairport != st->index) continue;
2118 assert(v->state == FLYING);
2120 Order *o = &v->current_order;
2121 /* The aircraft is heading to a hangar, but the new station doesn't have one,
2122 * or the aircraft can't land on the new station. Cancel current order. */
2123 if (o->IsType(OT_GOTO_DEPOT) && !(o->GetDepotOrderType() & ODTFB_PART_OF_ORDERS) && o->GetDestination() == st->index &&
2124 (!st->airport.HasHangar() || !CanVehicleUseStation(v, st))) {
2125 o->MakeDummy();
2126 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2128 v->pos = v->previous_pos = AircraftGetEntryPoint(v, ap, rotation);
2129 UpdateAircraftCache(v);
2132 /* Heliports don't have a hangar. Invalidate all go to hangar orders from all aircraft. */
2133 if (!st->airport.HasHangar()) RemoveOrderFromAllVehicles(OT_GOTO_DEPOT, st->index, true);