### C++ Iostreams Formatting Example Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/lib/fmt/README.md Demonstrates the verbosity of C++ iostreams for formatting floating-point numbers with a specific precision. It contrasts with the conciseness of printf for the same task. This illustrates the 'chevron hell' problem. ```c++ std::cout << std::setprecision(2) << std::fixed << 1.23456 << "\n"; ``` -------------------------------- ### Print to stdout using fmtlib in C++ Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/lib/fmt/README.md Demonstrates how to print a simple string to the standard output using the fmt::print function. This requires the fmt/core.h header. ```c++ #include int main() { fmt::print("Hello, world!\n"); } ``` -------------------------------- ### Applying Starting States to Aircraft Model with Visitor Pattern (Rust) Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/wasm/systems/README.md Demonstrates how to use the visitor pattern to apply different starting states to an A320 aircraft model. This allows for flexible initialization for various flight phases. ```rust fn main() { let mut airbus = A320::new(); // Ignore boxing for the sake of example simplicity. let startingStateVisitor = match starting_state { StartingState::ColdAndDark => ColdAndDarkStartVisitor {}, StartingState::InFlight => InFlightStartVisitor {}, // etc. } airbus.accept(&startingStateVisitor); } ``` -------------------------------- ### C printf Formatting Example Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/lib/fmt/README.md Shows a concise way to format a floating-point number with a specific precision using the C standard library's printf function. This is presented as a more compact alternative to C++ iostreams for similar tasks. ```c printf("%.2f\n", 1.23456); ``` -------------------------------- ### Write to a file with fmtlib in C++ Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/lib/fmt/README.md Demonstrates writing formatted output to a file using fmt::output_file. This method is noted for its potential speed improvements over fprintf. Requires the fmt/os.h header. ```c++ #include int main() { auto out = fmt::output_file("guide.txt"); out.print("Don't {}", "Panic"); } ``` -------------------------------- ### Unit Test for Contactor Behavior with Simulation Test Bed (Rust) Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/wasm/systems/README.md An example of a unit test using the `SimulationTestBed` to verify that a contactor opens after a specific duration when the APU start is in emergency electrical conditions. It showcases the use of builder-like testing types for complex scenarios. ```rust #[test] fn contactor_opens_after_three_minutes_of_being_closed_for_apu_start_in_emergency_elec() { let test_bed = test_bed_with() .emergency_elec() .available_emergency_generator() .and() .apu_master_sw_pb_on() .run(Duration::from_secs( ClosedContactorObserver::EMER_ELEC_APU_MASTER_MAXIMUM_CLOSED_SECONDS, )); assert!(!test_bed.battery_contactor_is_closed()); } ``` -------------------------------- ### Install Mach Globally via npm Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/systems/instruments/README.md Command to install Mach globally using npm, recommended for cross-platform usage to avoid esbuild-related errors. ```bash $ npm install -g @synaptic-simulations/mach ``` -------------------------------- ### Start Local Webserver for Dumping Source: https://github.com/flybywiresim/aircraft/blob/master/tools/heapdump/README.md This command starts a local Python webserver. This server is used in conjunction with the A32NX Object Dumper to capture and receive the object hierarchy from MSFS. Ensure you are in the correct directory before running this command. ```python python src\tools\heapdump\app.py ``` -------------------------------- ### Print with colors and styles using fmtlib in C++ Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/lib/fmt/README.md Shows how to add color and text styles (bold, underline, italic) to printed output using fmt::print. This requires the fmt/color.h header and a compatible terminal. ```c++ #include int main() { fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold, "Hello, {}!\n", "world"); fmt::print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) | fmt::emphasis::underline, "Olá, {}!\n", "Mundo"); fmt::print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, "你好{}!\n", "世界"); } ``` -------------------------------- ### Print dates and times using fmtlib in C++ Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/lib/fmt/README.md Demonstrates formatting and printing of date and time values using fmt::print with chrono support. This requires the fmt/chrono.h header and C++ chrono library. ```c++ #include #include int main() { auto now = std::chrono::system_clock::now(); fmt::print("Date and time: {} ", now); fmt::print("Time: {:%H:%M} ", now); } ``` -------------------------------- ### Print a container using fmtlib in C++ Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/lib/fmt/README.md Shows how to print the contents of a container, such as std::vector, directly using fmt::print. This requires the fmt/ranges.h header. ```c++ #include #include int main() { std::vector v = {1, 2, 3}; fmt::print("{}\n", v); } ``` -------------------------------- ### Format a string with fmtlib in C++ Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/lib/fmt/README.md Shows how to format a string with a single argument using fmt::format. The formatted string is stored in a std::string object. This requires the fmt/core.h header. ```c++ std::string s = fmt::format("The answer is {}.", 42); // s == "The answer is 42." ``` -------------------------------- ### Format a string with positional arguments in C++ Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/lib/fmt/README.md Illustrates string formatting using positional arguments with fmt::format. This allows for reordering or reusing arguments in the format string. Requires the fmt/core.h header. ```c++ std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy"); // s == "I'd rather be happy than right." ``` -------------------------------- ### Instrument Configuration JSON Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/systems/instruments/README.md Example JSON structure for configuring a new instrument, including the main entry file and interactivity. ```json { "index": "./index.tsx", "isInteractive": false, } ``` -------------------------------- ### Load and Parse XML File Example Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/lib/tinyxml2/readme.md A basic example demonstrating how to load and parse an XML file using the XMLDocument class. This is a fundamental operation for working with XML data in TinyXML-2. ```cpp { XMLDocument doc; doc.LoadFile( "dream.xml" ); } ``` -------------------------------- ### Compile-time format string check in C++ Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/lib/fmt/README.md An example showing how fmtlib can catch format string errors at compile time in C++20. This example intentionally uses an invalid format specifier for a string. ```c++ std::string s = fmt::format("{:d}", "I am not a number"); ``` -------------------------------- ### Install Localazy CLI Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/localization/README.md This command installs the Localazy Command Line Interface (CLI) globally on your system using npm (Node Package Manager). This allows you to use Localazy commands directly from your terminal for managing localization files. ```bash npm install -g @localazy/cli ``` -------------------------------- ### Instrument Rendering Logic (Vanilla JS) Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/systems/instruments/README.md Example JavaScript code demonstrating how to import a render target and manually modify its style for an instrument. ```javascript import { renderTarget } from '../util.js'; // modify it manually... renderTarget.style.backgroundColor = 'red'; ``` -------------------------------- ### Instrument Rendering Logic (React) Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/systems/instruments/README.md Example JavaScript code demonstrating how to import ReactDOM and render a React component into the instrument's render target. ```javascript import { renderTarget } from '../util.js'; // or use a rendering library... ReactDOM.render(, renderTarget); ``` -------------------------------- ### Start: Start motor time to W Raw Data Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/systems/systems/src/apu/PW980.md This raw data provides time points and corresponding 'W' values, likely representing engine power or thrust during the initial start phase. This data serves as the basis for the polynomial regression model. ```text second, W 0, 0; 1, 9938; 2, 8357; 3, 7057; 4, 6745; 5, 6483; 6, 6322; 7, 5875; 8, 5512; 9, 5232; 10, 4923; 11, 4642; 12, 4362; 13, 4055; 14, 3813; 15, 3645; 16, 3309; 17, 3085; 18, 2945; 21, 2575; 22, 2401; 23, 2256; 24, 2055; 25, 2053; 26, 467; 27, 0; ``` -------------------------------- ### Start: Start motor time to W Polynomial Regression (Desmos) Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/systems/systems/src/apu/PW980.md This is a 7th-degree polynomial regression equation generated using Desmos, modeling the relationship between time from start and the 'W' parameter (likely related to thrust or power). The equation is: y = 9933.45... - 1319.14x + ... - 0.000066x^7. It requires a computational environment capable of evaluating polynomial functions. ```text y=9933.45316867122252237659-1319.1431831932327x+236.32171392861937x^{2}-34.01201082369166x^{3}+3.168505536233231x^{4}-0.17850758460976182x^{5}+0.005403593330801297x^{6}-0.0000663926018728314x^{7} ``` -------------------------------- ### Start Motor: Time to W Data Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/systems/systems/src/apu/APS3200.md This dataset contains time in seconds from engine start and corresponding 'W' values. It serves as the raw data from which the polynomial regression formula for time to 'W' was derived. The data shows a rapid decrease in 'W' after an initial period. ```text second, W 0, 0; 1, 9938; 2, 8357; 3, 7057; 4, 6745; 5, 6483; 6, 6322; 7, 5875; 8, 5512; 9, 5232; 10, 4923; 11, 4642; 12, 4362; 13, 4055; 14, 3813; 15, 3645; 16, 3309; 17, 3085; 18, 2945; 21, 2575; 22, 2401; 23, 2256; 24, 2055; 25, 2053; 26, 467; 27, 0 ``` -------------------------------- ### Startup: Time to N Data Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/systems/systems/src/apu/APS3200.md This dataset maps time in seconds from the start of the engine to specific 'N' values, likely representing engine RPM or a related parameter. This data is intended for generating a polynomial regression to model the engine's N progression during startup. ```text second, N 0, 0; 1, 4; 2, 11; 3, 14; 4, 17; 5, 20; 6, 22; 7, 23; 8, 26; 9, 27; 10, 29; 11, 30; 12, 32; 13, 33; 14, 35; 15, 36; 16, 37; 17, 39; 18, 41; 19, 43; 20, 45; 21, 47; 22, 49; 23, 52; 24, 54; 25, 56; 26, 58; 27, 60; 28, 62; 29, 65; 30, 67; 31, 69; 32, 72; 33, 74; 34, 75; 35, 77; 36, 79; 37, 81; 38, 83; 39, 85; 40, 88; 41, 91; 42, 93; 43, 96; 44, 99; 45, 100 ``` -------------------------------- ### Create Symlink for FS2020 Community Folder (Windows CMD) Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/docs/resources.md This command creates a directory junction (symlink) on Windows using cmd. It links a local development repository to the Microsoft Flight Simulator Community folder, allowing for direct development and testing without manual file copying. Ensure you replace the placeholder paths with your actual user and repository paths. It's recommended to remove any existing mod installation before creating the symlink. ```cmd mklink /J "C:\users\\AppData\Microsoft Flight Simulator\Packages\Community\flybywire-aircraft-a320-neo" "C:\path\to\cloned\repo\flybywire-aircraft-a320-neo" ``` -------------------------------- ### Engine State Management (C++) Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/docs/a320-simvars.md Defines the actual state of an engine using numerical values. These states include OFF, ON, STARTING, and SHUTTING. This variable is essential for controlling engine lifecycle events within the simulation. ```c++ enum class EngineState { OFF = 0, ON = 1, STARTING = 2, SHUTTING = 3 }; // Example usage: int currentEngineState = 1; // Engine is ON ``` -------------------------------- ### Stream XML Printing without XMLDocument Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/lib/tinyxml2/readme.md Provides an example of printing XML content directly using XMLPrinter without constructing an XMLDocument. This is useful for streaming operations where DOM overhead is undesirable. ```cpp XMLPrinter printer( fp ); printer.OpenElement( "foo" ); printer.PushAttribute( "foo", "bar" ); printer.CloseElement(); ``` -------------------------------- ### BaseInstrument Initialization with Main Loop Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/docs/Classes.md The `BaseInstrument` class includes a `connectedCallback` method that initiates the main update loop for the instrument. This method is crucial for the instrument's operational cycle, ensuring that its systems and handlers are updated regularly to reflect the simulation's state. The call to `createMainLoop()` within `connectedCallback` signifies the start of this update process. ```javascript class BaseInstrument extends HTMLElement { connectedCallback() { createMainLoop(); } } ``` -------------------------------- ### Lookup XML Information with TinyXML-2 C++ Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/lib/tinyxml2/readme.md Demonstrates how to load an XML file and extract text content from specific elements using TinyXML-2. This example shows two methods for accessing text data within nested XML structures. It assumes the existence of a 'dream.xml' file with a 'PLAY' root element containing a 'TITLE' element. ```cpp /* ------ Example 2: Lookup information. ---- */ { XMLDocument doc; doc.LoadFile( "dream.xml" ); // Structure of the XML file: // - Element "PLAY" the root Element, which is the // FirstChildElement of the Document // - - Element "TITLE" child of the root PLAY Element // - - - Text child of the TITLE Element // Navigate to the title, using the convenience function, // with a dangerous lack of error checking. const char* title = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" )->GetText(); printf( "Name of play (1): %s\n", title ); // Text is just another Node to TinyXML-2. The more // general way to get to the XMLText: XMLText* textNode = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" )->FirstChild()->ToText(); title = textNode->Value(); printf( "Name of play (2): %s\n", title ); } ``` -------------------------------- ### Build All Instruments with Mach CLI Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/systems/instruments/README.md Command to build all instruments using the Mach CLI. Assumes the working directory is 'fbw-a32nx' or 'fbw-a380x'. ```bash $ mach build ``` -------------------------------- ### Rust: Standard Comments Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/systems/guidelines.md Illustrates the standard Rust comment format, which begins with a space followed by a sentence adhering to basic punctuation rules. These comments are not typically included in generated documentation. ```rust // Your sentence here. ``` -------------------------------- ### Build All Instruments with Custom Mach Config Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/systems/instruments/README.md Command to build all instruments using the Mach CLI with a specified configuration file and working directory. ```bash $ mach build --config path/to/mach.config.js --work-in-config-dir ``` -------------------------------- ### Build ACE Instruments with npm Script Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/systems/instruments/README.md Command to trigger the build process for ACE instruments using a convenience npm script, which utilizes the older rollup pipeline. ```bash $ npm run build:ace ``` -------------------------------- ### Upload Source File using Localazy CLI Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/localization/README.md These commands utilize the Localazy CLI to upload updated source localization files. The `-w ` flag authenticates the upload, `-c` specifies the configuration file, and `-d` indicates the target directory (flypad or msfs). A test run can be performed using the `-s` option. ```bash cd fbw-a32nx/src/localization localazy upload -w -c localazy-flypad-upload-config.json -d flypad ``` ```bash cd fbw-a32nx/src/localization localazy upload -w -c localazy-locPak-upload-config.json -d msfs ``` -------------------------------- ### Upload Localazy Source File for FlyPad (Shell) Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a380x/src/localization/README.md This command uploads the source file for the flyPad localization to Localazy. It requires a write key and a configuration file. The '-d flypad' argument specifies the target directory for flypad. ```shell cd fbw-a32nx/src/localization localazy upload -w -c localazy-flypad-upload-config.json -d flypad ``` -------------------------------- ### FADEC Igniter Status (C++) Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/docs/a320-simvars.md Represents the activation status of igniters A and B for each engine. This boolean variable is crucial for simulating the ignition sequence during engine start and for managing specific FADEC-related functionalities. ```c++ // Example of igniter status bool engine1_igniter_A_active = true; bool engine2_igniter_B_active = false; // This would be controlled by the FADEC logic and simulation events. ``` -------------------------------- ### Fetch and Configure Google Test Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/test/CMakeLists.txt Fetches the Google Test framework from a Git repository and configures it for the project. This ensures that the testing framework is available and properly integrated into the build environment. ```cmake set(FETCHCONTENT_QUIET OFF) set(FETCHCONTENT_UPDATES_DISCONNECTED ON) include(FetchContent) # GOOGLE TEST message("Downloading/Update Google Test") FetchContent_Declare( googletest GIT_REPOSITORY https://github.com/google/googletest.git GIT_TAG v1.13.0 ) FetchContent_Declare(googletest) set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) option(INSTALL_GMOCK OFF) option(INSTALL_GTEST OFF) FetchContent_MakeAvailable(googletest) ``` -------------------------------- ### Configure CMake Build for FlyByWire Aircraft Source: https://github.com/flybywiresim/aircraft/blob/master/CMakeLists.txt This is the main CMakeLists.txt file for the project. It initializes the build system, sets C++ standards, defines compiler flags for WASM targets, specifies include directories, and adds preprocessor definitions. It then includes subdirectories for common and aircraft-specific modules. ```cmake cmake_minimum_required(VERSION 3.18) project(flybywire-aircraft C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_VERBOSE_MAKEFILE OFF) set(FBW_ROOT ${CMAKE_CURRENT_SOURCE_DIR}) set(FBW_COMMON ${FBW_ROOT}/fbw-common/src/wasm) # cmake helper scripts include("${FBW_COMMON}/cpp-msfs-framework/cmake/TargetDefinition.cmake") # compiler refinement set(COMPILER_FLAGS "-Wall -Wextra -Wno-unused-function -Wno-unused-command-line-argument -Wno-ignored-attributes -Wno-macro-redefined -target wasm32-unknown-wasi --sysroot \"${MSFS_SDK}/WASM/wasi-sysroot\" -mthread-model single -fno-exceptions -fms-extensions -fvisibility=hidden -ffunction-sections -fdata-sections -Werror=return-type -fno-stack-protector -fstack-size-section -mbulk-memory") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${COMPILER_FLAGS}") set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -flto -O2 -DNDEBUG") set(CMAKE_C_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -DDEBUG") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COMPILER_FLAGS}") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -flto -O2 -DNDEBUG") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -DDEBUG") message("MSFS_SDK: " ${MSFS_SDK}) # add the include paths include_directories( "${MSFS_SDK}/WASM/include" "${MSFS_SDK}/WASM/wasi-sysroot/include" "${MSFS_SDK}/WASM/wasi-sysroot/include/c++/v1" "${MSFS_SDK}/SimConnect SDK/include" "${FBW_COMMON}/cpp-msfs-framework/lib" "${FBW_COMMON}/cpp-msfs-framework/MsfsHandler" "${FBW_COMMON}/cpp-msfs-framework/MsfsHandler/DataTypes" ) # add compiler definitions add_definitions( -D_MSFS_WASM=1 -D__wasi__ -D_LIBC_NO_EXCEPTIONS -D_LIBCPP_HAS_NO_THREADS -D_WINDLL -D_MBCS # ZERO_LVL=0 CRITICAL_LVL=1 ERROR_LVL=2 WARN_LVL=3 INFO_LVL=4 DEBUG_LVL=5 VERBOSE=6 TRACE_LVL=7 -DLOG_LEVEL=4 # EXAMPLES | NO_EXAMPLES -DNO_EXAMPLES #PROFILING | NO_PROFILING - for logging of profiling information of pre-, post-, update() calls -DNO_PROFILING # disable MSFS header min/max macros which clobber std::min/max -DNOMINMAX # MSFS stdlib uses 64-bit off_t for lseek etc. -D_FILE_OFFSET_BITS=64 ) # add the common components add_subdirectory(fbw-common/src/wasm) # add the A32NX components add_subdirectory(fbw-a32nx/src/wasm) # add the A380X components add_subdirectory(fbw-a380x/src/wasm) ``` -------------------------------- ### Shutdown: Time to N Data Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/systems/systems/src/apu/APS3200.md This dataset maps time in seconds from the start of the shutdown sequence to corresponding 'N' values. It shows the progression of the engine parameter 'N' as it decreases during shutdown, which can be used to model the shutdown timeline. ```text second, N 0, 100; 1, 79; 2, 60; 3, 48; 4, 39; 5, 32; 6, 27; 7, 23; 8, 21; 9, 19; 10, 17; 11, 16; 12, 14; 13, 13; 14, 12; 15, 11; 16, 10; 17, 10; 18, 9; 19, 8; 20, 8; 21, 8; 22, 7; 23, 7; 24, 6; 25, 6; 26, 6; 27, 5; 28, 5; 29, 5; 30, 4; 31, 4; 32, 4; 33, 4; 34, 4; 35, 3; 36, 3; 37, 3; 38, 3; 39, 3; 40, 2; 41, 2; 42, 2; 43, 2; 44, 2; 45, 1; 46, 0.8; 47, 0.6; 48, 0.4; 49, 0.2; 50, 0 ``` -------------------------------- ### Configure extra-backend-a32nx CMake Build Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/wasm/extra-backend-a32nx/CMakeLists.txt This snippet configures the CMake build for the extra-backend-a32nx library. It adds compiler definitions, includes necessary directories for source and common framework files, and defines the source and header files that constitute the library. It then creates an OBJECT library and a Wasm library target. ```cmake add_definitions() # add the local include directories include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/src/AircraftPresets ${CMAKE_CURRENT_SOURCE_DIR}/src/LightingPresets ${CMAKE_CURRENT_SOURCE_DIR}/src/Pushback ${FBW_COMMON}/cpp-msfs-framework/ ${FBW_COMMON}/extra-backend/ ) # define the source files set(SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/src/Gauge_Extra_Backend.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/LightingPresets/LightingPresets_A32NX.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Pushback/Pushback_A32NX.cpp ${FBW_COMMON}/cpp-msfs-framework/Example/ExampleModule.cpp ${FBW_COMMON}/extra-backend/Pushback/Pushback.cpp ${FBW_COMMON}/extra-backend/AircraftPresets/AircraftPresets.cpp ${FBW_COMMON}/extra-backend/LightingPresets/LightingPresets.cpp ) set(INCLUDE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/src/LightingPresets/LightingPresets_A32NX.h ${CMAKE_CURRENT_SOURCE_DIR}/src/Pushback/Pushback_A32NX.h ${FBW_COMMON}/cpp-msfs-framework/Example/ExampleModule.h ${FBW_COMMON}/cpp-msfs-framework/Example/longtext.h ${FBW_COMMON}/extra-backend/Pushback/Pushback.h ${FBW_COMMON}/extra-backend/AircraftPresets/AircraftPresets.h ${FBW_COMMON}/extra-backend/AircraftPresets/PresetProcedures.hpp ${FBW_COMMON}/extra-backend/AircraftPresets/ProcedureStep.hpp ${FBW_COMMON}/extra-backend/LightingPresets/LightingPresets.h ) # create the targets add_library(extra-backend-a32nx OBJECT ${SOURCE_FILES} ${INCLUDE_FILES}) add_wasm_library( NAME extra-backend-a32nx DEPENDENCIES extra-backend-a32nx cpp-msfs-framework-a32nx ) ``` -------------------------------- ### Configure New Instrument (JSON) Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a380x/src/systems/instruments/README.md Defines the main file and interactivity of a new instrument. The 'index' property specifies the entry point file, and 'isInteractive' determines if the instrument handles user input. ```json { "index": "./index.jsx", "isInteractive": false } ``` -------------------------------- ### Read Simulator Data using Rust's SimulationElement Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/systems/README.md Illustrates how to implement the `read` function for the `SimulationElement` trait in Rust to retrieve data from the simulator. It shows an example for an `Engine` struct, reading corrected N2 values and updating its internal state. ```rust pub struct Engine { corrected_n2_id: String, corrected_n2: Ratio, } impl Engine { pub fn new(number: usize) -> Engine { Engine { corrected_n2_id: format!("TURB ENG CORRECTED N2:{}", number), corrected_n2: Ratio::new::(0.), } } } impl SimulationElement for Engine { fn read(&mut self, reader: &mut SimulatorReader) { // As this function is invoked for every simulation tick // we try not to format the string here, but instead do it // once in the constructor function. self.corrected_n2 = Ratio::new::(reader.read_f64(&self.corrected_n2_id)); } } ``` -------------------------------- ### Avoiding Re-reading Written SimVars in Rust Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/wasm/systems/guidelines.md Rust code should not re-read SimVars that it has previously written. Instead, the data should be passed directly through structs. This example demonstrates how to refactor code to accept a trait object representing a pressure source, rather than reading a specific SimVar. ```rust // INCORRECT impl SimulationElement for X { fn read(&mut self, reader: &mut SimulatorReader) { // HYD_GREEN_PRESSURE is written by the hydraulic system in Rust. self.hyd_green_pressure = reader.read("HYD_GREEN_PRESSURE"); } } // CORRECT impl X { fn uses_hyd_green_pressure(&mut self, green: &impl PressureSource) { self.hyd_green_pressure = green.pressure(); } } ``` -------------------------------- ### Build FlyPad Translations Locally Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/systems/instruments/src/EFB/Localization/README.md This npm script command triggers a local build process to download and update the FlyPad translation files from Localazy. It is used to integrate the latest translations into the local development environment. ```bash npm run build:efb-translation local ``` -------------------------------- ### Implicit Enum Variant Values in Rust Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/wasm/systems/guidelines.md When defining enums with sequential integer values, explicitly assigning each variant's value is unnecessary and discouraged. The Rust compiler automatically assigns values starting from 0. This practice improves code readability by reducing verbosity. ```rust // INCORRECT enum FlapsConf { Conf0 = 0, Conf1 = 1, Conf1F = 2, } // CORRECT enum FlapsConf { Conf0, Conf1, Conf1F, } ``` -------------------------------- ### Multi-Stage Build Configuration - TypeScript (Igniter) Source: https://context7.com/flybywiresim/aircraft/llms.txt This configuration file for Igniter defines a multi-stage build process for the A32NX project. It orchestrates tasks for preparation, building TypeScript/React, and compiling WASM modules (Rust, C++), allowing for parallel execution of independent tasks to optimize build times. The configuration specifies dependencies between task groups and individual tasks. ```typescript // igniter.config.mjs - Build configuration import { ExecTask, TaskOfTasks } from '@flybywiresim/igniter'; export default new TaskOfTasks('all', [ new TaskOfTasks('a32nx', [ // Preparation phase - copy files new TaskOfTasks('preparation', [ new ExecTask('copy-base-files', [ 'npm run build-a32nx:copy-base-files', 'npm run build-a32nx:copy-large-files', ]), new TaskOfTasks('localization', [ new ExecTask('efb-translation', 'npm run build-a32nx:efb-translation'), new ExecTask('locPak-translation', 'npm run build-a32nx:locPak-translation'), ], true), // Run in parallel ], false), // Run sequentially // Build phase - TypeScript/React new TaskOfTasks('build', [ new ExecTask('model', 'npm run build-a32nx:model', [ 'fbw-a32nx/src/model', 'fbw-a32nx/out/flybywire-aircraft-a320-neo/SimObjects/AirPlanes/FlyByWire_A320_NEO/model', ]), new ExecTask('fmgc', 'node fbw-a32nx/src/systems/fmgc/build.js'), new ExecTask('instruments', 'mach build --config fbw-a32nx/mach.config.js'), ], true), // Run in parallel // WASM phase - Rust and C++ new TaskOfTasks('wasm', [ new ExecTask('systems', 'cargo build -p a320_systems_wasm --target wasm32-wasip1 --release'), new ExecTask('fbw', 'cd fbw-a32nx/src/wasm/fbw_a320 && ./build.sh'), new ExecTask('cpp-wasm-cmake', 'npm run build:cpp-wasm-cmake'), ], true), // Run in parallel ]), ]); ``` -------------------------------- ### Create Test Executable and Discover Tests Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/test/CMakeLists.txt Creates a C++ executable for running tests and links it with Google Test libraries. It then uses `gtest_discover_tests` to automatically find and register all tests defined in the source files. ```cmake include_directories( ${googletest_SOURCE_DIR}/googletest/include ${INCLUDE_FILES} ) # Google Test executable set(testExeName cpp-framework-test) include(GoogleTest) add_executable(${testExeName} ${SOURCE_FILES} ${INCLUDE_FILES}) target_link_libraries(${testExeName} PUBLIC gtest gtest_main) gtest_discover_tests(${testExeName}) ``` -------------------------------- ### Explicit Match Pattern Declaration in Rust Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/systems/guidelines.md Demonstrates the preferred method of explicitly declaring all patterns in a Rust 'match' statement instead of using a wildcard '_'. This ensures compile-time checking for exhaustiveness when new enum variants are added. It also shows an example where '_' is acceptable for numeric types when followed by a panic. ```rust enum AutobrakeMode { NONE, LOW, MED, MAX, HIGH, RTO, BTV, } // INCORRECT match self.mode { AutobrakeMode::NONE => // ..., AutobrakeMode::LOW | AutobrakeMode::MED => { // ... } _ => { // ... } } // CORRECT match self.mode { AutobrakeMode::NONE => // ..., AutobrakeMode::LOW | AutobrakeMode::MED => { // ... } AutobrakeMode::MAX | AutobrakeMode::HIGH | AutobrakeMode::RTO | AutobrakeMode::BTV => { // ... } } ``` ```rust enum PressureValveSignal { Open, Neutral, Close, } match value { 0 => PressureValveSignal::Open, 1 => PressureValveSignal::Neutral, 2 => PressureValveSignal::Close, _ => panic!("{}" cannot be converted into PressureValveSignal", value), } ``` -------------------------------- ### Build MSFS locPak Translations Locally Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/systems/instruments/src/EFB/Localization/README.md This npm script command initiates a local build process to download and update the MSFS locPak translation files from Localazy. This command is essential for developers to incorporate the latest translated strings into their local builds. ```bash npm run build:locPak-translation local ``` -------------------------------- ### Passing Structs vs. Values in Rust Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/wasm/systems/guidelines.md When passing data related to struct members, prefer passing the entire struct (or a reference to it) rather than individual values read from the struct. This prevents other types from being responsible for determining which data to pass. The example shows how to refactor incorrect sequential updates to a more consolidated approach. ```rust // INCORRECT self.sfcc .update(context, self.flaps_handle.signal_new_position()); self.flap_gear.update( context, self.sfcc.signal_flap_movement(self.flap_gear.current_angle()), ); // CORRECT self.sfcc.update( context, &self.flaps_handle, &self.flap_gear, ); self.flap_gear.update(context, &self.sfcc); ``` -------------------------------- ### Configure CMake Build for extra-backend-a380x Library Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a380x/src/wasm/extra-backend-a380x/CMakeLists.txt This snippet configures the CMake build for the 'extra-backend-a380x' library. It defines compiler definitions, include directories, source and header files, and creates both an object library and a WASM library target. ```cmake add_definitions() # add the local include directories include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/src/AircraftPresets ${CMAKE_CURRENT_SOURCE_DIR}/src/LightingPresets ${CMAKE_CURRENT_SOURCE_DIR}/src/Pushback ${FBW_COMMON}/cpp-msfs-framework/ ${FBW_COMMON}/extra-backend/ ) # define the source files set(SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/src/Gauge_Extra_Backend.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/LightingPresets/LightingPresets_A380X.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Pushback/Pushback_A380X.cpp ${FBW_COMMON}/cpp-msfs-framework/Example/ExampleModule.cpp ${FBW_COMMON}/extra-backend/Pushback/Pushback.cpp ${FBW_COMMON}/extra-backend/AircraftPresets/AircraftPresets.cpp ${FBW_COMMON}/extra-backend/LightingPresets/LightingPresets.cpp ) set(INCLUDE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/src/LightingPresets/LightingPresets_A380X.h ${CMAKE_CURRENT_SOURCE_DIR}/src/Pushback/Pushback_A380X.h ${FBW_COMMON}/cpp-msfs-framework/Example/ExampleModule.h ${FBW_COMMON}/cpp-msfs-framework/Example/longtext.h ${FBW_COMMON}/extra-backend/Pushback/Pushback.h ${FBW_COMMON}/extra-backend/AircraftPresets/AircraftPresets.h ${FBW_COMMON}/extra-backend/AircraftPresets/PresetProcedures.hpp ${FBW_COMMON}/extra-backend/AircraftPresets/ProcedureStep.hpp ${FBW_COMMON}/extra-backend/LightingPresets/LightingPresets.h ) # create the targets add_library(extra-backend-a380x OBJECT ${SOURCE_FILES} ${INCLUDE_FILES}) add_wasm_library( NAME extra-backend-a380x DEPENDENCIES extra-backend-a380x cpp-msfs-framework-a380x ) ``` -------------------------------- ### Simplifying Trait `where` Clauses in Rust Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/wasm/systems/guidelines.md When implementing traits, the `where Self: Sized` clause can often be omitted if it's already present in the trait definition. This reduces code redundancy and simplifies maintenance, as changes to the trait's `where` clause won't require updates in all implementations. The example shows the removal of an unnecessary `where` clause. ```rust // INCORRECT fn accept(&mut self, visitor: &mut T) where Self: Sized, { self.lo_button.accept(visitor); visitor.visit(self); } // CORRECT fn accept(&mut self, visitor: &mut T) { self.lo_button.accept(visitor); visitor.visit(self); } ``` -------------------------------- ### Modern Crate Imports in Rust (Avoiding `extern crate`) Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/wasm/systems/guidelines.md Use the `use` keyword for importing crates directly, avoiding the `extern crate` syntax. The `extern crate` declaration is generally unnecessary in Rust 2018 edition and later, making the code more concise and adhering to modern practices. The example illustrates the preferred `use` statement. ```rust // INCORRECT extern crate nalgebra; use nalgebra::Vector3; // CORRECT use nalgebra::Vector3; ``` -------------------------------- ### Initialize and Use ATSU/CPDLC for ATC Communications Source: https://context7.com/flybywiresim/aircraft/llms.txt Demonstrates initializing the ATSU system, logging on to an ATC station, sending CPDLC messages, handling position reports, and retrieving ATIS information. It also shows how to process incoming messages and send responses. ```typescript // Initialize ATSU const atsu = new Atsu(); await atsu.connectAtc(); // Log on to ATC station const logonResult = await atsu.atc.logon('EGLL_CTR'); if (logonResult === AtsuStatusCodes.Ok) { console.log(`Logged on to ${atsu.atc.currentStation()}`); } // Send a CPDLC message (request climb to FL370) const message = new CpdlcMessage(); message.Station = 'EGLL_CTR'; message.Content.push( CpdlcMessagesDownlink.DM9[1].deepCopy() // REQUEST [altitude] ); message.Content[0].Content[0].Value = 'FL370'; await atsu.atc.sendMessage(message); // Create and send position report const posReport = atsu.atc.createPositionReport(); await atsu.atc.sendMessage(posReport); // Enable automatic position reports atsu.atc.toggleAutomaticPositionReportActive(); // Receive ATIS for departure const atisResult = await atsu.atc.receiveAtis('EGLL', AtisType.Departure); if (atisResult === AtsuStatusCodes.Ok) { // ATIS received successfully const messages = atsu.atc.messages(); const atisMsg = messages.find(m => m.Type === AtsuMessageType.ATIS); console.log(`ATIS: ${atisMsg?.serialize()}`); } // Enable auto-update for arrival ATIS atsu.atc.activateAtisAutoUpdate({ icao: 'EGLL', type: AtisType.Arrival }); // Handle incoming messages const incomingMessages = atsu.atc.messages(); for (const msg of incomingMessages) { if (msg.Direction === AtsuMessageDirection.Input && !msg.Confirmed) { console.log(`New message from ${msg.Station}: ${msg.serialize()}`); // Send WILCO response atsu.atc.sendResponse(msg.UniqueId, CpdlcMessagesUplink.UM0[1].Response); } } ``` -------------------------------- ### Upload Localazy Source File for MSFS locPak (Shell) Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a380x/src/localization/README.md This command uploads the source file for the MSFS locPak localization to Localazy. It requires a write key and a configuration file. The '-d msfs' argument specifies the target directory for msfs. ```shell cd fbw-a32nx/src/localization localazy upload -w -c localazy-locPak-upload-config.json -d msfs ``` -------------------------------- ### Instantiate Custom Modules in Gauge C++ Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/wasm/cpp-msfs-framework/README.md This C++ code snippet shows how to instantiate custom modules within the Gauge_Extra_Backend.cpp file. It demonstrates adding new modules like LightingPresets, Pushback, and AircraftPresets by passing the MsfsHandler to their constructors. This is the primary location for adding new modules. ```cpp MsfsHandler msfsHandler("Gauge_Extra_Backend_A32NX", "A32NX_"); // ADD ADDITIONAL MODULES HERE // This is the only place these have to be added - everything else is handled automatically LightingPresets_A32NX lightingPresets(msfsHandler); Pushback pushback(msfsHandler); AircraftPresets aircraftPresets(msfsHandler, AircraftPresetProcedures_A32NX::aircraftProcedureDefinition); ``` -------------------------------- ### Initialize and Run A320 Simulation in MSFS Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-a32nx/src/wasm/systems/README.md This Rust code snippet initializes and runs the A320 simulation within the Microsoft Flight Simulator (MSFS) environment. It sets up the simulation loop, processing events and ticking the simulation state based on the simulator's delta time. The `A320SimulatorReaderWriter` and `A320` types are unaware of the simulator, promoting testability. ```rust #[msfs::gauge(name=systems)] async fn systems(mut gauge: msfs::Gauge) -> Result<(), Box> { let mut reader_writer = A320SimulatorReaderWriter::new()?; let mut a320 = A320::new(); let mut simulation = Simulation::new(&mut a320, &mut reader_writer); while let Some(event) = gauge.next_event().await { if let MSFSEvent::PreDraw(d) = event { simulation.tick(d.delta_time()); } } Ok(()) } ``` -------------------------------- ### Upload Localization File to Localazy Source: https://github.com/flybywiresim/aircraft/blob/master/fbw-common/src/systems/instruments/src/EFB/Localization/data/README.md Uploads the `en.json` localization file to Localazy using the Localazy CLI. Requires a write key and a configuration file. The `-d flypad` argument specifies the target for the upload. ```bash localazy upload -w -c localazy-flypad-upload-config.json -d flypad ```