diff --git a/README.md b/README.md index c17c22e1..28eb71d3 100644 --- a/README.md +++ b/README.md @@ -95,8 +95,8 @@ reference in **[docs/API.md](docs/API.md)**. | [NewItems](docs/API.md#newitems) | `C_NewItems.ClearAll`, `C_NewItems.IsNewItem`, `C_NewItems.RemoveNewItem` | | [PlayerInfo](docs/API.md#playerinfo) | `C_PlayerInfo.CanUseItem`, `C_PlayerInfo.GetClass`, `C_PlayerInfo.GetName`, `C_PlayerInfo.GetRace`, `C_PlayerInfo.GetSex`, `C_PlayerInfo.GUIDIsCreature`, `C_PlayerInfo.GUIDIsGameObject`, `C_PlayerInfo.GUIDIsPet`, `C_PlayerInfo.GUIDIsPlayer`, `C_PlayerInfo.IsConnected` | | [Quest](docs/API.md#quest) | `C_QuestLog.GetNumQuestObjectives`, `C_QuestLog.GetQuestDetails`, `C_QuestLog.GetHeaderIndexForQuest`, `C_QuestLog.GetLogIndexForQuestID`, `C_QuestLog.GetQuestIDForLogIndex`, `C_QuestLog.GetTitleForQuestID`, `C_QuestLog.IsOnQuest`, `C_QuestLog.IsQuestDataCachedByID`, `C_QuestLog.IsUnitOnQuest`, `C_QuestLog.RequestLoadQuestByID`, `GetQuestLogLeaderBoardID` | -| [Spell](docs/API.md#spell) | `C_Spell.CancelSpellByID`, `C_Spell.CastAtCursor`, `C_Spell.CastAtUnit`, `C_Spell.CastingInfo`, `C_Spell.ChannelInfo`, `C_Spell.DoesSpellExist`, `C_Spell.GetSchoolString`, `C_Spell.GetSpellCooldown`, `C_Spell.GetSpellDescription`, `C_Spell.GetSpellDispelType`, `C_Spell.GetSpellEffectInfo`, `C_Spell.GetSpellEffectMechanics`, `C_Spell.GetSpellInfo`, `C_Spell.GetSpellLevelInfo`, `C_Spell.GetSpellLink`, `C_Spell.GetSpellMechanicByID`, `C_Spell.GetSpellName`, `C_Spell.GetSpellPowerCost`, `C_Spell.GetSpellRadius`, `C_Spell.GetSpellReagents`, `C_Spell.GetSpellRequiredTargetLevel`, `C_Spell.GetSpellSubtext`, `C_Spell.GetSpellTexture`, `C_Spell.IsAutoAttackSpell`, `C_Spell.IsCurrentSpell`, `C_Spell.IsNextMeleeSpell`, `C_Spell.IsRangedAutoAttackSpell`, `C_Spell.IsSelfBuff`, `C_Spell.IsSpellHarmful`, `C_Spell.IsSpellHelpful`, `C_Spell.IsSpellInRange`, `C_Spell.IsSpellPassive`, `C_Spell.IsSpellUsable`, `C_Spell.ResetsMeleeSwing`, `C_Spell.SpellHasRange`, `C_Spell.UnitCastingInfo`, `C_Spell.UnitChannelInfo`, `CanDualWield`, `CancelSpellByName`, `CastSpellNoToggle`, `GetCraftSpellID`, `GetSpellBonusDamage`, `GetSpellBonusHealing`, `GetSpellInfo`, `GetSpellLink`, `GetSpellRadius`, `GetSpellRequiredTargetLevel`, `GetSpellSchool`, `IsHarmfulSpell`, `IsHelpfulSpell`, `IsPassiveSpell`, `IsPlayerSpell`, `IsSpellKnown`, `IsUsableSpell`, `SpellHasRange` | -| [SpellBook](docs/API.md#spellbook) | `C_SpellBook.GetCurrentLevelSpells`, `C_SpellBook.GetPlayerSpellsByAura`, `C_SpellBook.GetSkillLineName`, `C_SpellBook.GetSkillLineRank`, `C_SpellBook.GetSpellBookItemInfo`, `C_SpellBook.GetSpellLevelLearned`, `C_SpellBook.GetSpellSkillLine`, `C_SpellBook.IsAutoAttackSpellBookItem`, `C_SpellBook.IsRangedAutoAttackSpellBookItem`, `FindSpellBookSlotByID` | +| [Spell](docs/API.md#spell) | `C_Spell.CancelSpellByID`, `C_Spell.CastAtCursor`, `C_Spell.CastAtUnit`, `C_Spell.CastingInfo`, `C_Spell.ChannelInfo`, `C_Spell.DoesSpellExist`, `C_Spell.GetSchoolString`, `C_Spell.GetSpellCastCount`, `C_Spell.GetSpellCooldown`, `C_Spell.GetSpellDescription`, `C_Spell.GetSpellDispelType`, `C_Spell.GetSpellEffectInfo`, `C_Spell.GetSpellEffectMechanics`, `C_Spell.GetSpellInfo`, `C_Spell.GetSpellLevelInfo`, `C_Spell.GetSpellLink`, `C_Spell.GetSpellLossOfControlCooldown`, `C_Spell.GetSpellMechanicByID`, `C_Spell.GetSpellName`, `C_Spell.GetSpellPowerCost`, `C_Spell.GetSpellRadius`, `C_Spell.GetSpellReagents`, `C_Spell.GetSpellRequiredTargetLevel`, `C_Spell.GetSpellSubtext`, `C_Spell.GetSpellTexture`, `C_Spell.IsAutoAttackSpell`, `C_Spell.IsCurrentSpell`, `C_Spell.IsNextMeleeSpell`, `C_Spell.IsRangedAutoAttackSpell`, `C_Spell.IsSelfBuff`, `C_Spell.IsSpellHarmful`, `C_Spell.IsSpellHelpful`, `C_Spell.IsSpellInRange`, `C_Spell.IsSpellPassive`, `C_Spell.IsSpellUsable`, `C_Spell.ResetsMeleeSwing`, `C_Spell.SpellHasRange`, `C_Spell.UnitCastingInfo`, `C_Spell.UnitChannelInfo`, `CanDualWield`, `CancelSpellByName`, `CastSpellNoToggle`, `GetCraftSpellID`, `GetSpellBonusDamage`, `GetSpellBonusHealing`, `GetSpellInfo`, `GetSpellLink`, `GetSpellRadius`, `GetSpellRequiredTargetLevel`, `GetSpellSchool`, `IsHarmfulSpell`, `IsHelpfulSpell`, `IsPassiveSpell`, `IsPlayerSpell`, `IsSpellKnown`, `IsUsableSpell`, `SpellHasRange` | +| [SpellBook](docs/API.md#spellbook) | `C_SpellBook.ContainsAnyDisenchantSpell`, `C_SpellBook.GetCurrentLevelSpells`, `C_SpellBook.GetNumSpellBookSkillLines`, `C_SpellBook.GetPlayerSpellsByAura`, `C_SpellBook.GetSkillLineIndexByID`, `C_SpellBook.GetSkillLineName`, `C_SpellBook.GetSkillLineRank`, `C_SpellBook.GetSpellBookItemCastCount`, `C_SpellBook.GetSpellBookItemInfo`, `C_SpellBook.GetSpellBookItemLossOfControlCooldownDuration`, `C_SpellBook.GetSpellBookItemLossOfControlCooldownInfo`, `C_SpellBook.GetSpellBookItemSkillLineIndex`, `C_SpellBook.GetSpellBookSkillLineInfo`, `C_SpellBook.GetSpellLevelLearned`, `C_SpellBook.GetSpellSkillLine`, `C_SpellBook.IsAutoAttackSpellBookItem`, `C_SpellBook.IsClassTalentSpellBookItem`, `C_SpellBook.IsRangedAutoAttackSpellBookItem`, `FindSpellBookSlotByID` | | [State](docs/API.md#state) | `CancelShapeshiftForm`, `Dismount`, `GetMirrorTimerInfo`, `GetMirrorTimerProgress`, `GetShapeshiftFormID`, `GetSheathState`, `IsAssistingRitual`, `IsFalling`, `IsIndoors`, `IsInGroup`, `IsInRaid`, `IsLoggedIn`, `IsMounted`, `IsOutdoors`, `IsStealthed`, `IsSwimming` | | [System](docs/API.md#system) | `CopyToClipboard`, `GetPhysicalScreenSize` | | [Talent](docs/API.md#talent) | `GetTalentIDByIndex`, `GetTalentSpellID` | @@ -182,6 +182,7 @@ when launching with `-console`), not as Lua functions. See the | `GLOBAL_MOUSE_UP` | `button` | | `HEARTHSTONE_BOUND` | *(none)* | | `ITEM_DATA_LOAD_RESULT` | `itemID, success` | +| `LEARNED_SPELL_IN_SKILL_LINE` | `spellID, skillLineIndex, isGuildPerkSpell` | | `LOOT_HISTORY_ROLL_CHANGED` | `itemIndex, playerIndex` | | `LOOT_HISTORY_ROLL_COMPLETE` | `itemIndex` | | `LOOT_SCAN_COMPLETED` | *(none)* | diff --git a/docs/API.md b/docs/API.md index 5c22cded..dceb9cc4 100644 --- a/docs/API.md +++ b/docs/API.md @@ -158,6 +158,7 @@ build instructions. - [`EQUIPMENT_SWAP_FINISHED` event](#equipment_swap_finished-event) - [`FACTION_STANDING_CHANGED` event](#faction_standing_changed-event) - [`LOOT_HISTORY_ROLL_CHANGED` / `LOOT_HISTORY_ROLL_COMPLETE` / `LOOT_HISTORY_FULL_UPDATE` events](#loot_history_roll_changed--loot_history_roll_complete--loot_history_full_update-events) + - [`LEARNED_SPELL_IN_SKILL_LINE` event](#learned_spell_in_skill_line-event) - [`LOOT_SCAN_COMPLETED` event](#loot_scan_completed-event) - [`LOSS_OF_CONTROL_ADDED` / `LOSS_OF_CONTROL_UPDATE` events](#loss_of_control_added--loss_of_control_update-events) - [`MODIFIER_STATE_CHANGED` event](#modifier_state_changed-event) @@ -558,6 +559,7 @@ build instructions. - [`C_Spell.GetSpellRadius(spellID)` / `GetSpellRadius(slot, bookType)`](#c_spellgetspellradiusspellid--getspellradiusslot-booktype) - [`C_Spell.GetSpellPowerCost(spellIdentifier)`](#c_spellgetspellpowercostspellidentifier) - [`C_Spell.GetSpellReagents(spellID)`](#c_spellgetspellreagentsspellid) + - [`C_Spell.GetSpellCastCount(spellIdentifier)`](#c_spellgetspellcastcountspellidentifier) - [`C_Spell.GetSpellSubtext(spellIdentifier)`](#c_spellgetspellsubtextspellidentifier) - [`IsPassiveSpell(spellID)` / `IsPassiveSpell(slot, bookType)`](#ispassivespellspellid--ispassivespellslot-booktype) - [`C_Spell.IsSpellPassive(spellID)`](#c_spellisspellpassivespellid) @@ -569,6 +571,7 @@ build instructions. - [`IsUsableSpell(spell)` / `IsUsableSpell(slot, bookType)`](#isusablespellspell--isusablespellslot-booktype) - [`C_Spell.IsSpellUsable(spellID)`](#c_spellisspellusablespellid) - [`C_Spell.GetSpellCooldown(spellIdentifier)`](#c_spellgetspellcooldownspellidentifier) + - [`C_Spell.GetSpellLossOfControlCooldown(spellIdentifier)`](#c_spellgetspelllossofcontrolcooldownspellidentifier) - [`C_Spell.IsCurrentSpell(spellIdentifier)`](#c_spelliscurrentspellspellidentifier) - [`C_Spell.IsSelfBuff(spellID)`](#c_spellisselfbuffspellid) - [`C_Spell.SpellHasRange(spellIdentifier)` / `SpellHasRange(slot, bookType)`](#c_spellspellhasrangespellidentifier--spellhasrangeslot-booktype) @@ -592,6 +595,15 @@ build instructions. - [SpellBook](#spellbook) - [`FindSpellBookSlotByID(spellID)`](#findspellbookslotbyidspellid) - [`C_SpellBook.GetSpellBookItemInfo(slotIndex, spellBank)`](#c_spellbookgetspellbookiteminfoslotindex-spellbank) + - [`C_SpellBook.GetNumSpellBookSkillLines()`](#c_spellbookgetnumspellbookskilllines) + - [`C_SpellBook.GetSpellBookSkillLineInfo(skillLineIndex)`](#c_spellbookgetspellbookskilllineinfoskilllineindex) + - [`C_SpellBook.GetSpellBookItemSkillLineIndex(slotIndex, spellBank)`](#c_spellbookgetspellbookitemskilllineindexslotindex-spellbank) + - [`C_SpellBook.GetSkillLineIndexByID(skillLineID)`](#c_spellbookgetskilllineindexbyidskilllineid) + - [`C_SpellBook.GetSpellBookItemCastCount(slotIndex, spellBank)`](#c_spellbookgetspellbookitemcastcountslotindex-spellbank) + - [`C_SpellBook.GetSpellBookItemLossOfControlCooldownInfo(slotIndex, spellBank)`](#c_spellbookgetspellbookitemlossofcontrolcooldowninfoslotindex-spellbank) + - [`C_SpellBook.GetSpellBookItemLossOfControlCooldownDuration(slotIndex, spellBank)`](#c_spellbookgetspellbookitemlossofcontrolcooldowndurationslotindex-spellbank) + - [`C_SpellBook.IsClassTalentSpellBookItem(slotIndex, spellBank)`](#c_spellbookisclasstalentspellbookitemslotindex-spellbank) + - [`C_SpellBook.ContainsAnyDisenchantSpell()`](#c_spellbookcontainsanydisenchantspell) - [`C_SpellBook.GetSpellLevelLearned(spellID)`](#c_spellbookgetspelllevellearnedspellid) - [`C_SpellBook.GetCurrentLevelSpells([level])`](#c_spellbookgetcurrentlevelspellslevel) - [`C_SpellBook.GetPlayerSpellsByAura(auraName)`](#c_spellbookgetplayerspellsbyauraauraname) @@ -3756,6 +3768,31 @@ polling. Register like any engine event See the [LootHistory](#loothistory) section for the reconstruction and read API. +### `LEARNED_SPELL_IN_SKILL_LINE` event + +Fires when the player learns a spell that enters the spellbook. + +```lua +-- arg1 = spellID, arg2 = skillLineIndex, arg3 = isGuildPerkSpell +local f = CreateFrame("Frame") +f:RegisterEvent("LEARNED_SPELL_IN_SKILL_LINE") +f:SetScript("OnEvent", function() + local tab = C_SpellBook.GetSpellBookSkillLineInfo(arg2) + print("learned", C_Spell.GetSpellName(arg1), "in", tab.name) +end) +``` + +| Arg | Type | Notes | +|---|---|---| +| `spellID` | number | The spell that was learned. | +| `skillLineIndex` | number | The 1-based spellbook tab that now holds it. Feed it to [`C_SpellBook.GetSpellBookSkillLineInfo`](#c_spellbookgetspellbookskilllineinfoskilllineindex). | +| `isGuildPerkSpell` | nil | Always `nil` (false). | + +The event fires next to the stock `LEARNED_SPELL_IN_TAB`, under the same +rule: the game announced the new spell (a trainer, a quest reward, a talent) +and the spell got a spellbook slot. The spells restored at login do not fire +it. Profession recipes do not enter the spellbook, so they do not fire it. + ### `LOOT_SCAN_COMPLETED` event Fires (no payload) once a [`C_Loot.ScanNearbyLoot()`](#c_lootscannearbyloot) @@ -9862,6 +9899,10 @@ Fidelity notes: The `LOSS_OF_CONTROL_ADDED` / `LOSS_OF_CONTROL_UPDATE` events fire as these effects change — see [Events](#loss_of_control_added--loss_of_control_update-events). +For the effect that blocks one specific spell, shaped as a cooldown, see +[`C_Spell.GetSpellLossOfControlCooldown`](#c_spellgetspelllossofcontrolcooldownspellidentifier) +and its spellbook-slot variants. + ## Lua Standard-library functions that this Lua 5.0 is missing — restored by @@ -13377,6 +13418,24 @@ documented in some emulator sources places these at `+0x110` / `+0x130`, which is wrong for 1.12.1). Iteration stops at the first empty slot, matching how the engine walks its own reagent loop. +### `C_Spell.GetSpellCastCount(spellIdentifier)` + +Returns how many times the player can cast the spell with the reagents +they carry. Returns `0` for a spell without reagents, and for an unknown +spell. + +```lua +C_Spell.GetSpellCastCount(23028) -- Arcane Brilliance: your Arcane Powder count +C_Spell.GetSpellCastCount(133) -- Fireball: 0 (no reagents) +``` + +The count is the smallest `floor(carried / required)` over the spell's +reagents. "Carried" means equipped items and bags 0 to 4. Reagents in the +bank do not count, because a cast cannot use them. + +`spellIdentifier` accepts a spellID, a spell name, or a spell link, like +[`C_Spell.GetSpellCooldown`](#c_spellgetspellcooldownspellidentifier). + ### `C_Spell.GetSpellSubtext(spellIdentifier)` Returns the localized "Rank N" / "Passive" / "Racial Passive" / @@ -13639,6 +13698,39 @@ The `activeCategory`, `timeUntilEndOfStartRecovery`, and Returns `nil` if the resolved spellID is `0` or doesn't have a `Spell.dbc` row. +### `C_Spell.GetSpellLossOfControlCooldown(spellIdentifier)` + +Returns `startTime, duration` for the loss-of-control effect that stops +the player from casting this spell right now. Both values are seconds on +the `GetTime()` clock, like +[`C_Spell.GetSpellCooldown`](#c_spellgetspellcooldownspellidentifier). +Both are `0` when nothing blocks the spell. Returns `nil` for an unknown +spell. + +```lua +local start, duration = C_Spell.GetSpellLossOfControlCooldown(133) -- Fireball +if duration > 0 then + cooldownFrame:SetCooldown(start, duration) -- the loss-of-control swipe +end +``` + +Which effects block which spells: + +| Effect | Blocks | +|---|---| +| School lockout (Counterspell, Kick, ...) | Spells of the locked school. | +| Stun, fear, confuse, charm, possess | Every spell. | +| Silence | Spells that a silence prevents (most casts). | +| Pacify | Abilities that a pacify prevents (most melee and ranged abilities). | +| Root, disarm | Nothing. | + +The function reports only effects with a known end time. See the timing +note in [LossOfControl](#lossofcontrol): a school lockout always has one, +and a control effect has one when ClassicAPI saw the cast that applied it. +When only the end time is known, `startTime` is the current time and +`duration` is the remaining time. When several effects block the spell, +the function reports the one that ends last. + ### `C_Spell.IsCurrentSpell(spellIdentifier)` Returns `true` if the spell is currently being cast, queued mid-GCD, @@ -14422,9 +14514,115 @@ Returns `nil` for an empty or out-of-range slot. > **Deviations forced by the data.** `iconID` is a > texture path, not a `fileID` (there is no fileID system) — the same > deviation as [`C_Spell.GetSpellInfo`](#c_spellgetspellinfospellid). -> `skillLineIndex` is not returned (`nil`); spellbook tabs aren't -> SkillLines. `isOffSpec` is always `false` — there are no -> specializations. +> `skillLineIndex` is not returned (`nil`) — use +> [`C_SpellBook.GetSpellBookItemSkillLineIndex`](#c_spellbookgetspellbookitemskilllineindexslotindex-spellbank). +> `isOffSpec` is always `false` — there are no specializations. + +### `C_SpellBook.GetNumSpellBookSkillLines()` + +Returns the number of tabs in the player spellbook: General, then one tab +per skill line such as Fire or Fury. + +### `C_SpellBook.GetSpellBookSkillLineInfo(skillLineIndex)` + +Returns a table describing spellbook tab `skillLineIndex` (1-based), or +`nil` for an index outside `1 .. GetNumSpellBookSkillLines()`. + +```lua +for i = 1, C_SpellBook.GetNumSpellBookSkillLines() do + local tab = C_SpellBook.GetSpellBookSkillLineInfo(i) + for slot = tab.itemIndexOffset + 1, tab.itemIndexOffset + tab.numSpellBookItems do + local item = C_SpellBook.GetSpellBookItemInfo(slot, Enum.SpellBookSpellBank.Player) + print(tab.name, item.name) + end +end +``` + +| Field | Type | Notes | +|---|---|---| +| `name` | string | The tab name (`"General"`, `"Fire"`, `"Fury"`, ...). | +| `iconID` | string | The tab icon **path** — feed it to `texture:SetTexture(...)`. | +| `itemIndexOffset` | number | This value + 1 is the first `slotIndex` of the tab. | +| `numSpellBookItems` | number | The number of spells in the tab. | +| `isGuild` | boolean | Always `false`. | +| `shouldHide` | boolean | Always `false`. | +| `specID`, `offSpecID` | nil | Always `nil`. | + +The name, icon, offset, and count are the same values +`GetSpellTabInfo(skillLineIndex)` returns. + +### `C_SpellBook.GetSpellBookItemSkillLineIndex(slotIndex, spellBank)` + +Returns the 1-based tab index that holds player-book slot `slotIndex`. +Returns `nil` for a slot past the last spell, and for every pet-book slot +(the pet book has no tabs). + +```lua +C_SpellBook.GetSpellBookItemSkillLineIndex(1, Enum.SpellBookSpellBank.Player) -- 1 (General) +``` + +### `C_SpellBook.GetSkillLineIndexByID(skillLineID)` + +Returns the 1-based tab index for a `SkillLine.dbc` ID, or `nil` when the +player has no tab for that skill line. The General tab has no skill line +ID. + +```lua +local _, skillLineID = C_SpellBook.GetSpellSkillLine(133) -- Fireball: "Fire", 8 +local tab = C_SpellBook.GetSkillLineIndexByID(skillLineID) -- the Fire tab, or nil on a non-mage +``` + +Paired with +[`C_SpellBook.GetSpellSkillLine`](#c_spellbookgetspellskilllinespellid) it +answers "which of my tabs holds this spellID" without walking the book. + +### `C_SpellBook.GetSpellBookItemCastCount(slotIndex, spellBank)` + +Spellbook-slot variant of +[`C_Spell.GetSpellCastCount`](#c_spellgetspellcastcountspellidentifier). +Returns `0` for an empty slot. + +### `C_SpellBook.GetSpellBookItemLossOfControlCooldownInfo(slotIndex, spellBank)` + +Spellbook-slot variant of +[`C_Spell.GetSpellLossOfControlCooldown`](#c_spellgetspelllossofcontrolcooldownspellidentifier), +returned as a table. Returns `nil` for an empty slot. + +| Field | Type | Notes | +|---|---|---| +| `startTime` | number | Start of the blocking effect, in `GetTime()` seconds. `0` when nothing blocks the spell. | +| `duration` | number | Length of the blocking effect in seconds. `0` when nothing blocks the spell. | +| `modRate` | number | Always `1`. | +| `isActive` | boolean | `true` while an effect blocks the spell. | +| `shouldReplaceNormalCooldown` | boolean | `true` when the effect outlasts the spell's own cooldown. A button then draws the loss-of-control swipe instead of the normal one. | + +### `C_SpellBook.GetSpellBookItemLossOfControlCooldownDuration(slotIndex, spellBank)` + +The `duration` field above on its own. Returns `nil` for an empty slot. + +### `C_SpellBook.IsClassTalentSpellBookItem(slotIndex, spellBank)` + +Returns `true` when the spell in the slot comes from a talent: the +talent's own spell (Mortal Strike rank 1), or a higher rank of that +ability that you trained (Mortal Strike rank 2). Returns `false` for every +pet-book slot and for an empty slot. + +```lua +local bank = Enum.SpellBookSpellBank.Player +local info = C_SpellBook.GetSpellBookItemInfo(slot, bank) +if C_SpellBook.IsClassTalentSpellBookItem(slot, bank) then + print(info.name, "is a talent ability") +end +``` + +Higher ranks are found through the next-rank links in the client data. +Most ability chains carry them, and coverage is limited to the chains that +do. + +### `C_SpellBook.ContainsAnyDisenchantSpell()` + +Returns `true` when the player knows a spell that disenchants items +(Disenchant, from Enchanting). ### `C_SpellBook.GetSpellLevelLearned(spellID)` diff --git a/src/Offsets.h b/src/Offsets.h index 046bed58..9fcb9069 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -3742,6 +3742,14 @@ enum Offsets { OFF_SLA_CLASS_MASK = 0x10, OFF_SLA_EXCLUDE_RACE = 0x14, OFF_SLA_EXCLUDE_CLASS = 0x18, + // Field 8: the spellID of the NEXT rank that supersedes this row's + // spell (0 = none / not linked). Verified against the extracted DBC: + // Mortal Strike 12294 → 21551 → 21552, Kick 1766 → 1767. Populated + // for ability chains (660 of 6812 rows) but NOT for every chain — + // Fireball 133's row holds 0 — so treat it as "known next rank", not + // as a complete rank graph. `Talent::SpellSet` follows it to extend a + // talent's rank-1 spell to its trained higher ranks. + OFF_SLA_SUPERCEDED_BY_SPELL = 0x20, // Skill-up threshold ranks (grey / green) at record fields 10/11. // A row with either nonzero is a craftable recipe; profession // rank-up / passive rows have both zero. Empirically: the @@ -4467,6 +4475,42 @@ enum Offsets { VAR_PLAYER_SPELLBOOK = 0x00B700F0, VAR_PET_SPELLBOOK = 0x00B6F098, SPELLBOOK_MAX_SLOTS = 0x400, + // Populated-slot count of the player array above. The learn writer + // `FUN_LEARN_SPELL` appends a newly learned spell at + // `VAR_PLAYER_SPELLBOOK[count++]` (0x004B2B37: `mov [ecx*4 + B700F0], + // spellID; inc [B7116C]`), so a before/after read of this count is the + // exact "was it added to the book" gate the engine itself uses before + // firing LEARNED_SPELL_IN_TAB. Read by `Spell::Learn`. + VAR_PLAYER_SPELLBOOK_COUNT = 0x00B7116C, + + // Spellbook TABS — what `GetNumSpellTabs` / `GetSpellTabInfo` read. + // `[VAR_SPELL_TAB_ENTRIES]` is a `SpellTab **` (heap array of pointers, + // grown by `FUN_LEARN_SPELL` as new skill lines appear); `[VAR_SPELL_TAB_ + // COUNT]` is the live tab count. Each 8-byte `SpellTab` is + // `{ skillLineID @+0, numSpells @+4 }` — verified from + // `Script_GetSpellTabInfo` (0x004B3CE0), which reads `entry[0]` as the + // SkillLine.dbc ID (0 = the "General" tab, name from the GENERAL global + // string + `Interface\Icons\Ability_Kick`; else name `SkillLine+0x0C` + // localized, icon via `SkillLine+0x54` → SpellIcon.dbc) and pushes + // `entry[1]` as numSpells. Tabs partition the player spellbook array in + // order: tab i covers slots `[offset(i), offset(i) + numSpells)` where + // `offset` is `FUN_SPELL_TAB_SLOT_OFFSET`. The skillLineID per tab is + // never surfaced to Lua by the stock API — `Spell::Tabs` exposes it as + // `C_SpellBook.GetSkillLineIndexByID` / `GetSpellBookItemSkillLineIndex`. + VAR_SPELL_TAB_ENTRIES = 0x00B71160, + VAR_SPELL_TAB_COUNT = 0x00B71170, + OFF_SPELL_TAB_SKILL_LINE_ID = 0x00, + OFF_SPELL_TAB_NUM_SPELLS = 0x04, + // `int __fastcall(uint tabIndex0)` — sum of `numSpells` over tabs + // `[0, tabIndex0)`, i.e. the 0-based first slot of that tab (the `offset` + // return of `GetSpellTabInfo`). Returns 0 for tab 0 and for OOR input. + FUN_SPELL_TAB_SLOT_OFFSET = 0x004B2580, + // The engine's own `Script_GetSpellTabInfo(index)` Lua C function + // (`int __fastcall(void *L)`; reads `L[1]`, pushes `name, texture, + // offset, numSpells`). `C_SpellBook.GetSpellBookSkillLineInfo` reshapes + // the stack and calls it directly so the GENERAL-tab localization and the + // SkillLine → SpellIcon chain stay the engine's. + FUN_SCRIPT_GET_SPELL_TAB_INFO = 0x004B3CE0, // Active minimap-tracking spell ID (0 = none). Vanilla tracks exactly // one active tracker as a plain int here, derived from the player's @@ -4500,10 +4544,20 @@ enum Offsets { // spellbook arrays, and fires SPELLS_CHANGED; unlearn (`FUN_004b2c50`) // clears the bit and removes the spell. Both `__fastcall`: learn is // (uint spellID, int notify, uint replacedSpellID), unlearn is - // (uint spellID, int). Co-hooked (spell/Info.cpp) to bump + // (uint spellID, int). Co-hooked (spell/Learn.cpp) to bump // Player::StatSignal so a talent respec invalidates GetSpellBonusHealing's - // talent-conversion cache. They fire at login (SMSG_INITIAL_SPELLS) and on - // each learn/unlearn — never per-frame, so cool hook targets. + // talent-conversion cache, and to fire LEARNED_SPELL_IN_SKILL_LINE. They + // fire at login (SMSG_INITIAL_SPELLS) and on each learn/unlearn — never + // per-frame, so cool hook targets. + // + // Learn's own event gate (decompiled): it fires LEARNED_SPELL_IN_TAB + // (event 0x1FE, fmt "%d" at 0x00835154) only when `notify != 0` AND the + // spell was appended to the player spellbook array (non-trade, non- + // hidden spells; passives included). Shapeshift-form spells additionally + // hit the form list + UPDATE_SHAPESHIFT_FORMS; trade spells only get the + // "learned how to create" chat line (0x39). There is NO action-bar + // auto-placement anywhere in it — 1.12 never pushes a learned spell to a + // bar, so SPELL_PUSHED_TO_ACTIONBAR has no engine source. FUN_LEARN_SPELL = 0x004B25B0, FUN_UNLEARN_SPELL = 0x004B2C50, @@ -7259,6 +7313,9 @@ enum Offsets { SPELL_EFFECT_LEARN_SPELL = 36, SPELL_EFFECT_ENCHANT_ITEM = 53, SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY = 54, + // Verified from Spell.dbc: 13262 "Disenchant" has Effect[0] = 99 (the + // only row carrying it). Effect 32 is TRIGGER_MISSILE, not disenchant. + SPELL_EFFECT_DISENCHANT = 99, // EffectBasePoints[3] — the base magnitude of each effect, stored as // (value - 1) for the fixed-die spells that back item stats (the @@ -7313,6 +7370,19 @@ enum Offsets { OFF_SPELL_RECORD_ICON_ID = 0x1D4, // u32 SpellIconID (→ SpellIcon.dbc) OFF_SPELL_RECORD_ATTRIBUTES = 0x18, // u32 (column 6, base Attributes) SPELL_ATTR_PASSIVE = 0x40, // bit 6 — always-on aura + + // PreventionType (column 165) — which control-loss flag stops the cast: + // 0 none, 1 SILENCE (UNIT_FLAG_SILENCED), 2 PACIFY (UNIT_FLAG_PACIFIED); + // the server's `Spell::CheckCast` gate. Verified against the extracted + // Spell.dbc with the column chain Name@120 → Rank@129 → Family@160 → + // FamilyFlags@161-162 → MaxAffectedTargets@163 → DmgClass@164 → + // PreventionType@165: Fireball 133 = 1, Power Word: Fortitude 1243 = 1, + // Heroic Strike 78 = 2, Kick 1766 = 2, Throw 2764 = 2, Attack 6603 = 0. + // Only 0/1/2 occur (20549 / 6201 / 1268 rows). Read by + // `LossOfControl::LockoutForSpell`. + OFF_SPELL_RECORD_PREVENTION_TYPE = 0x294, + SPELL_PREVENTION_TYPE_SILENCE = 1, + SPELL_PREVENTION_TYPE_PACIFY = 2, OFF_SPELL_RECORD_ATTRIBUTES_EX = 0x1C, // u32 (column 7) OFF_SPELL_RECORD_ATTRIBUTES_EX2 = 0x20, // u32 (column 8) OFF_SPELL_RECORD_ATTRIBUTES_EX3 = 0x24, // u32 (column 9) diff --git a/src/lossofcontrol/Info.cpp b/src/lossofcontrol/Info.cpp index 5e265b8f..ce1443b4 100644 --- a/src/lossofcontrol/Info.cpp +++ b/src/lossofcontrol/Info.cpp @@ -43,6 +43,7 @@ #include "aura/Source.h" #include "dbc/Lookup.h" #include "event/Custom.h" +#include "lossofcontrol/Lockout.h" #include "net/PacketDispatch.h" #include "net/PacketReader.h" #include "spell/CrowdControl.h" @@ -52,6 +53,7 @@ #include "unit/Identity.h" #include +#include namespace LossOfControl { @@ -214,6 +216,31 @@ int BuildList(LocEntry *out, int maxOut) { return n; } +// Which spells a control-loss effect blocks — the server's cast gates +// (`Spell::CheckCast`) restated: a school lockout gates by the spell's school +// (`Unit::IsSpellSchoolLocked`); stun / fear / confuse / charm / possess gate +// every cast (UNIT_STAT_STUNNED / FLEEING / CONFUSED, or control handed to +// another unit); silence and pacify gate by the spell's PreventionType +// (UNIT_FLAG_SILENCED ↔ SPELL_PREVENTION_TYPE_SILENCE, UNIT_FLAG_PACIFIED ↔ +// _PACIFY). Root and disarm stop no cast. +bool Blocks(const LocEntry &e, int schoolIdx, int preventionType) { + const char *t = e.locType; + if (std::strcmp(t, "SCHOOL_INTERRUPT") == 0) + return (e.schoolMask & (1 << schoolIdx)) != 0; + if (std::strcmp(t, "STUN") == 0 || std::strcmp(t, "FEAR") == 0 || + std::strcmp(t, "CONFUSE") == 0 || std::strcmp(t, "CHARM") == 0 || + std::strcmp(t, "POSSESS") == 0) + return true; + const bool both = std::strcmp(t, "PACIFYSILENCE") == 0; + if ((both || std::strcmp(t, "SILENCE") == 0) && + preventionType == Offsets::SPELL_PREVENTION_TYPE_SILENCE) + return true; + if ((both || std::strcmp(t, "PACIFY") == 0) && + preventionType == Offsets::SPELL_PREVENTION_TYPE_PACIFY) + return true; + return false; +} + // ---- LOSS_OF_CONTROL_ADDED / _UPDATE events (WorldTick poll-and-diff) ------ // // Effect *expiry* (a school lockout timing out, a CC aura falling off) has no @@ -334,6 +361,34 @@ int __fastcall Script_GetActiveLossOfControlData(void *L) { } // namespace +bool LockoutForSpell(int spellID, uint32_t *startMs, uint32_t *endMs) { + const uint8_t *rec = Spell::Lookup::RecordForID(spellID); + if (rec == nullptr) + return false; + const int school = SpellSchoolIndex(rec); + const int prevention = + Game::Read(rec, Offsets::OFF_SPELL_RECORD_PREVENTION_TYPE); + + LocEntry entries[32]; + const int n = BuildList(entries, 32); + const uint32_t now = NowMs(); + bool found = false; + for (int i = 0; i < n; ++i) { + const LocEntry &e = entries[i]; + if (e.endMs == 0 || Reached(now, e.endMs)) + continue; // timing unknown, or already over + if (!Blocks(e, school, prevention)) + continue; + if (!found || Time::Clock::Remaining(now, e.endMs) > + Time::Clock::Remaining(now, *endMs)) { + *startMs = e.startMs; + *endMs = e.endMs; + found = true; + } + } + return found; +} + static void RegisterLuaFunctions() { Game::Lua::RegisterTableFunction( "C_LossOfControl", "GetActiveLossOfControlDataCount", diff --git a/src/lossofcontrol/Lockout.h b/src/lossofcontrol/Lockout.h new file mode 100644 index 00000000..0922b183 --- /dev/null +++ b/src/lossofcontrol/Lockout.h @@ -0,0 +1,37 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU 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 General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#pragma once + +#include + +namespace LossOfControl { + +// The loss-of-control effect currently blocking the local player from +// casting `spellID`, if any: writes its start / end engine ticks (unsigned +// ms, `GetTime()` epoch — see `Time::Clock`) and returns true. Considers +// only effects with KNOWN timing (a school lockout, or a CC aura whose +// applying cast was observed) — an effect with unknown timing has nothing a +// cooldown display could show. When several effects block the spell, the +// one ending last wins. Returns false for an unknown `spellID`. +// +// Which effects block which spells restates the server's cast gates: +// SCHOOL_INTERRUPT → spells of the locked school +// STUN / FEAR / CONFUSE / CHARM / POSSESS → every spell +// SILENCE → spells with PreventionType SILENCE (1) +// PACIFY → spells with PreventionType PACIFY (2) +// PACIFYSILENCE → both of the above +// ROOT / DISARM → nothing (neither stops a cast) +bool LockoutForSpell(int spellID, uint32_t *startMs, uint32_t *endMs); + +} // namespace LossOfControl diff --git a/src/lossofcontrol/SpellCooldown.cpp b/src/lossofcontrol/SpellCooldown.cpp new file mode 100644 index 00000000..430fa48a --- /dev/null +++ b/src/lossofcontrol/SpellCooldown.cpp @@ -0,0 +1,139 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU 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 General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +// `C_Spell.GetSpellLossOfControlCooldown(spellIdentifier)` -> +// startTime, duration +// `C_SpellBook.GetSpellBookItemLossOfControlCooldownInfo(slotIndex, +// spellBank)` -> SpellLossOfControlInfo | nil +// `C_SpellBook.GetSpellBookItemLossOfControlCooldownDuration(slotIndex, +// spellBank)` -> duration | nil +// +// The per-spell view of `C_LossOfControl`: the control-loss effect that +// stops THIS spell, shaped as a cooldown (`GetTime()`-epoch seconds) so an +// action button can draw the loss-of-control swipe over it. +// `LossOfControl::LockoutForSpell` decides which effects block which spells; +// this file only converts ticks and builds the Lua shapes. +// +// An effect whose end is known but whose start is not (a CC aura seen only +// in the aura array) is reported as starting now and lasting the remaining +// time — the same swipe a button would draw, just without the elapsed part. + +#include "Lockout.h" + +#include "Game.h" +#include "spell/Arg.h" +#include "spell/Cooldown.h" +#include "spell/Lookup.h" +#include "time/Clock.h" + +#include + +namespace LossOfControl::SpellCooldown { + +namespace { + +using Time::Clock::NowMs; + +struct Lockout { + bool active; + uint32_t startMs; + uint32_t endMs; +}; + +Lockout ForSpell(int spellID) { + Lockout lock{false, 0, 0}; + if (!LockoutForSpell(spellID, &lock.startMs, &lock.endMs)) + return lock; + lock.active = true; + if (lock.startMs == 0) + lock.startMs = NowMs(); // end known, start not: swipe from now + return lock; +} + +double StartSeconds(const Lockout &lock) { + return static_cast(lock.startMs) * 0.001; +} + +double DurationSeconds(const Lockout &lock) { + if (!lock.active) + return 0.0; + return static_cast(Time::Clock::Elapsed(lock.startMs, lock.endMs)) * + 0.001; +} + +// True when the lockout outlasts the spell's own cooldown — the case where +// a button should draw the loss-of-control swipe instead of the normal one. +bool OutlastsNormalCooldown(int spellID, const Lockout &lock) { + if (!lock.active) + return false; + uint32_t cdStart = 0, cdDuration = 0; + bool enabled = false; + if (!Spell::Cooldown::Query(spellID, &cdStart, &cdDuration, &enabled) || + cdDuration == 0) + return true; + const uint32_t now = NowMs(); + return Time::Clock::Remaining(now, lock.endMs) > + Time::Clock::Remaining(now, cdStart + cdDuration); +} + +int __fastcall Script_C_Spell_GetSpellLossOfControlCooldown(void *L) { + const int spellID = Spell::Arg::ResolveSpellID(L, 1); + if (Spell::Lookup::RecordForID(spellID) == nullptr) + return 0; + const Lockout lock = ForSpell(spellID); + Game::Lua::PushNumber(L, lock.active ? StartSeconds(lock) : 0.0); + Game::Lua::PushNumber(L, DurationSeconds(lock)); + return 2; +} + +int __fastcall Script_GetSpellBookItemLossOfControlCooldownInfo(void *L) { + const int spellID = Spell::Lookup::SpellbookItemArgsToID(L, 1, 2); + if (spellID <= 0) + return 0; // empty / out-of-range slot -> nil + const Lockout lock = ForSpell(spellID); + Game::Lua::NewTable(L); + Game::Lua::SetFieldNumber(L, "startTime", + lock.active ? StartSeconds(lock) : 0.0); + Game::Lua::SetFieldNumber(L, "duration", DurationSeconds(lock)); + Game::Lua::SetFieldNumber(L, "modRate", 1.0); + Game::Lua::SetFieldBool(L, "isActive", lock.active); + Game::Lua::SetFieldBool(L, "shouldReplaceNormalCooldown", + OutlastsNormalCooldown(spellID, lock)); + return 1; +} + +int __fastcall Script_GetSpellBookItemLossOfControlCooldownDuration(void *L) { + const int spellID = Spell::Lookup::SpellbookItemArgsToID(L, 1, 2); + if (spellID <= 0) + return 0; + Game::Lua::PushNumber(L, DurationSeconds(ForSpell(spellID))); + return 1; +} + +void RegisterLuaFunctions() { + Game::Lua::RegisterTableFunction( + "C_Spell", "GetSpellLossOfControlCooldown", + &Script_C_Spell_GetSpellLossOfControlCooldown); + Game::Lua::RegisterTableFunction( + "C_SpellBook", "GetSpellBookItemLossOfControlCooldownInfo", + &Script_GetSpellBookItemLossOfControlCooldownInfo); + Game::Lua::RegisterTableFunction( + "C_SpellBook", "GetSpellBookItemLossOfControlCooldownDuration", + &Script_GetSpellBookItemLossOfControlCooldownDuration); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +} // namespace + +} // namespace LossOfControl::SpellCooldown diff --git a/src/spell/CastCount.cpp b/src/spell/CastCount.cpp new file mode 100644 index 00000000..1914b504 --- /dev/null +++ b/src/spell/CastCount.cpp @@ -0,0 +1,93 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU 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 General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +// `C_Spell.GetSpellCastCount(spellIdentifier)` / +// `C_SpellBook.GetSpellBookItemCastCount(slotIndex, spellBank)` — how many +// times a spell can be cast with the reagents the player carries. +// +// There is no engine helper to mirror: 1.12's action-button count +// (`Script_GetActionCount` → 0x004E6C70, `Script_IsConsumableAction` → +// 0x004E5250) is ITEM-only — both gate on the action tag `0x80000000` and +// read the item stack cache — so a reagent-based count was never computed +// client-side. This is the server's own cast gate (`Spell::CheckItems` → +// `Player::HasItemCount(reagent, count)`) restated as a count: the minimum +// over the spell's reagent slots of floor(carried / required), where +// "carried" is equipped + bags 0..4 — the inventory the server checks; bank +// contents never satisfy a reagent. Spells with no reagents return 0, +// matching retail's `GetSpellCastCount`. + +#include "Arg.h" +#include "Lookup.h" + +#include "Game.h" +#include "Offsets.h" +#include "item/Count.h" + +#include + +namespace Spell::CastCount { + +namespace { + +// Reagent-limited casts of `spellID`; 0 for unknown spells and for spells +// with no reagents. Clobbers the Lua stack (the bag walk goes through the +// engine's slot packer), so callers read their arguments first. +int ForSpell(void *L, int spellID) { + const uint8_t *record = Spell::Lookup::RecordForID(spellID); + if (record == nullptr) + return 0; + auto *ids = Game::Ptr(record, Offsets::OFF_SPELL_REAGENT_ID); + auto *counts = + Game::Ptr(record, Offsets::OFF_SPELL_REAGENT_COUNT); + int casts = -1; + for (int i = 0; i < Offsets::SPELL_MAX_REAGENTS; ++i) { + if (ids[i] == 0) + break; // engine convention: the list ends at the first empty slot + if (counts[i] <= 0) + continue; + const int possible = Item::Count::InInventory(L, ids[i]) / counts[i]; + if (casts < 0 || possible < casts) + casts = possible; + } + return casts < 0 ? 0 : casts; +} + +int __fastcall Script_C_Spell_GetSpellCastCount(void *L) { + const int spellID = Spell::Arg::ResolveSpellID(L, 1); + const int casts = ForSpell(L, spellID); + Game::Lua::SetTop(L, 0); + Game::Lua::PushNumber(L, static_cast(casts)); + return 1; +} + +int __fastcall Script_C_SpellBook_GetSpellBookItemCastCount(void *L) { + const int spellID = Spell::Lookup::SpellbookItemArgsToID(L, 1, 2); + const int casts = ForSpell(L, spellID); + Game::Lua::SetTop(L, 0); + Game::Lua::PushNumber(L, static_cast(casts)); + return 1; +} + +void RegisterLuaFunctions() { + Game::Lua::RegisterTableFunction("C_Spell", "GetSpellCastCount", + &Script_C_Spell_GetSpellCastCount); + Game::Lua::RegisterTableFunction( + "C_SpellBook", "GetSpellBookItemCastCount", + &Script_C_SpellBook_GetSpellBookItemCastCount); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +} // namespace + +} // namespace Spell::CastCount diff --git a/src/spell/Cooldown.cpp b/src/spell/Cooldown.cpp index 6eddd378..c2eafcbd 100644 --- a/src/spell/Cooldown.cpp +++ b/src/spell/Cooldown.cpp @@ -19,6 +19,8 @@ // Same `FUN_SPELL_QUERY_COOLDOWN` helper `Spell::Usable` uses for // the cooldown gate, just exposed through the modern table shape. +#include "Cooldown.h" + #include "Arg.h" #include "Lookup.h" @@ -44,14 +46,11 @@ using QueryCooldown_t = void(__fastcall *)(int spellID, int bookType, int __fastcall Script_C_Spell_GetSpellCooldown(void *L) { const int spellID = Spell::Arg::ResolveSpellID(L, 1); - if (spellID <= 0 || Spell::Lookup::RecordForID(spellID) == nullptr) + uint32_t durationMs = 0, startMs = 0; + bool enabled = false; + if (!Query(spellID, &startMs, &durationMs, &enabled)) return 0; - auto fn = reinterpret_cast( - static_cast(Offsets::FUN_SPELL_QUERY_COOLDOWN)); - uint32_t durationMs = 0, startMs = 0, enable = 0; - fn(spellID, 0 /* bookType=player */, &durationMs, &startMs, &enable); - Game::Lua::NewTable(L); // Engine returns ms with the same epoch as `GetTime()` — multiply // by 0.001 to match modern's seconds-from-`GetTime` shape, same @@ -60,7 +59,7 @@ int __fastcall Script_C_Spell_GetSpellCooldown(void *L) { static_cast(startMs) * 0.001); Game::Lua::SetFieldNumber(L, "duration", static_cast(durationMs) * 0.001); - Game::Lua::SetFieldBool(L, "isEnabled", enable != 0); + Game::Lua::SetFieldBool(L, "isEnabled", enabled); // Vanilla has no haste-on-cooldown mechanic. Hard-code 1.0 so // modern code that divides remaining-time by `modRate` works. Game::Lua::SetFieldNumber(L, "modRate", 1.0); @@ -73,6 +72,20 @@ int __fastcall Script_C_Spell_GetSpellCooldown(void *L) { } // namespace +bool Query(int spellID, uint32_t *startMs, uint32_t *durationMs, + bool *enabled) { + if (spellID <= 0 || Spell::Lookup::RecordForID(spellID) == nullptr) + return false; + auto fn = reinterpret_cast( + static_cast(Offsets::FUN_SPELL_QUERY_COOLDOWN)); + uint32_t duration = 0, start = 0, enable = 0; + fn(spellID, 0 /* bookType=player */, &duration, &start, &enable); + *startMs = start; + *durationMs = duration; + *enabled = enable != 0; + return true; +} + static void RegisterLuaFunctions() { Game::Lua::RegisterTableFunction("C_Spell", "GetSpellCooldown", &Script_C_Spell_GetSpellCooldown); diff --git a/src/spell/Cooldown.h b/src/spell/Cooldown.h new file mode 100644 index 00000000..73fb3c19 --- /dev/null +++ b/src/spell/Cooldown.h @@ -0,0 +1,29 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU 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 General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#pragma once + +#include + +namespace Spell::Cooldown { + +// The engine's own cooldown query (`FUN_SPELL_QUERY_COOLDOWN`) for the +// local player's `spellID`: start tick and duration in engine milliseconds +// (unsigned, `GetTime()` epoch — see `Time::Clock`), and whether the +// cooldown is enabled (false = "on hold"). Both times are 0 when no +// cooldown is active. Returns false without touching the outputs when +// `spellID` has no Spell.dbc row. +bool Query(int spellID, uint32_t *startMs, uint32_t *durationMs, + bool *enabled); + +} // namespace Spell::Cooldown diff --git a/src/spell/Info.cpp b/src/spell/Info.cpp index 553b1c76..bfe33158 100644 --- a/src/spell/Info.cpp +++ b/src/spell/Info.cpp @@ -13,7 +13,6 @@ #include "Game.h" #include "Offsets.h" -#include "player/StatSignal.h" #include "spell/Arg.h" #include "spell/Lookup.h" @@ -480,55 +479,22 @@ static bool PlayerKnowsSpell(int spellID) { return (bitmap[spellID >> 5] & mask) != 0; } -// `C_SpellBook.GetPlayerSpellsByAura(auraName)` -> { spellID, ... } -// -// Every spell the player currently knows whose Spell.dbc record has an -// effect applying aura `auraName` (an EffectApplyAuraName code — 134 for -// MOD_MANA_REGEN_INTERRUPT, 217 for Turtle's MOD_ENERGY_REGEN_TIME, ...), -// as a 1-based ascending array of spell IDs. -// -// This is `IsPlayerSpell` turned around: rather than asking about one -// spell, it walks the same known-spell bitmap and reports the set bits -// whose record carries the aura. Only a set bit ever touches a record, -// so the cost is a few hundred lookups, not the ~28,000-row table — and -// it is the right table to walk, because "which of MY spells apply this" -// is the question a caller summing aura amounts is actually asking. The -// bitmap holds only a talent's CURRENT rank, so such a sum never -// double-counts ranks. -// -// Known is not the same as active. For a passive it is — known means in -// effect, and a passive never appears in the buff list. A castable buff -// in this result is merely learned; whether it is up is a buff-list -// question, and a buff another player put on us is not in the bitmap at -// all. Callers split on `C_Spell.IsSpellPassive` accordingly. -// -// `auraName` 0 means "applies no aura" and would match most of what the -// player knows, so it and negatives return the empty array. Empty before -// login too, when the bitmap is not yet allocated. -static int __fastcall Script_GetPlayerSpellsByAura(void *L) { - if (!Game::Lua::IsNumber(L, 1)) { - Game::Lua::Error(L, - "Usage: C_SpellBook.GetPlayerSpellsByAura(auraName)"); - return 0; - } - const int auraName = static_cast(Game::Lua::ToNumber(L, 1)); - - Game::Lua::SetTop(L, 0); - Game::Lua::NewTable(L); - if (auraName <= 0) - return 1; - +// Walks the known-spell bitmap and calls `fn(spellID, record)` for every +// set bit that has a Spell.dbc row, in ascending spellID order, until `fn` +// returns false. This is `IsPlayerSpell` turned around: only a set bit ever +// touches a record, so a full pass costs a few hundred lookups, not the +// ~28,000-row table. The bitmap covers spellIDs 0..spellCount inclusive, +// one bit each, so the last word is index spellCount >> 5; zero words — the +// vast majority — cost one compare. No-op before login, when the bitmap is +// not yet allocated. +template +static void ForEachKnownSpell(F fn) { auto *bitmap = Game::Read( static_cast(Offsets::VAR_PLAYER_SPELL_BITMAP)); if (bitmap == nullptr) - return 1; + return; const int spellCount = Game::Read( static_cast(Offsets::VAR_SPELL_RECORD_COUNT)); - - // The bitmap covers spellIDs 0..spellCount inclusive, one bit each, - // so the last word is index spellCount >> 5. Zero words — the vast - // majority — cost one compare. - int n = 0; for (int word = 0; word <= (spellCount >> 5); ++word) { const uint32_t bits = bitmap[word]; if (bits == 0) @@ -542,18 +508,82 @@ static int __fastcall Script_GetPlayerSpellsByAura(void *L) { const uint8_t *record = Spell::Lookup::RecordForID(spellID); if (record == nullptr) continue; - auto *auras = reinterpret_cast( - record + Offsets::OFF_SPELL_RECORD_EFFECT_APPLY_AURA_NAME); - for (int e = 0; e < Offsets::SPELL_RECORD_EFFECT_COUNT; ++e) { - if (auras[e] == auraName) { - Game::Lua::PushNumber(L, static_cast(++n)); - Game::Lua::PushNumber(L, static_cast(spellID)); - Game::Lua::RawSet(L, -3); - break; // one entry per spell, however many effects match - } - } + if (!fn(spellID, record)) + return; } } +} + +// `C_SpellBook.GetPlayerSpellsByAura(auraName)` -> { spellID, ... } +// +// Every spell the player currently knows whose Spell.dbc record has an +// effect applying aura `auraName` (an EffectApplyAuraName code — 134 for +// MOD_MANA_REGEN_INTERRUPT, 217 for Turtle's MOD_ENERGY_REGEN_TIME, ...), +// as a 1-based ascending array of spell IDs. +// +// The known-spell bitmap is the right table to walk, because "which of MY +// spells apply this" is the question a caller summing aura amounts is +// actually asking. The bitmap holds only a talent's CURRENT rank, so such +// a sum never double-counts ranks. +// +// Known is not the same as active. For a passive it is — known means in +// effect, and a passive never appears in the buff list. A castable buff +// in this result is merely learned; whether it is up is a buff-list +// question, and a buff another player put on us is not in the bitmap at +// all. Callers split on `C_Spell.IsSpellPassive` accordingly. +// +// `auraName` 0 means "applies no aura" and would match most of what the +// player knows, so it and negatives return the empty array. Empty before +// login too. +static int __fastcall Script_GetPlayerSpellsByAura(void *L) { + if (!Game::Lua::IsNumber(L, 1)) { + Game::Lua::Error(L, + "Usage: C_SpellBook.GetPlayerSpellsByAura(auraName)"); + return 0; + } + const int auraName = static_cast(Game::Lua::ToNumber(L, 1)); + + Game::Lua::SetTop(L, 0); + Game::Lua::NewTable(L); + if (auraName <= 0) + return 1; + + int n = 0; + ForEachKnownSpell([&](int spellID, const uint8_t *record) { + auto *auras = reinterpret_cast( + record + Offsets::OFF_SPELL_RECORD_EFFECT_APPLY_AURA_NAME); + for (int e = 0; e < Offsets::SPELL_RECORD_EFFECT_COUNT; ++e) { + if (auras[e] == auraName) { + Game::Lua::PushNumber(L, static_cast(++n)); + Game::Lua::PushNumber(L, static_cast(spellID)); + Game::Lua::RawSet(L, -3); + break; // one entry per spell, however many effects match + } + } + return true; + }); + return 1; +} + +// `C_SpellBook.ContainsAnyDisenchantSpell()` -> bool. True iff the player +// knows a spell with SPELL_EFFECT_DISENCHANT. That is 13262 "Disenchant" +// (the only such row in Spell.dbc), but the test is data-driven like the +// retail original — "any disenchant spell" — so a custom variant a server +// adds counts too. +static int __fastcall Script_ContainsAnyDisenchantSpell(void *L) { + bool found = false; + ForEachKnownSpell([&](int, const uint8_t *record) { + auto *effects = reinterpret_cast( + record + Offsets::OFF_SPELL_RECORD_EFFECT); + for (int e = 0; e < Offsets::SPELL_RECORD_EFFECT_COUNT; ++e) { + if (effects[e] == Offsets::SPELL_EFFECT_DISENCHANT) { + found = true; + return false; + } + } + return true; + }); + Game::Lua::PushBool(L, found); return 1; } @@ -695,34 +725,8 @@ static int __fastcall Script_C_Spell_IsSpellHelpful(void *L) { return 1; } -// --- Known-spell-bitmap change signal ------------------------------------ -// Learning/unlearning a spell rewrites the bitmap GetSpellBonusHealing scans -// for talent conversions (Spiritual Guidance / Ironclad). Co-hook the engine's -// learn + unlearn writers and bump Player::StatSignal, so a talent respec -// invalidates the healing cache immediately — the same event-driven path as -// aura/equipment changes, no polling. Both fire only at login and on -// learn/unlearn (never per-frame), so they're safe co-hook targets. -using LearnSpell_t = void(__fastcall *)(uint32_t spellID, int notify, - uint32_t replacedSpellID); -static LearnSpell_t g_origLearnSpell = nullptr; -static void __fastcall LearnSpell_h(uint32_t spellID, int notify, - uint32_t replacedSpellID) { - g_origLearnSpell(spellID, notify, replacedSpellID); - Player::StatSignal::Notify(); -} -static const Game::HookAutoRegister _hookLearnSpell{ - Offsets::FUN_LEARN_SPELL, reinterpret_cast(&LearnSpell_h), - reinterpret_cast(&g_origLearnSpell)}; - -using UnlearnSpell_t = void(__fastcall *)(uint32_t spellID, int param2); -static UnlearnSpell_t g_origUnlearnSpell = nullptr; -static void __fastcall UnlearnSpell_h(uint32_t spellID, int param2) { - g_origUnlearnSpell(spellID, param2); - Player::StatSignal::Notify(); -} -static const Game::HookAutoRegister _hookUnlearnSpell{ - Offsets::FUN_UNLEARN_SPELL, reinterpret_cast(&UnlearnSpell_h), - reinterpret_cast(&g_origUnlearnSpell)}; +// The learn / unlearn writer co-hooks (Player::StatSignal bump + +// LEARNED_SPELL_IN_SKILL_LINE) live in spell/Learn.cpp. // Enum.SpellBookItemType values (retail). Vanilla's spellbook only ever // produces real spells, so we emit Spell (player book) or PetAction (pet @@ -753,10 +757,7 @@ static int __fastcall Script_C_SpellBook_GetSpellBookItemInfo(void *L) { if (!Game::Lua::IsNumber(L, 1)) return 0; // modern returns nil (not an error) for a bad index const int slot = static_cast(Game::Lua::ToNumber(L, 1)); - const int bank = Game::Lua::IsNumber(L, 2) - ? static_cast(Game::Lua::ToNumber(L, 2)) - : 0; - const int bookType = (bank == 1) ? 1 : 0; // 1 = pet book, else player + const int bookType = Spell::Lookup::SpellBankArgToBookType(L, 2); const int spellID = Spell::Lookup::SpellbookSlotToID(slot, bookType); if (spellID <= 0) @@ -811,6 +812,8 @@ static void RegisterLuaFunctions() { &Script_C_SpellBook_GetSpellBookItemInfo); Game::Lua::RegisterTableFunction("C_SpellBook", "GetPlayerSpellsByAura", &Script_GetPlayerSpellsByAura); + Game::Lua::RegisterTableFunction("C_SpellBook", "ContainsAnyDisenchantSpell", + &Script_ContainsAnyDisenchantSpell); Game::Lua::RegisterIntegerEnum("Enum", "SpellBookSpellBank", kSpellBookSpellBankEntries, 2); Game::Lua::RegisterIntegerEnum("Enum", "SpellBookItemType", diff --git a/src/spell/Learn.cpp b/src/spell/Learn.cpp new file mode 100644 index 00000000..2bb4ad67 --- /dev/null +++ b/src/spell/Learn.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 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 General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +// `Spell::Learn` — co-hooks the engine's learn / unlearn writers +// (`FUN_LEARN_SPELL` / `FUN_UNLEARN_SPELL`), the two functions that mutate +// the known-spell bitmap. Two duties: +// +// 1. Bump `Player::StatSignal` so caches keyed on spell knowledge (the +// talent-conversion cache behind GetSpellBonusHealing — Spiritual +// Guidance / Ironclad) invalidate the moment a respec lands. Same +// event-driven path aura / equipment changes take; no polling. +// 2. Fire the modern `LEARNED_SPELL_IN_SKILL_LINE(spellID, skillLineIndex, +// isGuildPerkSpell)` next to the engine's own `LEARNED_SPELL_IN_TAB +// (tabIndex)`. The engine fires its event only when `notify != 0` AND it +// appended the spell to the player spellbook array (decompile notes at +// `Offsets::FUN_LEARN_SPELL`). We reproduce that exact gate by diffing +// `VAR_PLAYER_SPELLBOOK_COUNT` across the original call, then map the +// new slot to its tab through `Spell::Tabs`. Login's bulk +// SMSG_INITIAL_SPELLS passes notify = 0, so neither event fires there. +// +// Both writers run only at login and on learn / unlearn — never per-frame — +// so they are safe co-hook targets. + +#include "Game.h" +#include "Offsets.h" +#include "event/Custom.h" +#include "player/StatSignal.h" +#include "spell/Lookup.h" +#include "spell/Tabs.h" + +#include + +namespace Spell::Learn { + +namespace { + +const Event::Custom::AutoReserve _evtLearned{"LEARNED_SPELL_IN_SKILL_LINE"}; + +int PlayerBookCount() { + return Game::Read(Offsets::VAR_PLAYER_SPELLBOOK_COUNT); +} + +using LearnSpell_t = void(__fastcall *)(uint32_t spellID, int notify, + uint32_t replacedSpellID); +LearnSpell_t g_origLearnSpell = nullptr; + +void __fastcall LearnSpell_h(uint32_t spellID, int notify, + uint32_t replacedSpellID) { + const int before = PlayerBookCount(); + g_origLearnSpell(spellID, notify, replacedSpellID); + Player::StatSignal::Notify(); + + // The engine's LEARNED_SPELL_IN_TAB gate: notified AND added to the + // book. The original sorts the array before its own fire, so the slot + // lookup below already sees the final position. + if (notify == 0 || PlayerBookCount() <= before) + return; + int bookType = -1; + const int slot = Spell::Lookup::FindSpellbookSlot( + static_cast(spellID), &bookType); + if (slot <= 0 || bookType != 0) + return; + const int tab = Spell::Tabs::IndexForSlot(slot); + if (tab <= 0) + return; + // isGuildPerkSpell is always false: pushed as nil (falsy) through the + // dispatcher's `%s` + NULL → lua_pushnil path (see Event::Custom::Fire). + Event::Custom::Fire(_evtLearned.Slot(), "%d%d%s", + static_cast(spellID), tab, + static_cast(nullptr)); +} + +using UnlearnSpell_t = void(__fastcall *)(uint32_t spellID, int param2); +UnlearnSpell_t g_origUnlearnSpell = nullptr; + +void __fastcall UnlearnSpell_h(uint32_t spellID, int param2) { + g_origUnlearnSpell(spellID, param2); + Player::StatSignal::Notify(); +} + +} // namespace + +static const Game::HookAutoRegister _hookLearnSpell{ + Offsets::FUN_LEARN_SPELL, reinterpret_cast(&LearnSpell_h), + reinterpret_cast(&g_origLearnSpell)}; + +static const Game::HookAutoRegister _hookUnlearnSpell{ + Offsets::FUN_UNLEARN_SPELL, reinterpret_cast(&UnlearnSpell_h), + reinterpret_cast(&g_origUnlearnSpell)}; + +} // namespace Spell::Learn diff --git a/src/spell/Level.cpp b/src/spell/Level.cpp index 34703df7..02f1a49c 100644 --- a/src/spell/Level.cpp +++ b/src/spell/Level.cpp @@ -14,6 +14,7 @@ #include "Game.h" #include "Offsets.h" #include "spell/Lookup.h" +#include "talent/SpellSet.h" #include #include @@ -34,43 +35,6 @@ const uint8_t *PlayerDescriptor() { player, Offsets::OFF_UNIT_DESCRIPTOR); } -// Builds (or returns the cached) set of every spellID that appears -// in `Talent.dbc` — across all 9 rank slots of every talent record. -// Used to skip talent-tree spells in `GetCurrentLevelSpells`; modern -// `GetCurrentLevelSpells` only reports auto-learned / trainable -// class spells, never talents (which are point-purchased separately). -// -// Cache survives across calls in a session (Talent.dbc is a static -// DBC). First call before the engine has loaded the DBC (e.g., -// pre-login) leaves the set empty; subsequent calls retry until -// non-empty. -std::unordered_set &TalentSpellSet() { - static std::unordered_set set; - if (!set.empty()) - return set; - const uint8_t *const *records = Game::Read( - static_cast(Offsets::VAR_TALENT_DBC_RECORDS)); - const int count = Game::Read( - static_cast(Offsets::VAR_TALENT_DBC_COUNT)); - if (records == nullptr || count <= 0) - return set; - // Each Talent.dbc record stores rank-N spellIDs at +0x10 + N*4 - // for N = 0..8 (9 ranks). Many slots are 0 for unused ranks. - for (int i = 1; i <= count; ++i) { - const uint8_t *rec = records[i]; - if (rec == nullptr) - continue; - auto *ranks = Game::Ptr( - rec, Offsets::OFF_TALENT_SPELL_RANK); - for (int j = 0; j < 9; ++j) { - const uint32_t spellID = ranks[j]; - if (spellID != 0) - set.insert(static_cast(spellID)); - } - } - return set; -} - // Looks up the `BaseLevel` field of a Spell.dbc record. Returns 0 // for invalid spellIDs or records the engine doesn't have cached. int SpellBaseLevel(int spellID) { @@ -412,7 +376,7 @@ int __fastcall Script_GetCurrentLevelSpells(void *L) { // Skip talents — they're class spells in SLA but learned via // talent points, not auto-granted at level. Modern's // GetCurrentLevelSpells excludes them too. - if (TalentSpellSet().count(spellID) != 0) + if (Talent::SpellSet::IsTalentRank(spellID)) continue; // Skip engine-internal spellbook-hidden spells (HIDDEN_CLIENTSIDE): // they can carry a BaseLevel but never surface as learnable. diff --git a/src/spell/Lookup.cpp b/src/spell/Lookup.cpp index d68bd4b0..0544130e 100644 --- a/src/spell/Lookup.cpp +++ b/src/spell/Lookup.cpp @@ -13,6 +13,7 @@ #include "Lookup.h" +#include "Game.h" #include "Offsets.h" #include "dbc/Lookup.h" @@ -50,6 +51,19 @@ int SpellbookSlotToID(int slot1Based, int bookType) { return array[slot]; } +int SpellBankArgToBookType(void *L, int idx) { + if (!Game::Lua::IsNumber(L, idx)) + return 0; + return static_cast(Game::Lua::ToNumber(L, idx)) == 1 ? 1 : 0; +} + +int SpellbookItemArgsToID(void *L, int slotIdx, int bankIdx) { + if (!Game::Lua::IsNumber(L, slotIdx)) + return 0; + const int slot = static_cast(Game::Lua::ToNumber(L, slotIdx)); + return SpellbookSlotToID(slot, SpellBankArgToBookType(L, bankIdx)); +} + int RecipeSlotSpellID(uintptr_t entriesVar, uintptr_t countVar, int slotIndex0) { if (slotIndex0 < 0) return 0; diff --git a/src/spell/Lookup.h b/src/spell/Lookup.h index abdc35e7..71f8ad91 100644 --- a/src/spell/Lookup.h +++ b/src/spell/Lookup.h @@ -43,6 +43,18 @@ bool IsFitToFamily(const uint8_t *spellRecord, uint32_t family, // - "pet" → 1 (pet) int SpellbookSlotToID(int slot1Based, int bookType); +// Modern `Enum.SpellBookSpellBank` argument at Lua stack `idx` → the engine +// bookType above. `1` (Pet) selects the pet book; a missing arg, a +// non-number, or any other value reads as the player book — the same +// tolerance `C_SpellBook.GetSpellBookItemInfo` established. +int SpellBankArgToBookType(void *L, int idx); + +// The modern `(slotIndex, spellBank)` argument pair at Lua stack +// `slotIdx` / `bankIdx` → the spellID in that slot. 0 when the slot arg is +// not a number or the slot is empty / out of range. Pure stack reads — the +// caller may still read other arguments afterwards. +int SpellbookItemArgsToID(void *L, int slotIdx, int bankIdx); + // Inverse of `SpellbookSlotToID` — finds the 1-based slot where a // given `spellID` lives in the spellbook arrays. Searches the player // book first (`bookType=0`), then the pet book (`bookType=1`). On a diff --git a/src/spell/Tabs.cpp b/src/spell/Tabs.cpp new file mode 100644 index 00000000..b834f5e8 --- /dev/null +++ b/src/spell/Tabs.cpp @@ -0,0 +1,165 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU 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 General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +// `C_SpellBook.GetNumSpellBookSkillLines` / `GetSpellBookSkillLineInfo` / +// `GetSpellBookItemSkillLineIndex` / `GetSkillLineIndexByID` — the modern +// skill-line view of the spellbook tabs. +// +// The engine's tab array (`Offsets::VAR_SPELL_TAB_ENTRIES`) stores each +// tab's SkillLine.dbc ID next to its spell count, but the stock Lua surface +// (`GetSpellTabInfo`) exposes only name / texture / offset / count — neither +// the ID nor the slot → tab direction was ever reachable from Lua. Both are +// direct reads of that array here. `GetSpellBookSkillLineInfo` calls the +// engine's own `Script_GetSpellTabInfo` for the name / icon so the +// GENERAL-tab localization and the SkillLine → SpellIcon chain stay the +// engine's, then reshapes its four returns into the modern table. + +#include "Tabs.h" + +#include "Game.h" +#include "Lookup.h" +#include "Offsets.h" + +#include + +namespace Spell::Tabs { + +namespace { + +const uint8_t *TabEntry(int index0) { + auto *entries = Game::Read( + Offsets::VAR_SPELL_TAB_ENTRIES); + if (entries == nullptr) + return nullptr; + return entries[index0]; +} + +using ScriptFn_t = int(__fastcall *)(void *L); + +// `C_SpellBook.GetNumSpellBookSkillLines()` -> number. +int __fastcall Script_GetNumSpellBookSkillLines(void *L) { + Game::Lua::PushNumber(L, static_cast(Count())); + return 1; +} + +// `C_SpellBook.GetSpellBookSkillLineInfo(skillLineIndex)` -> table, or nil +// for an index outside `[1, Count()]`. +int __fastcall Script_GetSpellBookSkillLineInfo(void *L) { + if (!Game::Lua::IsNumber(L, 1)) + return 0; + const int index = static_cast(Game::Lua::ToNumber(L, 1)); + if (index < 1 || index > Count()) + return 0; + + // The engine function reads L[1] (our index) and pushes + // `name, texture, offset, numSpells`. Stack afterwards: + // [index, name, texture, offset, numSpells]. + Game::Lua::SetTop(L, 1); + reinterpret_cast( + static_cast(Offsets::FUN_SCRIPT_GET_SPELL_TAB_INFO))(L); + + Game::Lua::NewTable(L); + Game::Lua::SetFieldString(L, "name", Game::Lua::ToString(L, 2)); + // `iconID` is the texture PATH — the same deviation as + // `C_SpellBook.GetSpellBookItemInfo`'s iconID (no fileIDs here). + Game::Lua::SetFieldString(L, "iconID", Game::Lua::ToString(L, 3)); + Game::Lua::SetFieldNumber(L, "itemIndexOffset", Game::Lua::ToNumber(L, 4)); + Game::Lua::SetFieldNumber(L, "numSpellBookItems", + Game::Lua::ToNumber(L, 5)); + Game::Lua::SetFieldBool(L, "isGuild", false); + Game::Lua::SetFieldBool(L, "shouldHide", false); + // specID / offSpecID stay nil — no specializations. + return 1; +} + +// `C_SpellBook.GetSpellBookItemSkillLineIndex(slotIndex, spellBank)` -> +// number, or nil for a pet-book slot (pets have no skill lines) or a slot +// past the populated range. +int __fastcall Script_GetSpellBookItemSkillLineIndex(void *L) { + if (!Game::Lua::IsNumber(L, 1)) + return 0; + if (Spell::Lookup::SpellBankArgToBookType(L, 2) != 0) + return 0; + const int index = IndexForSlot(static_cast(Game::Lua::ToNumber(L, 1))); + if (index <= 0) + return 0; + Game::Lua::PushNumber(L, static_cast(index)); + return 1; +} + +// `C_SpellBook.GetSkillLineIndexByID(skillLineID)` -> number, or nil when +// no tab carries that skill line. +int __fastcall Script_GetSkillLineIndexByID(void *L) { + if (!Game::Lua::IsNumber(L, 1)) + return 0; + const int index = + IndexForSkillLine(static_cast(Game::Lua::ToNumber(L, 1))); + if (index <= 0) + return 0; + Game::Lua::PushNumber(L, static_cast(index)); + return 1; +} + +void RegisterLuaFunctions() { + Game::Lua::RegisterTableFunction("C_SpellBook", "GetNumSpellBookSkillLines", + &Script_GetNumSpellBookSkillLines); + Game::Lua::RegisterTableFunction("C_SpellBook", "GetSpellBookSkillLineInfo", + &Script_GetSpellBookSkillLineInfo); + Game::Lua::RegisterTableFunction("C_SpellBook", + "GetSpellBookItemSkillLineIndex", + &Script_GetSpellBookItemSkillLineIndex); + Game::Lua::RegisterTableFunction("C_SpellBook", "GetSkillLineIndexByID", + &Script_GetSkillLineIndexByID); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +} // namespace + +int Count() { + return Game::Read(Offsets::VAR_SPELL_TAB_COUNT); +} + +int IndexForSlot(int slot1) { + if (slot1 < 1) + return 0; + const int slot0 = slot1 - 1; + const int count = Count(); + int offset = 0; + for (int i = 0; i < count; ++i) { + const uint8_t *entry = TabEntry(i); + if (entry == nullptr) + return 0; + const int n = Game::Read(entry, Offsets::OFF_SPELL_TAB_NUM_SPELLS); + if (slot0 < offset + n) + return i + 1; + offset += n; + } + return 0; +} + +int IndexForSkillLine(int skillLineID) { + if (skillLineID <= 0) + return 0; + const int count = Count(); + for (int i = 0; i < count; ++i) { + const uint8_t *entry = TabEntry(i); + if (entry != nullptr && + Game::Read(entry, Offsets::OFF_SPELL_TAB_SKILL_LINE_ID) == + skillLineID) + return i + 1; + } + return 0; +} + +} // namespace Spell::Tabs diff --git a/src/spell/Tabs.h b/src/spell/Tabs.h new file mode 100644 index 00000000..8cc6bfb9 --- /dev/null +++ b/src/spell/Tabs.h @@ -0,0 +1,33 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU 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 General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#pragma once + +// Spellbook TABS — the engine's per-skill-line partition of the player +// spellbook array (what `GetNumSpellTabs` / `GetSpellTabInfo` read). Layout +// notes at `Offsets::VAR_SPELL_TAB_ENTRIES`. +namespace Spell::Tabs { + +// Live tab count (what `GetNumSpellTabs()` returns). 0 before login. +int Count(); + +// 1-based index of the tab holding 1-based PLAYER-book slot `slot1`, or 0 +// when the slot is past the populated range. Pet-book slots have no tab. +int IndexForSlot(int slot1); + +// 1-based index of the tab whose SkillLine.dbc ID is `skillLineID`, or 0 +// when the player has no tab for that skill line. `skillLineID <= 0` is +// always 0 — the General tab stores ID 0 and is not addressable by ID. +int IndexForSkillLine(int skillLineID); + +} // namespace Spell::Tabs diff --git a/src/talent/SpellSet.cpp b/src/talent/SpellSet.cpp new file mode 100644 index 00000000..68249330 --- /dev/null +++ b/src/talent/SpellSet.cpp @@ -0,0 +1,127 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU 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 General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +// `Talent::SpellSet` plus its one Lua consumer, +// `C_SpellBook.IsClassTalentSpellBookItem(slotIndex, spellBank)`. + +#include "SpellSet.h" + +#include "Game.h" +#include "Offsets.h" +#include "spell/Lookup.h" + +#include +#include +#include + +namespace Talent::SpellSet { + +namespace { + +// Every spellID in a Talent.dbc rank column. Each record stores rank-N +// spellIDs at `OFF_TALENT_SPELL_RANK + N*4` for N = 0..8; unused ranks are 0. +// +// Cached for the session (Talent.dbc is static). A call before the engine +// has loaded the DBC (pre-login) leaves the set empty and later calls retry +// until it fills. +const std::unordered_set &RankSet() { + static std::unordered_set set; + if (!set.empty()) + return set; + auto *records = Game::Read( + Offsets::VAR_TALENT_DBC_RECORDS); + const int count = Game::Read(Offsets::VAR_TALENT_DBC_COUNT); + if (records == nullptr || count <= 0) + return set; + for (int i = 1; i <= count; ++i) { + const uint8_t *rec = records[i]; + if (rec == nullptr) + continue; + auto *ranks = Game::Ptr(rec, Offsets::OFF_TALENT_SPELL_RANK); + for (int j = 0; j < Offsets::TALENT_MAX_RANKS; ++j) { + if (ranks[j] != 0) + set.insert(static_cast(ranks[j])); + } + } + return set; +} + +// `RankSet` closed over SkillLineAbility's next-rank links: every talent +// rank spell plus each higher rank reachable from it (12294 → 21551 → +// 21552). Built once, after `RankSet` is available. +const std::unordered_set &LineSet() { + static std::unordered_set set; + if (!set.empty()) + return set; + const std::unordered_set &ranks = RankSet(); + if (ranks.empty()) + return set; + + // spellID -> the spell that supersedes it, from every SLA row that + // carries a link. + std::unordered_map next; + auto *records = Game::Read( + Offsets::VAR_SKILL_LINE_ABILITY_RECORDS); + const int count = Game::Read(Offsets::VAR_SKILL_LINE_ABILITY_COUNT); + if (records != nullptr) { + for (int i = 1; i <= count; ++i) { + const uint8_t *rec = records[i]; + if (rec == nullptr) + continue; + const int spellID = Game::Read(rec, Offsets::OFF_SLA_SPELL_ID); + const int superseded = + Game::Read(rec, Offsets::OFF_SLA_SUPERCEDED_BY_SPELL); + if (spellID > 0 && superseded > 0) + next[spellID] = superseded; + } + } + + for (int spellID : ranks) { + int cur = spellID; + // A chain is at most a handful of ranks; the bound guards a cyclic + // link in a modded DBC. + for (int hops = 0; cur > 0 && hops < 32 && set.insert(cur).second; ++hops) { + const auto it = next.find(cur); + cur = (it == next.end()) ? 0 : it->second; + } + } + return set; +} + +// `C_SpellBook.IsClassTalentSpellBookItem(slotIndex, spellBank)` -> bool. +// A pet-book slot is never a talent. +int __fastcall Script_IsClassTalentSpellBookItem(void *L) { + const bool isPet = Spell::Lookup::SpellBankArgToBookType(L, 2) != 0; + const int spellID = Spell::Lookup::SpellbookItemArgsToID(L, 1, 2); + Game::Lua::PushBool(L, !isPet && spellID > 0 && IsTalentLine(spellID)); + return 1; +} + +void RegisterLuaFunctions() { + Game::Lua::RegisterTableFunction("C_SpellBook", "IsClassTalentSpellBookItem", + &Script_IsClassTalentSpellBookItem); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +} // namespace + +bool IsTalentRank(int spellID) { + return RankSet().count(spellID) != 0; +} + +bool IsTalentLine(int spellID) { + return LineSet().count(spellID) != 0; +} + +} // namespace Talent::SpellSet diff --git a/src/talent/SpellSet.h b/src/talent/SpellSet.h new file mode 100644 index 00000000..21ac703f --- /dev/null +++ b/src/talent/SpellSet.h @@ -0,0 +1,33 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU 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 General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#pragma once + +// The set of spells that belong to talents, derived once per session from +// Talent.dbc (static data). Shared by `C_SpellBook.GetCurrentLevelSpells` +// (skips talents) and `C_SpellBook.IsClassTalentSpellBookItem`. +namespace Talent::SpellSet { + +// True iff `spellID` appears in a Talent.dbc rank column — the spell a +// talent point grants directly (any rank of a passive, or rank 1 of an +// active talent ability such as Mortal Strike 12294). +bool IsTalentRank(int spellID); + +// `IsTalentRank` extended along SkillLineAbility's next-rank links: also +// true for the trained higher ranks of a talent ability (Mortal Strike +// 21551, 21552, ...), which a spellbook lists next to the talent-granted +// rank 1. Coverage follows the links the DBC provides (see +// `Offsets::OFF_SLA_SUPERCEDED_BY_SPELL`). +bool IsTalentLine(int spellID); + +} // namespace Talent::SpellSet