XPLMPlanes

To use:

import xp

The XPLMPlanes APIs allow you to control the various aircraft in X-Plane, both the user’s and the sim’s.

You cannot initialize a flight from just any XPLM callback. Only initialize in:

  • Command handlers

  • Menu handlers

  • UI handlers (mouse, keyboard callbacks from XPLMDisplay / widgets)

  • Flightmodel processing pre-flightmodel phase only

Do not initialize during:

  • Flightmodel processing post-flightmodel phase

  • Dataref get/set handlers

  • Drawing callbacks of any kind

Note that while it’s permitted to execute some of these functions in the XPluginStart or XPluginEnable callbacks in your global plugin, it may not be sensible. Start and Enable are usually executed before the aircraft has been loaded, so any update you provide may be over-written by the normal startup.

Check your work.

With X-Plane version 12.4 introduced a new powerful way to initialize and modify a flight. Modifications include changing time, weather, failures, and AI aircraft.

Functions

initFlight(data)
Parameters

data (str) – dict or JSON string.

Returns

0 on success raises FlightInitError exception on error

Requires at least X-Plane 12.4.

Initializes a new flight, ending the users’s current flight. The flight config is provided as a json string. If parameter is a dict type, we’ll convert it to JSON.

See Laminar Flight Initialization API for JSON format specification.

To start a new flight, you must provide an aircraft and a start location (runway or ramp or ground start or air start, etc.)

For example, a quick start at Boston:

>>> s = {'ramp_start': {
...           'airport_id': 'KBOS',
...           'ramp': 'B3'
...           },
...      'aircraft': {
...           'path': 'Aircraft/Laminar Research/Cessna 172 SP/Cessna_172SP.acf'
...           }
...     }
...
>>> xp.initFlight(s)
0

While there are resources you might use to determine available values for ramps and runways, Laminar has not provided any way list them a priori. They are visible on the Map, if you zoom in far enough. Check log files for errors.

updateFlight(data)
Parameters

data (str) – dict or JSON string.

Returns

0 on success raises FlightInitError exception on error

Requires at least X-Plane 12.4.

Updates the user’s current flight, modifying some flight parameters. The flight config is provided as a json string. If parameter is a dict type, we’ll convert it to JSON.

>>> xp.updateFlight({'local_time': {'day_of_year': 15, 'time_in_24_hours': 2.}})
0
>>> xp.updateFlight({'weather': {'definition': 'vfr_few_clouds'}})
Traceback (most recent call last):
XPLMPlanes.FlightInitError: weather json invalid, one or more of these keys are missing: 'definition',
'vertical_speed_in_thermal_in_feet_per_minute', 'wave_height_in_meters', 'wave_direction_in_degrees',
'terrain_state', 'variation_across_region_percentage', 'evolution_over_time_enum'. Provided
string was: "vfr_few_clouds"
(code=1)

See Laminar Flight Initialization API for JSON format specification.

Old style functions

For X-Plane 12.4 and greater, the new JSON style functions are preferred. Otherwise you may use these older style initialization functions.

setUsersAircraft(path)
Parameters

path (str) – Full or relative path to aircraft’s “.acf” file.

This routine changes the user’s aircraft. Note that this will reinitialize the user to be on the nearest airport’s first runway with its engines running.

path is either relative to X-Plane root, or fully qualified path, including the .acf extension.

If the acf file cannot be found the user will be notified and their aircraft will be re-initialized.

>>> xp.setUsersAircraft("Aircraft/Laminar Research/Cessna 172 SP/Cessna_172SP_G1000.acf")
>>> xp.setUsersAircraft("/Volumes/SSD1/X-Plane/Aircraft/Laminar Research/Cessna 172 SP/Cessna_172SP_G1000.acf")

Official SDK XPLMSetUsersAircraft

placeUserAtAirport(code)
Parameters

code (str) – Airport ICAO code

This routine places the user at a given airport. Specify the airport by its ICAO code (e.g. ‘KBOS’).

Warning

Using an invalid airport code will crash the sim, this includes using something other than ICAO. For example, ‘JFK’ does not work.

Note

You cannot call placeUserAtAirport() in your Start or Enable callback as the (initial) user aircraft has not yet been placed (you will crash the sim). You may create a flight loop callback and then execute placeUserAtAirport() within the callback, or in response to a menu or command.

>>> xp.placeUserAtAirport('KBOS')

Official SDK XPLMPlaceUserAtAirport

placeUserAtLocation(latitude, longitude, elevation, heading, speed)
Parameters
  • latitude (float) –

  • longitude (float) – location in decimal degrees

  • elevation (float) – meters MSL

  • heading (float) – degrees True.

  • speed (float) – meters per second

Places the user at a specific location after performing any necessary scenery loads.

As with in-air starts initiated from the X-Plane user interface, the aircraft will always start with its engines running, regardless of the user’s preferences (i.e., regardless of what the dataref sim/operation/prefs/startup_running says).

elevation is meters MSL (1 meter = 3.28084 feet),
heading is degrees True, (use getMagneticVariation() to convert.)
speed is meters per second (1 meter per second = 1.94384 knots).
>>> xp.placeUserAtLocation(35, -122.5, 2000 / 3.28084, 90, 110 / 1.94384)

Official SDK XPLMPlaceUserAtLocation

countAircraft()
Returns

Tuple of three integers (max aircraft, current aircraft, controlling plugin)

