diff --git a/README.md b/README.md index 5b8623e5..bc2506ff 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ Quick index: | AddOns | `C_AddOns.DoesAddOnExist`, `C_AddOns.GetAddOnName`, `C_AddOns.GetAddOnNotes`, `C_AddOns.GetAddOnSecurity`, `C_AddOns.GetAddOnTitle`, `C_AddOns.IsAddOnLoadable` | | Combat | `InCombatLockdown` | | Hooks | `hooksecurefunc` | +| Input | `IsLeftShiftKeyDown`, `IsRightShiftKeyDown`, `IsLeftControlKeyDown`, `IsRightControlKeyDown`, `IsLeftAltKeyDown`, `IsRightAltKeyDown`, `IsModifierKeyDown` (+ `MODIFIER_STATE_CHANGED` event) | | Talent | `GetTalentIDByIndex`, `GetTalentSpellID` | | Time | `GetServerTime` | | Events | `C_EventUtils.IsEventValid` | diff --git a/TODO.md b/TODO.md index 33789034..cab11bf9 100644 --- a/TODO.md +++ b/TODO.md @@ -2049,3 +2049,104 @@ directly off the frame's Lua table. Simpler, but doesn't compose with `HookScript` polyfills automatically (each addon would clobber the previous). +## ~~66. Left/right modifier keys + `MODIFIER_STATE_CHANGED` event~~ — DONE + +Shipped in [src/input/Modifier.cpp](src/input/Modifier.cpp). Adds +the seven query functions (`IsLeftShiftKeyDown`, `IsRightShiftKeyDown`, +`IsLeftControlKeyDown`, `IsRightControlKeyDown`, `IsLeftAltKeyDown`, +`IsRightAltKeyDown`, `IsModifierKeyDown`) plus the 2.4.3+ +`MODIFIER_STATE_CHANGED(key, down)` event. All seven match the +modern WoW return shape (`1` for down, `nil` for not-down). + +### Why this needed a Win32 hook + +The engine has **no L/R distinction anywhere in its state**. 1.12's +own `IsShiftKeyDown` chain bottoms out at `GetKeyState(VK_SHIFT)` — +the merged virtual key `0x10` — at `0x00436024`, never the L/R-aware +`VK_LSHIFT` / `VK_RSHIFT` (`0xA0` / `0xA1`). Helper3 at `0x00436D80` +returns a struct with only 3 modifier slots (shift/ctrl/alt), confirmed +by inspection. No amount of digging in engine memory finds L/R state +because **it never existed there**. + +There IS a 6-bit field at `[*[0x00C0ED38] + 0x269C]` that looks +structurally identical to 2.4.3's L/R modifier bitmask at `[+0x130]` +— same shift-and-mask helper at `0x005936C0`, same 6-bit dispatch +limit. We chased it for a while. Empirically the field is something +else entirely (some kind of input-device-flags bitmask) — it stays at +`0x3BF` regardless of which modifier is held. The 2.4.3 → 1.12 +structural similarity is misleading; the field's meaning evolved. + +The OS-level keystate **does** have the L/R distinction (VK_LSHIFT / +VK_RSHIFT etc.), and 1.12 already uses Win32 `GetKeyState` for its own +modifier checks — so calling `GetAsyncKeyState(VK_LSHIFT)` ourselves +is the same primitive the engine already uses, just with the L/R-aware +VK codes. + +### Why a `WH_GETMESSAGE` hook over `SetWindowLongPtr` subclass + +We initially subclassed WoW's `WNDPROC` (via `EnumWindows` to find the +`GxWindowClassD3d`/`GxWindowClassOpenGl` HWND, then `SetWindowLongPtrA` +to install a wrapper). Worked for L/R queries and the event. Then the +user toggled vsync and the event went silent — WoW destroys and +recreates its main window on some renderer state changes, so the +subclass was left dangling on a destroyed HWND. + +Switched to `SetWindowsHookExA(WH_GETMESSAGE, ..., GetCurrentThreadId())`. +The hook is per-thread, not per-HWND, so it survives any number of +window recreations. Decodes `WM_KEY{,SYS}{DOWN,UP}` messages, +maintains a 6-bit cached bitmap that the queries read, and fires +`MODIFIER_STATE_CHANGED` on transitions. + +### L/R decoding from WM_KEY messages + +- `VK_SHIFT` (the merged virtual key the OS delivers for either key) + → `MapVirtualKeyA(scancode, MAPVK_VSC_TO_VK_EX)` returns + `VK_LSHIFT` or `VK_RSHIFT` based on the hardware scancode. +- `VK_CONTROL` / `VK_MENU` → the `KF_EXTENDED` flag (bit 24) of + `lParam` discriminates: extended = right, plain = left. +- `VK_L*` / `VK_R*` delivered directly (some keyboards, SendInput) → + accepted as-is. + +### `MODIFIER_STATE_CHANGED` and the custom-event saga + +Documented as part of the broader event-table investigation in +CLAUDE.md's "Events" section. Short version: we tried three approaches +to inject custom event names into the engine's event table. + +**Approach A — slot-claim (original Event::Custom)**: walk the live +table for NULL slots, write our `SMemAlloc`+memcpy'd name. Works. +Downside: first NULL slots were near the head of the table (slot 1 +got `MINIMAP_BLIP_TRACKING_CHANGED` from VanillaMinimapTracking, +which felt off). + +**Approach B — rebuild-hook + tail-injection**: hook +`RebuildEventTable` at `0x00703D90`, pad the input array to 1024 +entries, place our names at the tail (slots 1020+). Engine's own +SStrDup handles allocation, so we never write to engine memory. +Worked for a single DLL. **Crashed when SuperWoWhook, nampower, +transmogfix, and VanillaMinimapTracking all hooked the same +function**: their layered modifications to `(names, count)` produced +a count→buffer-size mismatch, and the engine's fill loop wrote off +the end of the allocated buffer on its last iteration. + +**Approach C — slot-claim + backward walk (final)**: same as A but +walk the table from `count-1` downward looking for NULL slots, so +high indices are claimed first. Each DLL works on the table +independently — no hook chaining, no argument modification, no +crashes. Custom events naturally group at the tail (verified: slots +695..699 with all five custom events when ClassicAPI + +VanillaMinimapTracking are both loaded). Also swapped +`SMemAlloc + memcpy` for the engine's own `SStrDup` at `0x0064A620` +— cleaner allocator, exactly matches what the engine's bulk +rebuild does. + +The intermediate rebuild-hook approach also uncovered the engine's +**hardcoded post-rebuild slot writes**: the bulk rebuild populates +slots 0..548 from its `0x00BE1198` name array, then engine code +writes specific events to hardcoded slot indices in the 549..699 +range (`SPELL_DAMAGE_EVENT_SELF` at slot 549, +`SPELL_DAMAGE_EVENT_OTHER` at 550, etc.). Documented in CLAUDE.md. +This is why claiming slots from low indices early-on would have +gotten clobbered — the slot-claim approach only fires after Lua's +first `RegisterEvent` call, by which point the engine's writes have +settled. diff --git a/docs/API.md b/docs/API.md index 30cea5d2..0c4fbafd 100644 --- a/docs/API.md +++ b/docs/API.md @@ -76,6 +76,12 @@ build instructions. - [`C_AddOns.DoesAddOnExist(indexOrName)`](#c_addonsdoesaddonexistindexorname) - [Combat](#combat) - [`InCombatLockdown()`](#incombatlockdown) +- [Input](#input) + - [`IsLeftShiftKeyDown()` / `IsRightShiftKeyDown()`](#isleftshiftkeydown--isrightshiftkeydown) + - [`IsLeftControlKeyDown()` / `IsRightControlKeyDown()`](#isleftcontrolkeydown--isrightcontrolkeydown) + - [`IsLeftAltKeyDown()` / `IsRightAltKeyDown()`](#isleftaltkeydown--isrightaltkeydown) + - [`IsModifierKeyDown()`](#ismodifierkeydown) + - [`MODIFIER_STATE_CHANGED` event](#modifier_state_changed-event) - [Talent](#talent) - [`GetTalentSpellID(tabIndex, talentIndex, [rank])`](#gettalentspellidtabindex-talentindex-rank) - [`GetTalentIDByIndex(tabIndex, talentIndex)`](#gettalentidbyindextabindex-talentindex) @@ -1885,6 +1891,74 @@ Errors via `lua_error` on: - `target[name]` not resolvable to a function (covers typos and hooking unknown frame methods) +## Input + +1.12 ships `IsShiftKeyDown` / `IsControlKeyDown` / `IsAltKeyDown` but +they only report "any shift/ctrl/alt" — there's no built-in way to tell +left from right. These seven functions add the missing distinction +plus an `IsModifierKeyDown()` rollup. + +### `IsLeftShiftKeyDown()` / `IsRightShiftKeyDown()` +### `IsLeftControlKeyDown()` / `IsRightControlKeyDown()` +### `IsLeftAltKeyDown()` / `IsRightAltKeyDown()` + +Each returns `1` when the corresponding key is physically down, `nil` +otherwise — matching the convention 1.12's own `IsShiftKeyDown` etc. +use. + +```lua +if IsLeftShiftKeyDown() and not IsRightShiftKeyDown() then + -- left-shift-only binding +end +``` + +### `IsModifierKeyDown()` + +Returns `1` if **any** of the six modifier keys is down, `nil` +otherwise. Equivalent to +`IsShiftKeyDown() or IsControlKeyDown() or IsAltKeyDown()` but in one +call. + +### `MODIFIER_STATE_CHANGED` event + +Fires on every modifier-key press and release with `(key, down)`: + +| arg1 (`key`) | `LSHIFT`, `RSHIFT`, `LCTRL`, `RCTRL`, `LALT`, `RALT` | +| arg2 (`down`) | `1` on press, `0` on release | + +Only transitions fire — key autorepeat does not. Matches 2.4.3+ +semantics. + +```lua +local f = CreateFrame("Frame") +f:RegisterEvent("MODIFIER_STATE_CHANGED") +f:SetScript("OnEvent", function() + -- in vanilla 1.12 OnEvent receives no args; engine sets `event` and + -- `arg1..argN` as globals before invoking the handler. + if event == "MODIFIER_STATE_CHANGED" and arg1 == "LSHIFT" then + print("left shift", arg2 == 1 and "down" or "up") + end +end) +``` + +**Implementation notes** + +L/R modifier distinction doesn't exist anywhere in the 1.12 engine's +own state — its `IsShiftKeyDown` chain bottoms out at +`GetKeyState(VK_SHIFT)` (the merged virtual key, `0x10`), never the +L/R-aware `VK_LSHIFT` / `VK_RSHIFT`. The OS-level keystate *does* have +the distinction; we capture it by installing a `WH_GETMESSAGE` Win32 +thread hook on the engine's message-pump thread, decoding each +`WM_KEY{,SYS}{DOWN,UP}` message (using `MapVirtualKeyA(scancode, +MAPVK_VSC_TO_VK_EX)` to resolve `VK_SHIFT` to L/R and the `KF_EXTENDED` +bit in `lParam` for `VK_CONTROL` / `VK_MENU`), and maintaining a +6-bit cached bitmap that the seven query functions read. + +The thread-message hook is per-thread, not per-`HWND` — it survives +renderer-state changes that recreate WoW's main window (e.g. toggling +vertical sync), where an `SetWindowLongPtr`-style `WNDPROC` subclass +would be left dangling. + ## Talent ### `GetTalentSpellID(tabIndex, talentIndex, [rank])` diff --git a/src/DllMain.cpp b/src/DllMain.cpp index 0e2d9ace..64075195 100644 --- a/src/DllMain.cpp +++ b/src/DllMain.cpp @@ -31,13 +31,9 @@ static FrameRegisterEvent_t FrameRegisterEvent_o = nullptr; static void __fastcall InvalidFunctionPtrCheck_h() {} static bool __fastcall FrameScript_Initialize_h() { - // BEFORE the engine tears down the old event table (which it does at - // the start of FrameScript_Initialize), invalidate our cache. Our - // injected names are Storm allocations, so the engine's - // `SMemFree(entry.name)` teardown loop handles cleanup correctly on - // its own — but the table is rebuilt at a fresh address afterwards, - // and our cached slot indices point into the old layout. Drop the - // writes gate and reset slots so post-rebuild `RetryAll` re-claims. + // BEFORE the engine tears down the old event table (at the start of + // FrameScript_Initialize), invalidate our cached slot indices. The + // table is rebuilt at a fresh allocation; the old slots are stale. Event::Custom::PrepareForReload(); FrameScript_Initialize_o(); @@ -57,20 +53,22 @@ static bool __fastcall FrameScript_Initialize_h() { static void __fastcall LoadScriptFunctions_h() { LoadScriptFunctions_o(); Game::RunModuleRegistrations(); - // Permit table writes from this point on. Earlier writes (during the - // engine's own boot-time `RegisterEvent` calls, including those fired - // by SuperWoWhook) crash with `SMemFree` on slots the engine expected - // to still be NULL — see commit history / CLAUDE.md. + // Permit `Event::Custom::TryClaim` to actually write to the event + // table from here on. Earlier writes (during the engine's own + // boot-time `RegisterEvent` flurry, plus SuperWoWhook/etc.) can + // race with the engine's table init and trigger `SMemFree` on slots + // it still considers in-flight. Event::Custom::EnableWrites(); } -// Fires for every `frame:RegisterEvent(...)` call from Lua. By this point -// the engine's event table is fully populated, so any custom events we -// couldn't claim during the LoadScriptFunctions hook can be claimed now — -// before the engine's strcmp scan against `eventName` actually runs. +// Every Lua-side `frame:RegisterEvent(...)` is a chance to claim a slot +// for any custom event still waiting. By this point the engine's table +// is fully populated and SuperWoWhook / other DLLs have done their +// post-rebuild writes, so the table state is settled and our backwards +// walk finds genuine NULL slots near the tail. static void __fastcall FrameRegisterEvent_h(void *frame, void *edx, const char *eventName) { - Event::Custom::RetryAll(); + Event::Custom::RetryClaims(); FrameRegisterEvent_o(frame, edx, eventName); } diff --git a/src/Offsets.h b/src/Offsets.h index 46676385..65c58026 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -725,11 +725,28 @@ enum Offsets { // `0x00774A40`). `__thiscall` with `(this=frame, eventName)`. Walks // the entry array at `[VAR_EVENT_TABLE_BASE_PTR]`, case-insensitively // strcmps against each entry's name, and appends `frame` to the - // matching entry's chain. We hook this so any addon's RegisterEvent - // call gives `Event::Custom::RetryAll` a chance to fix up custom - // events that boot-time registration couldn't claim yet. + // matching entry's chain. FUN_FRAME_REGISTER_EVENT = 0x00702140, + // `RebuildEventTable` — the engine's bulk event-table population + // routine. `__fastcall(const char **names, int count) -> void` + // (ECX = names array, EDX = count). Tears down any existing table + // (calling the per-entry teardown helper at 0x00701A40 + freeing + // the base pointer via SMemFree), allocates a fresh table of size + // `count * 16`, then loops `names[0..count-1]` and for each + // non-empty entry calls `SStrDup(name, file, line)` to allocate + // an engine-owned copy at `entry+0x00`. + // + // Called twice during boot (with two different name arrays — 26 + // entries at 0x00B41E70, then 549 entries at 0x00BE1198) and once + // per `/reload`. We **don't hook this** — third-party DLLs + // (SuperWoWhook, transmogfix, nampower, etc.) all hook here too, and + // chaining their modifications to the `(names, count)` args makes the + // final table size unreliable (crashes seen with count → buffer-size + // mismatch). Instead, `Event::Custom` claims NULL slots from the live + // table after the rebuild settles. Kept for reference. + FUN_REBUILD_EVENT_TABLE = 0x00703D90, + // `FireEvent` — the engine's event dispatcher. 149 callers in the // binary. `__cdecl void(int eventID, const char *format, ...)`. // Indexes into `[VAR_EVENT_TABLE_BASE_PTR] + eventID * 0x10` and walks @@ -773,6 +790,13 @@ enum Offsets { FUN_STORM_SMEM_ALLOC = 0x006462E0, FUN_STORM_SMEM_FREE = 0x00646430, + // `SStrDup(const char *src, const char *file, int line)`. `__stdcall`. + // Storm's string-copy wrapper around `SMemAlloc` — used by the engine + // itself to populate event entry names. We use it from `Event::Custom` + // so the engine's reload-teardown `SMemFree` sees blocks that came + // from `SMemAlloc` (which it requires). + FUN_STORM_SSTRDUP = 0x0064A620, + // Talent system — per-player talent state populated at login from // (class, race) + Talent.dbc / TalentTab.dbc. The engine maintains // one `TabInfo *` per talent tab in the array at diff --git a/src/event/Custom.cpp b/src/event/Custom.cpp index 51ba4773..de3679c7 100644 --- a/src/event/Custom.cpp +++ b/src/event/Custom.cpp @@ -13,7 +13,9 @@ #include "Custom.h" +#include "Game.h" #include "Offsets.h" +#include "debug/Log.h" #include #include @@ -22,46 +24,38 @@ namespace Event::Custom { namespace { -// Cache of registrations keyed by eventName pointer (callers always pass a -// static literal, so pointer-equality is a valid identity check). A failed -// claim caches as `slot = -1`; subsequent `Register` calls retry until it -// succeeds. This is important because the engine's event table at -// `[VAR_EVENT_TABLE_BASE_PTR]` isn't populated yet by the time our -// `LoadScriptFunctions` hook fires — count starts at 0 and grows during -// later boot phases. Retry-on-call lets us register late without needing -// to find a precise "table is ready" hook point. -struct CacheEntry { +// Reservations registered by `AutoReserve` at static-init time, before +// any engine code runs. `RetryClaims` (triggered by the +// `Frame::RegisterEvent` hook) walks this list and claims a NULL slot +// for each unclaimed entry. +constexpr int MAX_RESERVED = 32; +struct ReservedName { const char *name; - int slot; + int slot; // -1 until claimed }; -constexpr int MAX_CACHE = 16; -CacheEntry g_cache[MAX_CACHE]; -int g_cacheCount = 0; +ReservedName g_reserved[MAX_RESERVED]; +int g_reservedCount = 0; bool g_writesEnabled = false; -// Storm-allocate a copy of `s`. The engine's event table treats every -// `entry.name` as a Storm-owned pointer — its reload teardown loop calls -// `SMemFree(entry.name)` and validates the block against Storm's registered -// allocations (panics with `ERROR #124 SMem3: ...` if the pointer didn't -// come from `SMemAlloc`). So when we inject a name, we must hand it a real -// Storm allocation, not a static literal in our DLL. -// -// We never call `SMemFree` ourselves — the engine's teardown owns the -// lifetime once we've written the pointer into a slot. -char *AllocStormCopy(const char *s) { +// Engine's SStrDup at `FUN_STORM_SSTRDUP` — uses `SMemAlloc` internally +// and is exactly what the engine itself does when filling event table +// entries. Reload teardown's `SMemFree(entry.name)` validates that the +// pointer came from `SMemAlloc`, so handing it an SStrDup'd block is +// the only safe way to inject a name. +char *SStrDup(const char *s) { if (s == nullptr) return nullptr; - using SMemAlloc_t = void *(__stdcall *)(size_t size, const char *file, - int line, int flags); - auto fn = reinterpret_cast(Offsets::FUN_STORM_SMEM_ALLOC); - const size_t len = std::strlen(s); - char *buf = static_cast(fn(len + 1, __FILE__, __LINE__, 0)); - if (buf == nullptr) - return nullptr; - std::memcpy(buf, s, len + 1); - return buf; + using SStrDup_t = char *(__stdcall *)(const char *src, const char *file, + int line); + auto fn = reinterpret_cast(Offsets::FUN_STORM_SSTRDUP); + return fn(s, __FILE__, __LINE__); } +// Walk the engine's event table from the END looking for a NULL-name +// slot. High slots are preferred so our event ids stay out of the +// engine's hardcoded slot-write range (the engine pre-fills slots +// 549..699 with `SPELL_DAMAGE_EVENT_SELF` etc.) and so the dump output +// in `_classicapi_DumpAllEvents` shows our events grouped at the tail. int TryClaim(const char *eventName) { if (!g_writesEnabled) return -1; @@ -69,18 +63,15 @@ int TryClaim(const char *eventName) { const int count = *reinterpret_cast(Offsets::VAR_EVENT_TABLE_COUNT); if (base == nullptr || count <= 0) return -1; - // Walk the live entry range looking for the first slot whose name is - // NULL. `Frame::RegisterEvent` skips NULL-name entries during its - // strcmp loop (see the bail at 0x00702171), so they're safe to claim - // without breaking any existing event. - for (int i = 0; i < count; i++) { + for (int i = count - 1; i >= 0; --i) { auto **namePtr = reinterpret_cast( - base + i * Offsets::EVENT_ENTRY_STRIDE + Offsets::OFF_EVENT_ENTRY_NAME); + base + i * Offsets::EVENT_ENTRY_STRIDE + + Offsets::OFF_EVENT_ENTRY_NAME); if (*namePtr == nullptr) { - char *stormName = AllocStormCopy(eventName); - if (stormName == nullptr) + char *copy = SStrDup(eventName); + if (copy == nullptr) return -1; - *namePtr = stormName; + *namePtr = copy; return i; } } @@ -89,57 +80,112 @@ int TryClaim(const char *eventName) { } // namespace -int Register(const char *eventName) { - if (eventName == nullptr) - return -1; - for (int i = 0; i < g_cacheCount; i++) { - if (g_cache[i].name == eventName) { - if (g_cache[i].slot < 0) - g_cache[i].slot = TryClaim(eventName); - return g_cache[i].slot; - } +AutoReserve::AutoReserve(const char *name) { + if (name == nullptr || g_reservedCount >= MAX_RESERVED) + return; + for (int i = 0; i < g_reservedCount; ++i) { + if (std::strcmp(g_reserved[i].name, name) == 0) + return; } - if (g_cacheCount >= MAX_CACHE) - return -1; - g_cache[g_cacheCount].name = eventName; - g_cache[g_cacheCount].slot = TryClaim(eventName); - return g_cache[g_cacheCount++].slot; + g_reserved[g_reservedCount].name = name; + g_reserved[g_reservedCount].slot = -1; + ++g_reservedCount; } -void RetryAll() { - for (int i = 0; i < g_cacheCount; i++) { - if (g_cache[i].slot < 0) - g_cache[i].slot = TryClaim(g_cache[i].name); +int Lookup(const char *name) { + if (name == nullptr) + return -1; + for (int i = 0; i < g_reservedCount; ++i) { + if (std::strcmp(g_reserved[i].name, name) == 0) + return g_reserved[i].slot; + } + return -1; +} + +void RetryClaims() { + for (int i = 0; i < g_reservedCount; ++i) { + if (g_reserved[i].slot < 0) + g_reserved[i].slot = TryClaim(g_reserved[i].name); } } void EnableWrites() { g_writesEnabled = true; } void PrepareForReload() { - // The engine's teardown at 0x00701A40 walks every entry and calls - // `SMemFree(entry.name)`, which validates the block came from - // `SMemAlloc`. Our injected names are Storm allocations (see - // `AllocStormCopy`), so the engine's free path handles them - // correctly — we don't need to touch the engine's table here. - // - // We DO still need to invalidate our cache: the engine's teardown - // is followed by a full table rebuild at a fresh allocation, so - // every cached `slot` index points into the old layout and is no - // longer ours. Reset everything to `slot = -1` and drop the writes - // gate; `LoadScriptFunctions_h` will re-enable writes after the - // rebuild, and `RetryAll` (fired by every subsequent - // `RegisterEvent` from Lua) will re-claim and re-allocate. - for (int i = 0; i < g_cacheCount; i++) - g_cache[i].slot = -1; + for (int i = 0; i < g_reservedCount; ++i) + g_reserved[i].slot = -1; g_writesEnabled = false; } void Fire_DD(int eventID, int arg1, int arg2) { if (eventID < 0) return; - using FireEvent_DD_t = void(__cdecl *)(int eventID, const char *format, int a, int b); + using FireEvent_DD_t = void(__cdecl *)(int eventID, const char *format, + int a, int b); auto fn = reinterpret_cast(Offsets::FUN_FIRE_EVENT); fn(eventID, "%d%d", arg1, arg2); } +void Fire_SD(int eventID, const char *arg1, int arg2) { + if (eventID < 0) + return; + using FireEvent_SD_t = void(__cdecl *)(int eventID, const char *format, + const char *a, int b); + auto fn = reinterpret_cast(Offsets::FUN_FIRE_EVENT); + fn(eventID, "%s%d", arg1, arg2); +} + +// Diagnostic Lua functions — registered via the auto-register pattern +// at the bottom of this file. Not on any hot path. +namespace { + +int __fastcall Script_DumpSlot(void *L) { + if (!Game::Lua::IsNumber(L, 1)) { + Debug::Log::Printf("[dumpslot] usage: _classicapi_DumpSlot(slot)"); + return 0; + } + const int slot = static_cast(Game::Lua::ToNumber(L, 1)); + auto *base = *reinterpret_cast(Offsets::VAR_EVENT_TABLE_BASE_PTR); + const int count = *reinterpret_cast(Offsets::VAR_EVENT_TABLE_COUNT); + const char *name = nullptr; + if (base != nullptr && slot >= 0 && slot < count) { + name = *reinterpret_cast( + base + slot * Offsets::EVENT_ENTRY_STRIDE + + Offsets::OFF_EVENT_ENTRY_NAME); + } + Debug::Log::Printf("[dumpslot] base=0x%08X count=%d slot=%d name='%s'", + static_cast(reinterpret_cast(base)), + count, slot, name ? name : "(null)"); + return 0; +} + +int __fastcall Script_DumpAllEvents(void *) { + auto *base = *reinterpret_cast(Offsets::VAR_EVENT_TABLE_BASE_PTR); + const int count = *reinterpret_cast(Offsets::VAR_EVENT_TABLE_COUNT); + Debug::Log::Printf("[dumpall] base=0x%08X count=%d", + static_cast(reinterpret_cast(base)), + count); + if (base == nullptr) + return 0; + for (int i = 0; i < count; ++i) { + const char *name = *reinterpret_cast( + base + i * Offsets::EVENT_ENTRY_STRIDE + + Offsets::OFF_EVENT_ENTRY_NAME); + if (name != nullptr && *name != '\0') + Debug::Log::Printf("[%d] %s", i, name); + } + Debug::Log::Printf("[dumpall] done"); + return 0; +} + +void RegisterDiagnostics() { + Game::Lua::RegisterGlobalFunction("_classicapi_DumpSlot", &Script_DumpSlot); + Game::Lua::RegisterGlobalFunction("_classicapi_DumpAllEvents", + &Script_DumpAllEvents); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterDiagnostics}; + +} // namespace + } // namespace Event::Custom diff --git a/src/event/Custom.h b/src/event/Custom.h index 279981c1..059259c7 100644 --- a/src/event/Custom.h +++ b/src/event/Custom.h @@ -15,52 +15,65 @@ namespace Event::Custom { -// Claims an unused (`name == NULL`) slot in the engine's event-registration -// table at `[VAR_EVENT_TABLE_BASE_PTR]`, sets its name to `eventName`, and -// returns the slot index. After a successful registration, addons can -// `frame:RegisterEvent(eventName)` and the engine will treat it like any -// built-in event; a matching `Fire*` call dispatches to those frames. +// Reserve an event name to be claimed in the engine's event table at +// the next safe opportunity. Place a static instance at file scope: // -// `eventName` must outlive the engine — pass a static string literal or -// DLL-owned storage. Returns -1 if the table isn't initialized yet, or if -// no NULL slot was found in the live entry range. A reasonable place to -// call this is from a module's `RegisterLuaFunctions`, which fires after -// engine boot. -int Register(const char *eventName); - -// Re-attempts `TryClaim` for any cached registration that hasn't succeeded -// yet. The engine populates the event table during boot AFTER our -// `LoadScriptFunctions` hook fires, so the boot-time `Register` calls -// usually return -1; calling `RetryAll` from a later hook point (e.g. -// `Frame::RegisterEvent`) catches them up just in time. -void RetryAll(); - -// Permits `TryClaim` to actually write to the event table. Until this is -// called, `Register` and `RetryAll` cache the name but DO NOT mutate the -// engine's table. Boot-time `RegisterEvent` calls (including those fired -// by SuperWoWhook and other DLLs) can race with the engine's own table -// init and trigger `SMemFree` on slots they expected to still be NULL — -// writing during that window crashed the engine. `DllMain.cpp` flips this -// after `LoadScriptFunctions_h` returns, so all our writes happen after -// the engine has finished its own setup. -void EnableWrites(); - -// Call this BEFORE the engine's `FrameScript_Initialize_o` runs (i.e. -// before each `/reload`). The engine's reload path iterates every entry -// and `SMemFree`s its name; we hand it Storm-allocated copies (see -// `AllocStormCopy` in Custom.cpp), so the free is safe — we don't need -// to touch the engine's table here. What we DO need: drop the writes -// gate and reset cached slot indices, since the engine reallocates the -// table at a fresh address and our previous slot indices are stale. -void PrepareForReload(); - -// Dispatches an event registered via `Register` with two int args -// (format `"%d%d"`). Use this for `(itemID, success)`-style payloads; -// pass booleans as 0/1 since the engine has no native bool format code. +// static const Event::Custom::AutoReserve _r{"MY_EVENT"}; // -// Standard C++ doesn't let us forward varargs through `...` to a varargs -// callee, so each call shape lives in its own typed wrapper here. Add new -// shapes (`Fire_S`, `Fire_SD`, etc.) as additional events come online. +// Static-init chains the name onto an internal list *before* `DllMain` +// runs. After the engine and any other DLLs have finished writing to +// the event table (signaled by the first `Frame::RegisterEvent` call +// from Lua, which our hook intercepts to fire `RetryClaims`), we walk +// the table from the END looking for NULL-name slots and claim them +// for our reserved names — engine-owned `SStrDup` storage, so the +// engine's reload teardown frees them correctly. +// +// We don't hook `RebuildEventTable` directly: chaining with other DLLs +// that hook the same function (SuperWoWhook, nampower, transmogfix, +// VanillaMinimapTracking) led to count→buffer-size mismatches and +// crashes in the engine's fill loop. The slot-claim approach lets each +// DLL operate on the table independently of the others. +// +// The name pointer must outlive the engine (a string literal does). +// Same name reserved twice is deduped; reserving more than 32 names +// total silently drops the overflow. +struct AutoReserve { + explicit AutoReserve(const char *name); +}; + +// Returns the slot id currently assigned to `name`, or -1 if not yet +// claimed (e.g. before the first Lua-side `RegisterEvent` has +// triggered `RetryClaims`). Slot indices may change across `/reload`, +// so call this at fire time rather than caching the value. +int Lookup(const char *name); + +// Dispatches an event with two int args (format `"%d%d"`). Pass +// booleans as 0/1 since the engine has no native bool format code. void Fire_DD(int eventID, int arg1, int arg2); +// Dispatches with `(string, int)` — used by `MODIFIER_STATE_CHANGED` +// for `(keyName, down)` payloads. `arg1` must outlive the call (the +// engine doesn't copy strings out of varargs); for compile-time +// literals this is automatic. +void Fire_SD(int eventID, const char *arg1, int arg2); + +// Internal: try to claim a slot for every reservation that's still +// unclaimed (`slot < 0`). Called from the `Frame::RegisterEvent` hook +// in DllMain — every time Lua calls `frame:RegisterEvent(...)`, we +// catch any reservations that couldn't claim earlier. +void RetryClaims(); + +// Internal: permit `TryClaim` to write to the event table. Held +// closed until `LoadScriptFunctions_h` returns, so the boot phase +// (during which the engine and SuperWoWhook fire many internal +// `RegisterEvent` calls) can't trigger our writes. Writing during +// that window crashes the engine in `SMemFree` on slots it expected +// to still be NULL. +void EnableWrites(); + +// Internal: invalidate cached slot indices before `/reload`. The +// engine rebuilds the event table at a fresh allocation; our cached +// slots point into the old layout and need to re-claim. +void PrepareForReload(); + } // namespace Event::Custom diff --git a/src/input/Modifier.cpp b/src/input/Modifier.cpp new file mode 100644 index 00000000..d70d7c97 --- /dev/null +++ b/src/input/Modifier.cpp @@ -0,0 +1,197 @@ +// 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 "Game.h" +#include "event/Custom.h" + +#include + +#include + +// `IsLeft/RightShiftKeyDown` / `IsLeft/RightControlKeyDown` / +// `IsLeft/RightAltKeyDown` / `IsModifierKeyDown` and the +// `MODIFIER_STATE_CHANGED(key, down)` event. +// +// 1.12's own modifier-key path collapses left and right into a single +// shift/ctrl/alt boolean (the engine's `IsShiftKeyDown` chain queries +// `GetKeyState(VK_SHIFT)` — `0x10`, the L+R-merged virtual key — at +// `0x00436024`, never the L/R-distinguishing `VK_LSHIFT` / `VK_RSHIFT` +// virtual keys). The information physically exists at the OS level but +// the engine doesn't expose it. +// +// We capture L/R distinction by installing a `WH_GETMESSAGE` hook on +// our thread (which is the engine's main message-pump thread). The +// hook intercepts every message dequeued by `GetMessage` / +// `PeekMessage` *before* it's dispatched — including +// `WM_KEY{,SYS}{DOWN,UP}`. The VK code in `wParam` plus the scancode + +// extended-key bit in `lParam` uniquely identify L vs R for each +// modifier; we maintain a cached 6-bit bitmap that the seven query +// functions read, and a transition (old != new) fires +// `MODIFIER_STATE_CHANGED`. +// +// Why a thread-message hook instead of a `SetWindowLongPtr` subclass: +// the engine recreates its main window on some renderer state changes +// (verified empirically — toggling vsync makes a previously-installed +// `WNDPROC` subclass go silent, because the new HWND has its own +// pristine WNDPROC and our subclass is left dangling on a destroyed +// window). A thread-level hook attaches to the message *thread*, not a +// specific HWND, so it survives any number of window recreations. + +namespace Input::Modifier { + +namespace { + +constexpr int BIT_LSHIFT = 0; +constexpr int BIT_RSHIFT = 1; +constexpr int BIT_LCTRL = 2; +constexpr int BIT_RCTRL = 3; +constexpr int BIT_LALT = 4; +constexpr int BIT_RALT = 5; +constexpr uint32_t MASK_ANY_MODIFIER = 0x3F; + +const char *const kKeyName[6] = { + "LSHIFT", "RSHIFT", "LCTRL", "RCTRL", "LALT", "RALT", +}; + +constexpr const char *kModifierStateChanged = "MODIFIER_STATE_CHANGED"; + +// Static-init reservation — runs before DllMain. The +// `RebuildEventTable` hook appends our name to the engine's event- +// table input when the engine populates it. +const Event::Custom::AutoReserve _reserveModifierStateChanged{kModifierStateChanged}; + +uint32_t g_modifierMask = 0; +HHOOK g_msgHook = nullptr; + +void PushDown(void *L, bool down) { + if (down) + Game::Lua::PushNumber(L, 1.0); + else + Game::Lua::PushNil(L); +} + +template +int __fastcall Script_IsKeyDown(void *L) { + const bool down = (g_modifierMask & (1u << BitIdx)) != 0; + PushDown(L, down); + return 1; +} + +int __fastcall Script_IsModifierKeyDown(void *L) { + const bool down = (g_modifierMask & MASK_ANY_MODIFIER) != 0; + PushDown(L, down); + return 1; +} + +// Decode the L/R bit position from a key message. +// - `VK_SHIFT` (the merged virtual key the OS sends for either key) +// resolves via `MapVirtualKeyA(scancode, MAPVK_VSC_TO_VK_EX)` — +// the only reliable way to distinguish LSHIFT/RSHIFT from a +// keyboard message, since shift has no extended-key bit. +// - `VK_CONTROL` / `VK_MENU` use the `KF_EXTENDED` (bit 24) flag in +// `lParam`: extended = right key, plain = left key. (Some +// keyboards' AltGr generates RMENU + LCONTROL; we accept that as-is +// since it's how the OS reports the keystate.) +// - The OS occasionally delivers VK_L*/VK_R* directly (e.g. via +// `SendInput`-injected synthetic events); accept them too. +// Returns -1 for non-modifier keys. +int VkToBitIdx(WPARAM wParam, LPARAM lParam) { + const UINT vk = static_cast(wParam); + const UINT scancode = (lParam >> 16) & 0xFF; + const bool extended = ((lParam >> 24) & 1) != 0; + + if (vk == VK_SHIFT) { + const UINT actual = MapVirtualKeyA(scancode, 3 /* MAPVK_VSC_TO_VK_EX */); + if (actual == VK_LSHIFT) return BIT_LSHIFT; + if (actual == VK_RSHIFT) return BIT_RSHIFT; + return BIT_LSHIFT; // best-effort fallback; treat as left + } + if (vk == VK_LSHIFT) return BIT_LSHIFT; + if (vk == VK_RSHIFT) return BIT_RSHIFT; + if (vk == VK_CONTROL) return extended ? BIT_RCTRL : BIT_LCTRL; + if (vk == VK_LCONTROL) return BIT_LCTRL; + if (vk == VK_RCONTROL) return BIT_RCTRL; + if (vk == VK_MENU) return extended ? BIT_RALT : BIT_LALT; + if (vk == VK_LMENU) return BIT_LALT; + if (vk == VK_RMENU) return BIT_RALT; + return -1; +} + +void ProcessKeyMessage(UINT msg, WPARAM wParam, LPARAM lParam) { + const int bitIdx = VkToBitIdx(wParam, lParam); + if (bitIdx < 0) + return; + + const uint32_t bit = 1u << bitIdx; + const bool wasDown = (g_modifierMask & bit) != 0; + const bool nowDown = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN); + if (nowDown == wasDown) + return; + + if (nowDown) g_modifierMask |= bit; + else g_modifierMask &= ~bit; + + // Slot was assigned when the engine populated its event table; our + // hook on `RebuildEventTable` recorded the index. Lookup at fire + // time rather than caching because `/reload` re-runs the rebuild + // and the index may shift. + const int slot = Event::Custom::Lookup(kModifierStateChanged); + if (slot >= 0) + Event::Custom::Fire_SD(slot, kKeyName[bitIdx], nowDown ? 1 : 0); +} + +LRESULT CALLBACK GetMsgHook(int code, WPARAM wParam, LPARAM lParam) { + // Only process when the message is being removed from the queue + // (`PM_REMOVE` / `GetMessage`); `PM_NOREMOVE` peeks would deliver + // the same key twice if we processed both. + if (code == HC_ACTION && wParam == PM_REMOVE) { + const MSG *m = reinterpret_cast(lParam); + if (m->message == WM_KEYDOWN || m->message == WM_KEYUP || + m->message == WM_SYSKEYDOWN || m->message == WM_SYSKEYUP) { + ProcessKeyMessage(m->message, m->wParam, m->lParam); + } + } + return CallNextHookEx(nullptr, code, wParam, lParam); +} + +void InstallHook() { + if (g_msgHook != nullptr) + return; + g_msgHook = SetWindowsHookExA(WH_GETMESSAGE, &GetMsgHook, nullptr, + GetCurrentThreadId()); +} + +void RegisterLuaFunctions() { + Game::Lua::RegisterGlobalFunction("IsLeftShiftKeyDown", + &Script_IsKeyDown); + Game::Lua::RegisterGlobalFunction("IsRightShiftKeyDown", + &Script_IsKeyDown); + Game::Lua::RegisterGlobalFunction("IsLeftControlKeyDown", + &Script_IsKeyDown); + Game::Lua::RegisterGlobalFunction("IsRightControlKeyDown", + &Script_IsKeyDown); + Game::Lua::RegisterGlobalFunction("IsLeftAltKeyDown", + &Script_IsKeyDown); + Game::Lua::RegisterGlobalFunction("IsRightAltKeyDown", + &Script_IsKeyDown); + Game::Lua::RegisterGlobalFunction("IsModifierKeyDown", + &Script_IsModifierKeyDown); + + InstallHook(); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +} // namespace + +} // namespace Input::Modifier diff --git a/src/item/Data.cpp b/src/item/Data.cpp index f79f3dff..55b57ac5 100644 --- a/src/item/Data.cpp +++ b/src/item/Data.cpp @@ -45,21 +45,23 @@ using GetItemRecord_t = const uint8_t *(__thiscall *)(void *cache, uint32_t item // fires exactly one event, never both, depending on what initiated // the request. We honor the split with two distinct callbacks. // -// Slots are looked up via `Event::Custom::Register` which caches by -// pointer and retries failed claims; the engine's event table isn't -// populated when our boot hook fires, so all early registrations -// return -1 until `RetryAll` claims them later. +// Names are reserved at static-init time via `Event::Custom::AutoReserve`; +// the `RebuildEventTable` hook appends them to the engine's input array +// at table-population time, so the engine itself allocates and tracks +// our entries identically to its own. static constexpr const char *kItemDataLoadResult = "ITEM_DATA_LOAD_RESULT"; static constexpr const char *kGetItemInfoReceived = "GET_ITEM_INFO_RECEIVED"; +static const Event::Custom::AutoReserve _reserveItemDataLoadResult{kItemDataLoadResult}; +static const Event::Custom::AutoReserve _reserveGetItemInfoReceived{kGetItemInfoReceived}; static void FireGetItemInfoReceived(int itemID, int success) { - const int slot = Event::Custom::Register(kGetItemInfoReceived); + const int slot = Event::Custom::Lookup(kGetItemInfoReceived); if (slot >= 0) Event::Custom::Fire_DD(slot, itemID, success); } static void FireItemDataLoadResult(int itemID, int success) { - const int slot = Event::Custom::Register(kItemDataLoadResult); + const int slot = Event::Custom::Lookup(kItemDataLoadResult); if (slot >= 0) Event::Custom::Fire_DD(slot, itemID, success); } @@ -217,15 +219,8 @@ static void RegisterLuaFunctions() { Game::Lua::RegisterTableFunction("C_Item", "RequestLoadItemDataByID", &Script_RequestLoadItemDataByID); Game::Lua::RegisterTableFunction("C_Item", "RequestLoadItemData", &Script_RequestLoadItemData); - - // Seed both events so `Event::Custom::RetryAll` (driven by our hook - // on `Frame::RegisterEvent`) knows to claim slots for them. The - // engine's event table isn't populated yet when this fires, so all - // these calls return -1; later attempts via `RetryAll` or any - // direct `Register` call land them. Once claimed, slots are cached - // and reused. - Event::Custom::Register(kItemDataLoadResult); - Event::Custom::Register(kGetItemInfoReceived); + // Event names are reserved at file scope via `AutoReserve`; nothing + // to do here for events. } static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; diff --git a/src/quest/Data.cpp b/src/quest/Data.cpp index 60af751e..5348121e 100644 --- a/src/quest/Data.cpp +++ b/src/quest/Data.cpp @@ -21,6 +21,7 @@ namespace Quest::Data { static constexpr const char *kQuestDataLoadResult = "QUEST_DATA_LOAD_RESULT"; +static const Event::Custom::AutoReserve _reserveQuestDataLoadResult{kQuestDataLoadResult}; // Same `__stdcall(userData, success)` shape as `Item::Data::ItemLoadCallback`. // The engine's invocation pattern at 0x00562EEB et al. is: @@ -31,7 +32,7 @@ static constexpr const char *kQuestDataLoadResult = "QUEST_DATA_LOAD_RESULT"; // `ret 8` cleans both args. We encode the questID into `userData` at // request time so the callback knows which quest completed. static void __stdcall QuestLoadCallback(void *userData, int success) { - const int slot = Event::Custom::Register(kQuestDataLoadResult); + const int slot = Event::Custom::Lookup(kQuestDataLoadResult); if (slot < 0) return; const auto questID = @@ -47,7 +48,7 @@ static void RequestAndMaybeNotify(uint32_t questID) { // invoking our callback. Fire the event ourselves so addons get the // notification regardless of cache state, matching modern semantics. if (wasCached) { - const int slot = Event::Custom::Register(kQuestDataLoadResult); + const int slot = Event::Custom::Lookup(kQuestDataLoadResult); if (slot >= 0) Event::Custom::Fire_DD(slot, static_cast(questID), 1); } @@ -68,11 +69,7 @@ static int __fastcall Script_RequestLoadQuestByID(void *L) { static void RegisterLuaFunctions() { Game::Lua::RegisterTableFunction("C_QuestLog", "RequestLoadQuestByID", &Script_RequestLoadQuestByID); - - // Seed the event-name cache so `Event::Custom::RetryAll` (driven by - // our hook on `Frame::RegisterEvent`) can claim a slot once the - // engine's event table is populated. Same pattern as Item::Data. - Event::Custom::Register(kQuestDataLoadResult); + // Event name reserved at file scope via `AutoReserve`. } static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};