From a8033c03b2879aa73b6d54f4854a40443fdcbb23 Mon Sep 17 00:00:00 2001 From: Refil <53364591+Refilewski@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:02:00 +0100 Subject: [PATCH 01/14] Migrate AzimuthRPC native entrypoint to FH2 Mod Platform --- native/FH2ML.AzimuthRPC/AzimuthRpcMod.cpp | 197 +++---- native/FH2ML.AzimuthRPC/CMakeLists.txt | 2 +- native/FH2ML.AzimuthRPC/platform-sdk/LICENSE | 21 + native/FH2ML.AzimuthRPC/platform-sdk/fh2mod.h | 489 ++++++++++++++++++ 4 files changed, 619 insertions(+), 90 deletions(-) create mode 100644 native/FH2ML.AzimuthRPC/platform-sdk/LICENSE create mode 100644 native/FH2ML.AzimuthRPC/platform-sdk/fh2mod.h diff --git a/native/FH2ML.AzimuthRPC/AzimuthRpcMod.cpp b/native/FH2ML.AzimuthRPC/AzimuthRpcMod.cpp index d0865fb..8211344 100644 --- a/native/FH2ML.AzimuthRPC/AzimuthRpcMod.cpp +++ b/native/FH2ML.AzimuthRPC/AzimuthRpcMod.cpp @@ -1,5 +1,5 @@ #include -#include "FH2ML.h" +#include "fh2mod.h" #include "LocationResolver.h" #include @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -41,14 +42,16 @@ constexpr std::uintptr_t kSimulationManagerVtableRva = 0x02C5FD70ull; constexpr std::size_t kCarIdOffset = 0x278; constexpr std::size_t kCarIdBytes = 64; constexpr char kDiscordApplicationId[] = "1445162899315363924"; -constexpr char kVersion[] = "0.9.9"; +constexpr char kVersion[] = "0.9.10"; +constexpr char kPlatformVersion[] = "2.7.3"; constexpr DWORD kDiscordReconnectMs = 5000; constexpr DWORD kPresenceUpdateMs = 4000; constexpr LONGLONG kMaxLogBytes = 2ll * 1024ll * 1024ll; std::atomic g_started{false}; std::atomic g_stop{false}; -const FH2ML_HostAPI* g_hostApi = nullptr; +const FH2ModApi* g_platformApi = nullptr; +FH2Mod* g_registeredMod = nullptr; struct Vec3 { @@ -175,8 +178,8 @@ void Trace(const std::string& message) OutputDebugStringA(debug.c_str()); AppendLog(message); - if (g_hostApi != nullptr && g_hostApi->Log != nullptr) - g_hostApi->Log("azimuth-rpc", message.c_str()); + if (g_platformApi != nullptr && g_registeredMod != nullptr && g_platformApi->log != nullptr) + g_platformApi->log(g_registeredMod, message.c_str()); } std::string WideToUtf8(const wchar_t* value) @@ -279,10 +282,10 @@ bool IsSupportedGameImage(const std::uintptr_t base) std::uintptr_t GetGameBaseFromHost() { - if (g_hostApi == nullptr || g_hostApi->GetGameModule == nullptr) + if (g_platformApi == nullptr || g_platformApi->game_base == nullptr) return 0; - const std::uintptr_t base = g_hostApi->GetGameModule(); + const std::uintptr_t base = reinterpret_cast(g_platformApi->game_base()); return IsSupportedGameImage(base) ? base : 0; } @@ -429,13 +432,13 @@ std::string AsciiBytes(const std::uint8_t* data, const std::size_t size) return result; } -bool ReadCarId(const std::uint8_t* raw, std::string& value, std::string& reason) +bool ReadCarId(const std::uint8_t* raw, std::string& value, std::string& reason, const std::size_t offset = kCarIdOffset) { value.clear(); reason.clear(); std::size_t length = 0; - while (length < kCarIdBytes && raw[kCarIdOffset + length] != 0) + while (length < kCarIdBytes && raw[offset + length] != 0) ++length; if (length == 0) @@ -456,7 +459,7 @@ bool ReadCarId(const std::uint8_t* raw, std::string& value, std::string& reason) for (std::size_t i = 0; i < length; ++i) { - const unsigned char c = raw[kCarIdOffset + i]; + const unsigned char c = raw[offset + i]; if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || @@ -486,6 +489,53 @@ bool ReadCarId(const std::uint8_t* raw, std::string& value, std::string& reason) return true; } +bool LooksLikeFallbackCarId(const std::string& id) +{ + const auto first = id.find('_'); + const auto last = id.rfind('_'); + if (first < 2 || first > 5 || last == first || last < first + 2) + return false; + for (std::size_t i = 0; i < first; ++i) + if (id[i] < 'A' || id[i] > 'Z') + return false; + const auto length = id.size() - last - 1; + if (length != 2 && length != 4) + return false; + for (std::size_t i = last + 1; i < id.size(); ++i) + if (id[i] < '0' || id[i] > '9') + return false; + return true; +} + +// Recover only a single plausible year-suffixed car ID inside the known object. +bool FindFallbackCar(const std::uintptr_t audio, std::string& car, std::size_t& offset) +{ + std::array buffer{}; + if (!ReadBytes(audio, buffer.data(), buffer.size())) + return false; + std::string found; + std::size_t foundAt = 0; + for (std::size_t at = 0x200; at <= 0x500; ++at) + { + if (at > 0 && buffer[at - 1] != 0) + continue; + std::string candidate, reason; + if (!ReadCarId(buffer.data(), candidate, reason, at) || !LooksLikeFallbackCarId(candidate)) + continue; + if (!found.empty() && found != candidate) + return false; + if (found.empty()) + { + found = candidate; + foundAt = at; + } + } + if (found.empty()) return false; + car = found; + offset = foundAt; + return true; +} + bool BytesEqual(const std::uint8_t* data, const std::size_t offset, const char* text) { const std::size_t length = std::strlen(text) + 1; @@ -682,7 +732,18 @@ Snapshot CaptureSnapshot(const std::uintptr_t gameBase) std::string car; std::string carReason; - const bool carParsed = ReadCarId(raw.data(), car, carReason); + bool carParsed = ReadCarId(raw.data(), car, carReason); + if (!carParsed) + { + std::size_t recoveredAt = 0; + if (FindFallbackCar(audio, car, recoveredAt)) + { + carParsed = true; + char status[80]{}; + std::snprintf(status, sizeof(status), "fallback@0x%zX", recoveredAt); + carReason = status; + } + } if (carParsed) { snapshot.carRaw = car; @@ -1127,7 +1188,7 @@ DWORD WINAPI RpcThread(LPVOID) const std::int64_t sessionStart = static_cast(std::time(nullptr)); - Trace(std::string("AzimuthRPC ") + kVersion + " FH2ML native worker started"); + Trace(std::string("AzimuthRPC ") + kVersion + " FH2 Mod Platform native worker started"); Trace("Log file: %LOCALAPPDATA%\\AzimuthRPC\\logs\\AzimuthRPC.log"); LogLoadedModules(); @@ -1146,7 +1207,7 @@ DWORD WINAPI RpcThread(LPVOID) std::snprintf( message, sizeof(message), - "FH2ML game module acquired at 0x%llX", + "FH2 Mod Platform game module acquired at 0x%llX", static_cast(gameBase)); Trace(message); } @@ -1216,103 +1277,61 @@ DWORD WINAPI RpcThread(LPVOID) if (discordPipe != INVALID_HANDLE_VALUE) CloseHandle(discordPipe); - Trace("FH2ML native worker stopped"); + Trace("FH2 Mod Platform native worker stopped"); return 0; } } // namespace -extern "C" __declspec(dllexport) int FH2ML_Initialize(const FH2ML_HostAPI* api) +FH2MOD_EXPORT int fh2mod_init(const FH2ModApi* api) { - // Log *before* checking the FH2ML ABI. Otherwise an incompatible loader, - // missing API callback, or unsupported game image could return silently and - // users would have no AzimuthRPC.log to include in a bug report. - Trace(std::string("AzimuthRPC ") + kVersion + " FH2ML_Initialize entered"); - + Trace(std::string("AzimuthRPC ") + kVersion + " fh2mod_init entered"); if (api == nullptr) { - Trace("FH2ML initialization rejected: host API pointer is null"); - return 0; - } - if (api->size < sizeof(FH2ML_HostAPI)) - { - char message[160]{}; - std::snprintf( - message, - sizeof(message), - "FH2ML initialization rejected: host API table too small (got %zu, expected at least %zu)", - static_cast(api->size), - sizeof(FH2ML_HostAPI)); - Trace(message); - return 0; - } - if (api->version != FH2ML_API_VERSION) - { - char message[160]{}; - std::snprintf( - message, - sizeof(message), - "FH2ML initialization rejected: API version mismatch (got %u, expected %u)", - static_cast(api->version), - static_cast(FH2ML_API_VERSION)); - Trace(message); - return 0; + Trace("FH2 Mod Platform rejected: null API"); + return 1; } - if (api->Log == nullptr || - api->RegisterMod == nullptr || - api->GetGameModule == nullptr) + constexpr std::size_t requiredSize = offsetof(FH2ModApi, wait_for_game) + sizeof(api->wait_for_game); + if (api->size < requiredSize || api->api_version < 1 || + api->register_mod == nullptr || api->log == nullptr || + api->game_base == nullptr || api->wait_for_game == nullptr) { - Trace("FH2ML initialization rejected: required Log, RegisterMod or GetGameModule callback missing"); - return 0; + Trace("FH2 Mod Platform rejected: incomplete API table"); + return 1; } - bool expected = false; if (!g_started.compare_exchange_strong(expected, true)) - { - Trace("FH2ML initialization skipped: AzimuthRPC is already running"); - return 1; - } - - g_stop.store(false, std::memory_order_relaxed); - g_hostApi = api; - - if (api->RegisterMod("azimuth-rpc", kVersion) == 0) - { - Trace("FH2ML initialization rejected: RegisterMod failed"); - g_hostApi = nullptr; - g_started.store(false, std::memory_order_relaxed); return 0; - } - - const std::uintptr_t gameBase = GetGameBaseFromHost(); - if (gameBase == 0) + g_stop.store(false, std::memory_order_relaxed); + g_platformApi = api; + FH2ModInfo info{}; + info.size = sizeof(info); + info.name = "AzimuthRPC"; + info.version = kVersion; + info.github_repo = "Refilewski/Azimuth-RPC"; + info.platform_version = kPlatformVersion; + info.check_updates = 1; + info.description = "Discord Rich Presence for Forza Horizon 2"; + g_registeredMod = api->register_mod(&info); + if (!g_registeredMod) { - Trace("FH2ML initialization rejected: GetGameModule returned no supported FH2 1.0.0.64 image"); - LogLoadedModules(); - g_hostApi = nullptr; + Trace("FH2 Mod Platform rejected: register_mod failed"); + g_platformApi = nullptr; g_started.store(false, std::memory_order_relaxed); - return 0; + return 1; } - - char registration[160]{}; - std::snprintf( - registration, - sizeof(registration), - "Registered with FH2ML API v%u; game module=0x%llX", - static_cast(api->version), - static_cast(gameBase)); - Trace(registration); - + // Azimuth maps FH2 after platform initialization: worker must wait. + Trace("Registered with FH2 Mod Platform; waiting for supported game image"); HANDLE thread = CreateThread(nullptr, 0, RpcThread, nullptr, 0, nullptr); - if (thread == nullptr) + if (!thread) { - Trace("Failed to start FH2ML native RPC worker"); - g_hostApi = nullptr; + Trace("Failed to start native RPC worker"); + g_registeredMod = nullptr; + g_platformApi = nullptr; g_started.store(false, std::memory_order_relaxed); - return 0; + return 1; } - CloseHandle(thread); - return 1; + return 0; } BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) diff --git a/native/FH2ML.AzimuthRPC/CMakeLists.txt b/native/FH2ML.AzimuthRPC/CMakeLists.txt index 8a7b6e2..f907a28 100644 --- a/native/FH2ML.AzimuthRPC/CMakeLists.txt +++ b/native/FH2ML.AzimuthRPC/CMakeLists.txt @@ -4,7 +4,7 @@ if(NOT WIN32 OR NOT CMAKE_SIZEOF_VOID_P EQUAL 8) message(FATAL_ERROR "AzimuthRPC requires Windows x64") endif() add_library(AzimuthRPCMod SHARED AzimuthRpcMod.cpp LocationResolver.cpp) -target_include_directories(AzimuthRPCMod PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/fh2ml-sdk") +target_include_directories(AzimuthRPCMod PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/platform-sdk") target_compile_features(AzimuthRPCMod PRIVATE cxx_std_20) target_compile_definitions(AzimuthRPCMod PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) if(MSVC) diff --git a/native/FH2ML.AzimuthRPC/platform-sdk/LICENSE b/native/FH2ML.AzimuthRPC/platform-sdk/LICENSE new file mode 100644 index 0000000..c98dafb --- /dev/null +++ b/native/FH2ML.AzimuthRPC/platform-sdk/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Trinculo54 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/native/FH2ML.AzimuthRPC/platform-sdk/fh2mod.h b/native/FH2ML.AzimuthRPC/platform-sdk/fh2mod.h new file mode 100644 index 0000000..abf0538 --- /dev/null +++ b/native/FH2ML.AzimuthRPC/platform-sdk/fh2mod.h @@ -0,0 +1,489 @@ +/* + * fh2mod.h -- FH2 Mod Platform API (MIT licensed, see LICENSE). + * + * The FH2 Mod Platform is the d3dcompiler_47.dll next to azimuth.exe. It + * loads every DLL in the fh2-mods folder and offers them the services in + * FH2ModApi below, so mods don't each reinvent them and don't step on each + * other's files. + * + * A mod is a 64-bit Windows DLL in fh2-mods that exports: + * + * FH2MOD_EXPORT int fh2mod_init(const FH2ModApi* api); + * + * The platform calls it once, on its own thread (never under the Windows + * loader lock), right after loading the DLL. Do your setup there, start + * your own threads for anything slow, and return 0. The api pointer stays + * valid for the life of the process. + * + * Strings passed in are copied; nothing you get back needs freeing. All + * functions are thread-safe. + * + * Compatibility: api->api_version only ever grows, and new members are only + * ever added at the end. Check api->size (or api_version) before using a + * member newer than the version you built against. + */ +#ifndef FH2MOD_H +#define FH2MOD_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define FH2MOD_API_VERSION 8 + +#ifdef __cplusplus +#define FH2MOD_EXPORT extern "C" __declspec(dllexport) +#else +#define FH2MOD_EXPORT __declspec(dllexport) +#endif + +/* Opaque handle for one registered mod. */ +typedef struct FH2Mod FH2Mod; +/* Opaque handle for one hook (API 3). */ +typedef struct FH2Hook FH2Hook; +/* One row on the Mods page (API 4), defined below FH2ModApi. */ +typedef struct FH2Setting FH2Setting; +/* A page of your own, and one of its rows (API 8), defined below FH2ModApi. */ +typedef struct FH2Page FH2Page; +typedef struct FH2PageRow FH2PageRow; + +/* The CPU's registers at an instruction hook (API 7): see hook_instruction. + rsp is what it was at the hooked instruction; changing it has no effect. */ +typedef struct FH2Xmm { + union { + float f[4]; + double d[2]; + uint32_t u32[4]; + uint64_t u64[2]; + }; +} FH2Xmm; +typedef struct FH2Context { + uint64_t rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi; + uint64_t r8, r9, r10, r11, r12, r13, r14, r15; + uint64_t rflags; + uint64_t reserved; + FH2Xmm xmm[16]; +} FH2Context; +typedef void (*FH2InstructionFn)(FH2Context* ctx, void* user); + +typedef struct FH2ModInfo { + uint32_t size; /* sizeof(FH2ModInfo) */ + const char* name; /* display name, UTF-8: "WheresMyBuddy" */ + const char* version; /* "1.3.0" */ + const char* github_repo; /* "Owner/Repo" to check for new releases, or NULL */ + const char* platform_version; /* the platform version this mod ships with, e.g. FH2MOD_PLATFORM_VERSION */ + int check_updates; /* 0 = never go online for this mod */ + /* API 6 (platform 2.5.0): what your mod adds, in a sentence or two, for the MODS tab's + Installed mods page. May be NULL. Leave it out (an older FH2ModInfo) on older platforms. */ + const char* description; +} FH2ModInfo; + +typedef struct FH2ModApi { + uint32_t size; /* sizeof(FH2ModApi) as the platform knows it */ + uint32_t api_version; /* FH2MOD_API_VERSION of the platform */ + const char* platform_version; /* "2.2.0" */ + const wchar_t* azimuth_dir; /* folder with azimuth.exe, no trailing slash */ + const wchar_t* game_dir; /* the game's Mount folder (game:\), or "" if not found */ + + /* Call once from fh2mod_init. Returns your handle for the calls below. + The platform then shows a title-screen notice when a newer release of + your mod is out on GitHub (checked at most every 6 hours, and again as + soon as a different version of your mod is installed), or when + the installed platform is older than info->platform_version. */ + FH2Mod* (*register_mod)(const FH2ModInfo* info); + + /* One line to fh2-mods\platform.log, prefixed with your mod's name. */ + void (*log)(FH2Mod* mod, const char* utf8_line); + + /* ---- String tables ----------------------------------------------------- + The game's text lives in string tables (media\Stripped\StringTables\ + .zip\.str). Edits are applied to every language and + written to Forza Horizon 2 Extra Options' mediaoverride folder, merged + with every other mod's edits to the same table. The game reads its + string tables once at startup: edits made in fh2mod_init are always in + time; later ones show from the next launch. See docs/string-tables.md + for how to find keys. */ + + /* Set the string with `key` in `table` ("Main.str") to `text`. */ + void (*set_string)(FH2Mod* mod, const char* table, uint16_t key, const wchar_t* text); + /* Replace every string in `table` that is exactly `from` with `to`. */ + void (*replace_string)(FH2Mod* mod, const char* table, const wchar_t* from, const wchar_t* to); + /* Forget this mod's edits to `table`, or to every table if NULL. */ + void (*clear_strings)(FH2Mod* mod, const char* table); + /* Write the changed tables now. Done for you after fh2mod_init returns; + call it yourself after edits you make later. */ + void (*apply_strings)(FH2Mod* mod); + + /* ---- Title screen ------------------------------------------------------ + Lines shown under "PRESS (A) TO START", with every other mod's. Keep + each under ~40 characters. "\n" separates lines; NULL or "" clears. + Written when apply_strings runs (or right away after init). */ + void (*set_notice)(FH2Mod* mod, const char* utf8_lines); + + /* ---- The game ---------------------------------------------------------- + Azimuth maps forza_durango_release_final.exe (the 24 Nov 2015 Xbox One + build) into its own process when you press Play. */ + + /* Base address of the mapped game, or NULL if it isn't mapped yet. */ + void* (*game_base)(void); + /* Waits until the game is mapped (or timeout_ms passes; 0xFFFFFFFF = + forever) and returns its base, or NULL. */ + void* (*wait_for_game)(uint32_t timeout_ms); + + /* ==== API version 2 (platform 2.1.0): check api_version >= 2 ======== */ + + /* ---- Game files -------------------------------------------------------- + Replace a file the game reads from game:\media, through Extra Options' + mediaoverride folder. `media_path` is relative to media, with a zip's + name standing in for the zip: "drivatarglobalcache/DefaultCache.bin", + or "UI/somefile.xml" for a file inside media\UI.zip. One mod per + file: returns 1 if written (or already identical), 0 if another mod + already replaces it or the write failed (the log says which). String + tables and the game database have their own functions above and + below, and can't be replaced whole. */ + int (*set_file)(FH2Mod* mod, const char* media_path, const void* data, size_t size); + /* Stop replacing a file (or all of yours, if NULL): the override is + deleted and the game reads its own copy again. Files a mod no longer + replaces at all (because it was removed) are cleaned up shortly after + startup. */ + void (*clear_file)(FH2Mod* mod, const char* media_path); + + /* ---- Game database ----------------------------------------------------- + media\Stripped\gamedbRC.slt is a SQLite database with most of the + game's data (cars, events, AI drivers). add_sql queues statements + (UTF-8, several per call is fine) to run against a copy of it; every + mod's statements run in load order, each mod's in a transaction of its + own, and the copy goes to mediaoverride. If a mod's SQL fails, only + that mod's changes are rolled back, and the error is logged. The copy + is rebuilt only when something changed. Statements added in + fh2mod_init are applied for you; later ones need apply_database. */ + void (*add_sql)(FH2Mod* mod, const char* utf8_sql); + /* Drop all of your statements (call apply_database after). */ + void (*clear_sql)(FH2Mod* mod); + /* Rebuild the database copy now if anything changed. Slow (seconds): + call it from your own thread. The game reads the database once, at + startup. */ + void (*apply_database)(FH2Mod* mod); + + /* ---- Other mods -------------------------------------------------------- + Mods can offer each other functions. Publish a struct of function + pointers under a name, like "WheresMyBuddy.Friends", and treat it like + this API: never change a published member, only add new ones at the + end and bump the version. */ + + /* Offer `iface` (which must stay valid) as `name`, version `version`. + Another mod can't take a name you published. */ + void (*publish_interface)(FH2Mod* mod, const char* name, uint32_t version, const void* iface); + /* The interface published as `name`, if its version is at least + `min_version`; otherwise NULL. Mods start in alphabetical order, so + look up interfaces after wait_for_mods. */ + const void* (*get_interface)(const char* name, uint32_t min_version); + /* Waits until every mod's fh2mod_init has returned (or timeout_ms + passes). Returns 1 when they have. Call it from your own thread: + from inside fh2mod_init it returns 0 straight away. */ + int (*wait_for_mods)(uint32_t timeout_ms); + /* The version string of the registered mod called `name`, or NULL if + it isn't installed. */ + const char* (*mod_version)(const char* name); + + /* ==== API version 3 (platform 2.2.0): check api_version >= 3 ======== */ + + /* ---- Hooks ------------------------------------------------------------- + Change what game code does, through the platform, so every mod's + changes to the same code fit together: several mods can hook one + function, each calls on to the next through `original`, and they can + be switched on and off in any order. Hooks on exactly the same function, + call site or pointer share it; the platform refuses a hook whose bytes + overlap any other hook's, or game code that Extra Options (or a mod + patching the game by itself) already changed, and logs who hooked + what. Crash reports list every hook in place. + + Hooks in game code have to wait for wait_for_code (below). Hooks + elsewhere (Azimuth, a Windows DLL) can be made at any time. + + Each call makes a hook, switched off, and returns it (or NULL, with + the reason in the log). `name` is for the log and crash reports, like + "RadioStreamFmod::createSound"; it may be NULL. `detour` is your + function, with the same signature and calling convention as the code + it replaces. `*original` is set before the call returns: call it from + your detour to run the code you replaced (and any other mod's detour + behind yours). It's safe to call at any time; while your hook is off + it goes straight to the game's own code. + + When several mods hook the same place, the most recently enabled + detour runs first. */ + + /* An inline hook at the start of a function (`target`), with MinHook. */ + FH2Hook* (*hook_function)(FH2Mod* mod, const char* name, void* target, void* detour, void** original); + /* One CALL rel32 or JMP rel32 instruction at `call_site`: only that + call goes to your detour; `*original` is the function it called. */ + FH2Hook* (*hook_call)(FH2Mod* mod, const char* name, void* call_site, void* detour, void** original); + /* A function pointer in memory, like a vtable slot: `*slot` is replaced, + and `*original` is what it held. */ + FH2Hook* (*hook_pointer)(FH2Mod* mod, const char* name, void** slot, void* detour, void** original); + /* Switch `hook` on or off, or all of your hooks if it's NULL (in one go: + the game's threads are paused once, for all of them). Returns 1 if + they all are now; 0 if any couldn't be, with the reason in the log. */ + int (*enable_hooks)(FH2Mod* mod, FH2Hook* hook); + int (*disable_hooks)(FH2Mod* mod, FH2Hook* hook); + /* Like wait_for_game, but also waits until Extra Options has finished + patching the game (it checks the code it patches first, and patches + nothing if any of it was changed). Returns the game's base when it's + safe to hook game code, or NULL on timeout. Call it from your own + thread. */ + void* (*wait_for_code)(uint32_t timeout_ms); + + /* ==== API version 4 (platform 2.3.0): check api_version >= 4 ======== */ + + /* ---- In-game settings -------------------------------------------------- + On/Off rows on the game's own Mods page (Pause > Settings > MODS), + next to every other mod's. The tile and the page only appear when at + least one mod adds a row. Add your rows from fh2mod_init: the page is + written when every mod's fh2mod_init has returned, and rows added + after that only show from the next launch. + + Your mod keeps owning the value: pass the current one in, and when the + player changes it, on_change tells you the new one, so you can save it + wherever you keep your settings (your ini) and use it. The platform + doesn't store values. Rows marked needs_restart get a note in their + description, and changing one brings up the game's own message box + when the player leaves the Mods page, offering to restart the game. + Returns 1 if the row was added, 0 if not (the log says why). */ + int (*add_setting)(FH2Mod* mod, const FH2Setting* setting); + /* The row's current value, or -1 if you have no row called `key`. */ + int (*get_setting)(FH2Mod* mod, const char* key); + /* You changed the value yourself (a hotkey, say): the page shows it the + next time it opens. on_change isn't called. */ + void (*set_setting)(FH2Mod* mod, const char* key, int value); + + /* ==== API version 5 (platform 2.4.0): check api_version >= 5 ======== */ + + /* Sliders on the Mods page: an FH2Setting with kind = FH2_SETTING_SLIDER + (see FH2Setting below). On an older platform a slider would come out as + an On/Off row, so only add one when api_version >= 5. */ + /* A slider's current value, or 0 if you have no slider called `key`. */ + float (*get_slider)(FH2Mod* mod, const char* key); + /* You changed a slider's value yourself: the page shows it the next time + it opens. on_slide isn't called. */ + void (*set_slider)(FH2Mod* mod, const char* key, float value); + + /* ==== API version 7 (platform 2.6.0): check api_version >= 7 ======== */ + + /* ---- Precise changes to game code --------------------------------------- + For when hooking a whole function, one call or one pointer is too + blunt: a constant in the middle of a function, a branch to flip, a + register to read at one exact instruction. Both kinds below come back + as an FH2Hook, made switched off, and are switched with enable_hooks + and disable_hooks like any other hook. The same rules hold: game code + has to wait for wait_for_code, the bytes are checked against the exe on + disk and against every other hook, and it's all in the log and in + crash reports. Addresses are exact: use them on the game build you + found them in (the one Azimuth runs). */ + + /* Bytes written in place: `size` bytes (at most 32) of `bytes` at `at`, + which has to hold `expect` (the same size) first; pass NULL to take + what's there as long as it matches the exe on disk. Disabling puts + the original bytes back. Only one patch can cover a byte, and a patch + can't overlap any other hook. */ + FH2Hook* (*patch_bytes)(FH2Mod* mod, const char* name, void* at, const void* expect, const void* bytes, uint32_t size); + + /* An instruction hook: when the game reaches the instruction at `at` + (anywhere in a function, not only its start), `fn(ctx, user)` is + called with the CPU's registers in `ctx`, before that instruction + runs. Change them in `ctx` (not rsp) and the game carries on with your + values. `at` has to be the start of an instruction, after the + function's prolog, with nothing in the function jumping into the + bytes the hook replaces (the platform checks; the log says why when it + refuses). Several mods may hook the same instruction: the most + recently enabled `fn` runs first. `fn` runs on the game's thread, + often every frame: keep it short. If it crashes, that hook is + switched off and the crash goes in the log. */ + FH2Hook* (*hook_instruction)(FH2Mod* mod, const char* name, void* at, FH2InstructionFn fn, void* user); + + /* ==== API version 8 (platform 2.7.0): check api_version >= 8 ======== */ + + /* ---- Pages ------------------------------------------------------------- + A page of your own in the game's menus, laid out like the Mods page: a + list of rows, each with a label on the left and a value on the right, + and the selected row's description beside the list. Your mod's page + under MODS > Installed mods gets a row that opens it. A page can also + take over a pause-menu tile that does nothing on PC: FH2Page.tile. + + Add pages from fh2mod_init (one added later only shows from the next + launch). Their rows can change at any time: the page is written each + time it's opened, from the rows you last set. Returns 1 if the page was + added, 0 if not (the log says why). */ + int (*add_page)(FH2Mod* mod, const FH2Page* page); + /* Your page `page_key` now has these `count` rows (copied), in this + order; the next time it opens, it shows them. Call it whenever they + change, or from the page's on_open. Returns 1, or 0 if you have no page + called `page_key` (or a row is unusable; the log says which). */ + int (*set_page_rows)(FH2Mod* mod, const char* page_key, const FH2PageRow* rows, uint32_t count); + + /* ---- Pages of your own design -------------------------------------- + Instead of rows, a page on a tile can be XAML you write: the game's + own controls, styles and textures, laid out however you like, inside + the frame of the game's options pages (background, player bar, help + bar). `content` replaces what's between the title and the help bar + (the HUD options page's BasicOptions panel), and must name the + element to focus first x:Name="FirstItem". `resources` (may be NULL) + goes into the page's ResourceDictionary. `help` (may be NULL) replaces + the help bar's DefaultHelpPanel; NULL leaves only Back. All three are + UTF-8 XAML fragments, using the page's xmlns (local: is ForzaUI). + Like rows, the XAML is copied, and the page is written from the last + you set each time it opens. A page with XAML shows it on its tile; + under MODS > Installed mods it shows its rows if it has any, and + otherwise its row says which tile opens it. Returns 1, or 0 if you + have no page called `page_key`, `content` has no FirstItem, or a + fragment's tags don't balance (the page keeps the XAML it had). + + Bindings: slot n (0..15) is an int of the page's, "FH2Mod_Slot_", + which XAML can bind two-way (a list's SelectedIndex, say), and + "FH2Mod_Slot__Is_" is true while it's v, 0..9999 (for + Visibility, with the converters FH2Mod_ShowIf, FH2Mod_ShowIfHidden + and FH2Mod_HideIf the platform puts in the page's resources). Slots + are 0 when the page opens; set the ones you want otherwise in + on_open. */ + int (*set_page_xaml)(FH2Mod* mod, const char* page_key, const char* resources, const char* content, const char* help); + /* A slot's value (0 if there's no such page or slot). */ + int (*get_page_slot)(FH2Mod* mod, const char* page_key, int slot); + /* Sets a slot. From on_button or on_slot, the page's bindings see it + straight away (from on_slot, except the slot being set). From + on_open, it's what the page opens with. Anywhere else, it's only + stored: the page doesn't show it, and opening resets it. Returns 1, + or 0 for no such page or slot. */ + int (*set_page_slot)(FH2Mod* mod, const char* page_key, int slot, int value); + /* Moves the focus to the Button, Slider or SpinnerControl named `name` + in the page's XAML, from on_button. Returns 1 if it did. */ + int (*focus_page_element)(FH2Mod* mod, const char* page_key, const char* name); + /* A line of text on the tile your page has taken over, at its bottom + left in the game's own style for a tile's count (a club tile's + member count): a score, say. Plain ASCII, up to 40 characters; NULL + or "" shows nothing. Call it from any thread, whenever it changes: + the pause menu reads it each time it's shown. Returns 1, or 0 if you + have no page called `page_key` or it isn't on a tile. */ + int (*set_page_tile_text)(FH2Mod* mod, const char* page_key, const char* text); + /* That tile's colours, as 0xAARRGGBB: `background`, and `text` for its + title and your line over it. 0 leaves the game's own (its light grey + tile, dark title and orange line). The icon takes the background's + colour, so it stays a shade of it. Like the text, the pause menu + reads them each time it's shown. Returns 1, or 0 if you have no page + called `page_key` or it isn't on a tile. */ + int (*set_page_tile_colors)(FH2Mod* mod, const char* page_key, uint32_t background, uint32_t text); +} FH2ModApi; + +/* Called on the game's UI thread when the player changes a row: keep it + short (save the value, flip a flag), and don't call back into the game. */ +typedef void (*FH2SettingChangedFn)(void* user, const char* key, int value); +/* The same for a slider (API 5). */ +typedef void (*FH2SliderChangedFn)(void* user, const char* key, float value); + +#define FH2_SETTING_ON_OFF 0 +#define FH2_SETTING_SLIDER 1 +#define FH2_SETTING_LINK 2 /* API 6 */ + +/* One row on the Mods page (API 4; sliders API 5). */ +struct FH2Setting { + uint32_t size; /* sizeof(FH2Setting) */ + const char* key; /* unique within your mod: letters, digits and '_', like "Trees" */ + const char* label; /* the row's label, UTF-8: "Breakable trees" */ + const char* description; /* shown beside the list while the row is selected; may be NULL */ + int value; /* current value: 0 = Off, 1 = On */ + int needs_restart; /* nonzero: a change only takes effect the next time the game starts */ + FH2SettingChangedFn on_change; /* may be NULL */ + void* user; /* passed to on_change and on_slide */ + + /* ---- API 5 (platform 2.4.0): sliders. Zeroed (as by FH2Setting s{}), + the row is On/Off and these are ignored. ---- */ + int kind; /* FH2_SETTING_ON_OFF or FH2_SETTING_SLIDER */ + float min, max; /* the slider's range */ + float step; /* how far one press of left or right moves it; 0 = a hundredth of the range */ + float slider_value; /* its current value (`value` is ignored) */ + float display_scale; /* the number shown is the value times this, so 100 shows 0.12 as 12; 0 = 1 */ + int decimals; /* digits shown after the decimal point, 0 to 3 */ + FH2SliderChangedFn on_slide; /* may be NULL */ + + /* ---- API 6 (platform 2.5.0): links. With kind = FH2_SETTING_LINK the row + opens a web page in the player's browser when they press A on it: your + dashboard, your docs. It shows on your mod's own page under MODS > + Installed mods (not on Settings > Mods), with the address under its + description. value, needs_restart, on_change and the slider fields are + ignored. On an older platform it would come out as an On/Off row, so + only add one when api_version >= 6. ---- */ + const char* url; /* "http://..." or "https://..." */ +}; + +/* Pages (API 8). Every page callback runs on the game's UI thread: keep them + short, and don't call into the game from them. */ +/* The page is about to be written to be shown: set its rows now if you + haven't kept them up to date. Opening MODS > Installed mods writes every + mod's pages, so it's called then too. */ +typedef void (*FH2PageOpenFn)(void* user, const char* page_key); +/* The player pressed A on a row that has a key. */ +typedef void (*FH2PageSelectFn)(void* user, const char* page_key, const char* row_key); +/* A page of your own design: a button was pressed (FH2_BUTTON_...). Return + FH2_PAGE_IGNORED for what it usually does (B leaves the page, A does + nothing, the others whatever the game does with them there), or one of + the FH2_PAGE_HANDLED values. */ +typedef int (*FH2PageButtonFn)(void* user, const char* page_key, int button); +/* A page of your own design: a binding changed slot `slot` to `value`. */ +typedef void (*FH2PageSlotFn)(void* user, const char* page_key, int slot, int value); + +#define FH2_BUTTON_A 1 +#define FH2_BUTTON_B 2 +#define FH2_BUTTON_X 3 +#define FH2_BUTTON_Y 4 +#define FH2_BUTTON_LB 5 +#define FH2_BUTTON_RB 6 +#define FH2_PAGE_IGNORED 0 +#define FH2_PAGE_HANDLED 1 /* nothing else happens */ +#define FH2_PAGE_HANDLED_SELECT 2 /* and the menus' select sound plays */ +#define FH2_PAGE_HANDLED_BACK 3 /* and the menus' back sound plays */ +#define FH2_PAGE_SLOTS 16 + +struct FH2Page { + uint32_t size; /* sizeof(FH2Page) */ + const char* key; /* unique within your mod: letters, digits and '_', like "List" */ + const char* title; /* the page's title, UTF-8: "Achievements" (shown in capitals) */ + const char* label; /* the row on your mod's page that opens it; NULL = the title */ + const char* description; /* that row's description; may be NULL */ + /* A pause-menu tile that opens this page instead of what it did on Xbox: + "Achievements" (the tile on the pause menu and on its Storm Island + tab). One mod per tile. NULL for none. */ + const char* tile; + FH2PageOpenFn on_open; /* may be NULL */ + FH2PageSelectFn on_select; /* may be NULL: A then does nothing on the page */ + void* user; /* passed to every callback */ + /* Pages of your own design (set_page_xaml). Both may be NULL. */ + FH2PageButtonFn on_button; + FH2PageSlotFn on_slot; +}; + +#define FH2_ROW_NORMAL 0 +#define FH2_ROW_DIM 1 /* label and value in grey: locked, not available yet */ +#define FH2_ROW_HEADING 2 /* label in the game's orange: a heading over the rows after it */ + +/* One row of a page (API 8). */ +struct FH2PageRow { + uint32_t size; /* sizeof(FH2PageRow) */ + const char* key; /* passed to on_select when A is pressed on it; NULL: A does nothing */ + const char* label; /* left, UTF-8: "Island Explorer" */ + const char* value; /* right: "12 / 50"; may be NULL */ + const char* description; /* beside the list while the row is selected; may be NULL */ + const char* footer; /* a line at the bottom of the description panel; may be NULL */ + int style; /* FH2_ROW_NORMAL, FH2_ROW_DIM or FH2_ROW_HEADING */ + int value_alert; /* nonzero: the value in red */ +}; + +/* What a mod exports. */ +typedef int (*FH2ModInitFn)(const FH2ModApi* api); + +#ifdef __cplusplus +} +#endif + +#endif /* FH2MOD_H */ From 30c5b1f1c38f289dd8591fc08074522b49be7416 Mon Sep 17 00:00:00 2001 From: Refil <53364591+Refilewski@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:04:07 +0100 Subject: [PATCH 02/14] Recover moved car identifier with bounded guarded probes in EXE and DLL --- native/FH2ML.AzimuthRPC/AzimuthRpcMod.cpp | 2 +- .../Game/GameSnapshotReader.cs | 54 +++++++++++++++++++ tests/AzimuthRPC.Core.Tests/Program.cs | 18 +++++++ 3 files changed, 73 insertions(+), 1 deletion(-) diff --git a/native/FH2ML.AzimuthRPC/AzimuthRpcMod.cpp b/native/FH2ML.AzimuthRPC/AzimuthRpcMod.cpp index 8211344..a6cd89f 100644 --- a/native/FH2ML.AzimuthRPC/AzimuthRpcMod.cpp +++ b/native/FH2ML.AzimuthRPC/AzimuthRpcMod.cpp @@ -477,7 +477,7 @@ bool ReadCarId(const std::uint8_t* raw, std::string& value, std::string& reason, } } - value.assign(reinterpret_cast(raw + kCarIdOffset), length); + value.assign(reinterpret_cast(raw + offset), length); if (value.find('_') == std::string::npos) { reason = "missing-underscore"; diff --git a/src/AzimuthRPC.Core/Game/GameSnapshotReader.cs b/src/AzimuthRPC.Core/Game/GameSnapshotReader.cs index addfdb0..04c1e8a 100644 --- a/src/AzimuthRPC.Core/Game/GameSnapshotReader.cs +++ b/src/AzimuthRPC.Core/Game/GameSnapshotReader.cs @@ -30,6 +30,17 @@ public GameSnapshot Capture(ulong gameBase, bool supportedBuild) if (raw is null) return GameSnapshot.Unavailable("Audio/vehicle snapshot read failed"); var ui = UiModeReader.ReadSnapshot(gameBase, true, frame.Read); string? car = ReadCar(raw.AsSpan(0x278, 64), out string carProbeStatus); + if (car is null) + { + // Bounded recovery within the same validated AudioEngine object. + // Keep the confirmed field as the primary source. + var extended = frame.Read(audio, 0x600); + if (extended is not null && TryFindFallbackCar(extended, out var recovered, out int recoveredAt)) + { + car = recovered; + carProbeStatus = $"fallback@0x{recoveredAt:X}"; + } + } if (car != _lastCarId) { _lastCarId = car; _displayName = FriendlyCarName(car); } float mph = F32(raw, 0x90); float? speed = float.IsFinite(mph) && mph >= 0 && mph <= 400 ? mph : null; @@ -106,6 +117,49 @@ private static WorldPresence VehiclePresence(UiMode mode, string? car, VehicleSt status = "ok"; return value; } + + private static bool TryFindFallbackCar(ReadOnlySpan raw, out string? car, out int offset) + { + car = null; + offset = 0; + for (int at = 0x200; at <= 0x500; at++) + { + if (raw[at - 1] != 0) + continue; + string? candidate = ReadCar(raw.Slice(at, 64), out _); + if (candidate is null || !LooksLikeFallbackCarId(candidate)) + continue; + if (car is not null && car != candidate) + { + car = null; + return false; + } + if (car is null) + { + car = candidate; + offset = at; + } + } + return car is not null; + } + + private static bool LooksLikeFallbackCarId(string id) + { + int first = id.IndexOf('_'), last = id.LastIndexOf('_'); + if (first < 2 || first > 5 || last <= first + 1) + return false; + for (int i = 0; i < first; i++) + if (id[i] < 'A' || id[i] > 'Z') + return false; + int yearLength = id.Length - last - 1; + if (yearLength != 2 && yearLength != 4) + return false; + for (int i = last + 1; i < id.Length; i++) + if (id[i] < '0' || id[i] > '9') + return false; + return true; + } + private static string? FriendlyCarName(string? raw) { if (string.IsNullOrWhiteSpace(raw)) diff --git a/tests/AzimuthRPC.Core.Tests/Program.cs b/tests/AzimuthRPC.Core.Tests/Program.cs index 06dc892..ec98ab2 100644 --- a/tests/AzimuthRPC.Core.Tests/Program.cs +++ b/tests/AzimuthRPC.Core.Tests/Program.cs @@ -63,6 +63,24 @@ var s when s.StartsWith("worldmap_") => UiMode.WorldMap, Check(!reader.Capture(gameBase, true).Attached, "Changing root published a mixed snapshot"); }); } +Test("Moved car field recovers uniquely but ambiguity fails closed", () => +{ + using var memory = new FixtureMemory(); + foreach (var (key, value) in captures[0].Memory()) + memory.Blocks[key] = value; + byte[] audio = memory.Blocks[SyntheticFixture.Audio]; + Array.Clear(audio, 0x278, 64); + System.Text.Encoding.ASCII.GetBytes("TOY_SupraRZ_98\0").CopyTo(audio, 0x360); + var reader = new GameSnapshotReader(memory); + var recovered = reader.Capture(SyntheticFixture.GameBase, true); + Check(recovered.Attached && recovered.Car.RawId == "TOY_SupraRZ_98" && + recovered.CarProbeStatus == "fallback@0x360", "Failed to recover moved car"); + System.Text.Encoding.ASCII.GetBytes("LAM_Huracan_15\0").CopyTo(audio, 0x420); + var ambiguous = reader.Capture(SyntheticFixture.GameBase, true); + Check(ambiguous.Attached && ambiguous.Car.RawId is null, + "Multiple plausible car IDs must not be guessed"); +}); + Test("Unsupported and overflowing bases fail without reads", () => { using var memory = new FixtureMemory(); var reader = new GameSnapshotReader(memory); From 982d624ea790c747a5e31f05e1f5d231c1dd0f3e Mon Sep 17 00:00:00 2001 From: Refil <53364591+Refilewski@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:05:01 +0100 Subject: [PATCH 03/14] Package official FH2 Mod Platform loader with native AzimuthRPC --- native/FH2ML.AzimuthRPC/build.ps1 | 70 +++++++++++++++++-------------- 1 file changed, 38 insertions(+), 32 deletions(-) diff --git a/native/FH2ML.AzimuthRPC/build.ps1 b/native/FH2ML.AzimuthRPC/build.ps1 index af7c7d8..1069688 100644 --- a/native/FH2ML.AzimuthRPC/build.ps1 +++ b/native/FH2ML.AzimuthRPC/build.ps1 @@ -2,47 +2,53 @@ param( [string]$Generator = '', [string]$Output = '' ) - $ErrorActionPreference = 'Stop' - $projectRoot = $PSScriptRoot -$repoRoot = [System.IO.Path]::GetFullPath((Join-Path $projectRoot '..\..')) +$repoRoot = [IO.Path]::GetFullPath((Join-Path $projectRoot '..\..')) $buildDir = Join-Path $projectRoot 'build' +[xml]$props = Get-Content (Join-Path $repoRoot 'Directory.Build.props') +$version = [string]$props.Project.PropertyGroup.Version +if ([string]::IsNullOrWhiteSpace($version)) { throw 'Missing AzimuthRPC version' } -$manifestPath = Join-Path $projectRoot 'mod.json' -$manifest = Get-Content $manifestPath -Raw | ConvertFrom-Json -$modVersion = [string]$manifest.version -if ([string]::IsNullOrWhiteSpace($modVersion)) { throw 'Native mod version not found in mod.json' } - -if ([string]::IsNullOrWhiteSpace($Output)) { - $packageDir = Join-Path $repoRoot "artifacts\FH2ML-AzimuthRPC-$modVersion" -} elseif ([System.IO.Path]::IsPathRooted($Output)) { - $packageDir = $Output -} else { - $packageDir = Join-Path $repoRoot $Output -} +$packageDir = if ([string]::IsNullOrWhiteSpace($Output)) { + Join-Path $repoRoot "artifacts\FH2ModPlatform-AzimuthRPC-$version" +} elseif ([IO.Path]::IsPathRooted($Output)) { $Output } else { Join-Path $repoRoot $Output } $configureArgs = @('-S', $projectRoot, '-B', $buildDir) -if (-not [string]::IsNullOrWhiteSpace($Generator)) { - $configureArgs += @('-G', $Generator, '-A', 'x64') -} - +if ($Generator) { $configureArgs += @('-G', $Generator, '-A', 'x64') } cmake @configureArgs -if ($LASTEXITCODE -ne 0) { throw 'CMake configure failed' } - +if ($LASTEXITCODE -ne 0) { throw 'CMake configuration failed' } cmake --build $buildDir --config Release -if ($LASTEXITCODE -ne 0) { throw 'Native mod build failed' } +if ($LASTEXITCODE -ne 0) { throw 'Native DLL build failed' } $packageDir = [IO.Path]::GetFullPath($packageDir) -$allowedPackageRoot = [IO.Path]::GetFullPath((Join-Path $repoRoot 'artifacts')) + [IO.Path]::DirectorySeparatorChar -if (-not $packageDir.StartsWith($allowedPackageRoot, [StringComparison]::OrdinalIgnoreCase)) { - throw 'Output must be a subdirectory of this repository artifacts directory' +$allowedRoot = [IO.Path]::GetFullPath((Join-Path $repoRoot 'artifacts')) + [IO.Path]::DirectorySeparatorChar +if (-not $packageDir.StartsWith($allowedRoot, [StringComparison]::OrdinalIgnoreCase)) { + throw 'Output must stay inside repository artifacts directory' } -if (Test-Path -LiteralPath $packageDir) { Remove-Item -LiteralPath $packageDir -Recurse -Force } -New-Item -ItemType Directory -Force -Path $packageDir | Out-Null -Copy-Item (Join-Path $buildDir 'Release\AzimuthRPC.dll') (Join-Path $packageDir 'AzimuthRPC.dll') -Force -Copy-Item $manifestPath (Join-Path $packageDir 'mod.json') -Force -Copy-Item (Join-Path $projectRoot 'README.md') (Join-Path $packageDir 'README.md') -Force -Copy-Item -LiteralPath (Join-Path $repoRoot 'LICENSE') -Destination (Join-Path $packageDir 'LICENSE') -Force -Write-Host "FH2ML AzimuthRPC $modVersion package: $packageDir" +# Package Trinculo54's official pinned platform binary, never our own proxy. +$platformVersion = '2.7.3' +$archive = Join-Path $buildDir "FH2-Mod-Platform-v$platformVersion.zip" +$expanded = Join-Path $buildDir "platform-v$platformVersion" +$uri = "https://github.com/Trinculo54/fh2-mod-platform/releases/download/v$platformVersion/FH2-Mod-Platform-v$platformVersion.zip" +Invoke-WebRequest -Uri $uri -OutFile $archive +if (Test-Path $expanded) { Remove-Item $expanded -Recurse -Force } +Expand-Archive -LiteralPath $archive -DestinationPath $expanded -Force +function Find-PlatformFile([string]$name) { + $found = @(Get-ChildItem -Path $expanded -Recurse -File | Where-Object { $_.Name -ieq $name }) + if ($found.Count -ne 1) { throw "Expected one $name in official release; found $($found.Count)" } + return $found[0].FullName +} +$platformDll = Find-PlatformFile 'd3dcompiler_47.dll' +$minHookLicense = Find-PlatformFile 'LICENSE-MinHook.txt' + +if (Test-Path $packageDir) { Remove-Item $packageDir -Recurse -Force } +New-Item -ItemType Directory -Force (Join-Path $packageDir 'fh2-mods') | Out-Null +Copy-Item -LiteralPath (Join-Path $buildDir 'Release\AzimuthRPC.dll') -Destination (Join-Path $packageDir 'fh2-mods\AzimuthRPC.dll') +Copy-Item -LiteralPath $platformDll -Destination (Join-Path $packageDir 'd3dcompiler_47.dll') +Copy-Item -LiteralPath $minHookLicense -Destination (Join-Path $packageDir 'LICENSE-MinHook.txt') +Copy-Item -LiteralPath (Join-Path $projectRoot 'platform-sdk\LICENSE') -Destination (Join-Path $packageDir 'LICENSE-FH2ModPlatform.txt') +Copy-Item -LiteralPath (Join-Path $repoRoot 'LICENSE') -Destination (Join-Path $packageDir 'LICENSE') +Copy-Item -LiteralPath (Join-Path $projectRoot 'README.md') -Destination (Join-Path $packageDir 'README.md') +Write-Host "FH2 Mod Platform AzimuthRPC $version package: $packageDir" From 953c5fed6452f1f60ec2738691ed8341a3399711 Mon Sep 17 00:00:00 2001 From: Refil <53364591+Refilewski@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:07:16 +0100 Subject: [PATCH 04/14] Bump AzimuthRPC version for native platform migration --- Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Build.props b/Directory.Build.props index 33252b8..5f681d6 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1 +1 @@ -0.9.90.9.9.00.9.9.0enableenabletruex64false \ No newline at end of file +0.9.100.9.10.00.9.10.0enableenabletruex64false \ No newline at end of file From 3da57d3629555bc6767ec7d2658a833df5986086 Mon Sep 17 00:00:00 2001 From: Refil <53364591+Refilewski@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:07:19 +0100 Subject: [PATCH 05/14] Align legacy internal version metadata --- native/FH2ML.AzimuthRPC/mod.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/FH2ML.AzimuthRPC/mod.json b/native/FH2ML.AzimuthRPC/mod.json index f48dd6e..93680cb 100644 --- a/native/FH2ML.AzimuthRPC/mod.json +++ b/native/FH2ML.AzimuthRPC/mod.json @@ -1,7 +1,7 @@ { "id": "azimuth-rpc", "name": "AzimuthRPC", - "version": "0.9.9", + "version": "0.9.10", "author": "Refilewski", "entry": "AzimuthRPC.dll", "enabled": true, From a85dc45942d73a466dfac6e8e4d70c31cfd3b12c Mon Sep 17 00:00:00 2001 From: Refil <53364591+Refilewski@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:07:22 +0100 Subject: [PATCH 06/14] Update native API contract test for FH2 Mod Platform --- tests/native-fh2ml-api-contract.ps1 | 65 +++++++---------------------- 1 file changed, 15 insertions(+), 50 deletions(-) diff --git a/tests/native-fh2ml-api-contract.ps1 b/tests/native-fh2ml-api-contract.ps1 index 3f02d24..699560b 100644 --- a/tests/native-fh2ml-api-contract.ps1 +++ b/tests/native-fh2ml-api-contract.ps1 @@ -1,54 +1,19 @@ $ErrorActionPreference = 'Stop' - $root = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) -$sourcePath = Join-Path $root 'native\FH2ML.AzimuthRPC\AzimuthRpcMod.cpp' -$source = Get-Content $sourcePath -Raw - -$required = @( - '#include "FH2ML.h"', - 'FH2ML_Initialize(const FH2ML_HostAPI* api)', - 'api->RegisterMod("azimuth-rpc", kVersion)', - 'g_hostApi->GetGameModule()', - 'g_hostApi->Log("azimuth-rpc", message.c_str())' -) - -foreach ($needle in $required) { - if (-not $source.Contains($needle)) { - throw "Missing FH2ML host API contract marker: $needle" - } +$source = Get-Content (Join-Path $root 'native\FH2ML.AzimuthRPC\AzimuthRpcMod.cpp') -Raw +$header = Get-Content (Join-Path $root 'native\FH2ML.AzimuthRPC\platform-sdk\fh2mod.h') -Raw +foreach ($needle in @('#include "fh2mod.h"', 'fh2mod_init(const FH2ModApi* api)', + 'api->register_mod(&info)', 'g_platformApi->game_base()', 'g_platformApi->log(g_registeredMod, message.c_str())', + 'FindFallbackCar(audio, car, recoveredAt)')) { + if (-not $source.Contains($needle)) { throw "Missing platform contract: $needle" } } - -# Initialization diagnostics must be written even when FH2ML is incompatible. -$startIndex = $source.IndexOf('FH2ML_Initialize(const FH2ML_HostAPI* api)') -$initTraceIndex = $source.IndexOf('Trace(std::string("AzimuthRPC ") + kVersion + " FH2ML_Initialize entered")', $startIndex) -$firstGuardIndex = $source.IndexOf('if (api == nullptr)', $startIndex) -if ($startIndex -lt 0 -or $initTraceIndex -lt 0 -or $firstGuardIndex -lt 0 -or - $initTraceIndex -gt $firstGuardIndex) { - throw 'FH2ML initialization must log entry before checking the host API' +if ($source.Contains('FH2ML_Initialize') -or $source.Contains('g_hostApi')) { throw 'Legacy host ABI remains' } +if (-not $header.Contains('#define FH2MOD_API_VERSION 8')) { throw 'Wrong platform SDK header' } +$start = $source.IndexOf('fh2mod_init(const FH2ModApi* api)') +$trace = $source.IndexOf('fh2mod_init entered', $start) +$guard = $source.IndexOf('if (api == nullptr)', $start) +if ($start -lt 0 -or $trace -lt 0 -or $guard -lt 0 -or $trace -gt $guard) { + throw 'The initializer must log entry before validating host API' } -foreach ($diagnostic in @( - 'host API pointer is null', - 'host API table too small', - 'API version mismatch', - 'required Log, RegisterMod or GetGameModule callback missing', - 'GetGameModule returned no supported FH2' -)) { - if (-not $source.Contains($diagnostic)) { - throw "Missing native startup diagnostics: $diagnostic" - } -} - -if ($source.Contains('VirtualQuery(')) { - throw 'Native FH2ML mod must use GetGameModule instead of VirtualQuery process scanning' -} -if ($source.Contains('(void)api;')) { - throw 'Native FH2ML initializer must not ignore the host API' -} - -$header = Get-Content (Join-Path $root 'native\FH2ML.AzimuthRPC\fh2ml-sdk\FH2ML.h') -Raw -if (-not $header.Contains('#define FH2ML_API_VERSION 1u') -or - -not $header.Contains('uintptr_t (*GetGameModule)(void);')) { - throw 'Vendored FH2ML SDK header does not expose the expected v1 contract' -} - -Write-Host 'FH2ML native host API contract verified.' \ No newline at end of file +if ($source.Contains('VirtualQuery(')) { throw 'Use the platform game base, not process scanning' } +Write-Host 'FH2 Mod Platform API integration verified.' From 52c035b9ab88cc9d064265bc812eeaf3e500c6d0 Mon Sep 17 00:00:00 2001 From: Refil <53364591+Refilewski@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:07:44 +0100 Subject: [PATCH 07/14] Document native migration in v0.9.10 release notes --- RELEASE_NOTES.md | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index d89e250..6634cd1 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,17 +1,14 @@ -# AzimuthRPC v0.9.9 +# AzimuthRPC v0.9.10 -Discord Rich Presence polish and car-detection diagnostics. +Native DLL migration to FH2 Mod Platform 2.7.3 and guarded car-ID compatibility recovery. -- "Loading Race" now appears **without a second line**: removes the generic "Forza Horizon 2 via Azimuth" state and prevents a stale car or speed from being shown while loading. This applies to both standalone EXE and native FH2ML DLL. -- The standalone log now records changes to a compact, privacy-conscious snapshot diagnostic: game UI mode, inferred activity, hook/telemetry status, event context and car ID parse result. No raw game-memory bytes are dumped. -- Car ID validation now reports a reason such as `empty`, `too-short`, `unterminated`, `invalid-character`, `missing-underscore`, or `ok` so users with missing vehicle names can provide actionable logs. -- Adds automated regression coverage for race-loading second-line suppression and snapshot diagnostics. -- Retains v0.9.8 standalone startup log fallback and the log folder shortcut, plus the v0.9.7 native startup diagnostics. +- Replaces the old FH2ML ABI with `fh2mod_init`, platform registration, logging and game-base discovery. +- The DLL no longer rejects startup when the game image is not yet mapped. +- The standalone EXE and native DLL prefer the known `AudioEngine+0x278` car-ID field, and try a bounded, unambiguous candidate within the same object when it is unavailable. +- Existing Discord IPC, presence, speed, location and game-state handling are unchanged. +- Platform release package ships the official v2.7.3 loader and required license notices. +- Synthetic regression covers both relocated and ambiguous car IDs. ## Compatibility -Still targets FH2 Xbox One 1.0.0.64 through Azimuth. This release does **not** change memory offsets or claim confirmed compatibility with every Azimuth version or mod combination. - -## Collecting useful reports - -Use `%LOCALAPPDATA%\AzimuthRPC\logs\AzimuthRPC.log` (or the standalone fallback `%TEMP%\AzimuthRPC\AzimuthRPC.log`). Include the **Snapshot diagnostic:** lines with your Azimuth version, other mods such as Extra Options, and whether you used the EXE or FH2ML DLL. Please review/redact any sensitive data before sharing. +Live gameplay testing on Azimuth 1.0.2 is **still required**. The fallback is a conservative compatibility heuristic, not a confirmed new offset. From a073eafb3c152e092642c4138bdcabe03f54453c Mon Sep 17 00:00:00 2001 From: Refil <53364591+Refilewski@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:07:47 +0100 Subject: [PATCH 08/14] Update Windows CI and release packaging paths for FH2 Mod Platform --- .github/workflows/build-pr.yml | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/.github/workflows/build-pr.yml b/.github/workflows/build-pr.yml index f1841ae..e1d6a5e 100644 --- a/.github/workflows/build-pr.yml +++ b/.github/workflows/build-pr.yml @@ -82,7 +82,7 @@ jobs: "VERSION=$version" >> $env:GITHUB_ENV "ARTIFACT_DIR=artifacts/AzimuthRPC-$version-win-x64" >> $env:GITHUB_ENV "MOD_VERSION=$modVersion" >> $env:GITHUB_ENV - "MOD_ARTIFACT_DIR=artifacts/FH2ML-AzimuthRPC-$modVersion" >> $env:GITHUB_ENV + "MOD_ARTIFACT_DIR=artifacts/FH2ModPlatform-AzimuthRPC-$modVersion" >> $env:GITHUB_ENV "version=$version" >> $env:GITHUB_OUTPUT "mod_version=$modVersion" >> $env:GITHUB_OUTPUT @@ -90,7 +90,7 @@ jobs: shell: pwsh run: ./publish.ps1 - - name: Build FH2ML DLL + - name: Build FH2 Mod Platform DLL shell: pwsh run: ./native/FH2ML.AzimuthRPC/build.ps1 @@ -98,11 +98,11 @@ jobs: shell: pwsh run: | $exe = Join-Path $env:ARTIFACT_DIR 'AzimuthRPC.exe' - $dll = Join-Path $env:MOD_ARTIFACT_DIR 'AzimuthRPC.dll' - $manifest = Join-Path $env:MOD_ARTIFACT_DIR 'mod.json' + $dll = Join-Path $env:MOD_ARTIFACT_DIR 'fh2-mods/AzimuthRPC.dll' + $platformDll = Join-Path $env:MOD_ARTIFACT_DIR 'd3dcompiler_47.dll' if (-not (Test-Path $exe)) { throw "Missing $exe" } if (-not (Test-Path $dll)) { throw "Missing $dll" } - if (-not (Test-Path $manifest)) { throw "Missing $manifest" } + if (-not (Test-Path $platformDll)) { throw "Missing $platformDll" } foreach ($folder in @($env:ARTIFACT_DIR, $env:MOD_ARTIFACT_DIR)) { $license = Join-Path $folder 'LICENSE' if (-not (Test-Path $license)) { throw "Missing $license" } @@ -118,10 +118,10 @@ jobs: if-no-files-found: error retention-days: 30 - - name: Upload FH2ML DLL artifact + - name: Upload FH2 Mod Platform DLL artifact uses: actions/upload-artifact@v4 with: - name: FH2ML-AzimuthRPC-${{ env.MOD_VERSION }} + name: FH2ModPlatform-AzimuthRPC-${{ env.MOD_VERSION }} path: ${{ env.MOD_ARTIFACT_DIR }} if-no-files-found: error retention-days: 30 @@ -182,14 +182,14 @@ jobs: if: steps.release_check.outputs.exists != 'true' uses: actions/download-artifact@v4 with: - name: FH2ML-AzimuthRPC-${{ needs.build.outputs.mod_version }} + name: FH2ModPlatform-AzimuthRPC-${{ needs.build.outputs.mod_version }} path: release/fh2ml - name: Package FH2ML ZIP if: steps.release_check.outputs.exists != 'true' shell: pwsh run: | - $zip = "release/FH2ML-AzimuthRPC-${{ needs.build.outputs.mod_version }}.zip" + $zip = "release/FH2ModPlatform-AzimuthRPC-${{ needs.build.outputs.mod_version }}.zip" if (Test-Path $zip) { Remove-Item $zip -Force } Compress-Archive -Path 'release/fh2ml/*' -DestinationPath $zip -CompressionLevel Optimal if (-not (Test-Path $zip)) { throw "Missing $zip" } @@ -204,8 +204,8 @@ jobs: run: | $tag = "v$env:VERSION" $exe = 'release/standalone/AzimuthRPC.exe' - $dll = 'release/fh2ml/AzimuthRPC.dll' - $zip = "release/FH2ML-AzimuthRPC-$env:MOD_VERSION.zip" + $dll = 'release/fh2ml/fh2-mods/AzimuthRPC.dll' + $zip = "release/FH2ModPlatform-AzimuthRPC-$env:MOD_VERSION.zip" $license = 'release/standalone/LICENSE' gh release create $tag $exe $dll $zip $license ` From 1f7213b673ae9ebd33bc5635dc536faded83640c Mon Sep 17 00:00:00 2001 From: Refil <53364591+Refilewski@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:09:41 +0100 Subject: [PATCH 09/14] Document FH2 Mod Platform installation and limitations --- README.md | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index d7f937f..dae6e87 100644 --- a/README.md +++ b/README.md @@ -41,49 +41,50 @@ Download the newest build from [GitHub Releases](https://github.com/Refilewski/A 4. Run `AzimuthRPC.exe`. 5. AzimuthRPC stays in the system tray and connects automatically when the supported FH2 build is detected. -### FH2ML mod +### FH2 Mod Platform mod -Download `FH2ML-AzimuthRPC-.zip` from the latest release and extract it as one FH2ML mod: +Download `FH2ModPlatform-AzimuthRPC-.zip` from the latest release and extract its contents next to `azimuth.exe`: ```text Azimuth/ - mods/ - azimuth-rpc/ - AzimuthRPC.dll - mod.json - README.md + azimuth.exe + d3dcompiler_47.dll + fh2-mods/ + AzimuthRPC.dll ``` -The native mod runs inside Azimuth/FH2ML and talks directly to Discord IPC. Do not run the standalone EXE and FH2ML DLL at the same time, or both may try to update the same Rich Presence. +The native DLL uses Trinculo54's **FH2 Mod Platform 2.7.3+**, not the earlier FH2ML manifest ABI. The zip ships the official platform loader. If other mods already installed a newer `d3dcompiler_47.dll`, keep the newer version. + +The plugin runs in-process, using the platform's game-base service and local Discord IPC. **Do not run the standalone EXE and native DLL together**, because both may update the same Rich Presence. ## Compatibility AzimuthRPC currently targets **Forza Horizon 2 Xbox One 1.0.0.64** on Windows x64 through Azimuth. Unknown game builds are rejected instead of using offsets against an unsupported executable. -Compatibility can vary with Azimuth and FH2ML versions or other mods. If something breaks, include your exact setup in the issue report. +Compatibility can vary with Azimuth and FH2 Mod Platform versions or other mods. If something breaks, include your exact setup in the issue report. **Linux / Wine support is not available yet.** A Linux Discord IPC path/bridge is being explored. ## Diagnostics & privacy -Both the standalone EXE and the FH2ML DLL write `%LOCALAPPDATA%\\AzimuthRPC\\logs\\AzimuthRPC.log` (paste that path into Windows Explorer). The native DLL now logs as soon as `FH2ML_Initialize` is called, including rejected host API versions or unsupported game-image checks. If no log is created, first verify the executable actually started or the loader called the DLL initializer; an absent log alone does **not** prove that car offsets changed. Logs can contain runtime telemetry, memory probe values, loaded module names and Discord IPC status, so **review the log before uploading it publicly**. +Both the standalone EXE and the FH2ML DLL write `%LOCALAPPDATA%\\AzimuthRPC\\logs\\AzimuthRPC.log` (paste that path into Windows Explorer). The native DLL now logs as soon as `fh2mod_init` is called, including rejected host API versions or unsupported game-image checks. If no log is created, first verify the executable actually started or the loader called the DLL initializer; an absent log alone does **not** prove that car offsets changed. Logs can contain runtime telemetry, memory probe values, loaded module names and Discord IPC status, so **review the log before uploading it publicly**. The **standalone EXE automatically removes `AzimuthRPC.log` and its rotated `.1` log after a normal exit** (tray `Exit`). If it crashes or is force-terminated, logs are kept for troubleshooting. To preserve logs while testing, launch the standalone with `--keep-logs`; copy the log before exiting if you need to share it. Cleanup is best-effort if another process keeps the file open. -The FH2ML native DLL still retains logs: it has no safe, guaranteed shutdown callback, and attempting deletion inside `DllMain` during process teardown could cause instability. Don't run the standalone and native DLL at the same time. +The FH2 Mod Platform native DLL still retains logs: it has no safe, guaranteed shutdown callback, and attempting deletion inside `DllMain` during process teardown could cause instability. Don't run the standalone and native DLL at the same time. ### Share diagnostics on Discord (standalone) Right-click the tray icon and choose **Send logs to Discord...**. A preview shows the exact content and nothing is uploaded until the user clicks Send. The EXE includes only recent diagnostic lines, with common Windows user profile names, credentials, and webhook URLs redacted. Please inspect the preview yourself before sharing. -The app contacts an HTTPS, rate-limited Supabase Edge Function owned by the FH2Mods project. It forwards a text attachment to the Discord support webhook, which is stored in Supabase Vault, **not embedded in the EXE or in GitHub**. This action is optional and does not run at startup or shutdown. The native FH2ML DLL has no tray menu; its logs can still be shared manually. +The app contacts an HTTPS, rate-limited Supabase Edge Function owned by the FH2Mods project. It forwards a text attachment to the Discord support webhook, which is stored in Supabase Vault, **not embedded in the EXE or in GitHub**. This action is optional and does not run at startup or shutdown. The native FH2 Mod Platform DLL has no tray menu; its logs can still be shared manually. AzimuthRPC does not ask for your Discord password or token. No game files, saves or raw memory captures are included in this repository. ## Build from source -The managed projects require the **.NET 8 SDK** on Windows x64. Building the native FH2ML DLL additionally requires **Visual Studio Build Tools** and **CMake**. +The managed projects require the **.NET 8 SDK** on Windows x64. Building the native FH2 Mod Platform DLL additionally requires **Visual Studio Build Tools** and **CMake**. Standalone build: @@ -91,7 +92,7 @@ Standalone build: ./publish.ps1 ``` -Native FH2ML build: +Native FH2 Mod Platform build: ```powershell ./native/FH2ML.AzimuthRPC/build.ps1 @@ -125,3 +126,5 @@ AzimuthRPC is **source-available**, not OSI open source. The [AzimuthRPC Use-Onl ## Disclaimer AzimuthRPC is an independent fan project by **Refilewski**. It is not affiliated with Microsoft, Xbox, Playground Games, Turn 10, Discord or Azimuth. No game, DLC, game files or license keys are included. + +Compatibility note: both runtimes now attempt a bounded, ambiguity-checked fallback if the known car ID field cannot be parsed. This is a hypothesis for Azimuth 1.0.2, **not** an in-game verified fix; see `native/FH2ML.AzimuthRPC/README.md` for diagnostics. From 2dbe93f2e0cc89ddf4b7f7951dd54b487242a314 Mon Sep 17 00:00:00 2001 From: Refil <53364591+Refilewski@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:09:45 +0100 Subject: [PATCH 10/14] Document platform-native build, installation, and car diagnostics --- native/FH2ML.AzimuthRPC/README.md | 103 +++++------------------------- 1 file changed, 17 insertions(+), 86 deletions(-) diff --git a/native/FH2ML.AzimuthRPC/README.md b/native/FH2ML.AzimuthRPC/README.md index 09ac333..b831fee 100644 --- a/native/FH2ML.AzimuthRPC/README.md +++ b/native/FH2ML.AzimuthRPC/README.md @@ -1,104 +1,35 @@ -# AzimuthRPC as an FH2ML native mod +# AzimuthRPC — FH2 Mod Platform -This directory builds the native x64 `AzimuthRPC.dll` intended to be loaded by FH2ML as a manifest mod. +Native Windows x64 Discord Rich Presence plugin for Trinculo54's FH2 Mod Platform 2.7.3+. It exports `fh2mod_init`, registers itself with the platform and uses platform-provided logging and the mapped FH2 base address. It is independent of the .NET runtime and does not patch gameplay. -The implementation is deliberately native C++ and does **not** host the .NET runtime inside Azimuth. +## Build and install -## Current runtime - -The DLL: - -- exports `FH2ML_Initialize`; -- starts a worker thread after initialization instead of doing RPC work in `DllMain`; -- validates the mapped FH2 Xbox One 1.0.0.64 PE identity; -- reads live car, speed, XYZ and velocity from the known game structures; -- reproduces the current Hub / Garage / Loading / Pause / Photo Mode / World Map detection; -- resolves mainland macro locations from live coordinates using the current anchor/polygon resolver; -- connects directly to Discord's local `discord-ipc-*` named pipes; -- publishes car and rounded speed while the conservative in-world fallback is positive; -- writes a capped diagnostic log for public bug reports. - -No gameplay patch or hook is installed by this runtime. Event-vs-free-roam telemetry and native road/region discovery are intentionally still separate research work. - -## Diagnostics - -The native mod writes (paste this path into Windows Explorer): - -```text -%LOCALAPPDATA%\AzimuthRPC\logs\AzimuthRPC.log -``` - -The log starts as soon as `FH2ML_Initialize` is called, including early failures caused by an incompatible FH2ML API or unsupported FH2 game image. If there is no log, confirm the mod DLL was loaded and its initializer invoked. - -The log rotates after roughly 2 MiB, keeping the previous log as `AzimuthRPC.log.1`. - -At startup it records the AzimuthRPC version, loaded module names, the detected FH2 image base and Discord IPC connection state. When the car probe changes it also records: - -- parser result (`ok`, `empty`, `too-short`, `unterminated`, `missing-underscore`, or the invalid character position); -- the `AudioEngine` pointer and `+0x278` car-field offset; -- current UI mode, speed and XYZ when available; -- 64 bytes from the car field as printable ASCII and hex. - -If RPC works but the current car is missing, reproduce the issue and attach a reviewed `AzimuthRPC.log`. Inspect/redact personal information first: logs include module filenames, memory probe bytes and runtime telemetry. The most useful entry begins with `Car probe:`. - -Only module file names are logged, not full module paths. - -## FH2ML ABI note - -`FH2ML_Initialize` receives the FH2ML host API pointer. The exact shared `sdk/FH2ML.h` is not vendored in this repository yet, so the current version treats that pointer as opaque instead of inventing an ABI layout. Once the real header is shared between the projects, host logging/registration can be wired without changing the runtime design. - -## Build - -From the repository root on Windows with Visual Studio Build Tools and CMake: +Build on Windows x64 with Visual Studio Build Tools and CMake: ```powershell ./native/FH2ML.AzimuthRPC/build.ps1 ``` -Output: - -```text -artifacts/FH2ML-AzimuthRPC-0.9.1/ - AzimuthRPC.dll - mod.json - README.md - LICENSE -``` - -The build script reads the package version from `mod.json`, so future versions do not require a hardcoded output path change. - -## Install - -Copy the packaged folder as one manifest-owned mod, for example: +The script downloads the official FH2 Mod Platform 2.7.3 distribution for packaging. Extract the contents of `FH2ModPlatform-AzimuthRPC-` next to `azimuth.exe`: ```text Azimuth/ - mods/ - azimuth-rpc/ - AzimuthRPC.dll - mod.json - README.md + azimuth.exe + d3dcompiler_47.dll + fh2-mods/ + AzimuthRPC.dll ``` -`mod.json` is enabled by default and currently uses priority `500` with no dependency or ordering edges. - -## Rich Presence behavior +Keep a newer official `d3dcompiler_47.dll` if another mod already installed it. The included `LICENSE`, `LICENSE-FH2ModPlatform.txt` and `LICENSE-MinHook.txt` are important redistributable notices. `mod.json` is internal version metadata only; it is not shipped or consumed by FH2 Mod Platform. -AzimuthRPC omits Discord's second `state` line when it has no useful value to show. For example, `Horizon Hub` is shown on its own if the car cannot currently be resolved instead of adding a redundant `Forza Horizon 2 via AzimuthRPC` line. +## Operation and diagnostics -## Limitations +The platform loads the plugin before the game is mapped. The AzimuthRPC worker waits for a validated FH2 1.0.0.64 image, then polls car, speed, approximate mainland location and game activity and updates Discord IPC. -- FH2ML itself is still a development loader and its Azimuth compatibility matrix is not yet fully live-validated. -- This DLL uses conservative memory-only world-presence logic rather than the standalone debug host's external telemetry hooks. -- The current location names are macro regions inferred from player coordinates, not a native FH2 road/landmark source. -- Discord IPC is retried automatically if Discord is not running or restarts. -- No hot-unload support is attempted. -## FH2ML Host API integration +- Native log: `%LOCALAPPDATA%\\AzimuthRPC\\logs\\AzimuthRPC.log` +- Platform load/registration log: `fh2-mods\\platform.log` +- If the known `AudioEngine+0x278` car ID cannot be parsed, the plugin tests a bounded region of the same object for a **unique** plausible identifier. The log reports `fallback@0x...` when recovery succeeds. Two different plausible IDs cause the fallback to reject the sample rather than guess. -The native DLL is built against the vendored FH2ML SDK v1 header in `fh2ml-sdk/`. -During `FH2ML_Initialize` it validates the host table, registers `azimuth-rpc`, -mirrors diagnostics through the FH2ML logger, and obtains the mapped FH2 image -from `GetGameModule()`. It does not scan the process address space for the game. +The same guarded fallback exists in standalone EXE. **No live test for Azimuth 1.0.2 is available yet**: neither a new offset nor a guaranteed fix is claimed. Reproduce in a car and check the logged probe status. Review/redact logs before sharing, because they may include module names and telemetry. -The vendored FH2ML SDK header is licensed separately under MIT; see -`fh2ml-sdk/LICENSE`. +Do not run EXE and DLL simultaneously. Hot unload is not implemented. From 803b7c003c672a68de4f9ee36dea9a068a9fefd4 Mon Sep 17 00:00:00 2001 From: Refil <53364591+Refilewski@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:09:59 +0100 Subject: [PATCH 11/14] Describe FH2 Mod Platform runtime architecture and verification boundary --- docs/ARCHITECTURE.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c299763..0299fab 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -12,21 +12,21 @@ AzimuthRPC now has two production-facing runtime targets plus developer tooling. `AzimuthRPC.Debug` remains developer tooling. It owns the WPF UI, process discovery, external read handle, research scanners/dumps and the existing external telemetry hooks. -### Native FH2ML mod +### Native FH2 Mod Platform mod -`native/FH2ML.AzimuthRPC` is a separate native x64 C++ runtime. It does not host Core or the .NET runtime. It exports `FH2ML_Initialize`, validates the supported FH2 image, performs direct in-process reads and talks to Discord IPC itself. +`native/FH2ML.AzimuthRPC` is a separate native C++ x64 runtime which does not host .NET. It exports `fh2mod_init`, uses the vendored MIT-licensed FH2 Mod Platform header, registers with the host and gets the FH2 image base via `game_base()`. Initialization is not blocked by game load timing: the worker waits for Azimuth to map the supported PE image. The native runtime performs guarded in-process reads and writes Discord IPC. It does not install gameplay hooks. -The current FH2ML host API pointer is deliberately treated as opaque because the shared `sdk/FH2ML.h` contract is not vendored here yet. No gameplay patch or hook is installed by the native RPC MVP. +Both native and managed car readers prefer the historically observed `AudioEngine+0x278` field. If that fails, a uniquely plausible ID within a bounded portion of the same audio object can serve as a fallback. The fallback is **not** a confirmed Azimuth 1.0.2 offset and must be validated in-game. ### Managed InProcess experiments -`AzimuthRPC.InProcess` is still a managed guarded-read adapter experiment. `NativeBootstrapImplemented` remains false. It should not be confused with the working native FH2ML C++ plugin. +`AzimuthRPC.InProcess` is still a managed guarded-read adapter experiment. `NativeBootstrapImplemented` remains false. It should not be confused with the working native FH2 Mod Platform C++ plugin. ## Snapshot/read model The managed reader uses bounded, guarded reads and revalidates roots before publishing a snapshot. One vehicle sample supplies the current car, speed, XYZ/mirror and velocity data. Unsupported PE layouts fail closed. -The native FH2ML implementation follows the same conservative principle: validate the supported build, validate pointer/data ranges and publish only coherent data. +The native FH2 Mod Platform implementation follows the same conservative principle: validate the supported build, validate pointer/data ranges and publish only coherent data. Neither runtime claims an atomic game transaction; the game may continue changing while a sample is taken. @@ -42,7 +42,7 @@ Current runtime state detection covers: - World Map; - in-world fallback from coherent vehicle telemetry. -The standalone debug path also retains external event-context / normalized-rev hooks used for research and richer activity interpretation. Those hooks are not currently installed by the native FH2ML DLL. +The standalone debug path also retains external event-context / normalized-rev hooks used for research and richer activity interpretation. Those hooks are not currently installed by the native FH2 Mod Platform DLL. Mainland location presence currently comes from player coordinates plus known anchors/coarse polygons. It is a pragmatic resolver, not a discovered native road/region/landmark source. Native location discovery stays under `docs/research/` until live evidence is strong enough to replace that resolver. @@ -50,7 +50,7 @@ Mainland location presence currently comes from player coordinates plus known an The standalone worker owns mutable process/IPC resources and clears state on detach/restart. Debug hooks verify ownership before restoration and remain best-effort because safe cross-mod hot-unload is not proven. -The native DLL performs substantial work outside `DllMain`; `FH2ML_Initialize` starts the runtime worker. No hot-unload contract is claimed yet. +The native DLL performs substantial work outside `DllMain`; `fh2mod_init` starts the runtime worker. No hot-unload contract is claimed yet. ## Repository/test boundaries @@ -62,7 +62,7 @@ Research notes, failed hypotheses and native-location investigation live under ` The next useful native steps are: -1. vendor/share the real FH2ML SDK header and use the versioned host API without guessing ABI layouts; +1. verify car-ID recovery in live Azimuth 1.0.2 and replace the heuristic with a confirmed source when available; 2. add validated event/free-roam telemetry to the native runtime without introducing unsafe hook ownership; 3. replace coarse location polygons only when a real FH2 road/region/landmark source is identified and live-validated; 4. define an explicit unload/shutdown contract before attempting hot unload. From a744a6a04f969deae87b7b54dffcad75cc5e9e9d Mon Sep 17 00:00:00 2001 From: Refil <53364591+Refilewski@users.noreply.github.com> Date: Tue, 27 Oct 2026 23:38:14 +0100 Subject: [PATCH 12/14] Use FH2 Mod Platform HUD hook and native vehicle-name object for active car --- native/FH2ML.AzimuthRPC/AzimuthRpcMod.cpp | 108 ++++++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/native/FH2ML.AzimuthRPC/AzimuthRpcMod.cpp b/native/FH2ML.AzimuthRPC/AzimuthRpcMod.cpp index a6cd89f..e2f604c 100644 --- a/native/FH2ML.AzimuthRPC/AzimuthRpcMod.cpp +++ b/native/FH2ML.AzimuthRPC/AzimuthRpcMod.cpp @@ -40,6 +40,12 @@ constexpr std::uintptr_t kGameManagerVtableRva = 0x02C5F8C8ull; constexpr std::uintptr_t kSimulationManagerVtableRva = 0x02C5FD70ull; constexpr std::size_t kCarIdOffset = 0x278; +// Game layout discovered in community research: VirtualDashboard and +// Extra Options. The string decoder below is an independent implementation. +constexpr std::uintptr_t kHudInstructionRva = 0x783E67ull; +constexpr std::uintptr_t kHudVehicleField = 0xE8ull; +constexpr std::uintptr_t kVehicleVtableRva = 0x2C5CB80ull; +constexpr std::uintptr_t kNativeCarNameOffset = 0x350ull; constexpr std::size_t kCarIdBytes = 64; constexpr char kDiscordApplicationId[] = "1445162899315363924"; constexpr char kVersion[] = "0.9.10"; @@ -52,6 +58,8 @@ std::atomic g_started{false}; std::atomic g_stop{false}; const FH2ModApi* g_platformApi = nullptr; FH2Mod* g_registeredMod = nullptr; +std::atomic g_hudVehicle{0}; +std::atomic g_hudSampleTick{0}; struct Vec3 { @@ -536,6 +544,90 @@ bool FindFallbackCar(const std::uintptr_t audio, std::string& car, std::size_t& return true; } +bool ReadHudVehicleName(const std::uintptr_t imageBase, std::string& result) +{ + const std::uintptr_t vehicle = g_hudVehicle.load(std::memory_order_acquire); + const ULONGLONG seen = g_hudSampleTick.load(std::memory_order_acquire); + const ULONGLONG now = GetTickCount64(); + if (!IsPointer(vehicle) || seen == 0 || now < seen || now - seen > 8000) + return false; + + std::uintptr_t type = 0; + if (!ReadValue(vehicle, type) || type != imageBase + kVehicleVtableRva) + return false; + std::array object{}; + if (!ReadBytes(vehicle + kNativeCarNameOffset, object.data(), object.size())) + return false; + + std::uint64_t count = 0, capacity = 0; + std::memcpy(&count, object.data() + 16, 8); + std::memcpy(&capacity, object.data() + 24, 8); + if (count < 5 || count >= 64 || capacity < count || capacity > 4096) + return false; + std::array bytes{}; + if (capacity < 16) + { + if (count > 15) return false; + std::memcpy(bytes.data(), object.data(), static_cast(count)); + } + else + { + std::uintptr_t ptr = 0; + std::memcpy(&ptr, object.data(), 8); + if (!IsPointer(ptr) || + !ReadBytes(ptr, bytes.data(), static_cast(count) + 1) || + bytes[static_cast(count)] != 0) + return false; + } + std::string id, why; + if (!ReadCarId(bytes.data(), id, why) || id.size() != count) + return false; + result = std::move(id); + return true; +} + +// Very short hook: only capture the HUD vehicle pointer. Read the name later, +// on our own thread, after revalidating the vehicle type and string layout. +void CaptureHudVehicle(FH2Context* ctx, void*) +{ + if (!ctx || !IsPointer(static_cast(ctx->rdi))) + return; + std::uintptr_t car = 0; + if (!ReadValue(static_cast(ctx->rdi) + kHudVehicleField, car) || + !IsPointer(car)) + return; + g_hudVehicle.store(car, std::memory_order_release); + g_hudSampleTick.store(GetTickCount64(), std::memory_order_release); +} + +void InstallHudVehicleHook(const std::uintptr_t imageBase) +{ + const FH2ModApi* api = g_platformApi; + if (!api || api->api_version < 7 || + api->size < offsetof(FH2ModApi, hook_instruction) + sizeof(api->hook_instruction) || + !api->wait_for_code || !api->hook_instruction || !api->enable_hooks || + !g_registeredMod) + { + Trace("HUD car hook unsupported; original AudioEngine source retained"); + return; + } + // Platform coordinates installation with other mods and Extra Options. + if (reinterpret_cast(api->wait_for_code(30000)) != imageBase) + { + Trace("HUD car hook unavailable: game code not ready"); + return; + } + FH2Hook* hook = api->hook_instruction( + g_registeredMod, "AzimuthRPC: active car from HUD", + reinterpret_cast(imageBase + kHudInstructionRva), CaptureHudVehicle, nullptr); + if (!hook || !api->enable_hooks(g_registeredMod, hook)) + { + Trace("HUD car hook declined by platform; original source retained"); + return; + } + Trace("HUD car hook installed (car name at vehicle+0x350)"); +} + bool BytesEqual(const std::uint8_t* data, const std::size_t offset, const char* text) { const std::size_t length = std::strlen(text) + 1; @@ -744,6 +836,15 @@ Snapshot CaptureSnapshot(const std::uintptr_t gameBase) carReason = status; } } + // The current HUD vehicle is authoritative when freshly observed. + // Keep AudioEngine (and its bounded recovery) as the compatibility path. + std::string observedCar; + if (ReadHudVehicleName(gameBase, observedCar)) + { + car = std::move(observedCar); + carParsed = true; + carReason = "hud-car+0x350"; + } if (carParsed) { snapshot.carRaw = car; @@ -1185,6 +1286,7 @@ DWORD WINAPI RpcThread(LPVOID) ULONGLONG lastPresenceUpdate = 0; std::uint64_t nonce = 0; std::string lastFingerprint; + bool hudHookAttempted = false; const std::int64_t sessionStart = static_cast(std::time(nullptr)); @@ -1212,6 +1314,12 @@ DWORD WINAPI RpcThread(LPVOID) Trace(message); } + if (!hudHookAttempted) + { + hudHookAttempted = true; + InstallHudVehicleHook(gameBase); + } + const ULONGLONG now = GetTickCount64(); if (discordPipe == INVALID_HANDLE_VALUE) From 33ef3f02bf6d30c1981ff9d8a70d023bb0c4e54d Mon Sep 17 00:00:00 2001 From: Refil <53364591+Refilewski@users.noreply.github.com> Date: Tue, 27 Oct 2026 23:39:22 +0100 Subject: [PATCH 13/14] Document native HUD-derived vehicle ID source --- RELEASE_NOTES.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 6634cd1..08d5cf8 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -4,10 +4,11 @@ Native DLL migration to FH2 Mod Platform 2.7.3 and guarded car-ID compatibility - Replaces the old FH2ML ABI with `fh2mod_init`, platform registration, logging and game-base discovery. - The DLL no longer rejects startup when the game image is not yet mapped. +- Native DLL: use FH2 Mod Platform's instruction hook in the game's HUD to capture a freshly displayed vehicle pointer, confirm the known player-car vtable and decode the native short/heap car-name string at `car+0x350`. The HUD path is preferred while fresh; no gameplay memory is patched directly. - The standalone EXE and native DLL prefer the known `AudioEngine+0x278` car-ID field, and try a bounded, unambiguous candidate within the same object when it is unavailable. - Existing Discord IPC, presence, speed, location and game-state handling are unchanged. - Platform release package ships the official v2.7.3 loader and required license notices. -- Synthetic regression covers both relocated and ambiguous car IDs. +- Synthetic regression covers both relocated and ambiguous car IDs. Live HUD hook decoding still needs in-game verification. ## Compatibility From 07213b9957339808002d08dde680082c91309536 Mon Sep 17 00:00:00 2001 From: Refil <53364591+Refilewski@users.noreply.github.com> Date: Tue, 27 Oct 2026 23:39:24 +0100 Subject: [PATCH 14/14] Document source-verified car name offsets and confidence --- docs/OFFSETS.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docs/OFFSETS.md b/docs/OFFSETS.md index 2b339d7..d9ffb66 100644 --- a/docs/OFFSETS.md +++ b/docs/OFFSETS.md @@ -15,6 +15,17 @@ Only **FH2 Xbox One1.0.0.64**. Image RVAs are added to dynamically resolved Game Mapped headers must match file identity. Preferred base is tried first, then eligible image/private allocation bases. No stable heap address is assumed. +## Current vehicle from HUD (new native FH2 Mod Platform path) + +**SOURCE-CONFIRMED / NEEDS LIVE AZIMUTH 1.0.2 VALIDATION** (based on public implementations, not our own live capture): +- HUD speedometer instruction `GameBase+0x783E67`: an FH2 Mod Platform instruction hook sees the HUD object in RDI. +- `HUD+0xE8`: pointer to the car currently displayed by the HUD. +- `Car+0x0` vtable: compare to `GameBase+0x2C5CB80` (player-car type from Extra Options). +- `Car+0x350`: native narrow car media-name string. 16-byte inline storage for short strings, heap pointer for longer strings; object length at +0x10 and capacity at +0x18. +- The platform-native DLL uses this read as primary when the hook is fresh (8-second window), validates type/string and falls back to the legacy AudioEngine path when unavailable. The EXE has no platform HUD hook; it retains its current AudioEngine mechanism. + +Sources: [VirtualDashboard](https://github.com/suderek22/FH2_VirtualDashboard/blob/main/VirtualDashboard.cpp#L32-L56) (HUD hook + car string); [Extra Options](https://github.com/RokkuDayo/ForzaHorizon2_ExtraOptions/blob/main/game_addresses.h) (player-car vtable). Both projects are GPL-3.0; only observed offsets/data layouts are documented here, not their source code. + ## Vehicle fields | Name | Offset; root | Type / meaning | Status; discovery; confidence | Guards / notes |