diff --git a/README.md b/README.md index f4c39d3b..d0a72673 100644 --- a/README.md +++ b/README.md @@ -32,12 +32,24 @@ Full per-function reference: **[docs/API.md](docs/API.md)**. | Input | `IsLeftAltKeyDown`, `IsLeftControlKeyDown`, `IsLeftShiftKeyDown`, `IsModifierKeyDown`, `IsRightAltKeyDown`, `IsRightControlKeyDown`, `IsRightShiftKeyDown` | | Item | `C_Item.EquipItemByName`, `C_Item.GetItemCount`, `C_Item.GetItemFamily`, `C_Item.GetItemIcon`, `C_Item.GetItemIconByID`, `C_Item.GetItemID`, `C_Item.GetItemInfoInstant`, `C_Item.GetItemSpell`, `C_Item.IsBound`, `C_Item.IsEquippableItem`, `C_Item.IsEquippedItem`, `C_Item.IsItemDataCached`, `C_Item.IsItemDataCachedByID`, `C_Item.RequestLoadItemData`, `C_Item.RequestLoadItemDataByID`, `GetInventoryItemDurability`, `GetInventoryItemID`, `GetItemIcon`, `OffhandHasWeapon` | | Quest | `C_QuestLog.GetTitleForQuestID`, `C_QuestLog.RequestLoadQuestByID`, `GetQuestIDFromLogIndex` | -| Spell | `C_Spell.GetSpellDescription`, `C_Spell.GetSpellInfo`, `C_Spell.GetSpellLink`, `C_Spell.GetSpellName`, `C_Spell.GetSpellTexture`, `C_Spell.IsSpellPassive`, `C_Spell.IsSpellUsable`, `FindSpellBookSlotByID`, `GetSpellInfo`, `GetSpellLink`, `GetSpellSchool`, `IsPassiveSpell`, `IsPlayerSpell`, `IsSpellKnown`, `IsUsableSpell` | +| Spell | `C_Spell.GetSpellDescription`, `C_Spell.GetSpellInfo`, `C_Spell.GetSpellLink`, `C_Spell.GetSpellName`, `C_Spell.GetSpellTexture`, `C_Spell.IsSpellPassive`, `C_Spell.IsSpellUsable`, `CastAutoRepeatSpell`, `FindSpellBookSlotByID`, `GetSpellInfo`, `GetSpellLink`, `GetSpellSchool`, `IsPassiveSpell`, `IsPlayerSpell`, `IsSpellKnown`, `IsUsableSpell` | | State | `IsAssistingRitual`, `IsFalling`, `IsMounted`, `IsStealthed`, `IsSwimming` | | Talent | `GetTalentIDByIndex`, `GetTalentSpellID` | | Time | `C_DateAndTime.AdjustTimeByDays`, `C_DateAndTime.AdjustTimeByMinutes`, `C_DateAndTime.CompareCalendarTime`, `C_DateAndTime.GetCalendarTimeFromEpoch`, `C_DateAndTime.GetCurrentCalendarTime`, `C_DateAndTime.GetSecondsUntilDailyReset`, `C_DateAndTime.GetServerTimeLocal`, `GetServerTime` | | Unit | `C_PlayerInfo.RememberPlayer`, `ClassicAPI.GetPersistentNameCacheEnabled`, `ClassicAPI.SetPersistentNameCacheEnabled`, `GetPlayerInfoByGUID`, `UnitGUID`, `UnitIsAFK`, `UnitIsDND`, `UnitIsFeignDeath`, `UnitIsInMyGuild`, `UnitIsPossessed` | +### Macros + +Engine-level extensions to macro parsing and dispatch — no new Lua +functions, just behavior the stock 1.12 engine didn't have. See the +[Macros section in the Lua reference](docs/API.md#macros) for details. + +| Form | What it does | +|------|--------------| +| `/cast ` | `/cast 5019` casts Shoot if known; macro slot tags correctly for action-bar UI | +| `CastSpellByName("")` | Same — numeric strings resolve through the engine's name resolver | +| `CastAutoRepeatSpell("")` in a macro | Engine's macro parser now recognizes it as a primary-spell line, so the macro slot highlights when its spell is auto-repeating | + ### Events | Event | Payload | diff --git a/docs/API.md b/docs/API.md index 1b25d1ce..45bfd79b 100644 --- a/docs/API.md +++ b/docs/API.md @@ -22,6 +22,10 @@ build instructions. - [`IsUsableSpell(spell)` / `IsUsableSpell(slot, bookType)`](#isusablespellspell--isusablespellslot-booktype) - [`C_Spell.IsSpellUsable(spellID)`](#c_spellisspellusablespellid) - [`GetSpellSchool(spellID)`](#getspellschoolspellid) + - [`CastAutoRepeatSpell(name | spellID)`](#castautorepeatspellname--spellid) +- [Macros](#macros) + - [Numeric spellIDs in `/cast` and `CastSpellByName`](#numeric-spellids-in-cast-and-castspellbyname) + - [`CastAutoRepeatSpell` as a macro cast line](#castautorepeatspell-as-a-macro-cast-line) - [GameTooltip](#gametooltip) - [`GameTooltip:SetSpellByID(spellID)`](#gametooltipsetspellbyidspellid) - [`GameTooltip:SetTalentByID(talentID)`](#gametooltipsettalentbyidtalentid) @@ -582,6 +586,133 @@ resistance-aware aura libraries, and damage-meter school tagging. Previously addons either maintained hardcoded `spellID → school` tables or scanned tooltips for the first-line color tag. +### `CastAutoRepeatSpell(name | spellID)` + +Spammable variant of `CastSpellByName` for auto-repeat spells +(Shoot/Wand/Auto-Shot). Only calls into the engine's cast path when +no auto-repeat is currently active, so a held keybind doesn't toggle +the same spell back off the way `CastSpellByName` does. + +| Engine state | Behavior | Return | +|----------------------------|---------------------|---------| +| Nothing auto-repeating | Starts the cast | `true` if the spell is now auto-repeating, else `false` (e.g. you passed a non-auto-repeat spell) | +| Already casting *this* spell | No-op | `true` | +| Already casting *other* spell | No-op | `false` | + +Replaces the action-bar loop workaround: + +```lua +-- Before +for i = 1, 120 do + if IsAutoRepeatAction(i) then return end +end +CastSpellByName("Shoot") + +-- After +CastAutoRepeatSpell("Shoot") +``` + +```lua +CastAutoRepeatSpell("Shoot") -- by name (matches what CastSpellByName accepts) +CastAutoRepeatSpell(75) -- by spellID (Auto Shot rank 1) +``` + +String input matches the active spell's `Spell.dbc` name case- +insensitively and tolerates a trailing `(Rank N)` suffix the same +way `CastSpellByName` itself does — `"Shoot"` and `"Shoot(Rank 1)"` +both compare equal to a Shoot that's already auto-repeating. + +Reads `[VAR_ACTIVE_AUTO_REPEAT_SPELL]` (`0x00CEAC30`) — the same +dword `IsAutoRepeatAction`'s inner helper at `0x004E55B0` consults. +Delegates to `Script_CastSpellByName` (`0x004B4AB0`) for the cast +itself, so resolution semantics (which rank, target rules, etc.) +are identical to the engine's own global. + +Using this from inside a macro action slot? See +[`CastAutoRepeatSpell` as a macro cast line](#castautorepeatspell-as-a-macro-cast-line) below for the additional +parser support that makes the slot tag correctly for action-bar UIs. + +## Macros + +Engine-level extensions to how macros are parsed and dispatched. These +don't add new Lua functions — they teach the engine to recognize input +forms it didn't accept in stock 1.12. Macro authors get them for free +once `ClassicAPI.dll` is loaded. + +Vanilla 1.12 doesn't support `[target=...]`-style macro conditionals +natively; we don't add those. If you have a separate DLL/addon that +does (nampower's conditional macros, SuperWoWhook, etc.), the +extensions below compose with it — that layer strips the bracket +clause and forwards the cleaned tail to `CastSpellByName`, which then +flows through our additions. + +### Numeric spellIDs in `/cast` and `CastSpellByName` + +Pure-numeric input is now accepted anywhere a spell name would be: + +``` +/cast 5019 -- in a macro line; casts Shoot if known +CastSpellByName("5019") -- same effect from Lua / /run / chat +``` + +The spellID is resolved through `Spell.dbc` to the locale-resolved +name, then handed to the engine's existing name resolver — so all the +normal downstream behavior applies: the spellbook lookup gates on +"player knows this spell," action-bar UI sees the cast as if it had +been named, macros containing `/cast 5019` get tagged with the right +spellID in the engine's spell-state cache (so `IsCurrentAction(slot)` +and `IsAutoRepeatAction(slot)` work for the macro slot). + +| Input | Outcome | +|--------------|--------------------------------------------------------| +| `/cast 5019` | Casts Shoot if you know it (any rank, highest known) | +| `/cast 1234` | Falls through as "unknown spell," same as `/cast Foo` | +| `/cast Shoot`| Unchanged from vanilla — names still work | +| `/cast 5019(Rank 1)` | Falls through — rank suffix with a numeric stem isn't supported (use the name form if you need a specific rank) | + +Implemented as a single hook on the engine's name → spellbook-slot +resolver at `0x004B3950` — covers `/cast`, `/castsequence` aliases, +`CastSpellByName`, the macro parser's tagging path, and anywhere +else the engine resolves a spell name. Numeric input with garbage +trailing characters falls through unchanged. + +### `CastAutoRepeatSpell` as a macro cast line + +Putting `CastAutoRepeatSpell("Shoot")` in a macro body now tags the +macro with Shoot's spellID the same way `/cast Shoot` or +`CastSpellByName("Shoot")` would. Without this, the macro casts +correctly but vanilla's macro parser doesn't know to associate the +slot with any spell — so action-bar UIs that call +`IsCurrentAction(slot)` / `IsAutoRepeatAction(slot)` (pfUI's +actionbar, ShaguTweaks, etc.) never light up the slot. + +Recognized forms in a macro body: + +``` +CastAutoRepeatSpell("Shoot") -- by name (string) +CastAutoRepeatSpell(5019) -- not yet — macro parser only recognizes the string form +``` + +The numeric form **works for the cast itself** (via the function's +runtime resolution), but the macro parser only scans for the string +form when tagging. To get the slot to highlight when using the +spellID, write `CastAutoRepeatSpell("Shoot")` instead. + +The engine's first-match-wins rule still applies — if your macro is: + +``` +/cast Wand +CastAutoRepeatSpell("Shoot") +``` + +…the macro is tagged with Wand (the engine recognized `/cast Wand` +on line 1; our additional pattern is only consulted when the engine +didn't find any of its own patterns). + +Macro tagging happens at macro edit/save time. Existing macros need +to be opened in the Macro UI and re-saved once after dropping in the +new DLL to pick up the new parser behavior. + ## GameTooltip ### `GameTooltip:SetItemByID(itemID)` diff --git a/src/Offsets.h b/src/Offsets.h index e2601ad3..ba8d0595 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -1018,6 +1018,75 @@ enum Offsets { // ); FUN_FORMAT_SPELL_DESCRIPTION = 0x005075F0, + // The currently-auto-repeating spellID (0 when nothing is + // auto-repeating). Same dword backs Shoot/Wand/Auto-Shot — no + // per-class branching. Written by the cast-start path at + // `FUN_006E54F0` (line `DAT_00ceac30 = *piVar5;` where `piVar5` is + // the Spell.dbc record) and cleared on logout/world unload. Read by + // `Script_IsAutoRepeatAction`'s inner helper at `0x004E55B0` and + // exposed as a 1-line getter at `0x006E9FD0`. + VAR_ACTIVE_AUTO_REPEAT_SPELL = 0x00CEAC30, + + // `Script_CastSpellByName` — engine's Lua wrapper for the + // `CastSpellByName(name [, onSelf])` global. `int __fastcall(void *L)` + // — standard Lua C function ABI. Reads `name` from stack[1] (string) + // and `onSelf` from stack[2] (boolean), resolves the name (with + // optional `(Rank N)` suffix) through `FUN_004B3950`, then dispatches + // to the engine's cast path at `FUN_004B3300`. Returns 0 (no Lua + // results). Callable directly from C++ — push args on stack, call. + FUN_SCRIPT_CAST_SPELL_BY_NAME = 0x004B4AB0, + + // Macro "primary spell" parser — `__fastcall(MacroEntry *entry)`. + // Walks the macro body (stored at `entry + OFF_MACRO_BODY`) line + // by line, looking for `/cast `, `/castsequence `, + // etc. (via the engine's `SLASH_CAST%d` registry) and the + // `CastSpellByName("")` Lua pattern. On first hit, resolves + // the name to a spellID via `FUN_004B3BC0` and writes it to + // `entry + OFF_MACRO_PRIMARY_SPELL`. Writes `0xFFFFFFFF` when a + // pattern matched but the name didn't resolve (unknown spell); + // writes `0` when no line matched any pattern. Called from macro + // create/edit/refresh paths. + // + // Hooked by `Spell::AutoRepeat` to teach the engine to recognize + // `CastAutoRepeatSpell("")` as a primary-spell pattern, so + // macros using it get tagged in the spell-state cache the same + // way `CastSpellByName` macros do. Without this, `IsAutoRepeatAction` + // returns false for macro slots whose only cast is via our function + // (the engine's parser doesn't know to look for our identifier), + // breaking action-bar highlighting in pfUI etc. + FUN_MACRO_PARSE_PRIMARY_SPELL = 0x004EFE00, + + // Engine's "spell name → spellbook-resolved spellID" helper. + // `__fastcall(const char *name, int *outIsPet)`. Internally calls + // `FUN_004B3950` (the rank-stripping name-with-`(Rank N)` parser) + // to get a spellbook slot, then returns + // `[VAR_PLAYER_SPELLBOOK][slot]` (or `[VAR_PET_SPELLBOOK][slot]` + // when `*outIsPet` is set on entry). Returns 0 if the name doesn't + // resolve to a known spellbook entry. This is the resolver the + // engine's macro parser uses — name → spellID lookup that respects + // the player's known spell list. + FUN_RESOLVE_SPELL_NAME_TO_BOOK_ID = 0x004B3BC0, + + // The single name → spellbook-slot resolver underneath everything + // spell-cast related. `__fastcall(const char *name, void *out) -> + // int slot` (or `-1`). Strips a trailing `(Rank N)` suffix, then + // calls `FUN_004B3A10` for the actual lookup. Called by + // `Script_CastSpellByName` (every Lua cast) AND by + // `FUN_RESOLVE_SPELL_NAME_TO_BOOK_ID` (which the macro parser + // uses). Hooking here makes one change to both the runtime cast + // path AND the macro-tagging path — useful for accepting numeric + // spellID input as if it were a name (the `Spell::CastByID` + // module does this to enable `/cast 5019`-style macros). + FUN_RESOLVE_SPELL_NAME_TO_SLOT = 0x004B3950, + + // MacroEntry struct offsets (verified by tracing FUN_004EFE00). + // The macro body is an inline null-terminated string at `+0x164`; + // line breaks are `\n`. The primary-spell cache (what + // `IsAutoRepeatAction` ultimately reads via the spell-state hash + // lookup at `[0x00C0E2A0]`) is at `+0x564`. + OFF_MACRO_BODY = 0x164, + OFF_MACRO_PRIMARY_SPELL = 0x564, + // Spell.dbc and friends. Pointer-to-records-array + record-count pairs. // Used by Script_GetSpellName/Texture and BuildSpellTooltip. VAR_SPELL_RECORDS = 0x00C0D788, // SpellRecord *records[spellID] diff --git a/src/spell/AutoRepeat.cpp b/src/spell/AutoRepeat.cpp new file mode 100644 index 00000000..86a9e25b --- /dev/null +++ b/src/spell/AutoRepeat.cpp @@ -0,0 +1,256 @@ +// 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 "Offsets.h" +#include "spell/Lookup.h" + +#include +#include +#include + +namespace Spell::AutoRepeat { + +// Offset of the locale-resolved Name[9] table inside a Spell.dbc record +// (same value used by `Spell::Info`; duplicated here to keep this module +// header-free). +static constexpr int OFF_NAME = 0x1E0; + +using CastSpellByName_t = int(__fastcall *)(void *L); +static const CastSpellByName_t Script_CastSpellByName_Engine = + reinterpret_cast(Offsets::FUN_SCRIPT_CAST_SPELL_BY_NAME); + +static int ReadActiveSpellID() { + return *reinterpret_cast( + static_cast(Offsets::VAR_ACTIVE_AUTO_REPEAT_SPELL)); +} + +static const char *LocaleName(int spellID) { + const uint8_t *record = Spell::Lookup::RecordForID(spellID); + if (record == nullptr) + return nullptr; + const int locale = *reinterpret_cast( + static_cast(Offsets::VAR_LOCALE_INDEX)); + return *reinterpret_cast(record + OFF_NAME + locale * 4); +} + +// Case-insensitive name match for the safety gate. Walks `userInput` and +// `spellName` together; on the user side, treats `(` and trailing spaces +// before `(` as end-of-name so `"Shoot(Rank 1)"` matches the bare +// `"Shoot"` we read out of Spell.dbc — mirrors how the engine's own name +// resolver (`FUN_004B3950`) strips the parenthetical rank suffix before +// looking the spell up. +static bool NameMatches(const char *userInput, const char *spellName) { + auto lc = [](unsigned char c) -> unsigned char { + return (c >= 'A' && c <= 'Z') ? static_cast(c + 32) : c; + }; + if (userInput == nullptr || spellName == nullptr) + return false; + while (*userInput != '\0' && *userInput != '(' && *spellName != '\0') { + if (lc(static_cast(*userInput)) != + lc(static_cast(*spellName))) { + return false; + } + ++userInput; + ++spellName; + } + while (*userInput == ' ') + ++userInput; + return (*userInput == '\0' || *userInput == '(') && *spellName == '\0'; +} + +// `CastAutoRepeatSpell(name | spellID)` — safe-to-spam variant of +// `CastSpellByName` for auto-repeat spells (Shoot/Wand/Auto-Shot). +// +// Reads the engine's "currently auto-repeating spellID" global at +// `[VAR_ACTIVE_AUTO_REPEAT_SPELL]` and branches: +// - global == 0 → safe to cast; delegate to `Script_CastSpellByName` +// to start the auto-repeat. Returns true iff the global went +// non-zero (so non-auto-repeat spells like Fireball, which would +// "succeed" via CastSpellByName but don't enter auto-repeat, +// correctly report false). +// - global == requested → already auto-repeating the right spell; +// no-op, return true. This is the spam-safety: a held bind doesn't +// toggle the auto-repeat back off. +// - global == something else → a different auto-repeat is active; +// no-op, return false. Don't disrupt the unrelated spell. +// +// Number arg compares by spellID directly. String arg compares by name +// against the active spell's locale-resolved Spell.dbc name (case- +// insensitive, rank-suffix tolerant via `NameMatches`). +static int __fastcall Script_CastAutoRepeatSpell(void *L) { + char nameBuf[128]; + int requestedID = 0; + + const int argType = Game::Lua::Type(L, 1); + if (argType == Game::Lua::TYPE_NUMBER) { + requestedID = static_cast(Game::Lua::ToNumber(L, 1)); + if (requestedID <= 0) { + Game::Lua::PushBoolean(L, 0); + return 1; + } + const char *name = LocaleName(requestedID); + if (name == nullptr || *name == '\0') { + Game::Lua::PushBoolean(L, 0); + return 1; + } + std::snprintf(nameBuf, sizeof(nameBuf), "%s", name); + } else if (argType == Game::Lua::TYPE_STRING) { + const char *s = Game::Lua::ToString(L, 1); + if (s == nullptr || *s == '\0') { + Game::Lua::PushBoolean(L, 0); + return 1; + } + // Copy off Lua's string heap — the SetTop+PushString below could + // shift it and invalidate `s`. + std::snprintf(nameBuf, sizeof(nameBuf), "%s", s); + } else { + Game::Lua::Error(L, "Usage: CastAutoRepeatSpell(\"name\" | spellID)"); + return 0; + } + + const int activeID = ReadActiveSpellID(); + if (activeID != 0) { + bool match; + if (requestedID > 0) { + match = (activeID == requestedID); + } else { + match = NameMatches(nameBuf, LocaleName(activeID)); + } + Game::Lua::PushBoolean(L, match ? 1 : 0); + return 1; + } + + // Safe to start auto-repeat — delegate to the engine's cast path + // with a fresh, one-arg stack so `lua_toboolean(L, 2)` (the + // `onSelf` flag inside Script_CastSpellByName) sees nil → false. + Game::Lua::SetTop(L, 0); + Game::Lua::PushString(L, nameBuf); + Script_CastSpellByName_Engine(L); + + Game::Lua::PushBoolean(L, ReadActiveSpellID() != 0 ? 1 : 0); + return 1; +} + +static void RegisterLuaFunctions() { + Game::Lua::RegisterGlobalFunction("CastAutoRepeatSpell", + &Script_CastAutoRepeatSpell); +} + +static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +// --------------------------------------------------------------------------- +// Macro parser hook +// +// Without this hook, a macro whose only cast statement is +// `CastAutoRepeatSpell("Shoot")` doesn't get tagged in the spell-state +// cache with Shoot's spellID, because the engine's parser +// (`FUN_004EFE00`) only knows to look for `/cast` slash-aliases and +// `CastSpellByName("...")`. `IsAutoRepeatAction(macroSlot)` then has +// nothing to match against the active auto-repeat spell, so the slot +// fails to highlight in action-bar UIs (pfUI etc.). +// +// We hook `FUN_004EFE00`, let the original parser run, and if it +// didn't recognize any pattern (cache field stays 0), scan the body +// ourselves for `CastAutoRepeatSpell("")` and use the engine's +// own name→spellID resolver to fill in the field. +// --------------------------------------------------------------------------- + +using MacroParse_t = void(__fastcall *)(int macroEntry); +static MacroParse_t MacroParse_o = nullptr; + +using NameToSpellID_t = int(__fastcall *)(const char *name, int *outIsPet); + +static int ResolveNameViaEngine(const char *name) { + auto fn = reinterpret_cast( + static_cast(Offsets::FUN_RESOLVE_SPELL_NAME_TO_BOOK_ID)); + int isPet = 0; + return fn(name, &isPet); +} + +// Scan a macro body for `CastAutoRepeatSpell("")` and return the +// resolved spellID, or 0 if no recognized invocation is present or the +// name doesn't resolve to a known spellbook entry. Mirrors the engine +// parser's "first hit wins, line-at-a-time" walk order so behavior is +// consistent with how `/cast` and `CastSpellByName` are matched. +static int ScanMacroBodyForOurPattern(const char *body) { + static constexpr char kPattern[] = "CastAutoRepeatSpell("; + static constexpr size_t kPatternLen = sizeof(kPattern) - 1; + + const char *line = body; + while (*line != '\0') { + const char *eol = line; + while (*eol != '\0' && *eol != '\n') + ++eol; + + const char *p = line; + const char *end = eol; + while (p + kPatternLen <= end) { + if (std::memcmp(p, kPattern, kPatternLen) == 0) { + p += kPatternLen; + while (p < end && (*p == ' ' || *p == '\t')) + ++p; + if (p < end && *p == '"') { + ++p; + const char *q = p; + while (q < end && *q != '"') + ++q; + if (q < end) { + const size_t n = static_cast(q - p); + if (n > 0 && n < 128) { + char name[128]; + std::memcpy(name, p, n); + name[n] = '\0'; + const int spellID = ResolveNameViaEngine(name); + if (spellID > 0) + return spellID; + } + } + } + break; // matched our prefix on this line; don't double-match + } + ++p; + } + + line = (*eol == '\n') ? eol + 1 : eol; + } + return 0; +} + +static void __fastcall MacroParse_h(int macroEntry) { + MacroParse_o(macroEntry); + + int *cacheField = reinterpret_cast( + macroEntry + Offsets::OFF_MACRO_PRIMARY_SPELL); + // Only fill in if the engine didn't recognize anything. A zero + // here means the parser walked every line and found no `/cast` + // or `CastSpellByName(`; `0xFFFFFFFF` means it did find a + // recognized line but the name was unresolvable — leave that + // alone so the user's `/cast UnknownSpell` line still "claims" + // the macro the way the engine intended. + if (*cacheField != 0) + return; + + const char *body = reinterpret_cast( + macroEntry + Offsets::OFF_MACRO_BODY); + const int spellID = ScanMacroBodyForOurPattern(body); + if (spellID > 0) + *cacheField = spellID; +} + +static const Game::HookAutoRegister _hookreg{ + Offsets::FUN_MACRO_PARSE_PRIMARY_SPELL, + reinterpret_cast(&MacroParse_h), + reinterpret_cast(&MacroParse_o)}; + +} // namespace Spell::AutoRepeat diff --git a/src/spell/CastByID.cpp b/src/spell/CastByID.cpp new file mode 100644 index 00000000..570ad31d --- /dev/null +++ b/src/spell/CastByID.cpp @@ -0,0 +1,101 @@ +// 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 "Offsets.h" +#include "spell/Lookup.h" + +#include + +namespace Spell::CastByID { + +// Offset of the locale-resolved Name[9] table inside a Spell.dbc record. +static constexpr int OFF_NAME = 0x1E0; + +using NameToSlot_t = int(__fastcall *)(const char *name, void *out); +static NameToSlot_t NameToSlot_o = nullptr; + +// Parse leading digits of `name` into an int. `*end` is set to the first +// non-digit. Caps at 100_000_000 (well above any plausible spellID) to +// avoid signed-int overflow on garbage input. +static int ParseLeadingInt(const char *name, const char **end) { + int value = 0; + while (*name >= '0' && *name <= '9') { + if (value > 100000000) { + value = 0; + break; + } + value = value * 10 + (*name - '0'); + ++name; + } + *end = name; + return value; +} + +static const char *LocaleNameForID(int spellID) { + const uint8_t *record = Spell::Lookup::RecordForID(spellID); + if (record == nullptr) + return nullptr; + const int locale = *reinterpret_cast( + static_cast(Offsets::VAR_LOCALE_INDEX)); + return *reinterpret_cast(record + OFF_NAME + locale * 4); +} + +// Hook on the single name → spellbook-slot resolver +// (`FUN_RESOLVE_SPELL_NAME_TO_SLOT`). When the input is a pure-numeric +// string, look the ID up in `Spell.dbc`, swap in the locale-resolved +// name, and call the original. Non-numeric input passes through +// unchanged. Same player-spellbook constraint as the original: spell +// IDs the player doesn't have in their spellbook still fail to resolve +// (the engine's downstream `[VAR_PLAYER_SPELLBOOK][slot]` deref returns +// 0 just like for unknown names). +// +// Covers two paths in one hook: +// - `Script_CastSpellByName("5019")` at runtime → casts the spellID 5019 +// spell if known, the same way `CastSpellByName("Shoot")` does. +// - Macro parser at `FUN_004EFE00` tagging a `/cast 5019` line — its +// call to `FUN_004B3BC0` flows through us, so the macro gets +// tagged with the resolved spellID in the spell-state cache. +static int __fastcall NameToSlot_h(const char *name, void *out) { + if (name != nullptr) { + const char *p = name; + while (*p == ' ' || *p == '\t') + ++p; + if (*p >= '0' && *p <= '9') { + const char *afterDigits = nullptr; + const int id = ParseLeadingInt(p, &afterDigits); + const char *tail = afterDigits; + while (*tail == ' ' || *tail == '\t') + ++tail; + // Only intercept if the entire input is digits (plus optional + // surrounding whitespace). Inputs like "5019(Rank 1)" or + // "5019foo" fall through to the original — the engine's name + // resolver handles those as-is (and a numeric stem with a + // `(Rank N)` suffix has no meaning anyway). + if (id > 0 && *tail == '\0') { + const char *resolvedName = LocaleNameForID(id); + if (resolvedName != nullptr && *resolvedName != '\0') { + return NameToSlot_o(resolvedName, out); + } + } + } + } + return NameToSlot_o(name, out); +} + +static const Game::HookAutoRegister _hookreg{ + Offsets::FUN_RESOLVE_SPELL_NAME_TO_SLOT, + reinterpret_cast(&NameToSlot_h), + reinterpret_cast(&NameToSlot_o)}; + +} // namespace Spell::CastByID