Extend object variable 0x60 to also return the view
[openttd/fttd.git] / src / aircraft_cmd.cpp
blobdaf389893c002524b94338b241e319523b1622ff
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /**
11 * @file aircraft_cmd.cpp
12 * This file deals with aircraft and airport movements functionalities
15 #include "stdafx.h"
16 #include "aircraft.h"
17 #include "landscape.h"
18 #include "news_func.h"
19 #include "newgrf_engine.h"
20 #include "newgrf_sound.h"
21 #include "spritecache.h"
22 #include "strings_func.h"
23 #include "command_func.h"
24 #include "window_func.h"
25 #include "date_func.h"
26 #include "vehicle_func.h"
27 #include "sound_func.h"
28 #include "cheat_type.h"
29 #include "company_base.h"
30 #include "ai/ai.hpp"
31 #include "game/game.hpp"
32 #include "company_func.h"
33 #include "effectvehicle_func.h"
34 #include "station_base.h"
35 #include "engine_base.h"
36 #include "core/random_func.hpp"
37 #include "core/backup_type.hpp"
38 #include "zoom_func.h"
40 #include "table/strings.h"
42 static const int ROTOR_Z_OFFSET = 5; ///< Z Offset between helicopter- and rotorsprite.
44 static const int PLANE_HOLDING_ALTITUDE = 150; ///< Altitude of planes in holding pattern (= lowest flight altitude).
45 static const int HELI_FLIGHT_ALTITUDE = 184; ///< Normal flight altitude of helicopters.
48 void Aircraft::UpdateDeltaXY(Direction direction)
50 this->x_offs = -1;
51 this->y_offs = -1;
52 this->x_extent = 2;
53 this->y_extent = 2;
55 switch (this->subtype) {
56 default: NOT_REACHED();
58 case AIR_AIRCRAFT:
59 case AIR_HELICOPTER:
60 switch (this->state) {
61 default: break;
62 case ENDTAKEOFF:
63 case LANDING:
64 case HELILANDING:
65 case FLYING:
66 this->x_extent = 24;
67 this->y_extent = 24;
68 break;
70 this->z_extent = 5;
71 break;
73 case AIR_SHADOW:
74 this->z_extent = 1;
75 this->x_offs = 0;
76 this->y_offs = 0;
77 break;
79 case AIR_ROTOR:
80 this->z_extent = 1;
81 break;
85 static bool AirportMove(Aircraft *v, const AirportFTAClass *apc);
86 static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
87 static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc);
88 static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc);
89 static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc);
90 static void CrashAirplane(Aircraft *v);
92 static const SpriteID _aircraft_sprite[] = {
93 0x0EB5, 0x0EBD, 0x0EC5, 0x0ECD,
94 0x0ED5, 0x0EDD, 0x0E9D, 0x0EA5,
95 0x0EAD, 0x0EE5, 0x0F05, 0x0F0D,
96 0x0F15, 0x0F1D, 0x0F25, 0x0F2D,
97 0x0EED, 0x0EF5, 0x0EFD, 0x0F35,
98 0x0E9D, 0x0EA5, 0x0EAD, 0x0EB5,
99 0x0EBD, 0x0EC5
102 template <>
103 bool IsValidImageIndex<VEH_AIRCRAFT>(uint8 image_index)
105 return image_index < lengthof(_aircraft_sprite);
108 /** Helicopter rotor animation states */
109 enum HelicopterRotorStates {
110 HRS_ROTOR_STOPPED,
111 HRS_ROTOR_MOVING_1,
112 HRS_ROTOR_MOVING_2,
113 HRS_ROTOR_MOVING_3,
117 * Find the nearest hangar to v
118 * INVALID_STATION is returned, if the company does not have any suitable
119 * airports (like helipads only)
120 * @param v vehicle looking for a hangar
121 * @return the StationID if one is found, otherwise, INVALID_STATION
123 static StationID FindNearestHangar(const Aircraft *v)
125 const Station *st;
126 uint best = 0;
127 StationID index = INVALID_STATION;
128 TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
129 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
131 FOR_ALL_STATIONS(st) {
132 if (st->owner != v->owner || !(st->facilities & FACIL_AIRPORT)) continue;
134 const AirportFTAClass *afc = st->airport.GetFTA();
135 if (!st->airport.HasHangar() || (
136 /* don't crash the plane if we know it can't land at the airport */
137 (afc->flags & AirportFTAClass::SHORT_STRIP) &&
138 (avi->subtype & AIR_FAST) &&
139 !_cheats.no_jetcrash.value)) {
140 continue;
143 /* v->tile can't be used here, when aircraft is flying v->tile is set to 0 */
144 uint distance = DistanceSquare(vtile, st->airport.tile);
145 if (v->acache.cached_max_range_sqr != 0) {
146 /* Check if our current destination can be reached from the depot airport. */
147 const Station *cur_dest = GetTargetAirportIfValid(v);
148 if (cur_dest != NULL && DistanceSquare(st->airport.tile, cur_dest->airport.tile) > v->acache.cached_max_range_sqr) continue;
150 if (distance < best || index == INVALID_STATION) {
151 best = distance;
152 index = st->index;
155 return index;
158 SpriteID Aircraft::GetImage(Direction direction, EngineImageType image_type) const
160 uint8 spritenum = this->spritenum;
162 if (is_custom_sprite(spritenum)) {
163 SpriteID sprite = GetCustomVehicleSprite(this, direction, image_type);
164 if (sprite != 0) return sprite;
166 spritenum = this->GetEngine()->original_image_index;
169 assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
170 return direction + _aircraft_sprite[spritenum];
173 SpriteID GetRotorImage(const Aircraft *v, EngineImageType image_type)
175 assert(v->subtype == AIR_HELICOPTER);
177 const Aircraft *w = v->Next()->Next();
178 if (is_custom_sprite(v->spritenum)) {
179 SpriteID sprite = GetCustomRotorSprite(v, false, image_type);
180 if (sprite != 0) return sprite;
183 /* Return standard rotor sprites if there are no custom sprites for this helicopter */
184 return SPR_ROTOR_STOPPED + w->state;
187 static SpriteID GetAircraftIcon(EngineID engine, EngineImageType image_type)
189 const Engine *e = Engine::Get(engine);
190 uint8 spritenum = e->u.air.image_index;
192 if (is_custom_sprite(spritenum)) {
193 SpriteID sprite = GetCustomVehicleIcon(engine, DIR_W, image_type);
194 if (sprite != 0) return sprite;
196 spritenum = e->original_image_index;
199 assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
200 return DIR_W + _aircraft_sprite[spritenum];
203 void DrawAircraftEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
205 SpriteID sprite = GetAircraftIcon(engine, image_type);
206 const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
207 preferred_x = Clamp(preferred_x, left - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI), right - UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI) - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI));
208 DrawSprite(sprite, pal, preferred_x, y);
210 if (!(AircraftVehInfo(engine)->subtype & AIR_CTOL)) {
211 SpriteID rotor_sprite = GetCustomRotorIcon(engine, image_type);
212 if (rotor_sprite == 0) rotor_sprite = SPR_ROTOR_STOPPED;
213 DrawSprite(rotor_sprite, PAL_NONE, preferred_x, y - 5);
218 * Get the size of the sprite of an aircraft sprite heading west (used for lists).
219 * @param engine The engine to get the sprite from.
220 * @param[out] width The width of the sprite.
221 * @param[out] height The height of the sprite.
222 * @param[out] xoffs Number of pixels to shift the sprite to the right.
223 * @param[out] yoffs Number of pixels to shift the sprite downwards.
224 * @param image_type Context the sprite is used in.
226 void GetAircraftSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
228 const Sprite *spr = GetSprite(GetAircraftIcon(engine, image_type), ST_NORMAL);
230 width = UnScaleByZoom(spr->width, ZOOM_LVL_GUI);
231 height = UnScaleByZoom(spr->height, ZOOM_LVL_GUI);
232 xoffs = UnScaleByZoom(spr->x_offs, ZOOM_LVL_GUI);
233 yoffs = UnScaleByZoom(spr->y_offs, ZOOM_LVL_GUI);
237 * Build an aircraft.
238 * @param tile tile of the depot where aircraft is built.
239 * @param flags type of operation.
240 * @param e the engine to build.
241 * @param data unused.
242 * @param ret[out] the vehicle that has been built.
243 * @return the cost of this operation or an error.
245 CommandCost CmdBuildAircraft(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
247 const AircraftVehicleInfo *avi = &e->u.air;
248 const Station *st = Station::GetByTile(tile);
250 /* Prevent building aircraft types at places which can't handle them */
251 if (!CanVehicleUseStation(e->index, st)) return CMD_ERROR;
253 /* Make sure all aircraft end up in the first tile of the hangar. */
254 tile = st->airport.GetHangarTile(st->airport.GetHangarNum(tile));
256 if (flags & DC_EXEC) {
257 Aircraft *v = new Aircraft(); // aircraft
258 Aircraft *u = new Aircraft(); // shadow
259 *ret = v;
261 v->direction = DIR_SE;
263 v->owner = u->owner = _current_company;
265 v->tile = tile;
267 uint x = TileX(tile) * TILE_SIZE + 5;
268 uint y = TileY(tile) * TILE_SIZE + 3;
270 v->x_pos = u->x_pos = x;
271 v->y_pos = u->y_pos = y;
273 u->z_pos = GetSlopePixelZ(x, y);
274 v->z_pos = u->z_pos + 1;
276 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
277 u->vehstatus = VS_HIDDEN | VS_UNCLICKABLE | VS_SHADOW;
279 v->spritenum = avi->image_index;
281 v->cargo_cap = avi->passenger_capacity;
282 v->refit_cap = 0;
283 u->cargo_cap = avi->mail_capacity;
284 u->refit_cap = 0;
286 v->cargo_type = e->GetDefaultCargoType();
287 u->cargo_type = CT_MAIL;
289 v->name = NULL;
290 v->last_station_visited = INVALID_STATION;
291 v->last_loading_station = INVALID_STATION;
293 v->acceleration = avi->acceleration;
294 v->engine_type = e->index;
295 u->engine_type = e->index;
297 v->subtype = (avi->subtype & AIR_CTOL ? AIR_AIRCRAFT : AIR_HELICOPTER);
298 v->UpdateDeltaXY(INVALID_DIR);
300 u->subtype = AIR_SHADOW;
301 u->UpdateDeltaXY(INVALID_DIR);
303 v->reliability = e->reliability;
304 v->reliability_spd_dec = e->reliability_spd_dec;
305 v->max_age = e->GetLifeLengthInDays();
307 _new_vehicle_id = v->index;
309 v->pos = GetVehiclePosOnBuild(tile);
311 v->state = HANGAR;
312 v->previous_pos = v->pos;
313 v->targetairport = GetStationIndex(tile);
314 v->SetNext(u);
316 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_aircraft);
318 v->date_of_last_service = _date;
319 v->build_year = u->build_year = _cur_year;
321 v->cur_image = u->cur_image = SPR_IMG_QUERY;
323 v->random_bits = VehicleRandomBits();
324 u->random_bits = VehicleRandomBits();
326 v->vehicle_flags = 0;
327 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
328 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
330 v->InvalidateNewGRFCacheOfChain();
332 v->cargo_cap = e->DetermineCapacity(v, &u->cargo_cap);
334 v->InvalidateNewGRFCacheOfChain();
336 UpdateAircraftCache(v, true);
338 VehicleUpdatePosition(v);
339 VehicleUpdatePosition(u);
341 /* Aircraft with 3 vehicles (chopper)? */
342 if (v->subtype == AIR_HELICOPTER) {
343 Aircraft *w = new Aircraft();
344 w->engine_type = e->index;
345 w->direction = DIR_N;
346 w->owner = _current_company;
347 w->x_pos = v->x_pos;
348 w->y_pos = v->y_pos;
349 w->z_pos = v->z_pos + ROTOR_Z_OFFSET;
350 w->vehstatus = VS_HIDDEN | VS_UNCLICKABLE;
351 w->spritenum = 0xFF;
352 w->subtype = AIR_ROTOR;
353 w->cur_image = SPR_ROTOR_STOPPED;
354 w->random_bits = VehicleRandomBits();
355 /* Use rotor's air.state to store the rotor animation frame */
356 w->state = HRS_ROTOR_STOPPED;
357 w->UpdateDeltaXY(INVALID_DIR);
359 u->SetNext(w);
360 VehicleUpdatePosition(w);
364 return CommandCost();
368 bool Aircraft::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
370 const Station *st = GetTargetAirportIfValid(this);
371 /* If the station is not a valid airport or if it has no hangars */
372 if (st == NULL || !st->airport.HasHangar()) {
373 /* the aircraft has to search for a hangar on its own */
374 StationID station = FindNearestHangar(this);
376 if (station == INVALID_STATION) return false;
378 st = Station::Get(station);
381 if (location != NULL) *location = st->xy;
382 if (destination != NULL) *destination = st->index;
384 return true;
387 static void CheckIfAircraftNeedsService(Aircraft *v)
389 if (Company::Get(v->owner)->settings.vehicle.servint_aircraft == 0 || !v->NeedsAutomaticServicing()) return;
390 if (v->IsChainInDepot()) {
391 VehicleServiceInDepot(v);
392 return;
395 /* When we're parsing conditional orders and the like
396 * we don't want to consider going to a depot too. */
397 if (!v->current_order.IsType(OT_GOTO_DEPOT) && !v->current_order.IsType(OT_GOTO_STATION)) return;
399 const Station *st = Station::Get(v->current_order.GetDestination());
401 assert(st != NULL);
403 /* only goto depot if the target airport has a depot */
404 if (st->airport.HasHangar() && CanVehicleUseStation(v, st)) {
405 v->current_order.MakeGoToDepot(st->index, ODTFB_SERVICE);
406 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
407 } else if (v->current_order.IsType(OT_GOTO_DEPOT)) {
408 v->current_order.MakeDummy();
409 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
413 Money Aircraft::GetRunningCost() const
415 const Engine *e = this->GetEngine();
416 uint cost_factor = GetVehicleProperty(this, PROP_AIRCRAFT_RUNNING_COST_FACTOR, e->u.air.running_cost);
417 return GetPrice(PR_RUNNING_AIRCRAFT, cost_factor, e->GetGRF());
420 void Aircraft::OnNewDay()
422 if (!this->IsNormalAircraft()) return;
424 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
426 CheckOrders(this);
428 CheckVehicleBreakdown(this);
429 AgeVehicle(this);
430 CheckIfAircraftNeedsService(this);
432 if (this->running_ticks == 0) return;
434 CommandCost cost(EXPENSES_AIRCRAFT_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
436 this->profit_this_year -= cost.GetCost();
437 this->running_ticks = 0;
439 SubtractMoneyFromCompanyFract(this->owner, cost);
441 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
442 SetWindowClassesDirty(WC_AIRCRAFT_LIST);
445 static void HelicopterTickHandler(Aircraft *v)
447 Aircraft *u = v->Next()->Next();
449 if (u->vehstatus & VS_HIDDEN) return;
451 /* if true, helicopter rotors do not rotate. This should only be the case if a helicopter is
452 * loading/unloading at a terminal or stopped */
453 if (v->current_order.IsType(OT_LOADING) || (v->vehstatus & VS_STOPPED)) {
454 if (u->cur_speed != 0) {
455 u->cur_speed++;
456 if (u->cur_speed >= 0x80 && u->state == HRS_ROTOR_MOVING_3) {
457 u->cur_speed = 0;
460 } else {
461 if (u->cur_speed == 0) {
462 u->cur_speed = 0x70;
464 if (u->cur_speed >= 0x50) {
465 u->cur_speed--;
469 int tick = ++u->tick_counter;
470 int spd = u->cur_speed >> 4;
472 SpriteID img;
473 if (spd == 0) {
474 u->state = HRS_ROTOR_STOPPED;
475 img = GetRotorImage(v, EIT_ON_MAP);
476 if (u->cur_image == img) return;
477 } else if (tick >= spd) {
478 u->tick_counter = 0;
479 u->state++;
480 if (u->state > HRS_ROTOR_MOVING_3) u->state = HRS_ROTOR_MOVING_1;
481 img = GetRotorImage(v, EIT_ON_MAP);
482 } else {
483 return;
486 u->cur_image = img;
488 VehicleUpdatePositionAndViewport(u);
492 * Set aircraft position.
493 * @param v Aircraft to position.
494 * @param x New X position.
495 * @param y New y position.
496 * @param z New z position.
498 void SetAircraftPosition(Aircraft *v, int x, int y, int z)
500 v->x_pos = x;
501 v->y_pos = y;
502 v->z_pos = z;
504 VehicleUpdatePosition(v);
505 v->UpdateViewport(true, false);
506 if (v->subtype == AIR_HELICOPTER) v->Next()->Next()->cur_image = GetRotorImage(v, EIT_ON_MAP);
508 Aircraft *u = v->Next();
510 int safe_x = Clamp(x, 0, MapMaxX() * TILE_SIZE);
511 int safe_y = Clamp(y - 1, 0, MapMaxY() * TILE_SIZE);
512 u->x_pos = x;
513 u->y_pos = y - ((v->z_pos - GetSlopePixelZ(safe_x, safe_y)) >> 3);
515 safe_y = Clamp(u->y_pos, 0, MapMaxY() * TILE_SIZE);
516 u->z_pos = GetSlopePixelZ(safe_x, safe_y);
517 u->cur_image = v->cur_image;
519 VehicleUpdatePositionAndViewport(u);
521 u = u->Next();
522 if (u != NULL) {
523 u->x_pos = x;
524 u->y_pos = y;
525 u->z_pos = z + ROTOR_Z_OFFSET;
527 VehicleUpdatePositionAndViewport(u);
532 * Handle Aircraft specific tasks when an Aircraft enters a hangar
533 * @param *v Vehicle that enters the hangar
535 void HandleAircraftEnterHangar(Aircraft *v)
537 v->subspeed = 0;
538 v->progress = 0;
540 Aircraft *u = v->Next();
541 u->vehstatus |= VS_HIDDEN;
542 u = u->Next();
543 if (u != NULL) {
544 u->vehstatus |= VS_HIDDEN;
545 u->cur_speed = 0;
548 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
551 static void PlayAircraftSound(const Vehicle *v)
553 if (!PlayVehicleSound(v, VSE_START)) {
554 SndPlayVehicleFx(AircraftVehInfo(v->engine_type)->sfx, v);
560 * Update cached values of an aircraft.
561 * Currently caches callback 36 max speed.
562 * @param v Vehicle
563 * @param update_range Update the aircraft range.
565 void UpdateAircraftCache(Aircraft *v, bool update_range)
567 uint max_speed = GetVehicleProperty(v, PROP_AIRCRAFT_SPEED, 0);
568 if (max_speed != 0) {
569 /* Convert from original units to km-ish/h */
570 max_speed = (max_speed * 128) / 10;
572 v->vcache.cached_max_speed = max_speed;
573 } else {
574 /* Use the default max speed of the vehicle. */
575 v->vcache.cached_max_speed = AircraftVehInfo(v->engine_type)->max_speed;
578 /* Update cargo aging period. */
579 v->vcache.cached_cargo_age_period = GetVehicleProperty(v, PROP_AIRCRAFT_CARGO_AGE_PERIOD, EngInfo(v->engine_type)->cargo_age_period);
580 Aircraft *u = v->Next(); // Shadow for mail
581 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_AIRCRAFT_CARGO_AGE_PERIOD, EngInfo(u->engine_type)->cargo_age_period);
583 /* Update aircraft range. */
584 if (update_range) {
585 v->acache.cached_max_range = GetVehicleProperty(v, PROP_AIRCRAFT_RANGE, AircraftVehInfo(v->engine_type)->max_range);
586 /* Squared it now so we don't have to do it later all the time. */
587 v->acache.cached_max_range_sqr = v->acache.cached_max_range * v->acache.cached_max_range;
593 * Special velocities for aircraft
595 enum AircraftSpeedLimits {
596 SPEED_LIMIT_TAXI = 50, ///< Maximum speed of an aircraft while taxiing
597 SPEED_LIMIT_APPROACH = 230, ///< Maximum speed of an aircraft on finals
598 SPEED_LIMIT_BROKEN = 320, ///< Maximum speed of an aircraft that is broken
599 SPEED_LIMIT_HOLD = 425, ///< Maximum speed of an aircraft that flies the holding pattern
600 SPEED_LIMIT_NONE = 0xFFFF, ///< No environmental speed limit. Speed limit is type dependent
604 * Sets the new speed for an aircraft
605 * @param v The vehicle for which the speed should be obtained
606 * @param speed_limit The maximum speed the vehicle may have.
607 * @param hard_limit If true, the limit is directly enforced, otherwise the plane is slowed down gradually
608 * @return The number of position updates needed within the tick
610 static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE, bool hard_limit = true)
613 * 'acceleration' has the unit 3/8 mph/tick. This function is called twice per tick.
614 * So the speed amount we need to accelerate is:
615 * acceleration * 3 / 16 mph = acceleration * 3 / 16 * 16 / 10 km-ish/h
616 * = acceleration * 3 / 10 * 256 * (km-ish/h / 256)
617 * ~ acceleration * 77 (km-ish/h / 256)
619 uint spd = v->acceleration * 77;
620 byte t;
622 /* Adjust speed limits by plane speed factor to prevent taxiing
623 * and take-off speeds being too low. */
624 speed_limit *= _settings_game.vehicle.plane_speed;
626 if (v->vcache.cached_max_speed < speed_limit) {
627 if (v->cur_speed < speed_limit) hard_limit = false;
628 speed_limit = v->vcache.cached_max_speed;
631 v->subspeed = (t = v->subspeed) + (byte)spd;
633 /* Aircraft's current speed is used twice so that very fast planes are
634 * forced to slow down rapidly in the short distance needed. The magic
635 * value 16384 was determined to give similar results to the old speed/48
636 * method at slower speeds. This also results in less reduction at slow
637 * speeds to that aircraft do not get to taxi speed straight after
638 * touchdown. */
639 if (!hard_limit && v->cur_speed > speed_limit) {
640 speed_limit = v->cur_speed - max(1, ((v->cur_speed * v->cur_speed) / 16384) / _settings_game.vehicle.plane_speed);
643 spd = min(v->cur_speed + (spd >> 8) + (v->subspeed < t), speed_limit);
645 /* adjust speed for broken vehicles */
646 if (v->vehstatus & VS_AIRCRAFT_BROKEN) spd = min(spd, SPEED_LIMIT_BROKEN);
648 /* updates statusbar only if speed have changed to save CPU time */
649 if (spd != v->cur_speed) {
650 v->cur_speed = spd;
651 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
654 /* Adjust distance moved by plane speed setting */
655 if (_settings_game.vehicle.plane_speed > 1) spd /= _settings_game.vehicle.plane_speed;
657 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
658 spd = v->GetOldAdvanceSpeed(spd);
660 spd += v->progress;
661 v->progress = (byte)spd;
662 return spd >> 8;
666 * Gets the cruise altitude of an aircraft.
667 * The cruise altitude is determined by the velocity of the vehicle
668 * and the direction it is moving
669 * @param v The vehicle. Should be an aircraft
670 * @returns Altitude in pixel units
672 int GetAircraftFlyingAltitude(const Aircraft *v)
674 if (v->subtype == AIR_HELICOPTER) return HELI_FLIGHT_ALTITUDE;
676 /* Make sure Aircraft fly no lower so that they don't conduct
677 * CFITs (controlled flight into terrain)
679 int base_altitude = PLANE_HOLDING_ALTITUDE;
681 /* Make sure eastbound and westbound planes do not "crash" into each
682 * other by providing them with vertical separation
684 switch (v->direction) {
685 case DIR_N:
686 case DIR_NE:
687 case DIR_E:
688 case DIR_SE:
689 base_altitude += 10;
690 break;
692 default: break;
695 /* Make faster planes fly higher so that they can overtake slower ones */
696 base_altitude += min(20 * (v->vcache.cached_max_speed / 200), 90);
698 return base_altitude;
702 * Find the entry point to an airport depending on direction which
703 * the airport is being approached from. Each airport can have up to
704 * four entry points for its approach system so that approaching
705 * aircraft do not fly through each other or are forced to do 180
706 * degree turns during the approach. The arrivals are grouped into
707 * four sectors dependent on the DiagDirection from which the airport
708 * is approached.
710 * @param v The vehicle that is approaching the airport
711 * @param apc The Airport Class being approached.
712 * @param rotation The rotation of the airport.
713 * @returns The index of the entry point
715 static byte AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc, Direction rotation)
717 assert(v != NULL);
718 assert(apc != NULL);
720 /* In the case the station doesn't exit anymore, set target tile 0.
721 * It doesn't hurt much, aircraft will go to next order, nearest hangar
722 * or it will simply crash in next tick */
723 TileIndex tile = 0;
725 const Station *st = Station::GetIfValid(v->targetairport);
726 if (st != NULL) {
727 /* Make sure we don't go to INVALID_TILE if the airport has been removed. */
728 tile = (st->airport.tile != INVALID_TILE) ? st->airport.tile : st->xy;
731 int delta_x = v->x_pos - TileX(tile) * TILE_SIZE;
732 int delta_y = v->y_pos - TileY(tile) * TILE_SIZE;
734 DiagDirection dir;
735 if (abs(delta_y) < abs(delta_x)) {
736 /* We are northeast or southwest of the airport */
737 dir = delta_x < 0 ? DIAGDIR_NE : DIAGDIR_SW;
738 } else {
739 /* We are northwest or southeast of the airport */
740 dir = delta_y < 0 ? DIAGDIR_NW : DIAGDIR_SE;
742 dir = ChangeDiagDir(dir, (DiagDirDiff)ReverseDiagDir(DirToDiagDir(rotation)));
743 return apc->entry_points[dir];
747 static void MaybeCrashAirplane(Aircraft *v);
750 * Controls the movement of an aircraft. This function actually moves the vehicle
751 * on the map and takes care of minor things like sound playback.
752 * @todo De-mystify the cur_speed values for helicopter rotors.
753 * @param v The vehicle that is moved. Must be the first vehicle of the chain
754 * @return Whether the position requested by the State Machine has been reached
756 static bool AircraftController(Aircraft *v)
758 int count;
760 /* NULL if station is invalid */
761 const Station *st = Station::GetIfValid(v->targetairport);
762 /* INVALID_TILE if there is no station */
763 TileIndex tile = INVALID_TILE;
764 Direction rotation = DIR_N;
765 uint size_x = 1, size_y = 1;
766 if (st != NULL) {
767 if (st->airport.tile != INVALID_TILE) {
768 tile = st->airport.tile;
769 rotation = st->airport.rotation;
770 size_x = st->airport.w;
771 size_y = st->airport.h;
772 } else {
773 tile = st->xy;
776 /* DUMMY if there is no station or no airport */
777 const AirportFTAClass *afc = tile == INVALID_TILE ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
779 /* prevent going to INVALID_TILE if airport is deleted. */
780 if (st == NULL || st->airport.tile == INVALID_TILE) {
781 /* Jump into our "holding pattern" state machine if possible */
782 if (v->pos >= afc->nofelements) {
783 v->pos = v->previous_pos = AircraftGetEntryPoint(v, afc, DIR_N);
784 } else if (v->targetairport != v->current_order.GetDestination()) {
785 /* If not possible, just get out of here fast */
786 v->state = FLYING;
787 UpdateAircraftCache(v);
788 AircraftNextAirportPos_and_Order(v);
789 /* get aircraft back on running altitude */
790 SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlyingAltitude(v));
791 return false;
795 /* get airport moving data */
796 const AirportMovingData amd = RotateAirportMovingData(afc->MovingData(v->pos), rotation, size_x, size_y);
798 int x = TileX(tile) * TILE_SIZE;
799 int y = TileY(tile) * TILE_SIZE;
801 /* Helicopter raise */
802 if (amd.flag & AMED_HELI_RAISE) {
803 Aircraft *u = v->Next()->Next();
805 /* Make sure the rotors don't rotate too fast */
806 if (u->cur_speed > 32) {
807 v->cur_speed = 0;
808 if (--u->cur_speed == 32) {
809 if (!PlayVehicleSound(v, VSE_START)) {
810 SndPlayVehicleFx(SND_18_HELICOPTER, v);
813 } else {
814 u->cur_speed = 32;
815 count = UpdateAircraftSpeed(v);
816 if (count > 0) {
817 v->tile = 0;
818 int z_dest = GetAircraftFlyingAltitude(v);
820 /* Reached altitude? */
821 if (v->z_pos >= z_dest) {
822 v->cur_speed = 0;
823 return true;
825 SetAircraftPosition(v, v->x_pos, v->y_pos, min(v->z_pos + count, z_dest));
828 return false;
831 /* Helicopter landing. */
832 if (amd.flag & AMED_HELI_LOWER) {
833 if (st == NULL) {
834 /* FIXME - AircraftController -> if station no longer exists, do not land
835 * helicopter will circle until sign disappears, then go to next order
836 * what to do when it is the only order left, right now it just stays in 1 place */
837 v->state = FLYING;
838 UpdateAircraftCache(v);
839 AircraftNextAirportPos_and_Order(v);
840 return false;
843 /* Vehicle is now at the airport. */
844 v->tile = tile;
846 /* Find altitude of landing position. */
847 int z = GetSlopePixelZ(x, y) + 1 + afc->delta_z;
849 if (z == v->z_pos) {
850 Vehicle *u = v->Next()->Next();
852 /* Increase speed of rotors. When speed is 80, we've landed. */
853 if (u->cur_speed >= 80) return true;
854 u->cur_speed += 4;
855 } else {
856 count = UpdateAircraftSpeed(v);
857 if (count > 0) {
858 if (v->z_pos > z) {
859 SetAircraftPosition(v, v->x_pos, v->y_pos, max(v->z_pos - count, z));
860 } else {
861 SetAircraftPosition(v, v->x_pos, v->y_pos, min(v->z_pos + count, z));
865 return false;
868 /* Get distance from destination pos to current pos. */
869 uint dist = abs(x + amd.x - v->x_pos) + abs(y + amd.y - v->y_pos);
871 /* Need exact position? */
872 if (!(amd.flag & AMED_EXACTPOS) && dist <= (amd.flag & AMED_SLOWTURN ? 8U : 4U)) return true;
874 /* At final pos? */
875 if (dist == 0) {
876 /* Change direction smoothly to final direction. */
877 DirDiff dirdiff = DirDifference(amd.direction, v->direction);
878 /* if distance is 0, and plane points in right direction, no point in calling
879 * UpdateAircraftSpeed(). So do it only afterwards */
880 if (dirdiff == DIRDIFF_SAME) {
881 v->cur_speed = 0;
882 return true;
885 if (!UpdateAircraftSpeed(v, SPEED_LIMIT_TAXI)) return false;
887 v->direction = ChangeDir(v->direction, dirdiff > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
888 v->cur_speed >>= 1;
890 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
891 return false;
894 if (amd.flag & AMED_BRAKE && v->cur_speed > SPEED_LIMIT_TAXI * _settings_game.vehicle.plane_speed) {
895 MaybeCrashAirplane(v);
896 if ((v->vehstatus & VS_CRASHED) != 0) return false;
899 uint speed_limit = SPEED_LIMIT_TAXI;
900 bool hard_limit = true;
902 if (amd.flag & AMED_NOSPDCLAMP) speed_limit = SPEED_LIMIT_NONE;
903 if (amd.flag & AMED_HOLD) { speed_limit = SPEED_LIMIT_HOLD; hard_limit = false; }
904 if (amd.flag & AMED_LAND) { speed_limit = SPEED_LIMIT_APPROACH; hard_limit = false; }
905 if (amd.flag & AMED_BRAKE) { speed_limit = SPEED_LIMIT_TAXI; hard_limit = false; }
907 count = UpdateAircraftSpeed(v, speed_limit, hard_limit);
908 if (count == 0) return false;
910 if (v->turn_counter != 0) v->turn_counter--;
912 do {
914 VehiclePos gp;
916 if (dist < 4 || (amd.flag & AMED_LAND)) {
917 /* move vehicle one pixel towards target */
918 gp.x = (v->x_pos != (x + amd.x)) ?
919 v->x_pos + ((x + amd.x > v->x_pos) ? 1 : -1) :
920 v->x_pos;
921 gp.y = (v->y_pos != (y + amd.y)) ?
922 v->y_pos + ((y + amd.y > v->y_pos) ? 1 : -1) :
923 v->y_pos;
925 /* Oilrigs must keep v->tile as st->airport.tile, since the landing pad is in a non-airport tile */
926 gp.new_tile = (st->airport.type == AT_OILRIG) ? st->airport.tile : TileVirtXY(gp.x, gp.y);
928 } else {
930 /* Turn. Do it slowly if in the air. */
931 Direction newdir = GetDirectionTowards(v, x + amd.x, y + amd.y);
932 if (newdir != v->direction) {
933 if (amd.flag & AMED_SLOWTURN && v->number_consecutive_turns < 8 && v->subtype == AIR_AIRCRAFT) {
934 if (v->turn_counter == 0 || newdir == v->last_direction) {
935 if (newdir == v->last_direction) {
936 v->number_consecutive_turns = 0;
937 } else {
938 v->number_consecutive_turns++;
940 v->turn_counter = 2 * _settings_game.vehicle.plane_speed;
941 v->last_direction = v->direction;
942 v->direction = newdir;
945 /* Move vehicle. */
946 gp = GetNewVehiclePos(v);
947 } else {
948 v->cur_speed >>= 1;
949 v->direction = newdir;
951 /* When leaving a terminal an aircraft often goes to a position
952 * directly in front of it. If it would move while turning it
953 * would need an two extra turns to end up at the correct position.
954 * To make it easier just disallow all moving while turning as
955 * long as an aircraft is on the ground. */
956 gp.x = v->x_pos;
957 gp.y = v->y_pos;
958 gp.new_tile = v->tile;
960 } else {
961 v->number_consecutive_turns = 0;
962 /* Move vehicle. */
963 gp = GetNewVehiclePos(v);
967 v->tile = gp.new_tile;
968 /* If vehicle is in the air, use tile coordinate 0. */
969 if (amd.flag & (AMED_TAKEOFF | AMED_SLOWTURN | AMED_LAND)) v->tile = 0;
971 /* Adjust Z for land or takeoff? */
972 int z = v->z_pos;
974 if (amd.flag & AMED_TAKEOFF) {
975 z = min(z + 2, GetAircraftFlyingAltitude(v));
978 /* Let the plane drop from normal flight altitude to holding pattern altitude */
979 if ((amd.flag & AMED_HOLD) && (z > PLANE_HOLDING_ALTITUDE)) z--;
981 if (amd.flag & AMED_LAND) {
982 if (st->airport.tile == INVALID_TILE) {
983 /* Airport has been removed, abort the landing procedure */
984 v->state = FLYING;
985 UpdateAircraftCache(v);
986 AircraftNextAirportPos_and_Order(v);
987 /* get aircraft back on running altitude */
988 SetAircraftPosition(v, gp.x, gp.y, GetAircraftFlyingAltitude(v));
989 continue;
992 int curz = GetSlopePixelZ(x + amd.x, y + amd.y) + 1;
994 /* We're not flying below our destination, right? */
995 assert(curz <= z);
996 int t = max(1U, dist - 4);
997 int delta = z - curz;
999 /* Only start lowering when we're sufficiently close for a 1:1 glide */
1000 if (delta >= t) {
1001 z -= CeilDiv(z - curz, t);
1003 if (z < curz) z = curz;
1006 /* We've landed. Decrease speed when we're reaching end of runway. */
1007 if (amd.flag & AMED_BRAKE) {
1008 int curz = GetSlopePixelZ(x, y) + 1;
1010 if (z > curz) {
1011 z--;
1012 } else if (z < curz) {
1013 z++;
1018 SetAircraftPosition(v, gp.x, gp.y, z);
1019 } while (--count != 0);
1020 return false;
1024 * Handle crashed aircraft \a v.
1025 * @param v Crashed aircraft.
1027 static bool HandleCrashedAircraft(Aircraft *v)
1029 v->crashed_counter += 3;
1031 Station *st = GetTargetAirportIfValid(v);
1033 /* make aircraft crash down to the ground */
1034 if (v->crashed_counter < 500 && st == NULL && ((v->crashed_counter % 3) == 0) ) {
1035 int z = GetSlopePixelZ(Clamp(v->x_pos, 0, MapMaxX() * TILE_SIZE), Clamp(v->y_pos, 0, MapMaxY() * TILE_SIZE));
1036 v->z_pos -= 1;
1037 if (v->z_pos == z) {
1038 v->crashed_counter = 500;
1039 v->z_pos++;
1043 if (v->crashed_counter < 650) {
1044 uint32 r;
1045 if (Chance16R(1, 32, r)) {
1046 static const DirDiff delta[] = {
1047 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
1050 v->direction = ChangeDir(v->direction, delta[GB(r, 16, 2)]);
1051 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1052 r = Random();
1053 CreateEffectVehicleRel(v,
1054 GB(r, 0, 4) - 4,
1055 GB(r, 4, 4) - 4,
1056 GB(r, 8, 4),
1057 EV_EXPLOSION_SMALL);
1059 } else if (v->crashed_counter >= 10000) {
1060 /* remove rubble of crashed airplane */
1062 /* clear runway-in on all airports, set by crashing plane
1063 * small airports use AIRPORT_BUSY, city airports use RUNWAY_IN_OUT_block, etc.
1064 * but they all share the same number */
1065 if (st != NULL) {
1066 CLRBITS(st->airport.flags, RUNWAY_IN_block);
1067 CLRBITS(st->airport.flags, RUNWAY_IN_OUT_block); // commuter airport
1068 CLRBITS(st->airport.flags, RUNWAY_IN2_block); // intercontinental
1071 delete v;
1073 return false;
1076 return true;
1081 * Handle smoke of broken aircraft.
1082 * @param v Aircraft
1083 * @param mode Is this the non-first call for this vehicle in this tick?
1085 static void HandleAircraftSmoke(Aircraft *v, bool mode)
1087 static const struct {
1088 int8 x;
1089 int8 y;
1090 } smoke_pos[] = {
1091 { 5, 5 },
1092 { 6, 0 },
1093 { 5, -5 },
1094 { 0, -6 },
1095 { -5, -5 },
1096 { -6, 0 },
1097 { -5, 5 },
1098 { 0, 6 }
1101 if (!(v->vehstatus & VS_AIRCRAFT_BROKEN)) return;
1103 /* Stop smoking when landed */
1104 if (v->cur_speed < 10) {
1105 v->vehstatus &= ~VS_AIRCRAFT_BROKEN;
1106 v->breakdown_ctr = 0;
1107 return;
1110 /* Spawn effect et most once per Tick, i.e. !mode */
1111 if (!mode && (v->tick_counter & 0x0F) == 0) {
1112 CreateEffectVehicleRel(v,
1113 smoke_pos[v->direction].x,
1114 smoke_pos[v->direction].y,
1116 EV_BREAKDOWN_SMOKE_AIRCRAFT
1121 void HandleMissingAircraftOrders(Aircraft *v)
1124 * We do not have an order. This can be divided into two cases:
1125 * 1) we are heading to an invalid station. In this case we must
1126 * find another airport to go to. If there is nowhere to go,
1127 * we will destroy the aircraft as it otherwise will enter
1128 * the holding pattern for the first airport, which can cause
1129 * the plane to go into an undefined state when building an
1130 * airport with the same StationID.
1131 * 2) we are (still) heading to a (still) valid airport, then we
1132 * can continue going there. This can happen when you are
1133 * changing the aircraft's orders while in-flight or in for
1134 * example a depot. However, when we have a current order to
1135 * go to a depot, we have to keep that order so the aircraft
1136 * actually stops.
1138 const Station *st = GetTargetAirportIfValid(v);
1139 if (st == NULL) {
1140 Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1141 CommandCost ret = DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_SEND_VEHICLE_TO_DEPOT);
1142 cur_company.Restore();
1144 if (ret.Failed()) CrashAirplane(v);
1145 } else if (!v->current_order.IsType(OT_GOTO_DEPOT)) {
1146 v->current_order.Free();
1151 TileIndex Aircraft::GetOrderStationLocation(StationID station)
1153 /* Orders are changed in flight, ensure going to the right station. */
1154 if (this->state == FLYING) {
1155 AircraftNextAirportPos_and_Order(this);
1158 /* Aircraft do not use dest-tile */
1159 return 0;
1162 void Aircraft::MarkDirty()
1164 this->colourmap = PAL_NONE;
1165 this->UpdateViewport(true, false);
1166 if (this->subtype == AIR_HELICOPTER) this->Next()->Next()->cur_image = GetRotorImage(this, EIT_ON_MAP);
1170 uint Aircraft::Crash(bool flooded)
1172 uint pass = Vehicle::Crash(flooded) + 2; // pilots
1173 this->crashed_counter = flooded ? 9000 : 0; // max 10000, disappear pretty fast when flooded
1175 return pass;
1179 * Bring the aircraft in a crashed state, create the explosion animation, and create a news item about the crash.
1180 * @param v Aircraft that crashed.
1182 static void CrashAirplane(Aircraft *v)
1184 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
1186 uint pass = v->Crash();
1187 SetDParam(0, pass);
1189 v->cargo.Truncate();
1190 v->Next()->cargo.Truncate();
1191 const Station *st = GetTargetAirportIfValid(v);
1192 StringID newsitem;
1193 if (st == NULL) {
1194 newsitem = STR_NEWS_PLANE_CRASH_OUT_OF_FUEL;
1195 } else {
1196 SetDParam(1, st->index);
1197 newsitem = STR_NEWS_AIRCRAFT_CRASH;
1200 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, st == NULL ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
1201 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, st == NULL ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
1203 AddVehicleNewsItem(newsitem, NT_ACCIDENT, v->index, st != NULL ? st->index : INVALID_STATION);
1205 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
1206 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
1210 * Decide whether aircraft \a v should crash.
1211 * @param v Aircraft to test.
1213 static void MaybeCrashAirplane(Aircraft *v)
1215 if (_settings_game.vehicle.plane_crashes == 0) return;
1217 Station *st = Station::Get(v->targetairport);
1219 /* FIXME -- MaybeCrashAirplane -> increase crashing chances of very modern airplanes on smaller than AT_METROPOLITAN airports */
1220 uint32 prob = (0x4000 << _settings_game.vehicle.plane_crashes);
1221 if ((st->airport.GetFTA()->flags & AirportFTAClass::SHORT_STRIP) &&
1222 (AircraftVehInfo(v->engine_type)->subtype & AIR_FAST) &&
1223 !_cheats.no_jetcrash.value) {
1224 prob /= 20;
1225 } else {
1226 prob /= 1500;
1229 if (GB(Random(), 0, 22) > prob) return;
1231 /* Crash the airplane. Remove all goods stored at the station. */
1232 for (CargoID i = 0; i < NUM_CARGO; i++) {
1233 st->goods[i].rating = 1;
1234 st->goods[i].cargo.Truncate();
1237 CrashAirplane(v);
1241 * Aircraft arrives at a terminal. If it is the first aircraft, throw a party.
1242 * Start loading cargo.
1243 * @param v Aircraft that arrived.
1245 static void AircraftEntersTerminal(Aircraft *v)
1247 if (v->current_order.IsType(OT_GOTO_DEPOT)) return;
1249 Station *st = Station::Get(v->targetairport);
1250 v->last_station_visited = v->targetairport;
1252 /* Check if station was ever visited before */
1253 if (!(st->had_vehicle_of_type & HVOT_AIRCRAFT)) {
1254 st->had_vehicle_of_type |= HVOT_AIRCRAFT;
1255 SetDParam(0, st->index);
1256 /* show newsitem of celebrating citizens */
1257 AddVehicleNewsItem(
1258 STR_NEWS_FIRST_AIRCRAFT_ARRIVAL,
1259 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
1260 v->index,
1261 st->index
1263 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
1264 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
1267 v->BeginLoading();
1271 * Aircraft touched down at the landing strip.
1272 * @param v Aircraft that landed.
1274 static void AircraftLandAirplane(Aircraft *v)
1276 v->UpdateDeltaXY(INVALID_DIR);
1278 if (!PlayVehicleSound(v, VSE_TOUCHDOWN)) {
1279 SndPlayVehicleFx(SND_17_SKID_PLANE, v);
1284 /** set the right pos when heading to other airports after takeoff */
1285 void AircraftNextAirportPos_and_Order(Aircraft *v)
1287 if (v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT)) {
1288 v->targetairport = v->current_order.GetDestination();
1291 const Station *st = GetTargetAirportIfValid(v);
1292 const AirportFTAClass *apc = st == NULL ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
1293 Direction rotation = st == NULL ? DIR_N : st->airport.rotation;
1294 v->pos = v->previous_pos = AircraftGetEntryPoint(v, apc, rotation);
1298 * Aircraft is about to leave the hangar.
1299 * @param v Aircraft leaving.
1300 * @param exit_dir The direction the vehicle leaves the hangar.
1301 * @note This function is called in AfterLoadGame for old savegames, so don't rely
1302 * on any data to be valid, especially don't rely on the fact that the vehicle
1303 * is actually on the ground inside a depot.
1305 void AircraftLeaveHangar(Aircraft *v, Direction exit_dir)
1307 v->cur_speed = 0;
1308 v->subspeed = 0;
1309 v->progress = 0;
1310 v->direction = exit_dir;
1311 v->vehstatus &= ~VS_HIDDEN;
1313 Vehicle *u = v->Next();
1314 u->vehstatus &= ~VS_HIDDEN;
1316 /* Rotor blades */
1317 u = u->Next();
1318 if (u != NULL) {
1319 u->vehstatus &= ~VS_HIDDEN;
1320 u->cur_speed = 80;
1324 VehicleServiceInDepot(v);
1325 SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
1326 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1327 SetWindowClassesDirty(WC_AIRCRAFT_LIST);
1330 ////////////////////////////////////////////////////////////////////////////////
1331 /////////////////// AIRCRAFT MOVEMENT SCHEME ////////////////////////////////
1332 ////////////////////////////////////////////////////////////////////////////////
1333 static void AircraftEventHandler_EnterTerminal(Aircraft *v, const AirportFTAClass *apc)
1335 AircraftEntersTerminal(v);
1336 v->state = apc->layout[v->pos].heading;
1340 * Aircraft arrived in an airport hangar.
1341 * @param v Aircraft in the hangar.
1342 * @param apc Airport description containing the hangar.
1344 static void AircraftEventHandler_EnterHangar(Aircraft *v, const AirportFTAClass *apc)
1346 VehicleEnterDepot(v);
1347 v->state = apc->layout[v->pos].heading;
1351 * Handle aircraft movement/decision making in an airport hangar.
1352 * @param v Aircraft in the hangar.
1353 * @param apc Airport description containing the hangar.
1355 static void AircraftEventHandler_InHangar(Aircraft *v, const AirportFTAClass *apc)
1357 /* if we just arrived, execute EnterHangar first */
1358 if (v->previous_pos != v->pos) {
1359 AircraftEventHandler_EnterHangar(v, apc);
1360 return;
1363 /* if we were sent to the depot, stay there */
1364 if (v->current_order.IsType(OT_GOTO_DEPOT) && (v->vehstatus & VS_STOPPED)) {
1365 v->current_order.Free();
1366 return;
1369 if (!v->current_order.IsType(OT_GOTO_STATION) &&
1370 !v->current_order.IsType(OT_GOTO_DEPOT))
1371 return;
1373 /* We are leaving a hangar, but have to go to the exact same one; re-enter */
1374 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->current_order.GetDestination() == v->targetairport) {
1375 VehicleEnterDepot(v);
1376 return;
1379 /* if the block of the next position is busy, stay put */
1380 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1382 /* We are already at the target airport, we need to find a terminal */
1383 if (v->current_order.GetDestination() == v->targetairport) {
1384 /* FindFreeTerminal:
1385 * 1. Find a free terminal, 2. Occupy it, 3. Set the vehicle's state to that terminal */
1386 if (v->subtype == AIR_HELICOPTER) {
1387 if (!AirportFindFreeHelipad(v, apc)) return; // helicopter
1388 } else {
1389 if (!AirportFindFreeTerminal(v, apc)) return; // airplane
1391 } else { // Else prepare for launch.
1392 /* airplane goto state takeoff, helicopter to helitakeoff */
1393 v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1395 const Station *st = Station::GetByTile(v->tile);
1396 AircraftLeaveHangar(v, st->airport.GetHangarExitDirection(v->tile));
1397 AirportMove(v, apc);
1400 /** At one of the Airport's Terminals */
1401 static void AircraftEventHandler_AtTerminal(Aircraft *v, const AirportFTAClass *apc)
1403 /* if we just arrived, execute EnterTerminal first */
1404 if (v->previous_pos != v->pos) {
1405 AircraftEventHandler_EnterTerminal(v, apc);
1406 /* on an airport with helipads, a helicopter will always land there
1407 * and get serviced at the same time - setting */
1408 if (_settings_game.order.serviceathelipad) {
1409 if (v->subtype == AIR_HELICOPTER && apc->num_helipads > 0) {
1410 /* an excerpt of ServiceAircraft, without the invisibility stuff */
1411 v->date_of_last_service = _date;
1412 v->breakdowns_since_last_service = 0;
1413 v->reliability = v->GetEngine()->reliability;
1414 SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
1417 return;
1420 if (v->current_order.IsType(OT_NOTHING)) return;
1422 /* if the block of the next position is busy, stay put */
1423 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1425 /* airport-road is free. We either have to go to another airport, or to the hangar
1426 * ---> start moving */
1428 bool go_to_hangar = false;
1429 switch (v->current_order.GetType()) {
1430 case OT_GOTO_STATION: // ready to fly to another airport
1431 break;
1432 case OT_GOTO_DEPOT: // visit hangar for servicing, sale, etc.
1433 go_to_hangar = v->current_order.GetDestination() == v->targetairport;
1434 break;
1435 case OT_CONDITIONAL:
1436 /* In case of a conditional order we just have to wait a tick
1437 * longer, so the conditional order can actually be processed;
1438 * we should not clear the order as that makes us go nowhere. */
1439 return;
1440 default: // orders have been deleted (no orders), goto depot and don't bother us
1441 v->current_order.Free();
1442 go_to_hangar = Station::Get(v->targetairport)->airport.HasHangar();
1445 if (go_to_hangar) {
1446 v->state = HANGAR;
1447 } else {
1448 /* airplane goto state takeoff, helicopter to helitakeoff */
1449 v->state = (v->subtype == AIR_HELICOPTER) ? HELITAKEOFF : TAKEOFF;
1451 AirportMove(v, apc);
1454 static void AircraftEventHandler_General(Aircraft *v, const AirportFTAClass *apc)
1456 error("OK, you shouldn't be here, check your Airport Scheme!");
1459 static void AircraftEventHandler_TakeOff(Aircraft *v, const AirportFTAClass *apc)
1461 PlayAircraftSound(v); // play takeoffsound for airplanes
1462 v->state = STARTTAKEOFF;
1465 static void AircraftEventHandler_StartTakeOff(Aircraft *v, const AirportFTAClass *apc)
1467 v->state = ENDTAKEOFF;
1468 v->UpdateDeltaXY(INVALID_DIR);
1471 static void AircraftEventHandler_EndTakeOff(Aircraft *v, const AirportFTAClass *apc)
1473 v->state = FLYING;
1474 /* get the next position to go to, differs per airport */
1475 AircraftNextAirportPos_and_Order(v);
1478 static void AircraftEventHandler_HeliTakeOff(Aircraft *v, const AirportFTAClass *apc)
1480 v->state = FLYING;
1481 v->UpdateDeltaXY(INVALID_DIR);
1483 /* get the next position to go to, differs per airport */
1484 AircraftNextAirportPos_and_Order(v);
1486 /* Send the helicopter to a hangar if needed for replacement */
1487 if (v->NeedsAutomaticServicing()) {
1488 Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1489 DoCommand(v->tile, v->index | DEPOT_SERVICE | DEPOT_LOCATE_HANGAR, 0, DC_EXEC, CMD_SEND_VEHICLE_TO_DEPOT);
1490 cur_company.Restore();
1494 static void AircraftEventHandler_Flying(Aircraft *v, const AirportFTAClass *apc)
1496 Station *st = Station::Get(v->targetairport);
1498 /* Runway busy, not allowed to use this airstation or closed, circle. */
1499 if (CanVehicleUseStation(v, st) && (st->owner == OWNER_NONE || st->owner == v->owner) && !(st->airport.flags & AIRPORT_CLOSED_block)) {
1500 /* {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
1501 * if it is an airplane, look for LANDING, for helicopter HELILANDING
1502 * it is possible to choose from multiple landing runways, so loop until a free one is found */
1503 byte landingtype = (v->subtype == AIR_HELICOPTER) ? HELILANDING : LANDING;
1504 const AirportFTA *current = apc->layout[v->pos].next;
1505 while (current != NULL) {
1506 if (current->heading == landingtype) {
1507 /* save speed before, since if AirportHasBlock is false, it resets them to 0
1508 * we don't want that for plane in air
1509 * hack for speed thingie */
1510 uint16 tcur_speed = v->cur_speed;
1511 uint16 tsubspeed = v->subspeed;
1512 if (!AirportHasBlock(v, current, apc)) {
1513 v->state = landingtype; // LANDING / HELILANDING
1514 /* it's a bit dirty, but I need to set position to next position, otherwise
1515 * if there are multiple runways, plane won't know which one it took (because
1516 * they all have heading LANDING). And also occupy that block! */
1517 v->pos = current->next_position;
1518 SETBITS(st->airport.flags, apc->layout[v->pos].block);
1519 return;
1521 v->cur_speed = tcur_speed;
1522 v->subspeed = tsubspeed;
1524 current = current->next;
1527 v->state = FLYING;
1528 v->pos = apc->layout[v->pos].next_position;
1531 static void AircraftEventHandler_Landing(Aircraft *v, const AirportFTAClass *apc)
1533 v->state = ENDLANDING;
1534 AircraftLandAirplane(v); // maybe crash airplane
1536 /* check if the aircraft needs to be replaced or renewed and send it to a hangar if needed */
1537 if (v->NeedsAutomaticServicing()) {
1538 Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1539 DoCommand(v->tile, v->index | DEPOT_SERVICE, 0, DC_EXEC, CMD_SEND_VEHICLE_TO_DEPOT);
1540 cur_company.Restore();
1544 static void AircraftEventHandler_HeliLanding(Aircraft *v, const AirportFTAClass *apc)
1546 v->state = HELIENDLANDING;
1547 v->UpdateDeltaXY(INVALID_DIR);
1550 static void AircraftEventHandler_EndLanding(Aircraft *v, const AirportFTAClass *apc)
1552 /* next block busy, don't do a thing, just wait */
1553 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1555 /* if going to terminal (OT_GOTO_STATION) choose one
1556 * 1. in case all terminals are busy AirportFindFreeTerminal() returns false or
1557 * 2. not going for terminal (but depot, no order),
1558 * --> get out of the way to the hangar. */
1559 if (v->current_order.IsType(OT_GOTO_STATION)) {
1560 if (AirportFindFreeTerminal(v, apc)) return;
1562 v->state = HANGAR;
1566 static void AircraftEventHandler_HeliEndLanding(Aircraft *v, const AirportFTAClass *apc)
1568 /* next block busy, don't do a thing, just wait */
1569 if (AirportHasBlock(v, &apc->layout[v->pos], apc)) return;
1571 /* if going to helipad (OT_GOTO_STATION) choose one. If airport doesn't have helipads, choose terminal
1572 * 1. in case all terminals/helipads are busy (AirportFindFreeHelipad() returns false) or
1573 * 2. not going for terminal (but depot, no order),
1574 * --> get out of the way to the hangar IF there are terminals on the airport.
1575 * --> else TAKEOFF
1576 * the reason behind this is that if an airport has a terminal, it also has a hangar. Airplanes
1577 * must go to a hangar. */
1578 if (v->current_order.IsType(OT_GOTO_STATION)) {
1579 if (AirportFindFreeHelipad(v, apc)) return;
1581 v->state = Station::Get(v->targetairport)->airport.HasHangar() ? HANGAR : HELITAKEOFF;
1585 * Signature of the aircraft handler function.
1586 * @param v Aircraft to handle.
1587 * @param apc Airport state machine.
1589 typedef void AircraftStateHandler(Aircraft *v, const AirportFTAClass *apc);
1590 /** Array of handler functions for each target of the aircraft. */
1591 static AircraftStateHandler * const _aircraft_state_handlers[] = {
1592 AircraftEventHandler_General, // TO_ALL = 0
1593 AircraftEventHandler_InHangar, // HANGAR = 1
1594 AircraftEventHandler_AtTerminal, // TERM1 = 2
1595 AircraftEventHandler_AtTerminal, // TERM2 = 3
1596 AircraftEventHandler_AtTerminal, // TERM3 = 4
1597 AircraftEventHandler_AtTerminal, // TERM4 = 5
1598 AircraftEventHandler_AtTerminal, // TERM5 = 6
1599 AircraftEventHandler_AtTerminal, // TERM6 = 7
1600 AircraftEventHandler_AtTerminal, // HELIPAD1 = 8
1601 AircraftEventHandler_AtTerminal, // HELIPAD2 = 9
1602 AircraftEventHandler_TakeOff, // TAKEOFF = 10
1603 AircraftEventHandler_StartTakeOff, // STARTTAKEOFF = 11
1604 AircraftEventHandler_EndTakeOff, // ENDTAKEOFF = 12
1605 AircraftEventHandler_HeliTakeOff, // HELITAKEOFF = 13
1606 AircraftEventHandler_Flying, // FLYING = 14
1607 AircraftEventHandler_Landing, // LANDING = 15
1608 AircraftEventHandler_EndLanding, // ENDLANDING = 16
1609 AircraftEventHandler_HeliLanding, // HELILANDING = 17
1610 AircraftEventHandler_HeliEndLanding, // HELIENDLANDING = 18
1611 AircraftEventHandler_AtTerminal, // TERM7 = 19
1612 AircraftEventHandler_AtTerminal, // TERM8 = 20
1613 AircraftEventHandler_AtTerminal, // HELIPAD3 = 21
1616 static void AirportClearBlock(const Aircraft *v, const AirportFTAClass *apc)
1618 /* we have left the previous block, and entered the new one. Free the previous block */
1619 if (apc->layout[v->previous_pos].block != apc->layout[v->pos].block) {
1620 Station *st = Station::Get(v->targetairport);
1622 CLRBITS(st->airport.flags, apc->layout[v->previous_pos].block);
1626 static void AirportGoToNextPosition(Aircraft *v)
1628 /* if aircraft is not in position, wait until it is */
1629 if (!AircraftController(v)) return;
1631 const AirportFTAClass *apc = Station::Get(v->targetairport)->airport.GetFTA();
1633 AirportClearBlock(v, apc);
1634 AirportMove(v, apc); // move aircraft to next position
1637 /* gets pos from vehicle and next orders */
1638 static bool AirportMove(Aircraft *v, const AirportFTAClass *apc)
1640 /* error handling */
1641 if (v->pos >= apc->nofelements) {
1642 DEBUG(misc, 0, "[Ap] position %d is not valid for current airport. Max position is %d", v->pos, apc->nofelements-1);
1643 assert(v->pos < apc->nofelements);
1646 const AirportFTA *current = &apc->layout[v->pos];
1647 /* we have arrived in an important state (eg terminal, hangar, etc.) */
1648 if (current->heading == v->state) {
1649 byte prev_pos = v->pos; // location could be changed in state, so save it before-hand
1650 byte prev_state = v->state;
1651 _aircraft_state_handlers[v->state](v, apc);
1652 if (v->state != FLYING) v->previous_pos = prev_pos;
1653 if (v->state != prev_state || v->pos != prev_pos) UpdateAircraftCache(v);
1654 return true;
1657 v->previous_pos = v->pos; // save previous location
1659 /* there is only one choice to move to */
1660 if (current->next == NULL) {
1661 if (AirportSetBlocks(v, current, apc)) {
1662 v->pos = current->next_position;
1663 UpdateAircraftCache(v);
1664 } // move to next position
1665 return false;
1668 /* there are more choices to choose from, choose the one that
1669 * matches our heading */
1670 do {
1671 if (v->state == current->heading || current->heading == TO_ALL) {
1672 if (AirportSetBlocks(v, current, apc)) {
1673 v->pos = current->next_position;
1674 UpdateAircraftCache(v);
1675 } // move to next position
1676 return false;
1678 current = current->next;
1679 } while (current != NULL);
1681 DEBUG(misc, 0, "[Ap] cannot move further on Airport! (pos %d state %d) for vehicle %d", v->pos, v->state, v->index);
1682 NOT_REACHED();
1685 /** returns true if the road ahead is busy, eg. you must wait before proceeding. */
1686 static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1688 const AirportFTA *reference = &apc->layout[v->pos];
1689 const AirportFTA *next = &apc->layout[current_pos->next_position];
1691 /* same block, then of course we can move */
1692 if (apc->layout[current_pos->position].block != next->block) {
1693 const Station *st = Station::Get(v->targetairport);
1694 uint64 airport_flags = next->block;
1696 /* check additional possible extra blocks */
1697 if (current_pos != reference && current_pos->block != NOTHING_block) {
1698 airport_flags |= current_pos->block;
1701 if (st->airport.flags & airport_flags) {
1702 v->cur_speed = 0;
1703 v->subspeed = 0;
1704 return true;
1707 return false;
1711 * "reserve" a block for the plane
1712 * @param v airplane that requires the operation
1713 * @param current_pos of the vehicle in the list of blocks
1714 * @param apc airport on which block is requsted to be set
1715 * @returns true on success. Eg, next block was free and we have occupied it
1717 static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
1719 const AirportFTA *next = &apc->layout[current_pos->next_position];
1720 const AirportFTA *reference = &apc->layout[v->pos];
1722 /* if the next position is in another block, check it and wait until it is free */
1723 if ((apc->layout[current_pos->position].block & next->block) != next->block) {
1724 uint64 airport_flags = next->block;
1725 /* search for all all elements in the list with the same state, and blocks != N
1726 * this means more blocks should be checked/set */
1727 const AirportFTA *current = current_pos;
1728 if (current == reference) current = current->next;
1729 while (current != NULL) {
1730 if (current->heading == current_pos->heading && current->block != 0) {
1731 airport_flags |= current->block;
1732 break;
1734 current = current->next;
1737 /* if the block to be checked is in the next position, then exclude that from
1738 * checking, because it has been set by the airplane before */
1739 if (current_pos->block == next->block) airport_flags ^= next->block;
1741 Station *st = Station::Get(v->targetairport);
1742 if (st->airport.flags & airport_flags) {
1743 v->cur_speed = 0;
1744 v->subspeed = 0;
1745 return false;
1748 if (next->block != NOTHING_block) {
1749 SETBITS(st->airport.flags, airport_flags); // occupy next block
1752 return true;
1756 * Combination of aircraft state for going to a certain terminal and the
1757 * airport flag for that terminal block.
1759 struct MovementTerminalMapping {
1760 AirportMovementStates state; ///< Aircraft movement state when going to this terminal.
1761 uint64 airport_flag; ///< Bitmask in the airport flags that need to be free for this terminal.
1764 /** A list of all valid terminals and their associated blocks. */
1765 static const MovementTerminalMapping _airport_terminal_mapping[] = {
1766 {TERM1, TERM1_block},
1767 {TERM2, TERM2_block},
1768 {TERM3, TERM3_block},
1769 {TERM4, TERM4_block},
1770 {TERM5, TERM5_block},
1771 {TERM6, TERM6_block},
1772 {TERM7, TERM7_block},
1773 {TERM8, TERM8_block},
1774 {HELIPAD1, HELIPAD1_block},
1775 {HELIPAD2, HELIPAD2_block},
1776 {HELIPAD3, HELIPAD3_block},
1780 * Find a free terminal or helipad, and if available, assign it.
1781 * @param v Aircraft looking for a free terminal or helipad.
1782 * @param i First terminal to examine.
1783 * @param last_terminal Terminal number to stop examining.
1784 * @return A terminal or helipad has been found, and has been assigned to the aircraft.
1786 static bool FreeTerminal(Aircraft *v, byte i, byte last_terminal)
1788 assert(last_terminal <= lengthof(_airport_terminal_mapping));
1789 Station *st = Station::Get(v->targetairport);
1790 for (; i < last_terminal; i++) {
1791 if ((st->airport.flags & _airport_terminal_mapping[i].airport_flag) == 0) {
1792 /* TERMINAL# HELIPAD# */
1793 v->state = _airport_terminal_mapping[i].state; // start moving to that terminal/helipad
1794 SETBITS(st->airport.flags, _airport_terminal_mapping[i].airport_flag); // occupy terminal/helipad
1795 return true;
1798 return false;
1802 * Get the number of terminals at the airport.
1803 * @param afc Airport description.
1804 * @return Number of terminals.
1806 static uint GetNumTerminals(const AirportFTAClass *apc)
1808 uint num = 0;
1810 for (uint i = apc->terminals[0]; i > 0; i--) num += apc->terminals[i];
1812 return num;
1816 * Find a free terminal, and assign it if available.
1817 * @param v Aircraft to handle.
1818 * @param apc Airport state machine.
1819 * @return Found a free terminal and assigned it.
1821 static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc)
1823 /* example of more terminalgroups
1824 * {0,HANGAR,NOTHING_block,1}, {0,255,TERM_GROUP1_block,0}, {0,255,TERM_GROUP2_ENTER_block,1}, {0,0,N,1},
1825 * Heading 255 denotes a group. We see 2 groups here:
1826 * 1. group 0 -- TERM_GROUP1_block (check block)
1827 * 2. group 1 -- TERM_GROUP2_ENTER_block (check block)
1828 * First in line is checked first, group 0. If the block (TERM_GROUP1_block) is free, it
1829 * looks at the corresponding terminals of that group. If no free ones are found, other
1830 * possible groups are checked (in this case group 1, since that is after group 0). If that
1831 * fails, then attempt fails and plane waits
1833 if (apc->terminals[0] > 1) {
1834 const Station *st = Station::Get(v->targetairport);
1835 const AirportFTA *temp = apc->layout[v->pos].next;
1837 while (temp != NULL) {
1838 if (temp->heading == 255) {
1839 if (!(st->airport.flags & temp->block)) {
1840 /* read which group do we want to go to?
1841 * (the first free group) */
1842 uint target_group = temp->next_position + 1;
1844 /* at what terminal does the group start?
1845 * that means, sum up all terminals of
1846 * groups with lower number */
1847 uint group_start = 0;
1848 for (uint i = 1; i < target_group; i++) {
1849 group_start += apc->terminals[i];
1852 uint group_end = group_start + apc->terminals[target_group];
1853 if (FreeTerminal(v, group_start, group_end)) return true;
1855 } else {
1856 /* once the heading isn't 255, we've exhausted the possible blocks.
1857 * So we cannot move */
1858 return false;
1860 temp = temp->next;
1864 /* if there is only 1 terminalgroup, all terminals are checked (starting from 0 to max) */
1865 return FreeTerminal(v, 0, GetNumTerminals(apc));
1869 * Find a free helipad, and assign it if available.
1870 * @param v Aircraft to handle.
1871 * @param apc Airport state machine.
1872 * @return Found a free helipad and assigned it.
1874 static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc)
1876 /* if an airport doesn't have helipads, use terminals */
1877 if (apc->num_helipads == 0) return AirportFindFreeTerminal(v, apc);
1879 /* only 1 helicoptergroup, check all helipads
1880 * The blocks for helipads start after the last terminal (MAX_TERMINALS) */
1881 return FreeTerminal(v, MAX_TERMINALS, apc->num_helipads + MAX_TERMINALS);
1885 * Handle the 'dest too far' flag and the corresponding news message for aircraft.
1886 * @param v The aircraft.
1887 * @param too_far True if the current destination is too far away.
1889 static void AircraftHandleDestTooFar(Aircraft *v, bool too_far)
1891 if (too_far) {
1892 if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) {
1893 SetBit(v->flags, VAF_DEST_TOO_FAR);
1894 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1895 AI::NewEvent(v->owner, new ScriptEventAircraftDestTooFar(v->index));
1896 if (v->owner == _local_company) {
1897 /* Post a news message. */
1898 SetDParam(0, v->index);
1899 AddVehicleAdviceNewsItem(STR_NEWS_AIRCRAFT_DEST_TOO_FAR, v->index);
1902 return;
1905 if (HasBit(v->flags, VAF_DEST_TOO_FAR)) {
1906 /* Not too far anymore, clear flag and message. */
1907 ClrBit(v->flags, VAF_DEST_TOO_FAR);
1908 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1909 DeleteVehicleNews(v->index, STR_NEWS_AIRCRAFT_DEST_TOO_FAR);
1913 static bool AircraftEventHandler(Aircraft *v, int loop)
1915 if (v->vehstatus & VS_CRASHED) {
1916 return HandleCrashedAircraft(v);
1919 if (v->vehstatus & VS_STOPPED) return true;
1921 v->HandleBreakdown();
1923 HandleAircraftSmoke(v, loop != 0);
1924 ProcessOrders(v);
1925 v->HandleLoading(loop != 0);
1927 if (v->current_order.IsType(OT_LOADING) || v->current_order.IsType(OT_LEAVESTATION)) return true;
1929 if (v->state >= ENDTAKEOFF && v->state <= HELIENDLANDING) {
1930 /* If we are flying, unconditionally clear the 'dest too far' state. */
1931 AircraftHandleDestTooFar(v, false);
1932 } else if (v->acache.cached_max_range_sqr != 0) {
1933 /* Check the distance to the next destination. This code works because the target
1934 * airport is only updated after take off and not on the ground. */
1935 Station *cur_st = Station::GetIfValid(v->targetairport);
1936 Station *next_st = v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT) ? Station::GetIfValid(v->current_order.GetDestination()) : NULL;
1938 if (cur_st != NULL && cur_st->airport.tile != INVALID_TILE && next_st != NULL && next_st->airport.tile != INVALID_TILE) {
1939 uint dist = DistanceSquare(cur_st->airport.tile, next_st->airport.tile);
1940 AircraftHandleDestTooFar(v, dist > v->acache.cached_max_range_sqr);
1944 if (!HasBit(v->flags, VAF_DEST_TOO_FAR)) AirportGoToNextPosition(v);
1946 return true;
1949 bool Aircraft::Tick()
1951 if (!this->IsNormalAircraft()) return true;
1953 this->tick_counter++;
1955 if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
1957 if (this->subtype == AIR_HELICOPTER) HelicopterTickHandler(this);
1959 this->current_order_time++;
1961 for (uint i = 0; i != 2; i++) {
1962 /* stop if the aircraft was deleted */
1963 if (!AircraftEventHandler(this, i)) return false;
1966 return true;
1971 * Returns aircraft's target station if v->target_airport
1972 * is a valid station with airport.
1973 * @param v vehicle to get target airport for
1974 * @return pointer to target station, NULL if invalid
1976 Station *GetTargetAirportIfValid(const Aircraft *v)
1978 assert(v->type == VEH_AIRCRAFT);
1980 Station *st = Station::GetIfValid(v->targetairport);
1981 if (st == NULL) return NULL;
1983 return st->airport.tile == INVALID_TILE ? NULL : st;
1987 * Updates the status of the Aircraft heading or in the station
1988 * @param st Station been updated
1990 void UpdateAirplanesOnNewStation(const Station *st)
1992 /* only 1 station is updated per function call, so it is enough to get entry_point once */
1993 const AirportFTAClass *ap = st->airport.GetFTA();
1994 Direction rotation = st->airport.tile == INVALID_TILE ? DIR_N : st->airport.rotation;
1996 Aircraft *v;
1997 FOR_ALL_AIRCRAFT(v) {
1998 if (!v->IsNormalAircraft() || v->targetairport != st->index) continue;
1999 assert(v->state == FLYING);
2000 v->pos = v->previous_pos = AircraftGetEntryPoint(v, ap, rotation);
2001 UpdateAircraftCache(v);