### Python Data Comparison Example Source: https://github.com/uglydwarf/x-plane_plugins/blob/master/XPython/README_TODO.txt Demonstrates Python's ability to compare dictionaries for equality regardless of key order. This is relevant for understanding how 'refcon' values might be compared in the plugin. ```python >>> a = {'a': 1, 'b': 2} >>> b = {'b': 2, 'a': 1} >>> a == b True ``` -------------------------------- ### Python Script Messaging API (Get Info) Source: https://github.com/uglydwarf/x-plane_plugins/blob/master/XPython/README_TODO.txt Fetches the name, signature, and description for a given X-Plane script ID. This function is essential for introspecting loaded scripts. ```python PI_GetScriptInfo(scriptID, &name, &signature, &description) ``` -------------------------------- ### XPLMLoadObjectAsync Callback Signature Change Source: https://github.com/uglydwarf/x-plane_plugins/blob/master/XPython/README_SDK.txt Illustrates the change in the callback registration for XPLMLoadObjectAsync. In XPPython3, 'self' is no longer passed as the first parameter to callback functions, simplifying the interface. ```python XPLMLoadObjectAsync(path, callback, refcon) ``` -------------------------------- ### Enable Native Paths in XPPython3 Source: https://github.com/uglydwarf/x-plane_plugins/blob/master/XPython/README_SDK.txt This code snippet demonstrates how to enable native path usage within XPPython3 plugins. Native paths are automatically enabled on startup in XPPython3, and this function explicitly sets the feature. ```python XPLMEnableFeature("XPLM_USE_NATIVE_PATHS", 1) ``` -------------------------------- ### XPLM API: Get Global Screen Bounds Source: https://github.com/uglydwarf/x-plane_plugins/blob/master/XPython/README_TODO.txt Returns the global screen boundaries of the X-Plane application window. This function is planned for an update to use return values instead of 'out' parameters. ```c void XPLMGetScreenBoundsGlobal(int *outLeft, int *outTop, int *outRight, int *outBottom); ``` -------------------------------- ### XPLM API: Get Hot Key Info Source: https://github.com/uglydwarf/x-plane_plugins/blob/master/XPython/README_TODO.txt Retrieves detailed information about a registered hot key, including its virtual key code, flags, description, and associated plugin. The function is to be updated to return values. ```c void XPLMGetHotKeyInfo(int inHotKey, int *outVirtualKey, int *outFlags, char *outDescription, XPLMPluginID *outPlugin); ``` -------------------------------- ### XPLM API: Get Window Geometry Source: https://github.com/uglydwarf/x-plane_plugins/blob/master/XPython/README_TODO.txt Retrieves the rectangular boundaries of a specified X-Plane window. The function signature will change from using 'out' parameters to direct return values. ```c void XPLMGetWindowGeometry(int inWindowID, int *outLeft, int *outTop, int *outRight, int *outBottom); ``` -------------------------------- ### XPLM API: Get Screen Size Source: https://github.com/uglydwarf/x-plane_plugins/blob/master/XPython/README_TODO.txt Retrieves the dimensions of the X-Plane screen. This function was previously using 'out' parameters and is being refactored to use real returns for better clarity and Pythonic style. ```c void XPLMGetScreenSize(int *outWidth, int *outHeight); ``` -------------------------------- ### Python Script Messaging API (Get Nth) Source: https://github.com/uglydwarf/x-plane_plugins/blob/master/XPython/README_TODO.txt Retrieves the ID of the script at a specific index in the list of loaded X-Plane scripts. Part of the script messaging interface. ```python scriptID = PI_GetNthScript(index) ``` -------------------------------- ### XPLM API: Get VR Window Geometry Source: https://github.com/uglydwarf/x-plane_plugins/blob/master/XPython/README_TODO.txt Provides the dimensions of an X-Plane window in VR (Virtual Reality) mode, specified in boxels. This function is targeted for refactoring to return values. ```c void XPLMGetWindowGeometryVR(int inWindowID, int *outWidthBoxels, int *outHeightBoxels); ``` -------------------------------- ### XPLM API: Get OS Window Geometry Source: https://github.com/uglydwarf/x-plane_plugins/blob/master/XPython/README_TODO.txt Fetches the operating system-level geometry for an X-Plane window. Similar to other geometry functions, this will be updated to return values instead of using 'out' parameters. ```c void XPLMGetWindowGeometryOS(int inWindowID, int *outLeft, int *outTop, int *outRight, int *outBottom); ``` -------------------------------- ### Handling Widget Callback Parameters in XPPython3 Source: https://github.com/uglydwarf/x-plane_plugins/blob/master/XPython/README_SDK.txt Details how mouse and keyboard event data is passed to widget callbacks in XPPython3. Functions like PI_GetMouseState() and PI_GetKeyState() are no longer supported, with data now provided directly as parameters. ```python # For Mouse Events (xpMsg_MouseDown, xpMsg_MouseDrag, xpMsg_MouseUp, xpMsp_CursorAdjust) # param1 will be a tuple (x, y, button, delta) # For Keyboard Events (xpMsg_KeyPress) # param1 will be a tuple (key, flags, vkey) # For Widget Geometry (xpMsg_Reshape) # param1 will be a tuple (dx, dy, dwidth, dheight) ``` -------------------------------- ### XPLM API: Get Global Mouse Location Source: https://github.com/uglydwarf/x-plane_plugins/blob/master/XPython/README_TODO.txt Obtains the current global coordinates of the mouse cursor within the X-Plane window. This API is being updated from 'out' parameters to return values. ```c void XPLMGetMouseLocationGlobal(int *outX, int *outY); ``` -------------------------------- ### Retrieve Internal Plugin Dictionaries with XPLMPythonGetDicts Source: https://github.com/uglydwarf/x-plane_plugins/blob/master/XPython/README_SDK.txt This function, XPLMPythonGetDicts, allows plugins to access internal Python dictionaries managed by XPPython3. These dictionaries store lists of items registered by each plugin and can be used for read-only access. ```python internal_dicts = XPLMUtilities.XPLMPythonGetDicts() ``` -------------------------------- ### XPPython3 Plugin Lifecycle Methods (Python) Source: https://context7.com/uglydwarf/x-plane_plugins/llms.txt Defines the standard lifecycle methods required for an XPPython3 plugin. These methods are called by X-Plane at different stages of the plugin's operation, including startup, shutdown, enabling, disabling, and message reception. The `XPluginStart` method is crucial for initializing the plugin by returning its name, signature, and description. ```python class PythonInterface: def XPluginStart(self): """Called when plugin is loaded. Return (name, signature, description) tuple.""" self.Name = "My Plugin" self.Sig = "com.example.myplugin" self.Desc = "A sample XPPython3 plugin" return self.Name, self.Sig, self.Desc def XPluginStop(self): """Called when plugin is unloaded. Clean up resources here.""" pass def XPluginEnable(self): """Called when plugin is enabled. Return 1 for success, 0 for failure.""" return 1 def XPluginDisable(self): """Called when plugin is disabled.""" pass def XPluginReceiveMessage(self, inFromWho, inMessage, inParam): """Called when X-Plane sends messages to plugins.""" pass ``` -------------------------------- ### Manage Commands in Python Source: https://context7.com/uglydwarf/x-plane_plugins/llms.txt Demonstrates how to find, create, register handlers for, and execute X-Plane commands using the XPLMCommand API. It covers registering custom command handlers and intercepting existing commands to add custom behavior. It also shows how to programmatically execute commands and handle command phases like begin, continue, and end. ```python from XPLMUtilities import ( XPLMFindCommand, XPLMCreateCommand, XPLMCommandOnce, XPLMCommandBegin, XPLMCommandEnd, XPLMRegisterCommandHandler, XPLMUnregisterCommandHandler, xplm_CommandBegin, xplm_CommandContinue, xplm_CommandEnd ) class PythonInterface: def XPluginStart(self): # Find existing X-Plane command self.pause_cmd = XPLMFindCommand("sim/operation/pause_toggle") # Create custom command self.my_command = XPLMCreateCommand( "myplugin/do_something", "Performs the plugin's main action" ) # Register handler for custom command self.cmd_handler_ref = self.command_handler XPLMRegisterCommandHandler( self.my_command, self.cmd_handler_ref, True, # Before X-Plane processes "cmd_refcon" ) # Intercept gear toggle to add custom behavior self.gear_cmd = XPLMFindCommand("sim/flight_controls/landing_gear_toggle") self.gear_handler_ref = self.gear_interceptor XPLMRegisterCommandHandler( self.gear_cmd, self.gear_handler_ref, True, "gear_refcon" ) return "Command Demo", "com.example.command", "Command demonstration" def command_handler(self, command_ref, phase, refcon): """Handle custom command execution.""" if phase == xplm_CommandBegin: print("Command started") self.perform_action() elif phase == xplm_CommandContinue: print("Command held down") elif phase == xplm_CommandEnd: print("Command released") return 1 # Let command continue to other handlers def gear_interceptor(self, command_ref, phase, refcon): """Intercept gear command to add sound effect.""" if phase == xplm_CommandBegin: self.play_gear_sound() return 1 # Allow normal gear processing def execute_pause(self): """Execute pause command programmatically.""" if self.pause_cmd: XPLMCommandOnce(self.pause_cmd) # Momentary press def hold_brakes(self, duration_seconds): """Hold brakes command for specified duration.""" brake_cmd = XPLMFindCommand("sim/flight_controls/brakes_toggle_max") if brake_cmd: XPLMCommandBegin(brake_cmd) # ... wait duration ... XPLMCommandEnd(brake_cmd) def XPluginStop(self): XPLMUnregisterCommandHandler( self.my_command, self.cmd_handler_ref, True, "cmd_refcon" ) XPLMUnregisterCommandHandler( self.gear_cmd, self.gear_handler_ref, True, "gear_refcon" ) ``` -------------------------------- ### Create Custom Menus in X-Plane with Python Source: https://context7.com/uglydwarf/x-plane_plugins/llms.txt Demonstrates how to create a custom menu, add menu items (including a toggle and a separator), and handle menu item clicks using the XPLMMenus API in Python. It covers finding the plugins menu, creating a new submenu, appending items, setting check states, and destroying the menu on plugin stop. ```python from XPLMMenus import ( XPLMFindPluginsMenu, XPLMCreateMenu, XPLMDestroyMenu, XPLMAppendMenuItem, XPLMAppendMenuSeparator, XPLMCheckMenuItem, XPLMEnableMenuItem, xplm_Menu_Checked, xplm_Menu_Unchecked, xplm_Menu_NoCheck ) class PythonInterface: def XPluginStart(self): self.menu_item_refs = {} # Get plugins menu plugins_menu = XPLMFindPluginsMenu() # Create submenu under Plugins self.my_menu = XPLMCreateMenu( "My Plugin", # Menu name plugins_menu, # Parent menu 0, # Item index (ignored for top-level) self.menu_handler, # Callback for menu items "menu_refcon" # Reference constant ) # Add menu items self.menu_item_refs["toggle"] = XPLMAppendMenuItem( self.my_menu, "Toggle Feature", "toggle_item", # Item reference for callback 0 # Deprecated, ignored ) XPLMAppendMenuSeparator(self.my_menu) self.menu_item_refs["settings"] = XPLMAppendMenuItem( self.my_menu, "Settings...", "settings_item", 0 ) # Set initial check state self.feature_enabled = False XPLMCheckMenuItem( self.my_menu, self.menu_item_refs["toggle"], xplm_Menu_Unchecked ) return "Menu Demo", "com.example.menu", "Menu demonstration" def menu_handler(self, menu_ref, item_ref): """Called when user clicks a menu item.""" if item_ref == "toggle_item": self.feature_enabled = not self.feature_enabled XPLMCheckMenuItem( self.my_menu, self.menu_item_refs["toggle"], xplm_Menu_Checked if self.feature_enabled else xplm_Menu_Unchecked ) print(f"Feature {'enabled' if self.feature_enabled else 'disabled'}") elif item_ref == "settings_item": self.show_settings_window() def XPluginStop(self): XPLMDestroyMenu(self.my_menu) ``` -------------------------------- ### Display and Window API Source: https://context7.com/uglydwarf/x-plane_plugins/llms.txt This API enables creating floating windows with mouse/keyboard input, drawing callbacks, hotkey registration, and key sniffers for UI development. ```APIDOC ## Display and Window API ### Description The Display API enables creating floating windows with mouse/keyboard input, drawing callbacks, hotkey registration, and key sniffers for UI development. ### Core Functions - **XPLMCreateWindowEx**: Creates a new window with specified parameters and callbacks. - **XPLMDestroyWindow**: Destroys an existing window. - **XPLMSetWindowTitle**: Sets the title of a window. - **XPLMSetWindowIsVisible**: Controls the visibility of a window. - **XPLMGetWindowIsVisible**: Retrieves the current visibility status of a window. - **XPLMSetWindowGeometry**: Sets the position and size of a window. - **XPLMGetWindowGeometry**: Retrieves the position and size of a window. - **XPLMSetWindowPositioningMode**: Sets how a window is positioned (e.g., centered). - **XPLMTakeKeyboardFocus**: Assigns keyboard focus to a specific window. - **XPLMRegisterHotKey**: Registers a keyboard shortcut. - **XPLMUnregisterHotKey**: Unregisters a previously registered hotkey. - **XPLMRegisterKeySniffer**: Registers a callback to intercept keyboard events. - **XPLMUnregisterKeySniffer**: Unregisters a key sniffer. - **XPLMGetScreenBoundsGlobal**: Gets the bounds of the primary screen. - **XPLMGetMouseLocationGlobal**: Gets the current global mouse coordinates. ### Window Creation Parameters (for XPLMCreateWindowEx) 1. `left` (integer): The left screen coordinate of the window. 2. `top` (integer): The top screen coordinate of the window. 3. `right` (integer): The right screen coordinate of the window. 4. `bottom` (integer): The bottom screen coordinate of the window. 5. `visible` (integer): 1 if the window should be visible, 0 otherwise. 6. `draw_callback` (function): A function to draw the window's content. 7. `mouse_callback` (function): A function to handle mouse events. 8. `key_callback` (function): A function to handle keyboard events. 9. `cursor_callback` (function): A function to determine the cursor type. 10. `refcon` (any): A reference constant passed to callbacks. 11. `decoration` (integer): The window decoration style (e.g., `xplm_WindowDecorationRoundRectangle`). 12. `layer` (integer): The window layer (e.g., `xplm_WindowLayerFloatingWindows`). 13. `content_refcon` (any): A reference constant for window content (used in some callbacks). 14. `right_click_callback` (function): A function to handle right-click events (optional). ### Hotkey Registration Parameters (for XPLMRegisterHotKey) 1. `virtual_key` (integer): The virtual key code (e.g., `XPLM_VK_P`). 2. `modifiers` (integer): Modifier flags (e.g., `xplm_ShiftFlag`). 3. `description` (string): A description of the hotkey. 4. `callback` (function): The function to call when the hotkey is pressed. 5. `refcon` (any): A reference constant passed to the callback. ### Callback Function Signatures - **`draw_callback(window_id, refcon)`**: Called to draw window content. Needs OpenGL drawing code. - **`handle_mouse(window_id, x, y, mouse_status, refcon)`**: Handles mouse events. `mouse_status` can be `xplm_MouseDown`, `xplm_MouseUp`, etc. Return 1 to consume the event. - **`handle_key(window_id, key, flags, vkey, refcon, losing_focus)`**: Handles keyboard input when the window has focus. - **`handle_cursor(window_id, x, y, refcon)`**: Returns the cursor type (e.g., `xplm_CursorDefault`). - **`handle_wheel(window_id, x, y, wheel, clicks, refcon)`**: Handles mouse wheel events. - **`handle_right_click(window_id, x, y, mouse_status, refcon)`**: Handles right-click events. - **`hotkey_callback(refcon)`**: Called when the registered hotkey is pressed. ### Example Usage (Python) ```python from XPLMDisplay import ( XPLMCreateWindowEx, XPLMDestroyWindow, XPLMSetWindowTitle, XPLMSetWindowIsVisible, XPLMGetWindowIsVisible, XPLMSetWindowGeometry, XPLMGetWindowGeometry, XPLMSetWindowPositioningMode, XPLMTakeKeyboardFocus, XPLMRegisterHotKey, XPLMUnregisterHotKey, XPLMRegisterKeySniffer, XPLMUnregisterKeySniffer, XPLMGetScreenBoundsGlobal, XPLMGetMouseLocationGlobal, xplm_WindowDecorationRoundRectangle, xplm_WindowLayerFloatingWindows, xplm_WindowCenterOnMonitor, xplm_CursorDefault, xplm_MouseDown, xplm_MouseUp, xplm_MouseDrag ) from XPLMDefs import xplm_ShiftFlag, XPLM_VK_P class PythonInterface: def XPluginEnable(self): # Get screen bounds for positioning l, t, r, b = [], [], [], [] XPLMGetScreenBoundsGlobal(l, t, r, b) # Define window callbacks self.win_refcon = ["my_window_data"] # Create modern X-Plane 11 style window params = [ l[0] + 100, t[0] - 100, # Left, Top l[0] + 400, t[0] - 300, # Right, Bottom 1, # Visible self.draw_window, # Draw callback self.handle_mouse, # Mouse click callback self.handle_key, # Key press callback self.handle_cursor, # Cursor callback self.handle_wheel, # Mouse wheel callback self.win_refcon, # Reference constant xplm_WindowDecorationRoundRectangle, xplm_WindowLayerFloatingWindows, self.handle_right_click # Right-click callback ] self.window_id = XPLMCreateWindowEx(params) XPLMSetWindowTitle(self.window_id, "My Plugin Window") XPLMSetWindowPositioningMode(self.window_id, xplm_WindowCenterOnMonitor, -1) # Register hotkey (Shift+P) self.hotkey_refcon = ["hotkey_data"] self.hotkey_id = XPLMRegisterHotKey( XPLM_VK_P, xplm_ShiftFlag, "Toggle My Window", self.hotkey_callback, self.hotkey_refcon ) return 1 def draw_window(self, window_id, refcon): """Called each frame to draw window contents.""" pass # Add OpenGL drawing code here def handle_mouse(self, window_id, x, y, mouse_status, refcon): """Handle mouse clicks.""" if mouse_status == xplm_MouseDown: print(f"Mouse clicked at ({x}, {y})") return 1 # Consume the click def handle_key(self, window_id, key, flags, vkey, refcon, losing_focus): """Handle keyboard input when window has focus.""" if not losing_focus: print(f"Key pressed: {key}") def handle_cursor(self, window_id, x, y, refcon): return xplm_CursorDefault def handle_wheel(self, window_id, x, y, wheel, clicks, refcon): print(f"Wheel: {'vertical' if wheel == 0 else 'horizontal'}, {clicks} clicks") return 1 def handle_right_click(self, window_id, x, y, mouse_status, refcon): return 1 def hotkey_callback(self, refcon): """Toggle window visibility when hotkey pressed.""" visible = XPLMGetWindowIsVisible(self.window_id) XPLMSetWindowIsVisible(self.window_id, 0 if visible else 1) def XPluginStop(self): XPLMUnregisterHotKey(self.hotkey_id) XPLMDestroyWindow(self.window_id) ``` -------------------------------- ### Access System Info and Utilities in Python Source: https://context7.com/uglydwarf/x-plane_plugins/llms.txt Provides functions to retrieve X-Plane version details, system paths, and directory contents using the XPLMUtilities API. It also demonstrates debugging by writing to Log.txt, using text-to-speech announcements, and checking the simulation's language setting. Includes a function to reload scenery. ```python from XPLMUtilities import ( XPLMGetVersions, XPLMGetSystemPath, XPLMGetPrefsPath, XPLMGetDirectoryContents, XPLMDebugString, XPLMSpeakString, XPLMReloadScenery, XPLMGetLanguage, xplm_Language_English ) class PythonInterface: def XPluginStart(self): # Get version information xplane_ver, xplm_ver, host_id = XPLMGetVersions() print(f"X-Plane {xplane_ver}, XPLM {xplm_ver}") # Get system paths system_path = XPLMGetSystemPath() # X-Plane installation folder prefs_path = XPLMGetPrefsPath() # User preferences folder # Write to Log.txt for debugging XPLMDebugString(f"[MyPlugin] Initialized at {system_path}\n") # Text-to-speech announcement XPLMSpeakString("Plugin loaded successfully") # List directory contents aircraft_folder = f"{system_path}Aircraft" result, files, total = XPLMGetDirectoryContents( aircraft_folder, 0, # Start at first file 2048, # Buffer size 100 # Max entries ) print(f"Found {total} items in Aircraft folder") for filename in files[:10]: print(f" - {filename}") # Check language lang = XPLMGetLanguage() if lang == xplm_Language_English: self.load_english_strings() return "Utilities Demo", "com.example.utils", "Utilities demonstration" def reload_scenery_area(self): """Reload scenery (useful after editing scenery files).""" XPLMReloadScenery() ``` -------------------------------- ### Create and Manage X-Plane Window with Python Source: https://context7.com/uglydwarf/x-plane_plugins/llms.txt This Python snippet demonstrates how to create and manage a floating window in X-Plane using the XPLMDisplay API. It includes registering callbacks for drawing, mouse events, keyboard input, cursor display, and mouse wheel events. It also shows how to set window properties like title, geometry, and positioning, and how to register and unregister a hotkey to toggle window visibility. ```python from XPLMDisplay import ( XPLMCreateWindowEx, XPLMDestroyWindow, XPLMSetWindowTitle, XPLMSetWindowIsVisible, XPLMGetWindowIsVisible, XPLMSetWindowGeometry, XPLMGetWindowGeometry, XPLMSetWindowPositioningMode, XPLMTakeKeyboardFocus, XPLMRegisterHotKey, XPLMUnregisterHotKey, XPLMRegisterKeySniffer, XPLMUnregisterKeySniffer, XPLMGetScreenBoundsGlobal, XPLMGetMouseLocationGlobal, xplm_WindowDecorationRoundRectangle, xplm_WindowLayerFloatingWindows, xplm_WindowCenterOnMonitor, xplm_CursorDefault, xplm_MouseDown, xplm_MouseUp, xplm_MouseDrag ) from XPLMDefs import xplm_ShiftFlag, XPLM_VK_P class PythonInterface: def XPluginEnable(self): # Get screen bounds for positioning l, t, r, b = [], [], [], [] XPLMGetScreenBoundsGlobal(l, t, r, b) # Define window callbacks self.win_refcon = ["my_window_data"] # Create modern X-Plane 11 style window params = [ l[0] + 100, t[0] - 100, # Left, Top l[0] + 400, t[0] - 300, # Right, Bottom 1, # Visible self.draw_window, # Draw callback self.handle_mouse, # Mouse click callback self.handle_key, # Key press callback self.handle_cursor, # Cursor callback self.handle_wheel, # Mouse wheel callback self.win_refcon, # Reference constant xplm_WindowDecorationRoundRectangle, xplm_WindowLayerFloatingWindows, self.handle_right_click # Right-click callback ] self.window_id = XPLMCreateWindowEx(params) XPLMSetWindowTitle(self.window_id, "My Plugin Window") XPLMSetWindowPositioningMode(self.window_id, xplm_WindowCenterOnMonitor, -1) # Register hotkey (Shift+P) self.hotkey_refcon = ["hotkey_data"] self.hotkey_id = XPLMRegisterHotKey( XPLM_VK_P, xplm_ShiftFlag, "Toggle My Window", self.hotkey_callback, self.hotkey_refcon ) return 1 def draw_window(self, window_id, refcon): """Called each frame to draw window contents.""" pass # Add OpenGL drawing code here def handle_mouse(self, window_id, x, y, mouse_status, refcon): """Handle mouse clicks.""" if mouse_status == xplm_MouseDown: print(f"Mouse clicked at ({x}, {y})") return 1 # Consume the click def handle_key(self, window_id, key, flags, vkey, refcon, losing_focus): """Handle keyboard input when window has focus.""" if not losing_focus: print(f"Key pressed: {key}") def handle_cursor(self, window_id, x, y, refcon): return xplm_CursorDefault def handle_wheel(self, window_id, x, y, wheel, clicks, refcon): print(f"Wheel: {{'vertical' if wheel == 0 else 'horizontal'}}, {clicks} clicks") return 1 def handle_right_click(self, window_id, x, y, mouse_status, refcon): return 1 def hotkey_callback(self, refcon): """Toggle window visibility when hotkey pressed.""" visible = XPLMGetWindowIsVisible(self.window_id) XPLMSetWindowIsVisible(self.window_id, 0 if visible else 1) def XPluginStop(self): XPLMUnregisterHotKey(self.hotkey_id) XPLMDestroyWindow(self.window_id) ``` -------------------------------- ### Utilities API Source: https://context7.com/uglydwarf/x-plane_plugins/llms.txt The Utilities API offers functions for retrieving system information, managing files, debugging, and controlling the simulation environment. ```APIDOC ## Utilities API ### Description The Utilities API provides system information, file operations, debugging, and simulation control functions. ### Methods - **XPLMGetVersions**: Retrieves X-Plane and XPLM version information. - **XPLMGetSystemPath**: Gets the path to the X-Plane installation directory. - **XPLMGetPrefsPath**: Gets the path to the user preferences directory. - **XPLMGetDirectoryContents**: Retrieves a list of files and subdirectories within a specified directory. - **XPLMDebugString**: Writes a string to the X-Plane Log.txt file for debugging. - **XPLMSpeakString**: Uses text-to-speech to announce a string. - **XPLMReloadScenery**: Reloads the scenery data for the current area. - **XPLMGetLanguage**: Gets the current language setting of X-Plane. ### Constants - **xplm_Language_English**: Represents the English language setting. ### Example Usage ```python # Get version information xplane_ver, xplm_ver, host_id = XPLMGetVersions() print(f"X-Plane {xplane_ver}, XPLM {xplm_ver}") # Get system paths system_path = XPLMGetSystemPath() prefs_path = XPLMGetPrefsPath() # Debugging output XPLMDebugString("[MyPlugin] Initialized.\n") # Text-to-speech XPLMSpeakString("Plugin loaded.") # Reload scenery XPLMReloadScenery() ``` ``` -------------------------------- ### Command Management API Source: https://context7.com/uglydwarf/x-plane_plugins/llms.txt The Command API allows for the creation, execution, and interception of commands within X-Plane, enabling custom plugin behaviors. ```APIDOC ## Command Management API ### Description The Command API lets you create new commands, execute existing commands, and intercept command execution for custom behavior. ### Methods - **XPLMFindCommand**: Finds an existing X-Plane command. - **XPLMCreateCommand**: Creates a new custom command. - **XPLMRegisterCommandHandler**: Registers a function to handle command events. - **XPLMUnregisterCommandHandler**: Unregisters a command handler. - **XPLMCommandOnce**: Executes a command once (momentary press). - **XPLMCommandBegin**: Starts the execution of a command. - **XPLMCommandEnd**: Ends the execution of a command. ### Event Phases - **xplm_CommandBegin**: Command is initially pressed or activated. - **xplm_CommandContinue**: Command is being held down. - **xplm_CommandEnd**: Command is released. ### Example Usage ```python # Find existing command self.pause_cmd = XPLMFindCommand("sim/operation/pause_toggle") # Create custom command self.my_command = XPLMCreateCommand("myplugin/do_something", "Performs the plugin's main action") # Register handler for custom command XPLMRegisterCommandHandler(self.my_command, self.command_handler, True, "cmd_refcon") def command_handler(self, command_ref, phase, refcon): if phase == xplm_CommandBegin: print("Command started") elif phase == xplm_CommandContinue: print("Command held down") elif phase == xplm_CommandEnd: print("Command released") return 1 # Let command continue # Execute command programmatically XPLMCommandOnce(self.pause_cmd) ``` ``` -------------------------------- ### X-Plane Data Access API (Python) Source: https://context7.com/uglydwarf/x-plane_plugins/llms.txt Demonstrates the use of the X-Plane Data Access API to interact with simulator datarefs. It shows how to find datarefs, check writability, read/write scalar and array values of different types (int, float, double), and register custom datarefs for inter-plugin communication. Datarefs are essential for accessing and modifying X-Plane's internal state. ```python from XPLMDataAccess import ( XPLMFindDataRef, XPLMCanWriteDataRef, XPLMGetDataRefTypes, XPLMGetDatai, XPLMSetDatai, XPLMGetDataf, XPLMSetDataf, XPLMGetDatad, XPLMSetDatad, XPLMGetDatavi, XPLMSetDatavi, XPLMRegisterDataAccessor, XPLMUnregisterDataAccessor, xplmType_Int, xplmType_Float, xplmType_Double ) # Look up datarefs once at startup (expensive operation) altitude_ref = XPLMFindDataRef("sim/flightmodel/position/elevation") nav1_freq_ref = XPLMFindDataRef("sim/cockpit/radios/nav1_freq_hz") battery_ref = XPLMFindDataRef("sim/cockpit2/electrical/battery_on") # Read scalar values current_altitude = XPLMGetDatad(altitude_ref) # Double precision nav_frequency = XPLMGetDatai(nav1_freq_ref) # Integer # Write values (check if writable first) if XPLMCanWriteDataRef(nav1_freq_ref): XPLMSetDatai(nav1_freq_ref, 11450) # Set NAV1 to 114.50 MHz # Read array values battery_status = [] num_read = XPLMGetDatavi(battery_ref, battery_status, 0, 8) # Read up to 8 batteries print(f"Battery states: {battery_status[:num_read]}") # Register custom dataref for other plugins to read my_value = [100] def get_my_int(refcon): return my_value[0] def set_my_int(refcon, value): my_value[0] = value my_dataref = XPLMRegisterDataAccessor( "myplugin/custom_value", # Dataref name xplmType_Int, # Data type True, # Writable get_my_int, set_my_int, # Int accessors None, None, # Float accessors None, None, # Double accessors None, None, # Int array accessors None, None, # Float array accessors None, None, # Byte array accessors "read_refcon", "write_refcon" ) # Remember to call XPLMUnregisterDataAccessor(my_dataref) in XPluginStop ``` -------------------------------- ### Configure Pylint with PythonStubs Path Source: https://github.com/uglydwarf/x-plane_plugins/blob/master/README.md This configuration snippet shows how to add the PythonStubs directory to the sys.path within Pylint's initialization hook. This allows Pylint to correctly analyze X-Plane SDK modules when developing plugins. ```ini [MASTER] init-hook="import sys;sys.path.extend(['.', '/path_to_stubs/PythonStubs'])" ``` -------------------------------- ### Camera Control API Source: https://context7.com/uglydwarf/x-plane_plugins/llms.txt The Camera API allows plugins to take control of the X-Plane camera for custom views, cinematic sequences, or external applications using X-Plane as a renderer. ```APIDOC ## Camera Control API ### Description The Camera API allows plugins to take control of the X-Plane camera for custom views, cinematic sequences, or external applications using X-Plane as a renderer. ### Methods #### `start_camera_control()` **Description:** Initiates camera control, reading the current position and setting up a callback for frame-by-frame updates. **Usage:** Call this method to begin controlling the camera. ```python from XPLMCamera import XPLMControlCamera, XPLMReadCameraPosition from XPLMGraphics import XPLMLocalToWorld # ... inside a class that has a camera_control method ... x, y, z, pitch, heading, roll, zoom = XPLMReadCameraPosition() lat, lng, alt = XPLMLocalToWorld(x, y, z) print(f"Camera at ({lat:.3f}, {lng:.3f}) altitude {alt:.1f}m") self.camera_callback_ref = self.camera_control XPLMControlCamera( xplm_ControlCameraUntilViewChanges, # Release when user changes view self.camera_callback_ref, ["camera_refcon"] ) ``` #### `camera_control(out_camera_position, is_losing_control, refcon)` **Description:** This callback function is invoked each frame to update the camera's position and orientation. It modifies `out_camera_position` in place and returns a value to indicate whether to continue control. **Parameters:** - `out_camera_position` (list): A list containing `[x, y, z, pitch, heading, roll, zoom]` that should be modified to set the new camera state. - `is_losing_control` (boolean): Indicates if X-Plane is about to take control away from the plugin. - `refcon` (any): A reference constant passed during `XPLMControlCamera`. **Return Value:** - `1` (integer): Continue controlling the camera. - `0` (integer): Release camera control. ```python # ... inside the camera_control method ... if is_losing_control: print("Camera control being taken away") return 0 # Rotate camera slowly (1 degree per frame) out_camera_position[4] += 1 # heading if out_camera_position[4] >= 360: out_camera_position[4] = 0 # Optionally release control if self.should_stop: XPLMDontControlCamera() return 0 return 1 # Continue controlling camera ``` #### `check_camera_status()` **Description:** Checks if the camera is currently being controlled by a plugin and returns the control duration mode. **Usage:** Call this method to query the current camera control status. ```python from XPLMCamera import XPLMIsCameraBeingControlled is_controlled, duration = XPLMIsCameraBeingControlled() if is_controlled: print(f"Camera controlled, duration mode: {duration}") ``` ### Related Functions - `XPLMDontControlCamera()`: Releases control of the camera. - `XPLMIsCameraBeingControlled()`: Checks if the camera is currently controlled. - `XPLMReadCameraPosition()`: Reads the current camera's position, pitch, heading, roll, and zoom. - `XPLMLocalToWorld()`: Converts local X-Plane coordinates to world coordinates (latitude, longitude, altitude). ``` -------------------------------- ### Control X-Plane Camera with Python Source: https://context7.com/uglydwarf/x-plane_plugins/llms.txt This Python snippet demonstrates how to take control of the X-Plane camera, read its position, and update it periodically. It utilizes XPLMCamera module functions and requires XPLMGraphics for coordinate conversion. The control can be released manually or when the user changes the view. ```python from XPLMCamera import ( XPLMControlCamera, XPLMDontControlCamera, XPLMIsCameraBeingControlled, XPLMReadCameraPosition, xplm_ControlCameraUntilViewChanges, xplm_ControlCameraForever ) from XPLMGraphics import XPLMLocalToWorld class PythonInterface: def start_camera_control(self): # Read current camera position x, y, z, pitch, heading, roll, zoom = XPLMReadCameraPosition() lat, lng, alt = XPLMLocalToWorld(x, y, z) print(f"Camera at ({lat:.3f}, {lng:.3f}) altitude {alt:.1f}m") # Take camera control self.camera_callback_ref = self.camera_control XPLMControlCamera( xplm_ControlCameraUntilViewChanges, # Release when user changes view self.camera_callback_ref, ["camera_refcon"] ) def camera_control(self, out_camera_position, is_losing_control, refcon): """Called each frame to update camera position. out_camera_position is a list: [x, y, z, pitch, heading, roll, zoom] Modify it in place to reposition camera. Return 1 to continue control, 0 to release. """ if is_losing_control: print("Camera control being taken away") return 0 # Rotate camera slowly (1 degree per frame) out_camera_position[4] += 1 # heading if out_camera_position[4] >= 360: out_camera_position[4] = 0 # Optionally release control if self.should_stop: XPLMDontControlCamera() return 0 return 1 # Continue controlling camera def check_camera_status(self): is_controlled, duration = XPLMIsCameraBeingControlled() if is_controlled: print(f"Camera controlled, duration mode: {duration}") ``` -------------------------------- ### Manage Flight Loop Callbacks in Python Source: https://context7.com/uglydwarf/x-plane_plugins/llms.txt This Python code snippet shows how to register and unregister flight loop callbacks using the XPLMProcessing module. It covers both simple callback registration and the creation of advanced flight loops with specific phase timing. Callbacks are used for periodic tasks within the X-Plane simulation loop. ```python from XPLMProcessing import ( XPLMRegisterFlightLoopCallback, XPLMUnregisterFlightLoopCallback, XPLMCreateFlightLoop, XPLMDestroyFlightLoop, XPLMScheduleFlightLoop, XPLMGetElapsedTime, XPLMGetCycleNumber, xplm_FlightLoop_Phase_BeforeFlightModel ) class PythonInterface: def XPluginStart(self): # Simple callback registration self.flight_loop_refcon = "my_loop" XPLMRegisterFlightLoopCallback( self.flight_loop_callback, 1.0, # Call 1 second after registration self.flight_loop_refcon ) # Modern flight loop creation with more control self.flight_loop_id = XPLMCreateFlightLoop([ xplm_FlightLoop_Phase_BeforeFlightModel, self.advanced_flight_loop, "advanced_refcon" ]) XPLMScheduleFlightLoop(self.flight_loop_id, 0.5, True) # 0.5 sec from now return "FlightLoop Demo", "com.example.flightloop", "Demo" def flight_loop_callback(self, since_last_call, since_last_loop, counter, refcon): """ Return value controls next callback timing: - 0: Stop receiving callbacks (callback stays registered but inactive) - Positive float: Seconds until next callback - Negative float: Number of loops until next callback (-1 = next loop) """ elapsed = XPLMGetElapsedTime() cycle = XPLMGetCycleNumber() print(f"Flight loop at {elapsed:.2f}s, cycle {cycle}") # Log data or perform I/O here self.log_aircraft_data() return 1.0 # Call again in 1 second def advanced_flight_loop(self, since_last_call, since_last_loop, counter, refcon): # Called before flight model integration return -1 # Call every loop for real-time monitoring def XPluginStop(self): XPLMUnregisterFlightLoopCallback( self.flight_loop_callback, self.flight_loop_refcon ) XPLMDestroyFlightLoop(self.flight_loop_id) ```