From f119f448ed45e6b09240ce46f725f3b092cbfbf9 Mon Sep 17 00:00:00 2001 From: Brues <5278969+brues-code@users.noreply.github.com> Date: Tue, 23 Jun 2026 19:28:05 -0500 Subject: [PATCH] Add C_CreatureInfo.RequestLoadCreatureByID + shared Cache::QueryLoad MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RequestLoadCreatureByID asynchronously fetches an uncached creature: issues SMSG_CREATURE_QUERY and fires CREATURE_DATA_LOAD_RESULT(id, success) when the response lands (or on timeout); fires success synchronously on a cache hit. Mirrors C_Item.RequestLoadItemData. New Cache::QueryLoad dispatcher generalizes Item::Data's pending/timeout/event machinery so multiple query caches share one response-handler hook. MinHook allows only one hook per target, and the creature/gameobject (and other non-item/quest) caches all route their SMSG_*_QUERY_RESPONSE through the generic parser FUN_00556E20 — so we hook it once and dispatch by cache instance to the right pending set + completion event. Item/quest use their own parsers, so no collision. The gameobject cache will register on this same dispatcher. Verified in-game: RequestLoadCreatureByID(10184) on an uncached Onyxia returned true, fired CREATURE_DATA_LOAD_RESULT, and populated the cache (type 2 Dragonkin, rank 3 world boss, displayID 8570). --- README.md | 2 +- docs/API.md | 42 ++++++++ src/Offsets.h | 11 +++ src/cache/QueryLoad.cpp | 209 ++++++++++++++++++++++++++++++++++++++++ src/cache/QueryLoad.h | 60 ++++++++++++ src/creature/Info.cpp | 46 ++++++++- 6 files changed, 364 insertions(+), 6 deletions(-) create mode 100644 src/cache/QueryLoad.cpp create mode 100644 src/cache/QueryLoad.h diff --git a/README.md b/README.md index 24b75a84..026dee00 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ Full per-function reference: **[docs/API.md](docs/API.md)**. | [Cursor](docs/API.md#cursor) | `GetCursorInfo` | | [Container](docs/API.md#container) | `C_Container.GetContainerItemCharges`, `C_Container.GetContainerItemDurability`, `C_Container.GetContainerItemID`, `C_Container.GetContainerItemRepairCost`, `C_Container.GetContainerNumFreeSlots`, `C_Container.GetItemCooldown`, `C_Container.IsContainerItemOpenable`, `C_Container.MoveItem`, `C_Container.PlayerHasHearthstone`, `C_Container.SwapItems`, `C_Container.UseHearthstone`, `GetItemCooldown` | | [Coroutine](docs/API.md#coroutine) | `coroutine.create`, `coroutine.resume`, `coroutine.yield`, `coroutine.status`, `coroutine.wrap` | -| [Creature](docs/API.md#creature) | `C_CreatureInfo.GetCreatureID`, `C_CreatureInfo.GetCreatureInfoByID` | +| [Creature](docs/API.md#creature) | `C_CreatureInfo.GetCreatureID`, `C_CreatureInfo.GetCreatureInfoByID`, `C_CreatureInfo.RequestLoadCreatureByID` | | EncodingUtil | `C_EncodingUtil.CompressString`, `C_EncodingUtil.DecompressString`, `C_EncodingUtil.EncodeBase64`, `C_EncodingUtil.DecodeBase64`, `C_EncodingUtil.EncodeHex`, `C_EncodingUtil.DecodeHex`, `C_EncodingUtil.SerializeJSON`, `C_EncodingUtil.DeserializeJSON`, `C_EncodingUtil.SerializeCBOR`, `C_EncodingUtil.DeserializeCBOR` | | [EquipmentSet](docs/API.md#equipmentset) | `C_EquipmentSet.CanUseEquipmentSets`, `C_EquipmentSet.ClearIgnoredSlotsForSave`, `C_EquipmentSet.CreateEquipmentSet`, `C_EquipmentSet.DeleteEquipmentSet`, `C_EquipmentSet.EquipmentSetContainsLockedItems`, `C_EquipmentSet.GetEquipmentSetID`, `C_EquipmentSet.GetEquipmentSetIDs`, `C_EquipmentSet.GetEquipmentSetInfo`, `C_EquipmentSet.GetIgnoredSlots`, `C_EquipmentSet.GetItemIDs`, `C_EquipmentSet.GetItemLocations`, `C_EquipmentSet.GetNumEquipmentSets`, `C_EquipmentSet.IgnoreSlotForSave`, `C_EquipmentSet.IsSlotIgnoredForSave`, `C_EquipmentSet.ModifyEquipmentSet`, `C_EquipmentSet.SaveEquipmentSet`, `C_EquipmentSet.UnignoreSlotForSave`, `C_EquipmentSet.UseEquipmentSet` | | [Events](docs/API.md#events) | `C_EventUtils.IsEventValid` | diff --git a/docs/API.md b/docs/API.md index ae7956c3..b6c216a4 100644 --- a/docs/API.md +++ b/docs/API.md @@ -61,6 +61,7 @@ build instructions. - [Creature](#creature) - [`C_CreatureInfo.GetCreatureID(guid)`](#c_creatureinfogetcreatureidguid) - [`C_CreatureInfo.GetCreatureInfoByID(creatureID)`](#c_creatureinfogetcreatureinfobyidcreatureid) + - [`C_CreatureInfo.RequestLoadCreatureByID(creatureID)`](#c_creatureinforequestloadcreaturebyidcreatureid) - [CVar](#cvar) - [`C_CVar.GetCVarBool(cvar)`](#c_cvargetcvarboolcvar) @@ -1531,6 +1532,47 @@ off the cached data block. Field offsets verified against the binary real `creaturecache.wdb` rows (Misthoof Stag→type 1, Nordrassil Nymph→type 7 rank 1, Greathorn Hunter→family 26). +For a creature that isn't cached yet, call +[`RequestLoadCreatureByID`](#c_creatureinforequestloadcreaturebyidcreatureid) +first and read it once `CREATURE_DATA_LOAD_RESULT` fires. + +### `C_CreatureInfo.RequestLoadCreatureByID(creatureID)` + +Asynchronously fetches a creature that isn't in the cache yet — issues +`SMSG_CREATURE_QUERY` and fires **`CREATURE_DATA_LOAD_RESULT(creatureID, +success)`** when the response lands, at which point +[`GetCreatureInfoByID`](#c_creatureinfogetcreatureinfobyidcreatureid) +returns its data. The same shape as +[`C_Item.RequestLoadItemData`](#c_itemrequestloaditemdatabyiditem--c_itemrequestloaditemdataitemlocation). + +```lua +local f = CreateFrame("Frame") +f:RegisterEvent("CREATURE_DATA_LOAD_RESULT") +f:SetScript("OnEvent", function() + -- 1.12 passes event args as globals: arg1 = creatureID, arg2 = success + if arg2 then + local info = C_CreatureInfo.GetCreatureInfoByID(arg1) + -- info.name, info.type, info.rank, … + end +end) + +C_CreatureInfo.RequestLoadCreatureByID(10184) -- Onyxia → fires the event, + -- then GetCreatureInfoByID works +``` + +Returns `true` if the request was accepted (`false` only on bad input +or a full pending set). If the creature is **already** cached, the +event fires synchronously with `success = true`. On a query that never +resolves it fires once with `success = false` after a timeout. + +Implementation: a shared `Cache::QueryLoad` dispatcher hooks the engine's +generic cache response parser (`FUN_00556E20`) **once** and routes by +cache instance — the same hook serves the gameobject cache too. The +creature/gameobject caches use this generic parser; the item and quest +caches have their own, so there's no hook collision. Verified in-game: `RequestLoadCreatureByID(10184)` on +an uncached Onyxia fired the event and populated the cache (type 2 +Dragonkin, rank 3 world boss). + ## CVar ### `C_CVar.GetCVarBool(cvar)` diff --git a/src/Offsets.h b/src/Offsets.h index 2e3bfad3..eab0daba 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -1995,6 +1995,17 @@ enum Offsets { // and quest caches have their own type-specific wrappers). Verified // via FUN_00604600 (`FUN_00556aa0(creatureID, &guid, cb, 0, 0)`). FUN_CACHE_GET_RECORD = 0x00556AA0, + // Generic cache response parser — `__thiscall(cache, packetReader, + // flag)`. Creature/gameobject (and the other generic-parser caches) + // route their `SMSG_*_QUERY_RESPONSE` through this: it fills the + // entry's data block (`FUN_007c8120`), sets the loaded flag, and + // walks the entry's pending-callback list. The item and quest caches + // use their own specialized parsers (`FUN_ITEMSTATS_CACHE_RESPONSE` + // etc.), so hooking this is conflict-free. `Cache::QueryLoad` hooks + // it once and dispatches by cache instance to fire the per-cache + // `*_DATA_LOAD_RESULT` event. The creature-specific wrapper that + // calls it (the registered SMSG handler) is `FUN_005550E0`. + FUN_CACHE_QUERY_RESPONSE = 0x00556E20, // Creature-query record field offsets, within the data block returned // by FUN_CACHE_GET_RECORD. Anchored by rank@+0x20 (read by the // classification helper FUN_00605620 as `[block+0x20]`) and the diff --git a/src/cache/QueryLoad.cpp b/src/cache/QueryLoad.cpp new file mode 100644 index 00000000..89d962aa --- /dev/null +++ b/src/cache/QueryLoad.cpp @@ -0,0 +1,209 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU Lesser General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License along with +// ClassicAPI. If not, see . + +#include "cache/QueryLoad.h" + +#include "Game.h" +#include "Offsets.h" +#include "event/Custom.h" +#include "tick/WorldTick.h" + +#include + +namespace Cache::QueryLoad { + +namespace { + +// Generic cache `_GetRecord` (FUN_CACHE_GET_RECORD). callback=nullptr → +// pure hash-table peek (returns the loaded data block or nullptr, no +// query). Non-null callback → also fires the network query on a miss and +// stores `(callback, userData)` on the entry's pending list. dedup=1 so +// repeat fetches for the same id before the response lands don't queue +// the callback twice. +using GetCacheRecord_t = const uint8_t *(__thiscall *)(void *cache, uint32_t id, + const uint64_t *guid, void *callback, + void *userData, char dedup); + +// Generic response parser we hook (FUN_CACHE_QUERY_RESPONSE). +using CacheResponse_t = void(__thiscall *)(void *cache, void *packetReader, int flag); + +// Engine callback shape (__stdcall, ret 8) — see Item::Data. We only +// pass it to make `_GetRecord` send the query (the trigger is +// `callback != NULL`); the actual completion is observed via the +// response hook + tick sweep, so the callback itself does nothing. +void __stdcall NoOpCallback(void * /*userData*/, int /*success*/) {} + +const uint8_t *CacheFetch(void *cache, uint32_t id, void *callback) { + auto fn = reinterpret_cast(Offsets::FUN_CACHE_GET_RECORD); + const uint64_t zeroGuid = 0; + void *userData = + callback ? reinterpret_cast(static_cast(id)) : nullptr; + return fn(cache, id, &zeroGuid, callback, userData, 1); +} + +struct Pending { + uint32_t id; + int ticksWaiting; +}; + +constexpr int kMaxCaches = 8; +constexpr int kMaxPending = 256; +constexpr int kMaxWaitTicks = 1200; // ~ a few minutes of WorldTicks → give up, fire failure + +struct Registered { + void *cache; + const char *eventName; + Pending pending[kMaxPending]; + int pendingCount; +}; + +Registered g_caches[kMaxCaches]; +int g_cacheCount = 0; + +Registered *Find(void *cache) { + for (int i = 0; i < g_cacheCount; ++i) { + if (g_caches[i].cache == cache) + return &g_caches[i]; + } + return nullptr; +} + +void Fire(const Registered *r, uint32_t id, bool success) { + Event::Custom::FireIdSuccess(Event::Custom::Lookup(r->eventName), + static_cast(id), success); +} + +int FindPending(const Registered *r, uint32_t id) { + for (int i = 0; i < r->pendingCount; ++i) { + if (r->pending[i].id == id) + return i; + } + return -1; +} + +void RemovePendingAt(Registered *r, int idx) { + --r->pendingCount; + if (idx != r->pendingCount) + r->pending[idx] = r->pending[r->pendingCount]; +} + +// Fire + remove any pending id whose entry is now loaded. +void Sweep(Registered *r) { + for (int i = 0; i < r->pendingCount;) { + if (CacheFetch(r->cache, r->pending[i].id, nullptr) != nullptr) { + const uint32_t id = r->pending[i].id; + RemovePendingAt(r, i); + Fire(r, id, true); + continue; + } + ++i; + } +} + +// Response-handler hook. The engine fills entries from +// `SMSG_*_QUERY_RESPONSE` and walks each entry's callback list inside the +// original; afterward we sweep the pending set for the cache that just +// got a response and fire the completion event for anything now-loaded. +// `__thiscall` mimicked as `__fastcall(ecx, edx_unused, …)` per the +// codebase convention. +CacheResponse_t g_origResponse = nullptr; + +void __fastcall Response_h(void *cache, void * /*edx*/, void *packetReader, int flag) { + using Trampoline_t = void(__fastcall *)(void *cache, void *edx, void *packetReader, int flag); + reinterpret_cast(g_origResponse)(cache, nullptr, packetReader, flag); + + // Only act on caches we track; other caches route through this same + // parser and are simply ignored. + Registered *r = Find(cache); + if (r != nullptr) + Sweep(r); +} + +const Game::HookAutoRegister _hookResponse{ + Offsets::FUN_CACHE_QUERY_RESPONSE, reinterpret_cast(&Response_h), + reinterpret_cast(&g_origResponse)}; + +// Timeout + safety net. The hook covers the happy path; this only fires +// failure for ids that never resolve (lost query / server silent) after +// `kMaxWaitTicks`, and re-checks loaded as a backstop in case a fill +// arrived through a path the hook didn't observe. +void OnWorldTick() { + for (int c = 0; c < g_cacheCount; ++c) { + Registered *r = &g_caches[c]; + for (int i = 0; i < r->pendingCount;) { + if (CacheFetch(r->cache, r->pending[i].id, nullptr) != nullptr) { + const uint32_t id = r->pending[i].id; + RemovePendingAt(r, i); + Fire(r, id, true); + continue; + } + if (r->pending[i].ticksWaiting >= kMaxWaitTicks) { + const uint32_t id = r->pending[i].id; + RemovePendingAt(r, i); + Fire(r, id, false); + continue; + } + ++r->pending[i].ticksWaiting; + ++i; + } + } +} + +const Tick::WorldTick::AutoSubscribe _tickSub{&OnWorldTick}; + +} // namespace + +void Register(void *cacheInstance, const char *eventName) { + if (cacheInstance == nullptr || eventName == nullptr) + return; + if (Find(cacheInstance) != nullptr) // idempotent (safe across /reload) + return; + if (g_cacheCount >= kMaxCaches) + return; + g_caches[g_cacheCount].cache = cacheInstance; + g_caches[g_cacheCount].eventName = eventName; + g_caches[g_cacheCount].pendingCount = 0; + ++g_cacheCount; +} + +bool IsCached(void *cacheInstance, uint32_t id) { + return CacheFetch(cacheInstance, id, nullptr) != nullptr; +} + +bool RequestLoad(void *cacheInstance, uint32_t id) { + Registered *r = Find(cacheInstance); + if (r == nullptr || id == 0) + return false; + + // Already cached — fire success synchronously (modern RequestLoad + // contract: the completion event fires even on a cache hit). + if (CacheFetch(cacheInstance, id, nullptr) != nullptr) { + Fire(r, id, true); + return true; + } + // Already in flight — one completion event per id. + if (FindPending(r, id) >= 0) + return true; + if (r->pendingCount >= kMaxPending) + return false; + + // Send the query (non-null callback is the trigger), then track until + // the response hook / tick fires the event. + CacheFetch(cacheInstance, id, reinterpret_cast(&NoOpCallback)); + r->pending[r->pendingCount].id = id; + r->pending[r->pendingCount].ticksWaiting = 0; + ++r->pendingCount; + return true; +} + +} // namespace Cache::QueryLoad diff --git a/src/cache/QueryLoad.h b/src/cache/QueryLoad.h new file mode 100644 index 00000000..fc3b754d --- /dev/null +++ b/src/cache/QueryLoad.h @@ -0,0 +1,60 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU Lesser General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License along with +// ClassicAPI. If not, see . + +#pragma once + +#include + +// Shared async-load dispatcher for the client query caches that use the +// generic response parser (`FUN_CACHE_QUERY_RESPONSE`) — creature, +// gameobject, and the other non-item/quest caches. Modeled on +// `Item::Data`'s pending/timeout/event machinery, generalized so several +// caches share one response-handler hook. +// +// Why shared: MinHook permits only one hook per target, and every one of +// these caches routes its `SMSG_*_QUERY_RESPONSE` through the same +// `FUN_CACHE_QUERY_RESPONSE`. So we hook it exactly once here and +// dispatch by cache instance to the right pending set + completion event. +// +// A module registers its cache once, then calls `RequestLoad`: +// +// static const char *kEvent = "CREATURE_DATA_LOAD_RESULT"; +// static const Event::Custom::AutoReserve _r{kEvent}; // reserve the event +// ... +// Cache::QueryLoad::Register(cacheInstance, kEvent); // at module init +// Cache::QueryLoad::RequestLoad(cacheInstance, id); // fire a load +// +// The completion event fires as `(id: number, success: bool)` — success +// when the cache fills, failure on timeout. + +namespace Cache::QueryLoad { + +// Register a query cache for async-load tracking. `cacheInstance` is the +// cache global (e.g. `Offsets::VAR_CREATURE_CACHE` cast to void*); +// `eventName` is a Custom event the caller has reserved via +// `Event::Custom::AutoReserve`, fired `(id, success)` on completion. Both +// must outlive the process (pass static values). Idempotent — calling +// again for the same cache is a no-op (safe across /reload). +void Register(void *cacheInstance, const char *eventName); + +// True if `id` is already in the cache (pure peek, no network query). +bool IsCached(void *cacheInstance, uint32_t id); + +// Issue an async load for `id`. If already cached, fires the completion +// event with success synchronously. Otherwise sends the query and tracks +// the id until the response lands (or it times out). Returns false only +// if the cache isn't registered or its pending set is full; true +// otherwise (already-cached, already-pending, or newly-tracked). +bool RequestLoad(void *cacheInstance, uint32_t id); + +} // namespace Cache::QueryLoad diff --git a/src/creature/Info.cpp b/src/creature/Info.cpp index 08285897..47863107 100644 --- a/src/creature/Info.cpp +++ b/src/creature/Info.cpp @@ -26,11 +26,12 @@ // displayID = 10957, -- model display ID // } // -// Synchronous *peek*: returns the data only if the creature is already -// cached (seen this session, or loaded from creaturecache.wdb at login); -// returns nil otherwise. To fetch an uncached creature, the companion -// `C_CreatureInfo.RequestLoadCreatureByID` issues the query and fires a -// `CREATURE_DATA_LOAD_RESULT` event when it lands (see — to be added). +// `GetCreatureInfoByID` is a synchronous *peek*: returns the data only +// if the creature is already cached (seen this session, or loaded from +// creaturecache.wdb at login); nil otherwise. `RequestLoadCreatureByID` +// fetches an uncached creature — it issues the query and fires +// `CREATURE_DATA_LOAD_RESULT(creatureID, success)` when the response +// lands, via the shared `Cache::QueryLoad` dispatcher. // // Field offsets verified against the binary (rank read by the engine's // classification helper as `[block+0x20]`) and real creaturecache.wdb @@ -38,6 +39,8 @@ #include "Game.h" #include "Offsets.h" +#include "cache/QueryLoad.h" +#include "event/Custom.h" #include @@ -45,6 +48,12 @@ namespace Creature::Info { namespace { +// Completion event for RequestLoadCreatureByID. Reserved at static-init +// so the engine allocates it in its event table; fired (creatureID, +// success) by the Cache::QueryLoad dispatcher. +constexpr const char *kCreatureDataLoadResult = "CREATURE_DATA_LOAD_RESULT"; +const Event::Custom::AutoReserve _reserveLoadResult{kCreatureDataLoadResult}; + // Generic cache `_GetRecord`. With callback=nullptr it only peeks the // hash table (no network query) and returns the data block (entry+0x18) // if the creature is loaded, else nullptr. @@ -90,9 +99,36 @@ int __fastcall Script_GetCreatureInfoByID(void *L) { return 1; } +// `C_CreatureInfo.RequestLoadCreatureByID(creatureID)` -> bool. Async +// fetch for an uncached creature: issues SMSG_CREATURE_QUERY and fires +// `CREATURE_DATA_LOAD_RESULT(creatureID, success)` when the response +// lands (or on timeout). Fires success synchronously if already cached. +// Returns true if the request was accepted (false for bad input or a +// full pending set) — mirrors C_Item.RequestLoadItemData(ByID). +int __fastcall Script_RequestLoadCreatureByID(void *L) { + if (!Game::Lua::IsNumber(L, 1)) { + Game::Lua::PushBool(L, false); + return 1; + } + const int creatureID = static_cast(Game::Lua::ToNumber(L, 1)); + if (creatureID <= 0) { + Game::Lua::PushBool(L, false); + return 1; + } + auto *cache = reinterpret_cast(Offsets::VAR_CREATURE_CACHE); + const bool accepted = + Cache::QueryLoad::RequestLoad(cache, static_cast(creatureID)); + Game::Lua::PushBool(L, accepted); + return 1; +} + void RegisterLuaFunctions() { Game::Lua::RegisterTableFunction("C_CreatureInfo", "GetCreatureInfoByID", &Script_GetCreatureInfoByID); + Game::Lua::RegisterTableFunction("C_CreatureInfo", "RequestLoadCreatureByID", + &Script_RequestLoadCreatureByID); + Cache::QueryLoad::Register(reinterpret_cast(Offsets::VAR_CREATURE_CACHE), + kCreatureDataLoadResult); } const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};