### Example HTTP Request Implementation Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/core.md Demonstrates how to implement the `HTTPResponseHandler` interface and make an HTTP GET request. The handler processes a successful response by printing it to the console. ```cpp struct MyHTTPHandler : HTTPResponseHandler { void onHTTPResponse(int status, StringView body) override { if (status == 200) { // Success core->printLn("Response: %.*s", (int)body.size(), body.data()); } } }; MyHTTPHandler handler; core->requestHTTP(&handler, HTTPRequestType_Get, "http://example.com/api"); ``` -------------------------------- ### Incoming Connection Handler Example Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/errors.md An example handler that demonstrates how to process incoming connections and return a NewConnectionResult. It specifically checks for and rejects older client versions. ```cpp struct MyConnectionHandler : NetworkEventHandler { NewConnectionResult onIncomingConnection(const PeerRequestParams& params, NewConnectionResult& result) override { if (params.version == ClientVersion::ClientVersion_SAMP_037) { // Only allow open.mp clients result = NewConnectionResult_VersionMismatch; return NewConnectionResult_VersionMismatch; } return NewConnectionResult_Success; } }; ``` -------------------------------- ### Get Online Players Example Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/player.md Example function to retrieve the count of currently online players. ```APIDOC ## Get Online Players Example ### Description Returns the number of players currently connected to the server. ### Function Signature ```cpp size_t GetOnlinePlayers(ICore* core) ``` ### Usage ```cpp return core->getPlayers().count(); ``` ``` -------------------------------- ### Complete Event-Driven Component Example Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/events.md A full example of a component demonstrating event handling for game ticks, player connections, and disconnections. It registers and unregisters handlers during component load and free phases. ```cpp #include #include struct GameEventHandler : CoreEventHandler, PlayerEventHandler { ICore* core = nullptr; int tickCount = 0; void onTick(Microseconds elapsed, TimePoint now) override { tickCount++; if (tickCount % 100 == 0) { // Every ~100 ticks size_t playerCount = core->getPlayers().count(); core->logLn(LogLevel::Debug, "Tick %d: %zu players online", tickCount, playerCount); } } void onPlayerConnect(IPlayer& player) override { core->logLn(LogLevel::Message, "%s (IP: %s) connected", player.getName().data(), player.getIP().data()); } void onPlayerDisconnect(IPlayer& player) { core->logLn(LogLevel::Message, "%s disconnected", player.getName().data()); } }; struct EventDemoComponent : IComponent { PROVIDE_UID(0x3333333333333333); ICore* core = nullptr; GameEventHandler eventHandler; void onLoad(ICore* c) override { core = c; eventHandler.core = c; // Register handlers core->getEventDispatcher().addEventHandler(&eventHandler); core->getPlayers().getEventDispatcher().addEventHandler(&eventHandler); } void onFree(IComponent* component) override { // Unregister handlers if (core) { core->getEventDispatcher().removeEventHandler(&eventHandler); core->getPlayers().getEventDispatcher().removeEventHandler(&eventHandler); } } void free() override {} void reset() override {} StringView componentName() const override { return "EventDemo"; } SemanticVersion componentVersion() const override { return SemanticVersion(1, 0, 0); } }; extern "C" SDK_EXPORT IComponent* __CDECL ComponentEntryPoint() { return new EventDemoComponent(); } ``` -------------------------------- ### Example: Setting Vehicle Parameters Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/vehicle.md Demonstrates how to instantiate and populate a VehicleParams struct to modify engine and lights, then apply them. ```cpp VehicleParams params; params.engine = 1; // Turn on engine params.lights = 1; // Turn on lights params.bonnet = 0; // Close bonnet vehicle->setParams(params); ``` -------------------------------- ### Complete Actor Management Example Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/actors.md A C++ example demonstrating how to create and manage actors, apply animations, and handle damage events using the IActorsComponent. This component should be loaded and initialized to manage actor lifecycle and events. ```cpp #include #include struct ActorGuard { IActor* actor = nullptr; Vector3 position; float angle = 0.0f; }; struct MyActorComponent : IComponent { PROVIDE_UID(0x9999999999999999); ICore* core = nullptr; IActorsComponent* actorsComponent = nullptr; std::vector guards; void onLoad(ICore* c) override { core = c; } void onInit(IComponentList* components) override { actorsComponent = components->queryComponent(); if (!actorsComponent) { core->logLn(LogLevel::Error, "Actors component not found"); return; } actorsComponent->getEventDispatcher().addEventHandler(&eventHandler); } void onReady() override { if (!actorsComponent) return; // Create guards at 4 corners of the map Vector3 positions[] = { Vector3(0, 0, 10), Vector3(0, 6000, 10), Vector3(6000, 0, 10), Vector3(6000, 6000, 10) }; for (auto& pos : positions) { IActor* actor = actorsComponent->create(120, pos, 0.0f); if (actor) { actor->setHealth(100.0f); actor->setInvulnerable(true); // Apply idle animation AnimationData anim; anim.ID = 1; anim.flags = 0; actor->applyAnimation(anim); ActorGuard guard; guard.actor = actor; guard.position = pos; guards.push_back(guard); core->logLn(LogLevel::Message, "Guard created at (%.1f, %.1f, %.1f)", pos.x, pos.y, pos.z); } } } void onFree(IComponent* component) override { if (actorsComponent) { actorsComponent->getEventDispatcher().removeEventHandler(&eventHandler); } } void free() override { guards.clear(); } void reset() override { guards.clear(); } StringView componentName() const override { return "ActorGuardComponent"; } SemanticVersion componentVersion() const override { return SemanticVersion(1, 0, 0); } struct EventHandler : ActorEventHandler { MyActorComponent* owner = nullptr; void onPlayerGiveDamageActor(IPlayer& player, IActor& actor, float amount, unsigned weapon, BodyPart part) override { if (owner && owner->core) { owner->core->logLn(LogLevel::Message, "Player %d hit actor %d with weapon %d (%.1f damage at %s)", player.getID(), actor.getID(), weapon, amount, BodyPartString[part].data()); } } void onActorStreamIn(IActor& actor, IPlayer& forPlayer) override { // Actor now visible to player } void onActorStreamOut(IActor& actor, IPlayer& forPlayer) override { // Actor no longer visible to player } } eventHandler; }; extern "C" SDK_EXPORT IComponent* __CDECL ComponentEntryPoint() { auto component = new MyActorComponent(); component->eventHandler.owner = component; return component; } ``` -------------------------------- ### SemanticVersion Comparison Example Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/types.md Demonstrates creating SemanticVersion objects and comparing them using the overloaded greater-than operator. ```cpp SemanticVersion v1(1, 2, 3); // Version 1.2.3 SemanticVersion v2(1, 2, 4); // Version 1.2.4 bool newer = v2 > v1; // true ``` -------------------------------- ### Providing Default Configuration Options Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/configuration.md Example of how to populate configuration with default values and set up aliases for backward compatibility within the provideConfiguration function. ```cpp void provideConfiguration(ILogger& logger, IEarlyConfig& config, bool defaults) override { if (defaults) { // Provide default values when generating config config.setInt("mycomponent.max_players", 500); config.setString("mycomponent.mode", "normal"); config.setBool("mycomponent.debug", false); config.setFloat("mycomponent.timeout", 30.5f); // Aliases for backwards compatibility config.addAlias("maxplayers", "mycomponent.max_players", false); config.addAlias("old_mode_name", "mycomponent.mode", true); // deprecated } } ``` -------------------------------- ### Broadcast Message Example Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/player.md Example function to send a message to all connected players using the IPlayerPool. ```APIDOC ## Broadcast Message Example ### Description Sends a specified message to all currently connected players. ### Function Signature ```cpp void BroadcastMessage(ICore* core, StringView message) ``` ### Usage ```cpp auto& playerPool = core->getPlayers(); for (auto player : playerPool) { player->sendMessage(Colour::Yellow(), message); } ``` ``` -------------------------------- ### Get Actor Spawn Data Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/actors.md Retrieves the initial spawn data for an actor, which includes its starting position, orientation, and appearance. ```cpp const ActorSpawnData& getSpawnData(); ``` -------------------------------- ### Example: Providing and Querying a Runtime Extension Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/component.md Illustrates how to define a custom extension, add it to a component with automatic deletion, and then query for it from another component. ```cpp struct MyExtension : IExtension { PROVIDE_EXT_UID(0xdeadbeefcafebabe); void freeExtension() override { // Called on removal if autoDeleteExt=true } void reset() override { // Called when owner resets } }; // In component: void onReady() override { auto ext = new MyExtension(); addExtension(ext, true); // auto-delete on component free } // Query from other component: auto ext = queryExtension(myComponent); ``` -------------------------------- ### Example: Querying a Component Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/component.md Demonstrates how to use the template version of queryComponent to obtain an instance of a specific component type, such as IVehiclesComponent. ```cpp auto vehicles = components->queryComponent(); if (vehicles) { // Use vehicles component } ``` -------------------------------- ### onReady Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/component.md Called after all components have been initialized. This is the appropriate time to fire events, interact with other components, and start any deferred initialization. ```APIDOC ## onReady ### Description Optional. Called after all components initialized. Use to fire events, interact with other components, and start any deferred initialization. ### Method `virtual void onReady();` ### Remarks This is safe for all cross-component interaction. ``` -------------------------------- ### Player Actions Example Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/player.md Demonstrates common player actions including spawning, setting health/armour, giving weapons, setting fighting style, and sending messages. ```APIDOC ## Player Actions Example ### Description Example usage of various `IPlayer` methods for managing player state and inventory. ### Spawning and Status ```cpp void GiveStarterKit(IPlayer& player, ICore* core) { player.spawn(Vector3(100, 200, 10), 0, 250, 0, 0); player.setHealth(100.0f); player.setArmour(100.0f); } ``` ### Weapon Management ```cpp player.giveWeapon(PlayerWeapon_Colt45, 500); player.giveWeapon(PlayerWeapon_AK47, 1000); player.giveWeapon(PlayerWeapon_Knife, 1); ``` ### Fighting Style ```cpp player.setFightingStyle(PlayerFightingStyle_Boxing); ``` ### Messaging ```cpp player.sendMessage(Colour::Green(), "Welcome! You've received starter weapons."); ``` ``` -------------------------------- ### Enumerating Configuration Options Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/configuration.md Provides an example of iterating through all available configuration options using a custom OptionEnumeratorCallback. It logs the name and type of each option found. ```cpp struct MyOptionEnumerator : OptionEnumeratorCallback { ICore* core; bool proc(StringView name, ConfigOptionType type) override { const char* types[] = {"", "int", "string", "float", "strings", "bool"}; core->logLn(LogLevel::Message, "Option: %.*s (type: %s)", (int)name.size(), name.data(), type >= 0 && type < 6 ? types[type] : "unknown"); return true; // Continue enumeration } }; MyOptionEnumerator enumerator; config.enumOptions(enumerator); ``` -------------------------------- ### C++ Component Loading and Initialization Example Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/core.md Demonstrates how to create a custom component, load it into the OpenMP SDK, and interact with core functionalities like logging, setting weather, and world time. Requires including 'component.hpp' and 'core.hpp'. ```cpp #include #include struct MyComponent : IComponent { PROVIDE_UID(0x1234567890abcdef); ICore* core; void onLoad(ICore* c) override { core = c; core->logLn(LogLevel::Message, "My Component loaded!"); core->setWeather(10); core->setWorldTime(Hours(18)); } void onInit(IComponentList* components) override { // Register event handlers auto dispatcher = &core->getEventDispatcher(); } void onReady() override { core->printLn("Server ready with %d players", core->getPlayers().count()); } void onFree(IComponent* component) override { } void free() override { } void reset() override { } StringView componentName() const override { return "MyComponent"; } SemanticVersion componentVersion() const override { return SemanticVersion(1, 0, 0); } }; extern "C" SDK_EXPORT IComponent* __CDECL ComponentEntryPoint() { return new MyComponent(); } ``` -------------------------------- ### Component with Custom Configuration Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/configuration.md Example of a component that loads its configuration from the SDK's config system. It defines default values and loads them on ready. ```cpp #include #include struct ConfigurableComponent : IComponent { PROVIDE_UID(0x2222222222222222); ICore* core = nullptr; int maxConnections = 100; float timeout = 30.5f; bool debugMode = false; void onLoad(ICore* c) override { core = c; } void provideConfiguration(ILogger& logger, IEarlyConfig& config, bool defaults) override { if (defaults) { config.setInt("mycomponent.max_connections", 100); config.setFloat("mycomponent.timeout", 30.5f); config.setBool("mycomponent.debug", false); } } void onReady() override { IConfig& config = core->getConfig(); // Load configuration int* maxConn = config.getInt("mycomponent.max_connections"); if (maxConn) { maxConnections = *maxConn; } float* timeoutVal = config.getFloat("mycomponent.timeout"); if (timeoutVal) { timeout = *timeoutVal; } bool* debug = config.getBool("mycomponent.debug"); if (debug) { debugMode = *debug; } core->logLn(LogLevel::Message, "Component configured: max=%d, timeout=%.1f, debug=%d", maxConnections, timeout, debugMode); } // ... rest of implementation void onInit(IComponentList* components) override {} void onFree(IComponent* component) override {} void free() override {} void reset() override {} StringView componentName() const override { return "ConfigurableComponent"; } SemanticVersion componentVersion() const override { return SemanticVersion(1, 0, 0); } }; ``` -------------------------------- ### NetworkBitStream Usage Example Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/network.md Demonstrates basic usage of the NetworkBitStream for writing and reading data, including integers, strings, and raw bits, as well as resetting the stream. ```cpp NetworkBitStream bs; bs.Write(100); bs.Write("Hello"); bs.WriteBits(&data, 16); // Write 16 bits bs.Reset(BSResetRead); int value = bs.Read(); ``` -------------------------------- ### Handling Network Events (Connect/Disconnect) Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/network.md Example of implementing `NetworkEventHandler` to respond to player connection and disconnection events. ```APIDOC ## Usage Example - Network Event Handling ### Description This example shows how to implement the `NetworkEventHandler` interface to log when players connect or disconnect. It also demonstrates registering these handlers with the network event dispatcher. ### Implementing Handlers ```cpp struct MyNetworkHandler : NetworkEventHandler { ICore* core; void onPeerConnect(IPlayer& peer) override { core->logLn(LogLevel::Message, "Peer connected: %s (%s)", peer.getName().data(), peer.getIP().data()); } void onPeerDisconnect(IPlayer& peer, PeerDisconnectReason reason) override { const char* reasons[] = {"Timeout", "Quit", "Kicked"}; core->logLn(LogLevel::Message, "Peer disconnected: %s (%s)", peer.getName().data(), reasons[reason]); } }; ``` ### Registering Handlers ```cpp struct MyComponent : IComponent { // ... void onLoad(ICore* c) override { core = c; // Register on all networks auto& networks = core->getNetworks(); for (auto network : networks) { network->getEventDispatcher().addEventHandler(&handler); } } }; ``` ``` -------------------------------- ### Set Server World Time Example Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/core.md Demonstrates how to set the server's world time to 12:00 noon using the Hours type. ```cpp core->setWorldTime(Hours(12)); // Set to 12:00 noon ``` -------------------------------- ### Add Event Handlers with Priorities Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/events.md Example demonstrating how to add event handlers to a dispatcher with specified priorities to control their execution order. ```cpp // Handler A runs first (highest priority) dispatcher.addEventHandler(&handlerA, EventPriority_Highest); // Handler B runs second (default) dispatcher.addEventHandler(&handlerB, EventPriority_Default); // Handler C runs last (lowest) dispatcher.addEventHandler(&handlerC, EventPriority_Lowest); ``` -------------------------------- ### Player Initialization and Messaging Example in C++ Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/player.md A C++ function that spawns a player at a specific location, sets their health and armor, gives them starter weapons, sets their fighting style, and sends a welcome message. This is useful for initializing new players. ```cpp #include #include void GiveStarterKit(IPlayer& player, ICore* core) { player.spawn(Vector3(100, 200, 10), 0, 250, 0, 0); player.setHealth(100.0f); player.setArmour(100.0f); player.giveWeapon(PlayerWeapon_Colt45, 500); player.giveWeapon(PlayerWeapon_AK47, 1000); player.giveWeapon(PlayerWeapon_Knife, 1); player.setFightingStyle(PlayerFightingStyle_Boxing); player.sendMessage(Colour::Green(), "Welcome! You've received starter weapons."); } ``` -------------------------------- ### Toggle Actor Invulnerability Example Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/actors.md Demonstrates how to make an actor invincible or vulnerable using the setInvulnerable function. ```cpp actor->setInvulnerable(true); // Cannot be damaged actor->setInvulnerable(false); // Can be damaged ``` -------------------------------- ### Registering a Per-Packet Handler Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/network.md Example of how to register a custom handler for specific incoming packet IDs using the per-packet event dispatcher. ```cpp struct MyPacketHandler : SingleNetworkInEventHandler { bool onReceive(IPlayer& peer, NetworkBitStream& bs) override { // Handle packet ID 123 return true; // Allow } }; MyPacketHandler handler; network->getPerPacketInEventDispatcher().addEventHandler(&handler, 123); ``` -------------------------------- ### Get SDK Version Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/core.md Retrieves the SemanticVersion of the SDK the server was built with. Useful for compatibility checks. ```cpp SemanticVersion getVersion() const; ``` -------------------------------- ### Simple C++ Component Example Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/component.md A basic C++ component demonstrating the structure and essential methods required by the OpenMP-SDK. This component logs messages on load and when ready. ```cpp #include #include #include struct SimpleComponent : IComponent { PROVIDE_UID(0x1111111111111111); ICore* core = nullptr; void onLoad(ICore* c) override { core = c; core->logLn(LogLevel::Message, "SimpleComponent loaded!"); } void onInit(IComponentList* components) override { // Query other components here } void onReady() override { core->logLn(LogLevel::Message, "SimpleComponent ready!"); } void onFree(IComponent* component) override { // Cleanup handlers } void free() override { // Delete allocated memory } void reset() override { // Clear data on GMX } StringView componentName() const override { return "SimpleComponent"; } SemanticVersion componentVersion() const override { return SemanticVersion(1, 0, 0); } }; extern "C" SDK_EXPORT IComponent* __CDECL ComponentEntryPoint() { return new SimpleComponent(); } ``` -------------------------------- ### Safe Pool Iteration Example (Manual Iterator) Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/pool.md Provides an equivalent manual iteration using `begin()` and `end()` iterators, demonstrating the underlying logic of safe pool iteration. ```cpp auto it = playerPool->begin(); while (it != playerPool->end()) { IPlayer* player = *it; player->setHealth(100.0f); ++it; } ``` -------------------------------- ### requestHTTP Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/core.md Launches an HTTP request and reads the response asynchronously. Supports GET, POST, and HEAD methods. ```APIDOC ## requestHTTP ### Description Launch an HTTP request and read the response asynchronously. ### Method ```cpp void requestHTTP(HTTPResponseHandler* handler, HTTPRequestType type, StringView url, StringView data = StringView()); ``` ### Parameters #### Path Parameters - **handler** (HTTPResponseHandler*) - Required - Handler to receive response - **type** (HTTPRequestType) - Required - GET, POST, or HEAD - **url** (StringView) - Required - Request URL - **data** (StringView) - Optional - POST data (only for POST) ### Request Example ```cpp struct MyHTTPHandler : HTTPResponseHandler { void onHTTPResponse(int status, StringView body) override { if (status == 200) { // Success core->printLn("Response: %.*s", (int)body.size(), body.data()); } } }; MyHTTPHandler handler; core->requestHTTP(&handler, HTTPRequestType_Get, "http://example.com/api"); ``` ### Response #### Success Response (200) - **status** (int) - HTTP status code - **body** (StringView) - Response body ``` -------------------------------- ### Get Network Instances Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/core.md Returns a collection of all available network instances. Typically, there is one main network instance for handling player connections and packet dispatching. ```cpp const FlatPtrHashSet& getNetworks(); ``` -------------------------------- ### Get Server Configuration Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/core.md Retrieves a reference to the server's configuration object. Use this to access loaded settings such as game mode and server name. ```cpp IConfig& getConfig(); ``` -------------------------------- ### Add Event Handler Example Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/events.md Demonstrates how to register a custom event handler with the event dispatcher. Ensure the handler type matches the dispatcher's template parameter. ```cpp struct MyPlayerHandler : PlayerEventHandler { // implement handlers }; MyPlayerHandler handler; auto& dispatcher = playerPool->getEventDispatcher(); dispatcher.addEventHandler(&handler, EventPriority_Highest); ``` -------------------------------- ### Registering Per-Packet Handlers Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/network.md This example demonstrates how to register a custom handler for specific network packet IDs to process incoming data. ```APIDOC ## Registering Per-Packet Handlers ### Description Allows for custom handling of incoming network packets based on their ID. You can define a handler class that inherits from `SingleNetworkInEventHandler` and implement the `onReceive` method to process the packet data. ### Usage ```cpp const int MY_PACKET_ID = 200; struct MyPacketHandler : SingleNetworkInEventHandler { bool onReceive(IPlayer& peer, NetworkBitStream& bs) override { int data = bs.Read(); // Process packet return true; // Allow packet } }; // In component: void onInit(IComponentList* components) override { auto networks = &core->getNetworks(); for (auto network : *networks) { auto& dispatcher = network->getPerPacketInEventDispatcher(); dispatcher.addEventHandler(&handler, MY_PACKET_ID); } } ``` ``` -------------------------------- ### Implement Core Event Handler Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/core.md Example of how to define a custom handler for core server events, specifically the onTick method which is called each server tick. ```cpp struct MyCoreEventHandler : CoreEventHandler { void onTick(Microseconds elapsed, TimePoint now) override { // Called once per server tick } }; ``` -------------------------------- ### Launch HTTP Request Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/core.md Initiates an asynchronous HTTP request. A handler is required to process the response. Supports GET, POST, and HEAD methods, with optional data for POST requests. ```cpp void requestHTTP(HTTPResponseHandler* handler, HTTPRequestType type, StringView url, StringView data = StringView()); ``` -------------------------------- ### reloadAll Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/core.md Creates all entities that appear when a game mode starts. This is typically called after loading a game mode. ```APIDOC ## reloadAll ### Description Create all entities that appear on game mode start. Typically called after loading game mode. ### Method void ``` -------------------------------- ### Retrieving String Lists Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/configuration.md Shows how to get the count of string list entries and then retrieve the actual string values using the IConfig interface. It iterates through the retrieved strings and logs them. ```cpp size_t count = config.getStringsCount("server.modes"); std::vector modes(count); size_t read = config.getStrings("server.modes", modes); for (auto mode : modes) { core->logLn(LogLevel::Message, "Mode: %.*s", (int)mode.size(), mode.data()); } ``` -------------------------------- ### Get Vehicle Model ID Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/vehicle.md Retrieves the model ID of a vehicle. For example, 411 for Infernus and 412 for Banshee. ```cpp int getModel() const; ``` -------------------------------- ### Setting and Getting Entity Rotation Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/entity.md Illustrates setting an entity's rotation using a GTAQuat quaternion and retrieving it. Essential for accurate 3D orientation control. ```cpp void setRotation(GTAQuat rotation); ``` -------------------------------- ### Setting and Getting Entity Position Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/entity.md Demonstrates how to set an entity's position using a Vector3 and then retrieve it. Useful for precise location manipulation and verification. ```cpp entity->setPosition(Vector3(100.0f, 200.0f, 50.0f)); Vector3 pos = entity->getPosition(); float distance = glm::distance(pos, Vector3(0, 0, 0)); ``` -------------------------------- ### Iterating and Accessing Players in C++ Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/player.md Demonstrates how to get the player pool and iterate through all connected players or access a specific player by index. The player object is locked during iteration. ```cpp IPlayerPool& playerPool = core->getPlayers(); // Iterate all players for (auto player : playerPool) { // player is locked during iteration player->sendMessage(Colour::White(), "Server message"); } // Get specific player IPlayer* player = playerPool->get(0); // Count active players size_t count = playerPool.count(); ``` -------------------------------- ### Get SDK Version Hash Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/core.md Retrieves the version hash string of the current SDK build. This is used for verifying the SDK version. ```cpp StringView getVersionHash() const; ``` -------------------------------- ### ICore::getTickCount Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/core.md Gets the total number of server ticks that have occurred since the server started. Note that this value is an unsigned 32-bit integer and may overflow on very long server runs. ```APIDOC ## getTickCount ### Description Returns the number of server ticks since startup. ### Method `unsigned getTickCount() const` ### Return Type `unsigned` (32-bit integer) ``` -------------------------------- ### Get Tick Count Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/core.md Returns the total number of server ticks that have occurred since the server started. Note that this value is an unsigned 32-bit integer and may overflow on extremely long server runs. ```cpp unsigned getTickCount() const; ``` -------------------------------- ### Get Actor by ID Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/actors.md Retrieves a specific actor from the pool using its unique ID. Ensure the ID is valid before attempting to get the actor. ```cpp // Get by ID IActor* actor = actorsComponent->get(0); ``` -------------------------------- ### Registering a Custom Packet Handler Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/events.md Example of how to add a custom packet handler to the network's per-packet event dispatcher. This involves defining a handler class and then registering an instance with a specific packet ID. ```cpp struct MyPacketHandler : SingleNetworkInEventHandler { bool onReceive(IPlayer& peer, NetworkBitStream& bs) override { // Handle packet return true; } }; const int CUSTOM_PACKET_ID = 200; MyPacketHandler handler; auto& dispatcher = network->getPerPacketInEventDispatcher(); dispatcher.addEventHandler(&handler, CUSTOM_PACKET_ID); ``` -------------------------------- ### Create and Configure a Vehicle Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/vehicle.md Demonstrates the creation of a vehicle with initial properties and subsequent modifications like setting health, paintjob, components, and doors. ```cpp #include #include void CreateVehicle(ICore* core, int modelID, Vector3 position) { // Assuming vehicles component available VehicleSpawnData data; data.modelID = modelID; data.position = position; data.zRotation = 0.0f; data.colour1 = 1; data.colour2 = 2; data.siren = false; data.interior = 0; data.respawnDelay = Seconds(60); IVehicle* vehicle = vehiclesComponent->create(data); // Repair and paint vehicle->setHealth(1000.0f); vehicle->setPaintjob(0); // Add components vehicle->addComponent(1039); // wheels // Set doors VehicleParams params; params.doors = 0; // Close all doors vehicle->setParams(params); } ``` -------------------------------- ### count Method Signatures Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/events.md Signatures for retrieving handler counts. Use `count()` to get the total number of handlers across all indices, or `count(size_t index)` to get the count for a specific index. ```cpp size_t count() const; size_t count(size_t index) const; ``` -------------------------------- ### Safe Pool Iteration Example (Range-based for loop) Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/pool.md Demonstrates safe iteration over a player pool using a range-based for loop. The player object is locked within the loop's scope and automatically unlocked at the end of each iteration. ```cpp for (auto player : playerPool) { // Player is locked during this scope player->setHealth(100.0f); // Automatically unlocked at end of iteration } ``` -------------------------------- ### IExtensible Interface Methods Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/component.md Provides the core methods for managing extensions within a component: getting an extension by UID, querying by type, and adding or removing extensions. ```cpp IExtension* getExtension(UID id); template ExtensionT* _queryExtension(); bool addExtension(IExtension* ext, bool autoDeleteExt); bool removeExtension(IExtension* ext); bool removeExtension(UID id); ``` -------------------------------- ### Vehicle Parameters Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/vehicle.md Functions for setting and getting vehicle state parameters. ```APIDOC ## setParams ### Description Set vehicle state parameters (doors, windows, panels, etc.). Use -1 to leave unchanged, 0 to close/off, 1 to open/on. ### Signature ```cpp void setParams(const VehicleParams& params); ``` ### Parameters #### Request Body - **params** (VehicleParams) - Required - An object containing the vehicle parameters to set. ### Request Example ```cpp VehicleParams params; params.engine = 1; // Turn on engine params.lights = 1; // Turn on lights params.bonnet = 0; // Close bonnet vehicle->setParams(params); ``` ### Struct VehicleParams - **engine** (int8_t) - Optional - -1 = unchanged, 0 = off, 1 = on - **lights** (int8_t) - Optional - -1 = unchanged, 0 = off, 1 = on - **alarm** (int8_t) - Optional - -1 = unchanged, 0 = off, 1 = on - **doors** (int8_t) - Optional - All doors. -1 = unchanged, 0 = closed, 1 = open - **bonnet** (int8_t) - Optional - -1 = unchanged, 0 = closed, 1 = open - **boot** (int8_t) - Optional - Trunk. -1 = unchanged, 0 = closed, 1 = open - **objective** (int8_t) - Optional - -1 = unchanged, 0 = off, 1 = on - **siren** (int8_t) - Optional - -1 = unchanged, 0 = off, 1 = on - **doorDriver** (int8_t) - Optional - Driver door. -1 = unchanged, 0 = closed, 1 = open - **doorPassenger** (int8_t) - Optional - Passenger door. -1 = unchanged, 0 = closed, 1 = open - **doorBackLeft** (int8_t) - Optional - Back left door. -1 = unchanged, 0 = closed, 1 = open - **doorBackRight** (int8_t) - Optional - Back right door. -1 = unchanged, 0 = closed, 1 = open - **windowDriver** (int8_t) - Optional - Driver window. -1 = unchanged, 0 = closed, 1 = open - **windowPassenger** (int8_t) - Optional - Passenger window. -1 = unchanged, 0 = closed, 1 = open - **windowBackLeft** (int8_t) - Optional - Back left window. -1 = unchanged, 0 = closed, 1 = open - **windowBackRight** (int8_t) - Optional - Back right window. -1 = unchanged, 0 = closed, 1 = open ``` ```APIDOC ## getParams ### Description Get current vehicle parameters. ### Signature ```cpp VehicleParams getParams() const; ``` ### Returns `VehicleParams` with current state (all 0 or 1, not -1). ``` -------------------------------- ### Load Game Mode Entities Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/core.md Invoke this method to recreate all entities that are normally present when a game mode starts. This is usually done after the game mode has been loaded. ```cpp void reloadAll(); ``` -------------------------------- ### Registering Actor Event Handler Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/actors.md Demonstrates how to create a custom handler for actor events and register it with the actor's event dispatcher. Ensure the actorsComponent is valid before attempting to get the event dispatcher. ```cpp struct MyActorHandler : ActorEventHandler { void onPlayerGiveDamageActor(IPlayer& player, IActor& actor, float amount, unsigned weapon, BodyPart part) override { // Handle damage } }; MyActorHandler handler; actorsComponent->getEventDispatcher().addEventHandler(&handler); ``` -------------------------------- ### onInit Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/component.md Called after all components are loaded. Use to query other components, register handlers on other components, and set up component dependencies. Interaction with other components or firing events is not recommended here. ```APIDOC ## onInit ### Description Optional. Called after all components are loaded. Use to query other components by UID, register handlers on other components, and set up component dependencies. ### Method `virtual void onInit(IComponentList* components); ` ### Parameters #### Path Parameters - **components** (`IComponentList*`) - Required - List of all loaded components ### Remarks **Important:** Do NOT interact with other components or fire events here. Only query and register. ### Example ```cpp void onInit(IComponentList* components) override { auto vehicles = components->queryComponent(); if (vehicles) { vehicles->getEventDispatcher().addEventHandler(&myVehicleHandler); } } ``` ``` -------------------------------- ### Get Player Weapon Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/player.md Retrieves the player's currently equipped weapon. ```cpp PlayerWeapon getWeapon() const; ``` -------------------------------- ### Get Player Fighting Style Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/player.md Retrieves the player's current fighting style. ```cpp PlayerFightingStyle getFightingStyle() const; ``` -------------------------------- ### Get Player Special Action Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/player.md Retrieves the player's current special action. ```cpp PlayerSpecialAction getSpecialAction() const; ``` -------------------------------- ### Get Vehicle Damage Status Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/vehicle.md Retrieves the current damage status bitfield of a vehicle. ```cpp uint32_t getDamageStatus() const; ``` -------------------------------- ### Setting Vehicle Spawn Data Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/vehicle.md Demonstrates how to set the initial spawn data for a vehicle using the `setSpawnData` method and a `VehicleSpawnData` struct. ```cpp VehicleSpawnData data; data.modelID = 411; // Infernus data.position = Vector3(100, 200, 10); data.zRotation = 0.0f; data.colour1 = 1; data.colour2 = 2; data.siren = false; data.interior = 0; data.respawnDelay = Seconds(10); vehicle->setSpawnData(data); ``` -------------------------------- ### Get Vehicle Paint Job Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/vehicle.md Retrieves the current paint job ID of a vehicle. ```cpp int getPaintjob() const; ``` -------------------------------- ### Count Total Actors Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/actors.md Gets the total number of actors currently managed by the ActorsComponent. ```cpp // Count size_t count = actorsComponent->count(); ``` -------------------------------- ### Create PeerAddress from String Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/network.md Demonstrates how to create PeerAddress objects for both IPv4 and IPv6 from string representations. ```cpp PeerAddress addr; addr.ipv6 = false; // IPv4 PeerAddress::FromString(addr, "192.168.1.1"); // IPv6 PeerAddress addr6; addr6.ipv6 = true; PeerAddress::FromString(addr6, "2001:db8::1"); ``` -------------------------------- ### Get Network Type Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/network.md Determines the underlying network implementation being used (e.g., RakNet, ENet). ```cpp ENetworkType getNetworkType() const; ``` -------------------------------- ### Get Vehicle Parameters Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/vehicle.md Retrieves the current state of all vehicle parameters, returning a VehicleParams struct. ```cpp VehicleParams getParams() const; ``` -------------------------------- ### Accessing Configuration Values Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/configuration.md Demonstrates how to retrieve string, integer, and float configuration values using the IConfig interface. It includes checks for successful retrieval before using the values. ```cpp IConfig& config = core->getConfig(); // Get string value StringView hostname = config.getString("server.hostname"); // Get integer pointer (non-null on success) int* maxPlayers = config.getInt("server.maxplayers"); if (maxPlayers) { core->logLn(LogLevel::Message, "Max players: %d", *maxPlayers); } // Get float pointer float* streamRadius = config.getFloat("network.stream_radius"); if (streamRadius) { core->logLn(LogLevel::Message, "Stream radius: %.1f", *streamRadius); } // Check option type ConfigOptionType type = config.getType("server.hostname"); // Returns ConfigOptionType_String, ConfigOptionType_Int, etc. ``` -------------------------------- ### Get Pool Entity Count Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/pool.md Returns the current number of active entities within the pool. ```cpp size_t count(); ``` -------------------------------- ### Provide Custom Component Configuration Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/component.md Implement this method to set custom configuration options for your component. Use the `defaults` flag to either populate default values or load existing configurations. ```cpp void provideConfiguration(ILogger& logger, IEarlyConfig& config, bool defaults) override { if (defaults) { config.setInt("mycomponent.max_players", 500); config.setString("mycomponent.mode", "normal"); config.setBool("mycomponent.debug", false); } } ``` -------------------------------- ### Actor Appearance Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/actors.md Manage the visual appearance of an actor by setting and getting their character model (skin). ```APIDOC ## setSkin / getSkin ### Description Set or get the actor's character model/skin. ### Method - `setSkin(int id)`: Sets the actor's skin. - `getSkin()`: Gets the current actor's skin. ### Parameters #### setSkin - **id** (int) - Required - The ID of the skin to apply (0-299). ### Return Value #### getSkin - **int**: The current skin ID of the actor. ### Example ```cpp setSkin(250); // Sets the actor to use the CJ skin. int currentSkin = getSkin(); ``` ``` -------------------------------- ### Accessing Network Configuration and Statistics Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/network.md Demonstrates how to retrieve a list of all available networks and access their type and statistics. ```APIDOC ## Network Configuration ### Description Access global network settings and information through `ICore::getNetworks()`. This allows you to iterate through all available network interfaces and retrieve details such as the network type and performance statistics. ### Usage Example ```cpp const FlatPtrHashSet& networks = core->getNetworks(); for (INetwork* network : networks) { ENetworkType type = network->getNetworkType(); const NetworkStats& stats = network->getStatistics(); // Access network details } ``` ``` -------------------------------- ### Create a Custom SDK Component Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/README.md Provides a template for creating a new SDK component. This includes defining the component's interface, providing a unique ID, and implementing the entry point for component instantiation. ```cpp struct MyComponent : IComponent { PROVIDE_UID(0x1234567890abcdef); void onLoad(ICore* c) override { /* ... */ } void onInit(IComponentList* c) override { /* ... */ } void onReady() override { /* ... */ } void free() override { /* ... */ } void reset() override { /* ... */ } StringView componentName() const override { return "MyComponent"; } SemanticVersion componentVersion() const override { return SemanticVersion(1,0,0); } }; extern "C" SDK_EXPORT IComponent* __CDECL ComponentEntryPoint() { return new MyComponent(); } ``` -------------------------------- ### Handle Configuration Type Mismatch Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/errors.md Demonstrates checking the configuration option type using config.getType() before attempting to retrieve it as a specific type, ensuring safe access. ```cpp ConfigOptionType type = config.getType("server.maxplayers"); if (type == ConfigOptionType_Int) { int* value = config.getInt("server.maxplayers"); // Safe access } ``` -------------------------------- ### HTTP Request Types Enum Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/core.md Defines the available types for HTTP requests: GET, POST, and HEAD. ```cpp enum HTTPRequestType { HTTPRequestType_Get = 1, HTTPRequestType_Post = 2, HTTPRequestType_Head = 3 }; ``` -------------------------------- ### Get Weapon Ammunition Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/player.md Retrieves the ammunition count for a specific weapon. Returns 0 if the player does not own the weapon. ```cpp int getWeaponAmmo(PlayerWeapon weapon) const; ``` -------------------------------- ### Get Network Statistics Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/network.md Retrieves network performance statistics, either globally for all connections or for a specific player. ```cpp const NetworkStats& getStatistics() const; const NetworkStats& getStatistics(const IPlayer& peer) const; ``` -------------------------------- ### getMaxPassengers Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/vehicle.md Get the maximum number of passenger seats available in a vehicle, excluding the driver's seat. ```APIDOC ## getMaxPassengers ### Description Get the maximum number of passenger seats available in a vehicle, excluding the driver's seat. ### Method `int getMaxPassengers() const;` ### Return Value - int - The number of available passenger seats. ``` -------------------------------- ### Implement Component Entry Point Function Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/component.md Implement the exported function that returns an instance of your component. The server calls this function after loading the component's module. ```cpp extern "C" SDK_EXPORT IComponent* __CDECL ComponentEntryPoint() { return new MyComponent(); } ``` -------------------------------- ### setTrainSpeed / getTrainSpeed Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/vehicle.md Set or get the movement speed of a train. This function controls how fast the train is moving. ```APIDOC ## setTrainSpeed / getTrainSpeed ### Description Set or get the movement speed of a train. This function controls how fast the train is moving. ### Method `void setTrainSpeed(float speed);` `float getTrainSpeed() const;` ### Parameters #### setTrainSpeed Parameters - **speed** (float) - Required - The movement speed of the train. ### Return Value #### getTrainSpeed Return Value - float - The current movement speed of the train. ``` -------------------------------- ### Get Vehicle Health Source: https://github.com/openmultiplayer/open.mp-sdk/blob/master/_autodocs/api-reference/vehicle.md Retrieves the current health points of a vehicle as a float. The maximum health is 1000.0f. ```cpp float getHealth(); ``` ```cpp if (vehicle->getHealth() < 250.0f) { // Vehicle will explode soon } vehicle->setHealth(1000.0f); // Repair vehicle ```