Return three integers representing:

  • the number of aircraft X-Plane is capable of having,

  • the number of aircraft that are currently active.

  • The pluginID of the plugin currently controlling the aircraft. (-1 for none)

These numbers count the user’s aircraft plus the number of AI Aircraft (to increase the max you would need to manually add more AI Aircraft).

>>> xp.countAircraft()
(4, 4, -1)

Official SDK XPLMCountAircraft

getNthAircraftModel(int: index) (model, path):
Parameters

index (int) – 0-based index of aircraft information to get

Returns

Tuple with two elements: (filename, full path)

Return two strings based on the aircraft index. User’s aircraft is always 0.

  • filename of aircraft

  • path to the model filename

>>> xp.getNthAircraftModel(0)
('Cessna_172SP.acf', '/Volumes/SSD1/X-Plane/Aircraft/Laminar Research/Cessna 172SP/Cessna_172SP.acf')

Official SDK XPLMGetNthAircraftModel

acquirePlanes(aircraft=None, callable=None, refCon=none)
Parameters
  • aircraft (None) – this parameter is deprecated

  • callable (Callable) – Callback to notify you when you’re able to acquire planes

  • refCon (Any) – Reference Constant passed to your callback

Returns

1 on successful acquisition.

Grants your plugin exclusive access to the aircraft. It returns 1 if you gain access, 0 if you do not. If you received 0 and you provided a callback, you’ll get notification when acquired.

In the simplest form, attempt to acquire all the aircraft:

>>> xp.acquirePlanes()
1

If you provide a callback, and do not immediately get access, acquirePlanes() will return 0, and call you callback when able. Your callback() is passed the refCon. If you are able to acquire immediately, you callback will not be called.

>>> def MyCallback(refCon):
...    xp.log("Acquired airplanes")
...
>>> xp.acquirePlanes(callback=MyCallback)
1

aircraft is supposed to be a list of strings, specifying the planes you want to load, this does not appear to do anything in X-Plane 11, so keep it set to None. (Laminar has confirmed this does nothing in 11.5, and they suggest the parameter is deprecated and will not be fixed.)

Official SDK XPLMAcquirePlanes

releasePlanes()

Call this function to release access to the planes (acquirePlanes()). Note that if your plugin is disabled, access to planes is released for you and you must reacquire it.

Official SDK XPLMReleasePlanes

setActiveAircraftCount(count)
Parameters

count (int) – Sets number of active planes (effectively reducing # of AI aircraft)

This routine sets the number of active planes. If you pass in a number higher than the total number of planes available, only the total number of planes available is actually used.

You must have exclusive access to planes first (acquirePlanes())

>>> xp.countAircraft()
(4, 4, -1)
>>> xp.acquirePlanes()
1
>>> xp.setActiveAircraftCount(6)
>>> xp.countAircraft()
(4, 4, 3)  # '3' being my plugin ID
>>> xp.setActiveAircraftCount(2)
>>> xp.countAircraft()
(4, 2, 3)  # '3' being my plugin ID
>>> xp.releasePlanes()

Official SDK XPLMSetActiveAircraftCount

setAircraftModel(index, path)
Parameters
  • index (int) – aircraft index (i.e., which AI aircraft…)

  • path (str) – Aircraft *.acf file

This routine loads an aircraft model. It may only be called if you have exclusive access to the airplane APIs (acquirePlanes()). Pass in the path of the model with the .acf extension. Path may be relative X-Plane Root. The index is zero based, but you may not pass in 0 (use setUsersAircraft() to load the user’s aircraft).

This does not add a new AI aircraft, if you use an index greater than current aircraft count. (It will do nothing.)

If the aircraft path is invalid, the user will be notified.

>>> xp.acquirePlanes()
1
>>> xp.setAircraftModel(2, 'Aircraft/Laminar Research/Boeing B737-800/b738.acf')
>>> xp.releasePlanes()

Official SDK XPLMSetAircraftModel

disableAIForPlane(index)
Parameters

index (int) – aircraft index

This routine turns off X-Plane’s AI for a given plane. The plane will continue to be drawn and be a “real” plane in X-Plane, but will not move itself.

Note

There is no enableAIForPlane() function: you cannot simple re-enable AI. However, if you acquire all planes, set the active count to 1 (User aircraft only) and then reset the count to something larger than 1, all of the added aircraft will have their AI re-enabled once you call xp.releasePlanes()

It seems this is likely an unintended side-effect, but works for XP11 and XP12.

Official SDK XPLMDisableAIForPlane

Constants

FlightInitError

Exception raised on bad initFlight() and updateFlight(). Has two attributes.

  • code: one of XPLMInitResult, and

  • message: string describing the problem.

USER_AIRCRAFT = 0

User’s Aircraft

Return value from initialization

XPLMInitResult

Code

Meaning

Init_Success

The initialization succeeded

Init_Invalid = 1

Provided argument was invalid. Either not valid json, or does not contain correct fields.

Init_MissingAircraft = 2

Valid argument, but one of the requested aircraft could not be found on disk or loaded.

Init_MissingLivery = 3

Valid argument, but one of the requested aircraft’s liveries could not be found or loaded.

Init_MissingAirport = 4

Valid argument, but the requested airport was not found.

Init_MissingRamp = 5

Valid argument, but the requested ram start was not found at the specified airport.

Init_MissingRunway = 6

Valid argument, but the requested runway was not found at the specified airport.