### Lua Example for Handling HTTP Requests Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/SetHttpHandler.md An example demonstrating how to set up an HTTP handler in Lua to respond to GET requests on the /ping path with 'pong', and return a 404 for other requests. It shows how to set response headers and send data. ```lua SetHttpHandler(function(request, response) if request.method == 'GET' and request.path == '/ping' then -- if a GET request was sent to the `/ping` path response.writeHead(200, { ['Content-Type'] = 'text/plain' }) -- set the response status code to `200 OK` and the body content type to plain text response.send('pong') -- respond to the request with `pong` else -- otherwise response.writeHead(404) -- set the response status code to `404 Not Found` response.send() -- respond to the request with no data end end) ``` -------------------------------- ### Example Usage of GET_WATER_QUAD_AT_COORDS Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetWaterQuadAtCoords.md This Lua example demonstrates how to get the current player's ped position and then use GET_WATER_QUAD_AT_COORDS to find the water quad index at that location. ```lua local currentPedPosition = GetEntityCoords(PlayerPedId()) local waterQuadIndex = GetWaterQuadAtCoords(currentPedPosition.x, currentPedPosition.y) ``` -------------------------------- ### Install Python Setuptools Source: https://github.com/citizenfx/fivem/blob/master/docs/building.md Installs the setuptools package for Python, which may be required if using Python 3.12 or higher. Ensure Python is installed and in your PATH. ```bat pip install setuptools ``` -------------------------------- ### Set Interior Portal Room From Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/SetInteriorPortalRoomFrom.md Example demonstrating how to set the 'room from' value for an interior portal and refresh the interior. Ensure the interior ID is valid before proceeding. ```c void SET_INTERIOR_PORTAL_ROOM_FROM(int interiorId, int portalIndex, int roomFrom); ``` ```lua local playerPed = PlayerPedId() local interiorId = GetInteriorFromEntity(playerPed) if interiorId ~= 0 then local portalIndex = 0 SetInteriorPortalRoomFrom(interiorId, portalIndex, 0) RefreshInterior(interiorId) end ``` -------------------------------- ### Start a Server Resource Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/StartResource.md Use this function to start a server resource by its name. Ensure the resource name is correct. ```c BOOL START_RESOURCE(char* resourceName); ``` -------------------------------- ### Get Calming Quad Bounds Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetCalmingQuadBounds.md Example of how to call the GetCalmingQuadBounds native function and retrieve the bounds. Ensure the waterQuad index is valid. ```lua local success, minX, minY, maxX, maxY = GetCalmingQuadBounds(1) ``` -------------------------------- ### Register Raw Keymap Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/RegisterRawKeymap.md Example demonstrating how to register a raw keymap with specified functions for key press and release events. Ensure the keymap name is unique. ```lua function on_key_up() print("key no longer pressed") end function on_key_down() print("key is pressed") end local KEY_E = 69 local canBeDisabled = false RegisterRawKeymap("our_keymap", on_key_up, on_key_down, KEY_E, canBeDisabled) ``` -------------------------------- ### Example: Set Steering Lock - C++ Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/SetHandlingField.md This example demonstrates how to set the 'fSteeringLock' field for the 'AIRTUG' vehicle class to 360.0. ```cpp SetHandlingField('AIRTUG', 'CHandlingData', 'fSteeringLock', 360.0) ``` -------------------------------- ### Get Player License Identifier (C#) Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetPlayerIdentifierByType.md This C# example illustrates fetching a player's license identifier when they join and storing it in a dictionary. Ensure the necessary using statements are included. ```csharp using System.Collections.Generic; using static CitizenFX.Core.Native.API; // ... // In class private Dictionary PlayerLicenses = new Dictionary(); // In class constructor EventHandlers["playerJoining"] += new Action(SetLicense); // Delegate method private void SetLicense([FromSource]Player player) { PlayerLicenses.Add(player.Handle, GetPlayerIdentifierByType(player.Handle, "license")); } ``` -------------------------------- ### Get Interior Portal Entity Archetype Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetInteriorPortalEntityArchetype.md Iterates through entities in a specified interior portal and prints their archetypes. Ensure the interior ID is valid before proceeding. ```lua local playerPed = PlayerPedId() local interiorId = GetInteriorFromEntity(playerPed) local portalIndex = 0 if interiorId ~= 0 then local count = GetInteriorPortalEntityCount(interiorId, portalIndex) for i=0, count-1 do local archetype = GetInteriorPortalEntityArchetype(interiorId, portalIndex, i) print("portal " .. portalIndex .." entity " .. i .. " archetype is: " .. archetype) end end ``` -------------------------------- ### Example Usage of SET_INTERIOR_PROBE_LENGTH Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/SetInteriorProbeLength.md Lua examples demonstrating how to use the SET_INTERIOR_PROBE_LENGTH native to extend and reset the interior probe length. ```lua RegisterCommand("setInteriorProbeLength", function(src, args, raw) local probeLength = (tonumber(args[1]) + 0.0) print("Extending interior detection probes to: ", probeLength) SetInteriorProbeLength(probeLength) end) RegisterCommand("resetInteriorProbeLength", function() print("Resetting interior detection probes to default settings") SetInteriorProbeLength(0.0) end) ``` -------------------------------- ### Define a Mojom Interface Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/public/tools/bindings/README.md This is a basic example of a Mojom file defining a simple interface within a module. It serves as a starting point for defining communication protocols. ```mojom module widget.mojom; interface Frobinator { Frobinate(); }; ``` -------------------------------- ### Get Interior Portal Flag Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetInteriorPortalFlag.md Demonstrates how to retrieve and print the flag of the first portal (index 0) of an interior. Ensure the interior ID is valid before calling the function. ```lua local playerPed = PlayerPedId() local interiorId = GetInteriorFromEntity(playerPed) if interiorId ~= 0 then local portalFlag = GetInteriorPortalFlag(interiorId, 0) print("portal 0 flag is: " .. portalRoomFrom) end ``` -------------------------------- ### Setting up JniMocker for Native Method Testing Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/base/android/jni_generator/README.md Provides an example of setting up JniMocker in a JUnit test class to mock native method interfaces. The JniMocker rule and mocker.mock() call in setUp() are essential for stubbing native calls. ```java @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) public class AnimationFrameTimeHistogramTest { @Rule public JniMocker mocker = new JniMocker(); @Mock AnimationFrameTimeHistogram.Natives mNativeMock; @Before public void setUp() { MockitoAnnotations.initMocks(this); mocker.mock(AnimationFrameTimeHistogramJni.TEST_HOOKS, mNativeMock); } @Test public void testNatives() { AnimationFrameTimeHistogram hist = new AnimationFrameTimeHistogram("histName"); hist.startRecording(); hist.endRecording(); verify(mNativeMock).saveHistogram(eq("histName"), any(long[].class), anyInt()); } } ``` -------------------------------- ### Example Usage of GET_PED_BONE_MATRIX Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetPedBoneMatrix.md Example of how to call GET_PED_BONE_MATRIX in Lua to get bone matrix components. ```lua local fowardVector, rightVector, upVector, position = GetPedBoneMatrix(PlayerPedId(),boneId) ``` -------------------------------- ### Example: Using REQUEST_RESOURCE_FILE_SET Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/RequestResourceFileSet.md This example demonstrates how to define a file set in fxmanifest.lua and then request and load files from it in a main script. It includes a command to trigger the file set request and print file contents before and after. ```lua -- fxmanifest.lua file_set 'addon_ui' { 'ui/addon/index.html', 'ui/addon/**.js', } ``` ```lua -- fxmanifest.lua file_set 'dummies' { 'dummy/**.txt', 'potato.txt', } ``` ```lua -- main script local function PrintTest() local tests = { 'potato.txt', 'dummy/1.txt', 'dummy/b/2.txt' } for _, v in ipairs(tests) do local data = LoadResourceFile(GetCurrentResourceName(), v) print(v, data) end end RegisterCommand('fileset', function() PrintTest() while not RequestResourceFileSet('dummies') do Wait(100) end PrintTest() end) ``` -------------------------------- ### Build `event-doc-gen` Source: https://github.com/citizenfx/fivem/blob/master/ext/event-doc-gen/README.md Run this command to generate client and server event documentation in the `out/` directory. Ensure you are in the root of the `event-doc-gen` project. ```bash node index.js ../../code/ ``` -------------------------------- ### Get Aspect Ratio (C++) Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetAspectRatio.md Gets the current aspect ratio of the game screen. No setup or imports are required. ```c++ float GET_ASPECT_RATIO(); ``` -------------------------------- ### Get Number of Doors Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/DoorSystemGetSystemSize.md Call this function to get the total number of doors currently registered in the system. No setup is required. ```c int DOOR_SYSTEM_GET_SIZE(); ``` -------------------------------- ### Use Database and Table Interfaces Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/public/cpp/bindings/README.md Demonstrates how to use the Database and Table interfaces by creating remotes and adding rows. ```cpp mojo::Remote database; DatabaseImpl db_impl(database.BindNewPipeAndPassReceiver()); mojo::Remote table1, table2; database->AddTable(table1.BindNewPipeAndPassReceiver()); database->AddTable(table2.BindNewPipeAndPassReceiver()); table1->AddRow(1, "hiiiiiiii"); table2->AddRow(2, "heyyyyyy"); ``` -------------------------------- ### Run FxDK with SDK URL and Root Path Source: https://github.com/citizenfx/fivem/blob/master/ext/sdk/README.md Use this command to launch FxDK with custom SDK configurations. Ensure the SDK root path uses forward slashes. ```batch .\FiveM.exe -fxdk +set sdk_url http://%COMPUTERNAME%:3000 +set sdk_root_path "%SDK_ROOT_PATH%" ``` -------------------------------- ### Get Calming Quad Count - Lua Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetCalmingQuadCount.md Example of how to call the GetCalmingQuadCount native function in Lua and store the result in a variable. ```lua local calmingQuadCount = GetCalmingQuadCount() ``` -------------------------------- ### Get Invoking Resource Name Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetInvokingResource.md Use this function to get the name of the resource that invoked the current script. No setup or imports are required. ```c char* GET_INVOKING_RESOURCE(); ``` -------------------------------- ### Register Key Mapping Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/RegisterKeyMapping.md This example demonstrates how to register a key mapping for a custom command. It includes setting up a thread to handle the action when the key is pressed and defining the command registration. Use this to create custom controls for your resource. ```lua local handsUp = false CreateThread(function() while true do Wait(0) if handsUp then TaskHandsUp(PlayerPedId(), 250, PlayerPedId(), -1, true) end end end) RegisterCommand('+handsup', function() handsUp = true end, false) RegisterCommand('-handsup', function() handsUp = false end, false) RegisterKeyMapping('+handsup', 'Hands Up', 'keyboard', 'i') -- Alternate keybinding syntax RegisterKeyMapping('~!+handsup', 'Hands Up - Alternate Key', 'keyboard', 'o') ``` -------------------------------- ### Get Interior Room Flag Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetInteriorRoomFlag.md This Lua example demonstrates how to get the flag of the current room a player is in. It first gets the player's ped, then the interior and room hash, converts the hash to an interior room index, and finally retrieves and prints the room's flag. Ensure the room ID is valid before calling GetInteriorRoomFlag. ```lua local playerPed = PlayerPedId() local interiorId = GetInteriorFromEntity(playerPed) local roomHash = GetRoomKeyFromEntity(playerPed) local roomId = GetInteriorRoomIndexByHash(interiorId, roomHash) if roomId ~= -1 then local roomFlag = GetInteriorRoomFlag(interiorId, roomId) print("current room flag is: " .. roomFlag) end ``` -------------------------------- ### Get Ped Collection Local Index Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetPedCollectionLocalIndexFromDrawable.md This Lua example demonstrates how to get the local index for a ped's component variation using the global drawable ID. It then uses this local index along with the collection name to set the ped's component variation. ```lua local ped = PlayerPedId() -- Top for mp_f_freemode_01. From female_freemode_beach collection under index 1. -- Global index is 17 because there is 16 top variations in the base game collection that goes before the female_freemode_beach collection. local name = GetPedDrawableCollectionName(ped, 11, 17) local index = GetPedDrawableCollectionLocalIndex(ped, 11, 17) -- Equivalent to SetPedComponentVariation(ped, 11, 17, 0, 0) SetPedCollectionComponentVariation(ped, 11, name, index, 0, 0) ``` -------------------------------- ### Using Bindings with Invitations Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/public/cpp/system/README.md Demonstrates how to use Mojo bindings interfaces with message pipes obtained from invitations. Shows attaching a message pipe as a receiver in one process and creating a remote interface in another. ```cpp // Process A mojo::OutgoingInvitation invitation; auto pipe = invitation->AttachMessagePipe("x"); mojo::Binding binding( &bar_impl, foo::mojom::BarRequest(std::move(pipe))); // Process B auto invitation = mojo::IncomingInvitation::Accept(...); auto pipe = invitation->ExtractMessagePipe("x"); mojo::Remote bar(mojo::PendingRemote(std::move(pipe), 0)); // Will asynchronously invoke bar_impl.DoSomething() in process A. bar->DoSomething(); ``` -------------------------------- ### Example Usage of GET_CALMING_QUAD_AT_COORDS Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetCalmingQuadAtCoords.md This Lua example demonstrates how to get the player's current ped position and then use it to find the calming quad index at those coordinates. ```lua local currentPedPosition = GetEntityCoords(PlayerPedId()) local calmingQuadIndex = GetCalmingQuadAtCoords(currentPedPosition.x, currentPedPosition.y) ``` -------------------------------- ### Get Vehicle Dashboard Oil Pressure Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetVehicleDashboardOilPressure.md Use this function to get the current oil pressure value from a vehicle's dashboard. No setup or imports are required. ```c float GET_VEHICLE_DASHBOARD_OIL_PRESSURE(); ``` -------------------------------- ### Begin Reading from a Data Pipe (Two-Phase I/O) Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/public/c/system/README.md Use `MojoBeginReadData` to request read access to data in the pipe. `buffer` will point to the data and `num_bytes` will indicate the amount of data available. ```c void* buffer; uint32_t num_bytes = 1024; MojoResult result = MojoBeginReadData(consumer, nullptr, &buffer, &num_bytes); printf("Pipe says: %s", (const char*)buffer); // Should say "hello". // Say we only consumed one byte. result = MojoEndReadData(consumer, 1, nullptr); num_bytes = 1024; result = MojoBeginReadData(consumer, nullptr, &buffer, &num_bytes); printf("Pipe says: %s", (const char*)buffer); // Should say "ello". result = MojoEndReadData(consumer, 5, nullptr); ``` -------------------------------- ### Accept IncomingInvitation in Main Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/public/cpp/system/README.md Accepts an incoming Mojo IPC invitation in the main function of a new process. Initializes Mojo and sets up IPC support. Extracts a message pipe from the invitation using a specific name. ```cpp #include "base/command_line.h" #include "base/threading/thread.h" #include "mojo/core/embedder/embedder.h" #include "mojo/core/embedder/scoped_ipc_support.h" #include "mojo/public/cpp/platform/platform_channel.h" #include "mojo/public/cpp/system/invitation.h" #include "mojo/public/cpp/system/message_pipe.h" int main(int argc, char** argv) { // Basic Mojo initialization for a new process. mojo::core::Init(); base::Thread ipc_thread("ipc!"); ipc_thread.StartWithOptions( base::Thread::Options(base::MessagePumpType::IO, 0)); mojo::core::ScopedIPCSupport ipc_support( ipc_thread.task_runner(), mojo::core::ScopedIPCSupport::ShutdownPolicy::CLEAN); // Accept an invitation. mojo::IncomingInvitation invitation = mojo::IncomingInvitation::Accept( mojo::PlatformChannel::RecoverPassedEndpointFromCommandLine( *base::CommandLine::ForCurrentProcess())); mojo::ScopedMessagePipeHandle pipe = invitation->ExtractMessagePipe("arbitrary pipe name"); // etc... return GoListenForMessagesAndRunForever(std::move(pipe)); } ``` -------------------------------- ### Get Interior Portal Corner Position Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetInteriorPortalCornerPosition.md This Lua script demonstrates how to get the position of a portal corner within an interior. It first retrieves the player's current interior and then uses the native function to get the coordinates. ```lua local playerPed = PlayerPedId() local interiorId = GetInteriorFromEntity(playerPed) if interiorId ~= 0 then local portalIndex = 0 local cornerIndex = 0 local x, y, z = GetInteriorPortalCornerPosition(interiorId, portalIndex, cornerIndex) print("position of portal " .. portalIndex .. "corner index " .. cornerIndex .. " is: " .. vec(x, y, z)) end ``` -------------------------------- ### PREPARE_LIGHT Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/PrepareLight.md Creates a new light with specified properties. ```APIDOC ## PREPARE_LIGHT ### Description Create a new light with specified type, flags, position, color, and intensity. ### Method NATIVE ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```c PREPARE_LIGHT(lightType, flags, x, y, z, r, g, b, intensity); ``` ### Response #### Success Response (void) This function does not return a value. #### Response Example N/A ``` -------------------------------- ### Get Resource Name by Index Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetResourceByFindIndex.md Iterates through all available resources, retrieves their names using GET_RESOURCE_BY_FIND_INDEX, and filters for those that are currently started. The names of started resources are then printed to the console. ```lua local resourceList = {} for i = 0, GetNumResources(), 1 do local resource_name = GetResourceByFindIndex(i) if resource_name and GetResourceState(resource_name) == "started" then table.insert(resourceList, resource_name) end end print(table.unpack(resourceList)) ``` -------------------------------- ### Create and Connect to a Named Platform Channel Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/public/cpp/platform/README.md Demonstrates how to create a NamedPlatformChannel server in one process and connect to it from another. The server name must be communicated out-of-band. ```cpp // In one process mojo::NamedPlatformChannel::Options options; mojo::NamedPlatformChannel named_channel(options); OutgoingInvitation::Send(std::move(invitation), named_channel.TakeServerEndpoint()); SendServerNameToRemoteProcessSomehow(named_channel.GetServerName()); // In the other process void OnGotServerName(const mojo::NamedPlatformChannel::ServerName& name) { // Connect to the server. mojo::PlatformChannelEndpoint endpoint = mojo::NamedPlatformChannel::ConnectToServer(name); // Proceed normally with invitation acceptance. auto invitation = mojo::IncomingInvitation::Accept(std::move(endpoint)); // ... } ``` -------------------------------- ### Get Interior Position Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetInteriorPosition.md This snippet demonstrates how to get the position of the player's current interior. It first checks if the player is inside an interior before attempting to retrieve its coordinates. ```lua local playerPed = PlayerPedId() local interiorId = GetInteriorFromEntity(playerPed) if interiorId ~= 0 then local x, y, z = GetInteriorPosition(interiorId) print("current interior " .. interiorId .. " position is: " .. vec(x, y, z)) end ``` -------------------------------- ### Get Ped Face Feature Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetPedFaceFeature.md Use this to get a ped's facial feature value. Returns 0.0 if the feature cannot be retrieved. Ensure the ped and feature index are valid. ```lua local noseWidth = GetPedFaceFeature(PlayerPedId(), 0) if noseWidth == 1.0 then print("You have big nose!") end ``` -------------------------------- ### Creating and Using StructPtr with New() Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/public/cpp/bindings/README.md Demonstrates two equivalent ways to create and initialize a `mojo::StructPtr` for a generated C++ struct, using `New()` with arguments or manual field assignment. ```cpp mojom::EmployeePtr e1 = mojom::Employee::New(); e1->id = 42; e1->username = "mojo"; e1->department = mojom::Department::kEngineering; ``` ```cpp auto e1 = mojom::Employee::New(42, "mojo", mojom::Department::kEngineering); ``` -------------------------------- ### Initialize Mojo Core with IPC Support Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/core/embedder/README.md Initialize Mojo Core and configure IPC support by creating a ScopedIPCSupport object. This requires a background thread running a base::MessagePumpType::IO loop. ```cpp #include "base/threading/thread.h" #include "mojo/core/embedder/embedder.h" #include "mojo/core/embedder/scoped_ipc_support.h" int main(int argc, char** argv) { mojo::core::Init(); base::Thread ipc_thread("ipc!"); ipc_thread.StartWithOptions( base::Thread::Options(base::MessagePumpType::IO, 0)); // As long as this object is alive, all Mojo API surface relevant to IPC // connections is usable, and message pipes which span a process boundary will // continue to function. mojo::core::ScopedIPCSupport ipc_support( ipc_thread.task_runner(), mojo::core::ScopedIPCSupport::ShutdownPolicy::CLEAN); return 0; } ``` -------------------------------- ### Get Interior Portal Count Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetInteriorPortalCount.md This Lua snippet demonstrates how to get the number of portals in the player's current interior. Ensure the interior ID is valid before calling the function. ```lua local playerPed = PlayerPedId() local interiorId = GetInteriorFromEntity(playerPed) if interiorId ~= 0 then local count = GetInteriorPortalCount(interiorId) print("interior " .. interiorId .. "has " .. count .. " portals") end ``` -------------------------------- ### Create a New Light Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/PrepareLight.md Use PREPARE_LIGHT to create a new light source in the game world. Specify the light type, position, color, and intensity. ```c void PREPARE_LIGHT(int lightType, int flags, float x, float y, float z, int r, int g, int b, float intensity); ``` -------------------------------- ### Get Vehicle Wheel Steering Angle Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetVehicleWheelSteeringAngle.md Use this native to get the steering angle of a specific wheel. The wheel index starts from 0. The maximum number of wheels can be found using GET_VEHICLE_NUMBER_OF_WHEELS. ```c float GET_VEHICLE_WHEEL_STEERING_ANGLE(Vehicle vehicle, int wheelIndex); ``` -------------------------------- ### Get Number of Resources Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetNumResources.md Call this function to retrieve the count of active resources. No setup or imports are required. ```c int GET_NUM_RESOURCES(); ``` -------------------------------- ### Get Interior Room Name Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetInteriorRoomName.md Demonstrates how to get the current room name for a player's entity. Requires obtaining the interior ID, room hash, and then the room index before calling the native function. ```lua local playerPed = PlayerPedId() local interiorId = GetInteriorFromEntity(playerPed) local roomHash = GetRoomKeyFromEntity(playerPed) local roomId = GetInteriorRoomIndexByHash(interiorId, roomHash) if roomId ~= -1 then local roomName = GetInteriorRoomName(interiorId, roomId) print("current room name is: " .. roomName) end ``` -------------------------------- ### Initialize Mojo Core Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/core/embedder/README.md Call mojo::core::Init() to enable local API calls. This is sufficient for some scenarios, like many unit tests. ```cpp #include "mojo/core/embedder/embedder.h" int main(int argc, char** argv) { mojo::core::Init(); // Now you can create message pipes, write messages, etc return 0; } ``` -------------------------------- ### Draw Prepared Light - C++ Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/DrawLight.md Call this function after preparing a light to draw it in the game world. Ensure the light is properly configured before calling. ```cpp void DRAW_LIGHT(); ``` -------------------------------- ### Get Vehicle Dashboard Temperature Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetVehicleDashboardTemp.md Retrieves the current dashboard temperature of a vehicle. No setup or imports are required for this function. ```c float GET_VEHICLE_DASHBOARD_TEMP(); ``` -------------------------------- ### Get Console Buffer - C Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetConsoleBuffer.md Retrieves the most recent game console output as a string. No setup or imports are required. ```c char* GET_CONSOLE_BUFFER(); ``` -------------------------------- ### Implementing and Calling an Interface with StructPtr Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/public/cpp/bindings/README.md Shows the C++ interface generated from a Mojom interface definition and how to call its methods with `EmployeePtr`. ```cpp interface EmployeeManager { AddEmployee(Employee e); }; ``` ```cpp class EmployeeManager { public: virtual ~EmployeManager() {} virtual void AddEmployee(EmployeePtr e) = 0; }; ``` ```cpp mojom::EmployeManagerPtr manager = ...; manager->AddEmployee( Employee::New(42, "mojo", mojom::Department::kEngineering)); // or auto e = Employee::New(42, "mojo", mojom::Department::kEngineering); manager->AddEmployee(std::move(e)); ``` -------------------------------- ### Get Interior Rotation - Lua Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetInteriorRotation.md This snippet demonstrates how to get the current interior's rotation using the GET_INTERIOR_ROTATION native. It first finds the player's current interior and then prints its rotation if it's a valid interior. ```lua local playerPed = PlayerPedId() local interiorId = GetInteriorFromEntity(playerPed) if interiorId ~= 0 then local x, y, z, w = GetInteriorRotation(interiorId) print("current interior " .. interiorId .. " rotation is: " .. vec(x, y, z, w)) end ``` -------------------------------- ### Example: Periodically Fetching Player Peer Statistics Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetPlayerPeerStatistics.md This JavaScript example demonstrates how to periodically fetch various peer statistics for a player using `GetPlayerPeerStatistics`. It logs the raw values and scaled packet loss values to the console every 10 seconds. ```javascript setInterval(() => { const ENET_PACKET_LOSS_SCALE = 65536; const PLAYER_SERVER_ID = 1; const packetLoss = GetPlayerPeerStatistics(PLAYER_SERVER_ID, 0 /* PacketLoss */); const packetLossVariance = GetPlayerPeerStatistics(PLAYER_SERVER_ID, 1 /* PacketLossVariance */); const packetLossEpoch = GetPlayerPeerStatistics(PLAYER_SERVER_ID, 2 /* PacketLossEpoch */) const rtt = GetPlayerPeerStatistics(PLAYER_SERVER_ID, 3 /* RoundTripTime */); const rttVariance = GetPlayerPeerStatistics(PLAYER_SERVER_ID, 4 /* RoundTripTimeVariance */); const lastRtt = GetPlayerPeerStatistics(PLAYER_SERVER_ID, 5 /* LastRoundTripTime */); const lastRttVariance = GetPlayerPeerStatistics(PLAYER_SERVER_ID, 6 /* LastRoundTripTimeVariance */); const packetThrottleEpoch = GetPlayerPeerStatistics(PLAYER_SERVER_ID, 7 /* PacketThrottleEpoch */); console.log(`packetLoss: ${packetLoss}`); console.log(`packetLossVariance: ${packetLossVariance}`); console.log(`packetLossEpch: ${packetLossEpoch}`); console.log(`packetLossScaled: ${packetLoss / ENET_PACKET_LOSS_SCALE}`); console.log(`packetLossVarianceScaled: ${packetLossVariance / ENET_PACKET_LOSS_SCALE}`); console.log(`rtt: ${rtt}`); console.log(`rttVariance: ${rttVariance}`); console.log(`lastRtt: ${lastRtt}`); console.log(`lastRttVariance: ${lastRttVariance}`); console.log(`packetThrottleEpoch: ${packetThrottleEpoch}`); }, 10000) ``` -------------------------------- ### Generate and Build FiveM Project Files Source: https://github.com/citizenfx/fivem/blob/master/docs/building.md Generates project files for the FiveM game and builds the solution. Use '-game server' or '-game rdr3' for other targets. ```bat fxd gen -game five fxd vs -game five ``` -------------------------------- ### Begin Writing to a Data Pipe (Two-Phase I/O) Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/public/c/system/README.md Use `MojoBeginWriteData` to request write access to a portion of the data pipe's storage for direct memory access. `num_bytes` indicates the maximum size of the available buffer. ```c void* buffer; uint32_t num_bytes = 1024; MojoResult result = MojoBeginWriteData(producer, nullptr, &buffer, &num_bytes); ``` -------------------------------- ### Get Player GUID Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetPlayerGuid.md Retrieves the unique identifier for a given player source. Ensure the player source is valid before calling. ```c char* GET_PLAYER_GUID(char* playerSrc); ``` -------------------------------- ### Get Vehicle Dashboard Vacuum Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetVehicleDashboardVacuum.md Retrieves the current dashboard vacuum value for a vehicle. No setup or imports are required for this function. ```c float GET_VEHICLE_DASHBOARD_VACUUM(); ``` -------------------------------- ### Allocate, Write, and Read Message Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/public/cpp/system/README.md Demonstrates allocating a message, getting its buffer, writing data into it, and then writing the message to a pipe. It also shows how to read a message from the pipe later. ```cpp mojo::ScopedMessageHandle message; mojo::AllocMessage(6, nullptr, 0, MOJO_ALLOC_MESSAGE_FLAG_NONE, &message); void *buffer; mojo::GetMessageBuffer(message.get(), &buffer); const std::string kMessage = "hello"; std::copy(kMessage.begin(), kMessage.end(), static_cast(buffer)); mojo::WriteMessageNew(client.get(), std::move(message), MOJO_WRITE_MESSAGE_FLAG_NONE); mojo::ScopedMessageHandle received_message; uint32_t num_bytes; mojo::ReadMessageNew(server.get(), &received_message, &num_bytes, nullptr, nullptr, MOJO_READ_MESSAGE_FLAG_NONE); ``` -------------------------------- ### Spawn a Helicopter using CREATE_VEHICLE_SERVER_SETTER Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/server/CreateVehicleServerSetter.md This example demonstrates spawning a helicopter using the `CreateVehicleServerSetter` native. Ensure the correct model hash and type are provided. The coordinates are obtained relative to the player's ped. ```lua local heli = CreateVehicleServerSetter(`seasparrow`, 'heli', GetEntityCoords(GetPlayerPed(GetPlayers()[1])) + vector3(0, 0, 15), 0.0) print(GetEntityCoords(heli)) -- should return correct coordinates ``` -------------------------------- ### Get Ped Model Personality Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetPedModelPersonality.md Retrieves the personality type of a ped model using its hash. No setup or imports are required. ```c Hash GET_PED_MODEL_PERSONALITY(Hash modelHash); ``` -------------------------------- ### Get Network Walk Mode Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetNetworkWalkMode.md Use this function to retrieve the current network walk mode. No setup or imports are required. ```c bool GET_NETWORK_WALK_MODE(); ``` -------------------------------- ### Launch and Connect with OutgoingInvitation Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/public/cpp/system/README.md Launches a child process and establishes an IPC connection by sending an OutgoingInvitation. Attaches a message pipe to the invitation for communication. Ensure 'some_executable' is a valid executable path. ```cpp #include "base/command_line.h" #include "base/process/launch.h" #include "mojo/public/cpp/platform/platform_channel.h" #include "mojo/public/cpp/system/invitation.h" #include "mojo/public/cpp/system/message_pipe.h" mojo::ScopedMessagePipeHandle LaunchAndConnectSomething() { // Under the hood, this is essentially always an OS pipe (domain socket pair, // Windows named pipe, Fuchsia channel, etc). mojo::PlatformChannel channel; mojo::OutgoingInvitation invitation; // Attach a message pipe to be extracted by the receiver. The other end of the // pipe is returned for us to use locally. mojo::ScopedMessagePipeHandle pipe = invitation->AttachMessagePipe("arbitrary pipe name"); base::LaunchOptions options; base::CommandLine command_line("some_executable") channel.PrepareToPassRemoteEndpoint(&options, &command_line); base::Process child_process = base::LaunchProcess(command_line, options); channel.RemoteProcessLaunchAttempted(); OutgoingInvitation::Send(std::move(invitation), child_process.Handle(), channel.TakeLocalEndpoint()); return pipe; } ``` -------------------------------- ### Get Wave Quad Count Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetWaveQuadCount.md Use this function to retrieve the amount of wave quads loaded. No specific setup or imports are required. ```c int GET_WAVE_QUAD_COUNT(); ``` ```lua local waveQuadCount = GetWaveQuadCount() ``` -------------------------------- ### Find External KVP Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/kvp/external/StartFindExternalKvp.md Use this snippet to find and retrieve key-value pairs from an external resource. Ensure the resource name and prefix are correctly specified. The loop iterates through all found keys until no more are available. ```lua local kvpHandle = StartFindExternalKvp('drugs', 'mollis:') if kvpHandle ~= -1 then local key repeat key = FindKvp(kvpHandle) if key then print(('%s: %s'):format(key, GetResourceKvpString(key))) end until not key EndFindKvp(kvpHandle) else print('No KVPs found') end ``` -------------------------------- ### Get Instance ID - C++ Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetInstanceId.md Retrieves the unique identifier for the current game instance. This function does not require any specific setup or imports. ```cpp int GET_INSTANCE_ID(); ``` -------------------------------- ### Get Resource KVP Float Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/kvp/GetResourceKvpFloat.md Use this to retrieve a float value stored under a specific key. Returns 0.0 if the key is not found. ```lua local kvpValue = GetResourceKvpFloat('mollis') if kvpValue ~= 0.0 then -- do something! end ``` -------------------------------- ### Set Interior Portal Flag Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/SetInteriorPortalFlag.md This example demonstrates how to set a flag for an interior portal. Ensure the interior ID is valid before proceeding. The portal index refers to a specific portal within that interior. ```lua local playerPed = PlayerPedId() local interiorId = GetInteriorFromEntity(playerPed) if interiorId ~= 0 then local portalIndex = 0 SetInteriorPortalFlag(interiorId, portalIndex, 1) RefreshInterior(interiorId) end ``` -------------------------------- ### Get Mumble Talker Proximity Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/MumbleGetTalkerProximity.md Call this function to retrieve the current proximity setting for Mumble voice chat. No setup or imports are required. ```c float MUMBLE_GET_TALKER_PROXIMITY(); ``` -------------------------------- ### Find and Iterate KVPs by Prefix Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/kvp/StartFindKvp.md Use this to find and iterate through all KVPs that start with a specific prefix. Ensure to close the KVP handle when done. ```c int START_FIND_KVP(char* prefix); ``` ```lua SetResourceKvp('mollis:2', 'should be taken with alcohol') SetResourceKvp('mollis:1', 'vesuvius citrate') SetResourceKvp('mollis:manufacturer', 'Betta Pharmaceuticals') local kvpHandle = StartFindKvp('mollis:') if kvpHandle ~= -1 then local key repeat key = FindKvp(kvpHandle) if key then print(('%s: %s'):format(key, GetResourceKvpString(key))) end until not key EndFindKvp(kvpHandle) else print('No KVPs found') end ``` -------------------------------- ### Get Vehicle Dashboard Oil Temperature Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetVehicleDashboardOilTemp.md Use this function to retrieve the oil temperature from a vehicle's dashboard. No setup or imports are required. ```c float GET_VEHICLE_DASHBOARD_OIL_TEMP(); ``` -------------------------------- ### Start Listening to a Voice Channel Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/MumbleAddVoiceChannelListen.md Use this function to begin listening to a specified game voice channel. Ensure the channel ID is valid. ```c void MUMBLE_ADD_VOICE_CHANNEL_LISTEN(int channel); ``` -------------------------------- ### Enter Profiler Scope Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/ProfilerEnterScope.md Use this function to mark the beginning of a scope for profiling. Pass the name of the scope as a string. ```c void PROFILER_ENTER_SCOPE(char* scopeName); ``` -------------------------------- ### Get Player From State Bag Name Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetPlayerFromStateBagName.md This example demonstrates how to use GetPlayerFromStateBagName within a state bag change handler to identify the player associated with the change. It logs whether the player died or is alive. Ensure the player handle is valid before proceeding. ```javascript AddStateBagChangeHandler("isDead", null, async (bagName, key, value /* boolean */) => { const ply = GetPlayerFromStateBagName(bagName); // The player doesn't exist! if (ply === 0) return; console.log(`Player: ${GetPlayerName(ply)} ${value ? 'died!' : 'is alive!'}`) }) ``` ```lua AddStateBagChangeHandler("isDead", nil, function(bagName, key, value) local ply = GetPlayerFromStateBagName(bagName) -- The player doesn't exist! if ply == 0 then return end print("Player: " .. GetPlayerName(ply) .. value and 'died!' or 'is alive!') end) ``` -------------------------------- ### Example Native Function Declaration Source: https://github.com/citizenfx/fivem/blob/master/ext/natives/README.md This Lua snippet demonstrates the input format for defining a native function, including its hash, arguments, namespace, return type, and documentation. ```lua native "GET_PLAYER_PED" hash "0x43A66C31C68491C0" jhash (0x6E31E993) arguments { Player "playerId", } ns "PLAYER" returns "Ped" doc [[! returns the players ped used in many functions ]] ``` -------------------------------- ### Get Train Door Open Ratio Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetTrainDoorOpenRatio.md Iterates through all doors of a train and prints their open ratio. Requires the train entity and API.GetTrainDoorCount native. ```csharp int doorCount = API.GetTrainDoorCount(train); for (int doorIndex = 0; doorIndex < doorCount; doorIndex++) { float ratio = API.GetTrainDoorOpenRatio(train, doorIndex); Debug.WriteLine($"Door {doorIndex} is open by a ratio of {ratio}"); } ``` -------------------------------- ### Get Train Door Open Ratio Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetTrainDoorOpenRatio.md Iterates through all doors of a train and prints their open ratio. Requires the train entity and GetTrainDoorCount native. ```lua local doorCount = GetTrainDoorCount(train) for doorIndex = 0, doorCount - 1 do local ratio = GetTrainDoorOpenRatio(train, doorIndex) print("Door " .. tostring(doorIndex) .. " is open by a ratio of " .. tostring(ratio)) end ``` -------------------------------- ### Implement and Use Echo Interface in JavaScript Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/public/js/README.md JavaScript code demonstrating how to implement a Mojo interface, create an interface pointer and request, and make a method call. It uses Promises for asynchronous responses. ```javascript function EchoImpl() {} EchoImpl.prototype.echoInteger = function(value) { return Promise.resolve({result: value}); }; var echoServicePtr = new test.echo.mojom.EchoPtr(); var echoServiceRequest = mojo.makeRequest(echoServicePtr); var echoServiceBinding = new mojo.Binding(test.echo.mojom.Echo, new EchoImpl(), echoServiceRequest); echoServicePtr.echoInteger({value: 123}).then(function(response) { console.log('The result is ' + response.value); }); ``` -------------------------------- ### Import Mojom Definitions Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/public/tools/bindings/README.md Use the 'import' keyword to include definitions from other Mojom files. Import paths are relative to the top-level directory. Circular imports are not supported. ```mojom import "services/widget/public/mojom/frobinator.mojom"; ``` -------------------------------- ### Get Resource KVP String Example Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/kvp/GetResourceKvpString.md Fetches a string value from the resource KVP store using the GetResourceKvpString function. Check if the returned value is not nil before using it. ```lua local kvpValue = GetResourceKvpString('codfish') if kvpValue then -- do something! end ``` -------------------------------- ### Build Mojo Interface with GN Source: https://github.com/citizenfx/fivem/blob/master/vendor/chromium/mojo/docs/basics.md Specifies how to build a Mojo interface using the 'mojom' GN template. This configuration generates C++, Java, and JavaScript interfaces from the specified .mojom files. ```gn mojom("mojom") { sources = ["math.mojom"] } ``` -------------------------------- ### Get Entity Coordinates in C# Source: https://github.com/citizenfx/fivem/blob/master/ext/native-decls/GetEntityCoords.md This C# example demonstrates retrieving player coordinates using the native function and the C# wrapper. It sets up an event handler for 'myCoordinates'. ```csharp using static CitizenFX.Core.Native.API; // ... // In class constructor EventHandlers["myCoordinates"] += new Action(ShowCoordinates); // Delegate method private void ShowCoordinates([FromSource]Player player) { Vector3 playerCoords = GetEntityCoords(player.Character); // or the preferred use of C# wrapper Vector3 playerCoords = player.Character.Position; Debug.WriteLine($"{playerCoords}"); } ```