45#include "table/strings.h"
51 this->
bounds = {{-1, -1, 0}, {2, 2, 0}, {}};
54 default: NOT_REACHED();
58 switch (this->
state) {
90static const SpriteID _aircraft_sprite[] = {
91 0x0EB5, 0x0EBD, 0x0EC5, 0x0ECD,
92 0x0ED5, 0x0EDD, 0x0E9D, 0x0EA5,
93 0x0EAD, 0x0EE5, 0x0F05, 0x0F0D,
94 0x0F15, 0x0F1D, 0x0F25, 0x0F2D,
95 0x0EED, 0x0EF5, 0x0EFD, 0x0F35,
96 0x0E9D, 0x0EA5, 0x0EAD, 0x0EB5,
101bool IsValidImageIndex<VEH_AIRCRAFT>(uint8_t image_index)
103 return image_index <
lengthof(_aircraft_sprite);
130 const Station *last_dest =
nullptr;
131 const Station *next_dest =
nullptr;
132 if (max_range != 0) {
155 if (max_range != 0) {
158 if (last_dist > max_range || next_dist > max_range)
continue;
163 if (distance < best || index == StationID::Invalid()) {
175 if (IsCustomVehicleSpriteNum(
spritenum)) {
176 GetCustomVehicleSprite(
this,
direction, image_type, result);
182 assert(IsValidImageIndex<VEH_AIRCRAFT>(
spritenum));
191 if (IsCustomVehicleSpriteNum(v->
spritenum)) {
192 GetCustomRotorSprite(v, image_type, result);
197 result->
Set(SPR_ROTOR_STOPPED + w->
state);
203 uint8_t spritenum = e->u.air.image_index;
205 if (IsCustomVehicleSpriteNum(spritenum)) {
206 GetCustomVehicleIcon(engine,
DIR_W, image_type, result);
212 assert(IsValidImageIndex<VEH_AIRCRAFT>(spritenum));
213 result->
Set(
DIR_W + _aircraft_sprite[spritenum]);
219 GetAircraftIcon(engine, image_type, &seq);
223 preferred_x =
Clamp(preferred_x,
229 if (!(AircraftVehInfo(engine)->subtype &
AIR_CTOL)) {
231 GetCustomRotorIcon(engine, image_type, &rotor_seq);
232 if (!rotor_seq.
IsValid()) rotor_seq.
Set(SPR_ROTOR_STOPPED);
249 GetAircraftIcon(engine, image_type, &seq);
311 CargoType mail = GetCargoTypeByLabel(CT_MAIL);
384 w->
state = HRS_ROTOR_STOPPED;
404 if (station == StationID::Invalid())
return ClosestDepot();
412static void CheckIfAircraftNeedsService(
Aircraft *v)
426 assert(st !=
nullptr);
462 CheckVehicleBreakdown(
this);
463 CheckIfAircraftNeedsService(
this);
478static void HelicopterTickHandler(
Aircraft *v)
507 u->
state = HRS_ROTOR_STOPPED;
510 }
else if (tick >= spd) {
513 if (u->
state > HRS_ROTOR_MOVING_3) u->
state = HRS_ROTOR_MOVING_1;
586static void PlayAircraftSound(
const Vehicle *v)
589 SndPlayVehicleFx(AircraftVehInfo(v->
engine_type)->sfx, v);
603 if (max_speed != 0) {
605 max_speed = (max_speed * 128) / 10;
666 if (v->
cur_speed < speed_limit) hard_limit =
false;
678 if (!hard_limit && v->
cur_speed > speed_limit) {
768int GetAircraftFlightLevel(T *v,
bool takeoff)
772 int aircraft_min_altitude;
773 int aircraft_max_altitude;
775 int aircraft_middle_altitude = (aircraft_min_altitude + aircraft_max_altitude) / 2;
778 assert(aircraft_min_altitude < aircraft_middle_altitude);
779 assert(aircraft_middle_altitude < aircraft_max_altitude);
782 if (z < aircraft_min_altitude ||
788 z += takeoff ? 2 : 1;
789 }
else if (!takeoff && (z > aircraft_max_altitude ||
807template int GetAircraftFlightLevel(
Aircraft *v,
bool takeoff);
825 assert(v !=
nullptr);
826 assert(apc !=
nullptr);
843 if (
abs(delta_y) <
abs(delta_x)) {
871 uint size_x = 1, size_y = 1;
916 SoundID sfx = AircraftVehInfo(v->
engine_type)->sfx;
920 SndPlayVehicleFx(sfx, v);
933 if (v->
z_pos >= z_dest) {
1021 bool hard_limit =
true;
1029 if (count == 0)
return false;
1036 bool nudge_towards_target =
static_cast<uint
>(count) + 3 > dist;
1046 gp.x = (v->
x_pos != (x + amd.
x)) ?
1049 gp.
y = (v->
y_pos != (y + amd.
y)) ?
1059 Direction newdir = GetDirectionTowards(v, x + amd.
x, y + amd.
y);
1062 if (v->
turn_counter == 0 || newdir == v->last_direction) {
1063 if (newdir == v->last_direction) {
1097 if (amd.
flags.
Any({AirportMovingDataFlag::Takeoff, AirportMovingDataFlag::SlowTurn, AirportMovingDataFlag::Land})) v->
tile =
TileIndex{};
1103 z = GetAircraftFlightLevel(v,
true);
1107 }
else if (amd.
flags.
All({AirportMovingDataFlag::SlowTurn, AirportMovingDataFlag::NoSpeedClamp})) {
1108 z = GetAircraftFlightLevel(v);
1117 int airport_z = v->
z_pos;
1118 if (amd.
flags.
Any({AirportMovingDataFlag::Land, AirportMovingDataFlag::Brake}) && st !=
nullptr) {
1145 assert(airport_z <= z);
1146 int t = std::max(1U, dist - 4);
1147 int delta = z - airport_z;
1151 z -=
CeilDiv(z - airport_z, t);
1153 if (z < airport_z) z = airport_z;
1159 if (z > airport_z) {
1161 }
else if (z < airport_z) {
1168 }
while (--count != 0);
1186 if (v->
z_pos <= z) {
1198 static const DirDiff delta[] = {
1217 if (st !=
nullptr) {
1239 static const struct {
1273void HandleMissingAircraftOrders(
Aircraft *v)
1291 if (st ==
nullptr) {
1294 cur_company.Restore();
1340 uint victims = v->
Crash();
1348 if (st ==
nullptr) {
1354 AI::NewEvent(v->
owner,
new ScriptEventVehicleCrashed(v->
index, vt, st ==
nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING, victims, v->
owner));
1355 Game::NewEvent(
new ScriptEventVehicleCrashed(v->
index, vt, st ==
nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING, victims, v->
owner));
1362 AddTileNewsItem(std::move(headline), newstype, vt, st !=
nullptr ? st->
index : StationID::Invalid());
1364 ModifyStationRatingAround(vt, v->
owner, -160, 30);
1387 if (
GB(
Random(), 0, 22) > prob)
return;
1392 if (ge.HasData()) ge.GetData().cargo.Truncate();
1564 AirportMove(v, apc);
1572 AircraftEventHandler_EnterTerminal(v, apc);
1596 bool go_to_hangar =
false;
1598 case OT_GOTO_STATION:
1603 case OT_CONDITIONAL:
1610 go_to_hangar =
true;
1619 AirportMove(v, apc);
1624 FatalError(
"OK, you shouldn't be here, check your Airport Scheme!");
1629 PlayAircraftSound(v);
1658 cur_company.Restore();
1673 while (current !=
nullptr) {
1674 if (current->
heading == landingtype) {
1681 v->
state = landingtype;
1693 current = current->
next.get();
1709 cur_company.Restore();
1761 AircraftEventHandler_General,
1771 AircraftEventHandler_TakeOff,
1772 AircraftEventHandler_StartTakeOff,
1773 AircraftEventHandler_EndTakeOff,
1774 AircraftEventHandler_HeliTakeOff,
1775 AircraftEventHandler_Flying,
1776 AircraftEventHandler_Landing,
1777 AircraftEventHandler_EndLanding,
1778 AircraftEventHandler_HeliLanding,
1779 AircraftEventHandler_HeliEndLanding,
1800static void AirportGoToNextPosition(
Aircraft *v)
1807 AirportClearBlock(v, apc);
1808 AirportMove(v, apc);
1816 Debug(misc, 0,
"[Ap] position {} is not valid for current airport. Max position is {}", v->
pos, apc->
nofelements-1);
1823 uint8_t prev_pos = v->
pos;
1824 uint8_t prev_state = v->
state;
1826 if (v->state !=
FLYING) v->previous_pos = prev_pos;
1831 v->previous_pos = v->pos;
1834 if (current->
next ==
nullptr) {
1852 current = current->
next.get();
1853 }
while (current !=
nullptr);
1855 Debug(misc, 0,
"[Ap] cannot move further on Airport! (pos {} state {}) for vehicle {}", v->pos, v->state, v->index);
1871 if (current_pos != reference && current_pos->
blocks != AirportBlock::Nothing) {
1902 if (current == reference) current = current->
next.get();
1903 while (current !=
nullptr) {
1908 current = current->
next.get();
1922 if (next->
blocks != AirportBlock::Nothing) {
1964 for (; i < last_terminal; i++) {
2011 while (temp !=
nullptr) {
2021 uint group_start = 0;
2022 for (uint i = 1; i < target_group; i++) {
2026 uint group_end = group_start + apc->
terminals[target_group];
2027 if (
FreeTerminal(v, group_start, group_end))
return true;
2034 temp = temp->
next.get();
2086static bool AircraftEventHandler(
Aircraft *v,
int loop)
2136 for (uint i = 0; i != 2; i++) {
2138 if (!AircraftEventHandler(
this, i))
return false;
2156 if (st ==
nullptr)
return nullptr;
Base functions for all AIs.
static constexpr int AIRCRAFT_MIN_FLYING_ALTITUDE
Base values for flight levels above ground level for 'normal' flight and holding patterns.
static constexpr int HELICOPTER_HOLD_MAX_FLYING_ALTITUDE
holding flying altitude above tile of helicopters.
static const int ROTOR_Z_OFFSET
Z Offset between helicopter- and rotorsprite.
static constexpr int PLANE_HOLD_MAX_FLYING_ALTITUDE
holding flying altitude above tile of planes.
void AircraftNextAirportPos_and_Order(Aircraft *v)
set the right pos when heading to other airports after takeoff
Station * GetTargetAirportIfValid(const Aircraft *v)
Returns aircraft's target station if v->target_airport is a valid station with airport.
@ VAF_HELI_DIRECT_DESCENT
The helicopter is descending directly at its destination (helipad or in front of hangar)
@ VAF_DEST_TOO_FAR
Next destination is too far away.
@ VAF_IN_MIN_HEIGHT_CORRECTION
The vehicle is currently raising its altitude because it hit the lower bound.
@ VAF_IN_MAX_HEIGHT_CORRECTION
The vehicle is currently lowering its altitude because it hit the upper bound.
@ AIR_AIRCRAFT
an airplane
@ AIR_ROTOR
rotor of an helicopter
@ AIR_SHADOW
shadow of the aircraft
@ AIR_HELICOPTER
an helicopter
static constexpr int AIRCRAFT_MAX_FLYING_ALTITUDE
Maximum flying altitude above tile.
static void HandleAircraftSmoke(Aircraft *v, bool mode)
Handle smoke of broken aircraft.
static void AircraftEventHandler_InHangar(Aircraft *v, const AirportFTAClass *apc)
Handle aircraft movement/decision making in an airport hangar.
static StationID FindNearestHangar(const Aircraft *v)
Find the nearest hangar to v StationID::Invalid() is returned, if the company does not have any suita...
static uint GetNumTerminals(const AirportFTAClass *apc)
Get the number of terminals at the airport.
void UpdateAirplanesOnNewStation(const Station *st)
Updates the status of the Aircraft heading or in the station.
void AircraftNextAirportPos_and_Order(Aircraft *v)
set the right pos when heading to other airports after takeoff
int GetTileHeightBelowAircraft(const Vehicle *v)
Get the tile height below the aircraft.
void GetAircraftSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
Get the size of the sprite of an aircraft sprite heading west (used for lists).
static uint8_t AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc, Direction rotation)
Find the entry point to an airport depending on direction which the airport is being approached from.
static const MovementTerminalMapping _airport_terminal_mapping[]
A list of all valid terminals and their associated blocks.
static bool AirportHasBlock(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
returns true if the road ahead is busy, eg.
static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const AirportFTAClass *apc)
"reserve" a block for the plane
Station * GetTargetAirportIfValid(const Aircraft *v)
Returns aircraft's target station if v->target_airport is a valid station with airport.
static void AircraftLandAirplane(Aircraft *v)
Aircraft touched down at the landing strip.
int GetAircraftHoldMaxAltitude(const Aircraft *v)
Gets the maximum 'flight level' for the holding pattern of the aircraft, in pixels 'z_pos' 0,...
static bool FreeTerminal(Aircraft *v, uint8_t i, uint8_t last_terminal)
Find a free terminal or helipad, and if available, assign it.
static constexpr uint16_t SPEED_LIMIT_BROKEN
Maximum speed of an aircraft that is broken.
static void AircraftHandleDestTooFar(Aircraft *v, bool too_far)
Handle the 'dest too far' flag and the corresponding news message for aircraft.
static bool AircraftController(Aircraft *v)
Controls the movement of an aircraft.
void AircraftLeaveHangar(Aircraft *v, Direction exit_dir)
Aircraft is about to leave the hangar.
static bool AirportFindFreeHelipad(Aircraft *v, const AirportFTAClass *apc)
Find a free helipad, and assign it if available.
static constexpr uint16_t SPEED_LIMIT_NONE
No environmental speed limit. Speed limit is type dependent.
static void AircraftEntersTerminal(Aircraft *v)
Aircraft arrives at a terminal.
HelicopterRotorStates
Helicopter rotor animation states.
static void AircraftEventHandler_AtTerminal(Aircraft *v, const AirportFTAClass *apc)
At one of the Airport's Terminals.
void SetAircraftPosition(Aircraft *v, int x, int y, int z)
Set aircraft position.
static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit=SPEED_LIMIT_NONE, bool hard_limit=true)
Sets the new speed for an aircraft.
static void MaybeCrashAirplane(Aircraft *v)
Decide whether aircraft v should crash.
static constexpr uint16_t SPEED_LIMIT_HOLD
Maximum speed of an aircraft that flies the holding pattern.
void GetAircraftFlightLevelBounds(const Vehicle *v, int *min_level, int *max_level)
Get the 'flight level' bounds, in pixels from 'z_pos' 0 for a particular vehicle for normal flight si...
static bool HandleCrashedAircraft(Aircraft *v)
Handle crashed aircraft v.
void UpdateAircraftCache(Aircraft *v, bool update_range)
Update cached values of an aircraft.
static AircraftStateHandler *const _aircraft_state_handlers[]
Array of handler functions for each target of the aircraft.
static void AircraftEventHandler_EnterHangar(Aircraft *v, const AirportFTAClass *apc)
Aircraft arrived in an airport hangar.
CommandCost CmdBuildAircraft(DoCommandFlags flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build an aircraft.
static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc)
Find a free terminal, and assign it if available.
void HandleAircraftEnterHangar(Aircraft *v)
Handle Aircraft specific tasks when an Aircraft enters a hangar.
static constexpr uint16_t SPEED_LIMIT_APPROACH
Maximum speed of an aircraft on finals.
static void CrashAirplane(Aircraft *v)
Bring the aircraft in a crashed state, create the explosion animation, and create a news item about t...
static constexpr uint16_t SPEED_LIMIT_TAXI
Special velocities for aircraft.
void AircraftStateHandler(Aircraft *v, const AirportFTAClass *apc)
Signature of the aircraft handler function.
Command definitions related to aircraft.
uint8_t GetVehiclePosOnBuild(TileIndex hangar_tile)
Get the vehicle position when an aircraft is build at the given tile.
const AirportFTAClass * GetAirport(const uint8_t airport_type)
Get the finite state machine of an airport type.
AirportMovingData RotateAirportMovingData(const AirportMovingData *orig, Direction rotation, uint num_tiles_x, uint num_tiles_y)
Rotate the airport moving data to another rotation.
static const uint MAX_TERMINALS
Some airport-related constants.
AirportBlock
Movement Blocks on Airports blocks (eg_airport_flags).
@ Zeppeliner
Block for the zeppeliner disaster vehicle.
@ Term2
Block belonging to terminal 2.
@ AirportClosed
Dummy block for indicating a closed airport.
@ Term5
Block belonging to terminal 5.
@ Term6
Block belonging to terminal 6.
@ Term4
Block belonging to terminal 4.
@ Helipad3
Block belonging to helipad 3.
@ Term7
Block belonging to terminal 7.
@ Helipad1
Block belonging to helipad 1.
@ Term3
Block belonging to terminal 3.
@ Term1
Block belonging to terminal 1.
@ Helipad2
Block belonging to helipad 2.
@ Term8
Block belonging to terminal 8.
@ HeliRaise
Helicopter take-off.
@ HeliLower
Helicopter landing.
@ Land
Landing onto landing strip.
@ Takeoff
Takeoff movement.
@ SlowTurn
Turn slowly (mostly used in the air).
@ Brake
Taxiing at the airport.
@ NoSpeedClamp
No speed restrictions.
@ Hold
Holding pattern movement (above the airport).
@ ExactPosition
Go exactly to the destination coordinates.
AirportMovementStates
Movement States on Airports (headings target)
@ HELITAKEOFF
Helicopter wants to leave the airport.
@ TERM4
Heading for terminal 4.
@ STARTTAKEOFF
Airplane has arrived at a runway for take-off.
@ HELIPAD2
Heading for helipad 2.
@ ENDTAKEOFF
Airplane has reached end-point of the take-off runway.
@ TERM5
Heading for terminal 5.
@ TERM6
Heading for terminal 6.
@ TERM3
Heading for terminal 3.
@ TERM8
Heading for terminal 8.
@ HELIPAD3
Heading for helipad 3.
@ HELIPAD1
Heading for helipad 1.
@ TERM2
Heading for terminal 2.
@ HANGAR
Heading for hangar.
@ FLYING
Vehicle is flying in the air.
@ TAKEOFF
Airplane wants to leave the airport.
@ HELILANDING
Helicopter wants to land.
@ TO_ALL
Go in this direction for every target.
@ ENDLANDING
Airplane wants to finish landing.
@ HELIENDLANDING
Helicopter wants to finish landing.
@ TERM1
Heading for terminal 1.
@ LANDING
Airplane wants to land.
@ TERM7
Heading for terminal 7.
@ TERMGROUP
Aircraft is looking for a free terminal in a terminalgroup.
@ AT_OILRIG
Oilrig airport.
Class for backupping variables and making sure they are restored later.
@ BuiltAsPrototype
Vehicle is a prototype (accepted as exclusive preview).
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
debug_inline static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
uint8_t CargoType
Cargo slots to indicate a cargo type within a game.
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Cheats _cheats
All the cheats.
Types related to cheating.
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
constexpr bool All(const Timpl &other) const
Test if all of the values are set.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Flip(Tvalue_type value)
Flip the value-th bit.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Common return value for all commands.
Money GetCost() const
The costs as made up to this moment.
bool Failed() const
Did this command fail?
Container for an encoded string, created by GetEncodedString.
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static constexpr int DAYS_IN_YEAR
days per year
static Date date
Current date in days (day counter).
uint Truncate(uint max_move=UINT_MAX)
Truncates the cargo in this list to the given amount.
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Execute
execute the given command
Definition of stuff that is very close to a company, like the company struct itself.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
Subtract money from a company, including the money fraction.
Functions related to companies.
static constexpr Owner OWNER_NONE
The tile has no ownership.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
DiagDirection ChangeDiagDir(DiagDirection d, DiagDirDiff delta)
Applies a difference on a DiagDirection.
DiagDirDiff DiagDirDifference(DiagDirection d0, DiagDirection d1)
Calculate the difference between two DiagDirection values.
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
DirDiff
Enumeration for the difference between two directions.
@ DIRDIFF_45LEFT
Angle of 45 degrees left.
@ DIRDIFF_REVERSE
One direction is the opposite of the other one.
@ DIRDIFF_45RIGHT
Angle of 45 degrees right.
@ DIRDIFF_SAME
Both directions faces to the same direction.
Direction
Defines the 8 directions on the map.
DiagDirection
Enumeration for diagonal directions.
@ DIAGDIR_NE
Northeast, upper right on your monitor.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
@ EXPENSES_AIRCRAFT_RUN
Running costs aircraft.
EffectVehicle * CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular vehicle.
Functions related to effect vehicles.
@ EV_EXPLOSION_SMALL
Various explosions.
@ EV_EXPLOSION_LARGE
Various explosions.
@ EV_BREAKDOWN_SMOKE_AIRCRAFT
Smoke of broken aircraft.
@ AIR_CTOL
Conventional Take Off and Landing, i.e. planes.
@ ExclusivePreview
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
Error reporting related functions.
fluid_settings_t * settings
FluidSynth settings handle.
Types for recording game performance data.
@ PFE_GL_AIRCRAFT
Time spent processing aircraft.
Base functions for all Games.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
uint32_t PaletteID
The number of the palette.
int GetSlopePixelZ(int x, int y, bool ground_vehicle)
Return world Z coordinate of a given point of a tile.
Functions related to OTTD's landscape.
@ Random
Randomise borders.
uint DistanceSquare(TileIndex t0, TileIndex t1)
Gets the 'Square' distance between the two given tiles.
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
static debug_inline TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
NewGRF handling of airport tiles.
Functions for NewGRF engines.
@ PROP_AIRCRAFT_RANGE
Aircraft range.
@ PROP_AIRCRAFT_RUNNING_COST_FACTOR
Yearly runningcost.
@ PROP_AIRCRAFT_SPEED
Max. speed: 1 unit = 8 mph = 12.8 km-ish/h.
@ PROP_AIRCRAFT_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event, bool force)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Functions related to NewGRF provided sounds.
@ VSE_TOUCHDOWN
Whenever a plane touches down.
@ VSE_START
Vehicle starting, i.e. leaving, the station.
Functions related to news.
void AddVehicleNewsItem(EncodedString &&headline, NewsType type, VehicleID vehicle, StationID station=StationID::Invalid())
Adds a newsitem referencing a vehicle.
void AddVehicleAdviceNewsItem(AdviceType advice_type, EncodedString &&headline, VehicleID vehicle)
Adds a vehicle-advice news item.
void DeleteVehicleNews(VehicleID vid, AdviceType advice_type=AdviceType::Invalid)
Delete news with a given advice type about a vehicle.
@ ArrivalCompany
First vehicle arrived for company.
@ AccidentOther
An accident or disaster has occurred.
@ ArrivalOther
First vehicle arrived for competitor.
@ Accident
An accident or disaster has occurred.
@ AircraftDestinationTooFar
Next (order) destination is too far for the aircraft type.
bool ProcessOrders(Vehicle *v)
Handle the orders of a vehicle and determine the next place to go to if needed.
void CheckOrders(const Vehicle *v)
Check the orders of a vehicle, to see if there are invalid orders and stuff.
void RemoveOrderFromAllVehicles(OrderType type, DestinationID destination, bool hangar)
Removes an order from all vehicles.
@ ODTFB_PART_OF_ORDERS
This depot order is because of a regular order.
@ ODTFB_SERVICE
This depot order is because of the servicing limit.
@ ODATFB_NEAREST_DEPOT
Send the vehicle to the nearest depot.
Pseudo random number generator.
bool Chance16R(const uint32_t a, const uint32_t b, uint32_t &r, const std::source_location location=std::source_location::current())
Flips a coin with a given probability and saves the randomize-number in a variable.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
ClientSettings _settings_client
The current settings for this game.
Functions related to sound.
static const uint ORIGINAL_SAMPLE_COUNT
The number of sounds in the original sample.cat.
@ SND_18_TAKEOFF_HELICOPTER
22 == 0x16 Takeoff: helicopter
@ SND_17_SKID_PLANE
21 == 0x15 Plane landing / touching ground
@ SND_12_EXPLOSION
16 == 0x10 Destruction, crashes, disasters, ...
Functions to cache sprites in memory.
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Base classes/functions for stations.
StationID GetStationIndex(Tile t)
Get StationID from a tile.
@ HVOT_AIRCRAFT
Station has seen an aircraft.
@ Airport
Station with an airport.
@ AirplaneTouchdown
Triggered when an airplane (not a helicopter) touches down at the airport (for single tile).
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Functions related to OTTD's strings.
uint32_t cached_max_range_sqr
Cached squared maximum range.
uint16_t cached_max_range
Cached maximum range.
Information about a aircraft vehicle.
uint16_t max_speed
Maximum speed (1 unit = 8 mph = 12.8 km-ish/h)
uint8_t mail_capacity
Mail capacity (bags).
uint8_t subtype
Type of aircraft.
uint16_t passenger_capacity
Passenger capacity (persons).
uint16_t max_range
Maximum range of this aircraft.
Aircraft, helicopters, rotors and their shadows belong to this class.
bool Tick() override
Calls the tick handler of the vehicle.
uint8_t pos
Next desired position of the aircraft.
uint8_t state
State of the airport.
uint8_t flags
Aircraft flags.
Money GetRunningCost() const override
Gets the running cost of a vehicle.
void UpdateDeltaXY() override
Updates the x and y offsets and the size of the sprite used for this vehicle.
uint8_t number_consecutive_turns
Protection to prevent the aircraft of making a lot of turns in order to reach a specific point.
void OnNewEconomyDay() override
Economy day handler.
uint Crash(bool flooded=false) override
Crash the (whole) vehicle chain.
void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const override
Gets the sprite to show for the given direction.
void OnNewCalendarDay() override
Calendar day handler.
uint8_t turn_counter
Ticks between each turn to prevent > 45 degree turns.
TileIndex GetOrderStationLocation(StationID station) override
Determine the location for the station where the vehicle goes to next.
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow.
void MarkDirty() override
Marks the vehicles to be redrawn and updates cached variables.
uint8_t previous_pos
Previous desired position of the aircraft.
StationID targetairport
Airport to go to next.
ClosestDepot FindClosestDepot() override
Find the closest depot for this vehicle and tell us the location, DestinationID and whether we should...
uint16_t crashed_counter
Timer for handling crash animations.
Finite sTate mAchine (FTA) of an airport.
const uint8_t num_helipads
Number of helipads on this airport. When 0 helicopters will go to normal terminals.
const AirportMovingData * MovingData(uint8_t position) const
Get movement data at a position.
@ Airplanes
Can planes land on this airport type?
@ ShortStrip
This airport has a short landing strip, dangerous for fast aircraft.
uint8_t delta_z
Z adjustment for helicopter pads.
std::vector< AirportFTA > layout
state machine for airport
const uint8_t * terminals
Array with the number of terminal groups, followed by the number of terminals in each group.
const uint8_t * entry_points
when an airplane arrives at this airport, enter it at position entry_point, index depends on directio...
uint8_t nofelements
number of positions the airport consists of
Flags flags
Flags for this airport type.
Internal structure used in openttd - Finite sTate mAchine --> FTA.
std::unique_ptr< AirportFTA > next
possible extra movement choices from this position
uint8_t heading
heading (current orders), guiding an airplane to its target on an airport
AirportBlocks blocks
bitmap of blocks that could be reserved
uint8_t position
the position that an airplane is at
uint8_t next_position
next position from this position
A single location on an airport where aircraft can move to.
int16_t x
x-coordinate of the destination.
AirportMovingDataFlags flags
special flags when moving towards the destination.
int16_t y
y-coordinate of the destination.
Direction direction
Direction to turn the aircraft after reaching the destination.
AirportBlocks blocks
stores which blocks on the airport are taken. was 16 bit earlier on, then 32
bool HasHangar() const
Check if this airport has at least one hangar.
uint GetHangarNum(TileIndex tile) const
Get the hangar number of the hangar at a specific tile.
Direction rotation
How this airport is rotated.
uint8_t type
Type of this airport,.
Direction GetHangarExitDirection(TileIndex tile) const
Get the exit direction of the hangar at a specific tile.
const AirportFTAClass * GetFTA() const
Get the finite-state machine for this airport or the finite-state machine for the dummy airport in ca...
TileIndex GetHangarTile(uint hangar_num) const
Get the first tile of the given hangar.
Class to backup a specific variable and restore it later.
std::string name
Name of vehicle.
TimerGameTick::Ticks current_order_time
How many ticks have passed since this order started.
VehicleFlags vehicle_flags
Used for gradual loading and other miscellaneous things (.
TileIndex xy
Base tile of the station.
Owner owner
The owner of this station.
static BaseStation * GetByTile(TileIndex tile)
Get the base station belonging to a specific tile.
VehicleType type
Type of vehicle.
bool value
tells if the bool cheat is active or not
Cheat no_jetcrash
no jet will crash on small airports anymore
SoundSettings sound
sound effect settings
Structure to return information about the closest depot location, and whether it could be found.
Disasters, like submarines, skyrangers and their shadows, belong to this class.
uint16_t cargo_age_period
Number of ticks before carried cargo is aged.
uint16_t reliability_spd_dec
Speed of reliability decay between services (per day).
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
uint DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity=nullptr) const
Determines capacity of a given vehicle from scratch.
EngineFlags flags
Flags of the engine.
uint8_t original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
TimerGameCalendar::Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
CargoType GetDefaultCargoType() const
Determines the default cargo type of an engine.
uint16_t reliability
Current reliability of the engine.
VehicleSettings vehicle
options for vehicles
OrderSettings order
settings related to orders
Position information of a vehicle after it moved.
TileIndex new_tile
Tile of the vehicle after moving.
int y
x and y position of the vehicle after moving
TileIndex old_tile
Current tile of the vehicle.
Stores station stats for a single cargo.
static uint MaxY()
Gets the maximum Y coordinate within the map, including MP_VOID.
static debug_inline uint MaxX()
Gets the maximum X coordinate within the map, including MP_VOID.
Combination of aircraft state for going to a certain terminal and the airport flag for that terminal ...
AirportBlock blocks
Bitmask in the airport flags that need to be free for this terminal.
AirportMovementStates state
Aircraft movement state when going to this terminal.
VehicleSpriteSeq sprite_seq
Vehicle appearance.
bool serviceathelipad
service helicopters at helipads automatically (no need to send to depot)
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
DestinationID GetDestination() const
Gets the destination of this order.
bool IsType(OrderType type) const
Check whether this order is of the given type.
OrderType GetType() const
Get the type of order of this order.
void MakeDummy()
Makes this order a Dummy order.
OrderDepotActionFlags GetDepotActionType() const
What are we going to do when in the depot.
void Free()
'Free' the order
void MakeGoToDepot(DestinationID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS, OrderDepotActionFlags action=ODATF_SERVICE_ONLY, CargoType cargo=CARGO_NO_REFIT)
Makes this order a Go To Depot order.
uint16_t w
The width of the area.
TileIndex tile
The base tile of the area.
uint16_t h
The height of the area.
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
static Titem * Get(auto index)
Returns Titem with given index.
Tindex index
Index of this pool item.
Specification of a rectangle with absolute coordinates of all edges.
int Width() const
Get width of Rect.
int Height() const
Get height of Rect.
Titem value
Value of current item.
bool disaster
Play disaster and accident sounds.
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
static Station * Get(auto index)
Gets station with given index.
static Station * GetIfValid(auto index)
Returns station if the index is a valid index for this station type.
T * Next() const
Get next vehicle in the chain.
static Aircraft * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
Coord3D< int8_t > origin
Position of northern corner within tile.
Coord3D< uint8_t > extent
Size of bounding box.
std::array< GoodsEntry, NUM_CARGO > goods
Goods at this station.
Airport airport
Tile area the airport covers.
uint16_t cached_cargo_age_period
Number of ticks before carried cargo is aged.
uint16_t cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
uint8_t plane_crashes
number of plane crashes, 0 = none, 1 = reduced, 2 = normal
uint8_t plane_speed
divisor for speed of aircraft
Sprite sequence for a vehicle part.
bool IsValid() const
Check whether the sequence contains any sprites.
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
void Set(SpriteID sprite)
Assign a single sprite to the sequence.
void CopyWithoutPalette(const VehicleSpriteSeq &src)
Copy data from another sprite sequence, while dropping all recolouring information.
void Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
EngineID engine_type
The type of engine used for this vehicle.
int32_t z_pos
z coordinate.
Direction direction
facing
StationIDStack GetNextStoppingStation() const
Get the next station the vehicle will stop at.
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
virtual uint Crash(bool flooded=false)
Crash the (whole) vehicle chain.
virtual bool IsChainInDepot() const
Check whether the whole vehicle chain is in the depot.
VehicleCargoList cargo
The cargo this vehicle is carrying.
TimerGameEconomy::Date date_of_last_service
Last economy date the vehicle had a service at a depot.
uint16_t cargo_cap
total capacity
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
uint8_t subtype
subtype (Filled with values from AircraftSubType/DisasterSubType/EffectVehicleType/GroundVehicleSubty...
uint16_t random_bits
Bits used for randomized variational spritegroups.
uint8_t day_counter
Increased by one for each day.
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
SpriteID colourmap
NOSAVE: cached colour mapping.
uint8_t breakdown_ctr
Counter for managing breakdown events.
uint GetOldAdvanceSpeed(uint speed)
Determines the effective direction-specific vehicle movement speed.
VehStates vehstatus
Status.
TimerGameCalendar::Date date_of_last_service_newgrf
Last calendar date the vehicle had a service at a depot, unchanged by the date cheat to protect again...
uint8_t subspeed
fractional speed
void LeaveUnbunchingDepot()
Leave an unbunching depot and calculate the next departure time for shared order vehicles.
CargoType cargo_type
type of cargo this vehicle is carrying
uint8_t acceleration
used by train & aircraft
Order current_order
The current order (+ status, like: loading)
Vehicle * Next() const
Get the next vehicle of this vehicle.
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
uint16_t refit_cap
Capacity left over from before last refit.
VehicleCache vcache
Cache of often used vehicle values.
SpriteBounds bounds
Bounding box of vehicle.
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
uint8_t spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
uint16_t cur_speed
current speed
bool IsWaitingForUnbunching() const
Check whether a vehicle inside a depot is waiting for unbunching.
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
uint8_t breakdowns_since_last_service
Counter for the amount of breakdowns.
TimerGameCalendar::Date max_age
Maximum age.
MutableSpriteCache sprite_cache
Cache of sprites and values related to recalculating them, see MutableSpriteCache.
uint16_t reliability
Reliability.
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds,...
uint8_t progress
The percentage (if divided by 256) this vehicle already crossed the tile unit.
void UpdatePositionAndViewport()
Update the position of the vehicle, and update the viewport.
uint16_t reliability_spd_dec
Reliability decrease speed.
uint8_t tick_counter
Increased by one for each tick.
TileIndex tile
Current tile index.
void UpdatePosition()
Update the position of the vehicle.
StationID last_station_visited
The last station we stopped at.
void InvalidateNewGRFCacheOfChain()
Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle)
TimerGameCalendar::Year build_year
Year the vehicle has been built.
Owner owner
Which company owns the vehicle?
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
uint8_t running_ticks
Number of ticks this vehicle was not stopped this day.
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
static debug_inline uint TileHeight(Tile tile)
Returns the height of a tile.
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
static constexpr uint TILE_SIZE
Tile size in world coordinates.
static constexpr uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in ZOOM_BASE.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it,...
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
void EconomyAgeVehicle(Vehicle *v)
Update economy age of a vehicle.
bool CanVehicleUseStation(EngineID engine_type, const Station *st)
Can this station be used by the given engine type?
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
@ Unclickable
Vehicle is not clickable by the user (shadow vehicles).
@ Crashed
Vehicle is crashed.
@ Shadow
Vehicle is a shadow vehicle.
@ AircraftBroken
Aircraft is broken down.
@ Hidden
Vehicle is not visible.
@ DefaultPalette
Use default vehicle palette.
@ Stopped
Vehicle is stopped by the player.
Command definitions for vehicles.
Functions related to vehicles.
EngineImageType
Visualisation contexts of vehicles and engines.
@ EIT_ON_MAP
Vehicle drawn in viewport.
@ VEH_AIRCRAFT
Aircraft vehicle type.
DepotCommandFlag
Flags for goto depot commands.
@ Service
The vehicle will leave the depot right after arrival (service only)
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Window functions not directly related to making/drawing windows.
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers:
@ WC_AIRCRAFT_LIST
Aircraft list; Window numbers:
Functions related to zooming.
int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.