From e8a03d584bf0518b613eb7ce45db6b36e2c52e60 Mon Sep 17 00:00:00 2001 From: Brues <5278969+brues-code@users.noreply.github.com> Date: Sat, 18 Jul 2026 03:51:20 -0500 Subject: [PATCH] spell: add GetSpellBonusDamage / GetSpellBonusHealing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GetSpellBonusDamage(school) reads the player's per-school spell damage directly from the CGPlayer sub-struct at [player+0xE68]+0xFD4 (POS) / +0xFF0 (NEG), net = POS-NEG. That field isn't in the broadcast descriptor (+0x110 reads zero — the vanilla server never sends it there), but the client keeps a fully-computed copy at +0xE68 with gear/enchants/buffs/talents/sets baked in. Same source nampower's GetSpellPower reads; verified 613 generic / 647 Fire on a geared mage. 1-based school, matching 3.3.5's Script_GetSpellBonusDamage. GetSpellBonusHealing() has no such field (vanilla lacks a healing-done field entirely), so it's derived to mirror the server's SpellBaseHealingBonusDone: - flat healing: SPELL_AURA_MOD_HEALING_DONE (135) off gear equip-effects, item enchants, random suffixes, and active buffs - Spirit conversion: SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT (175) x total Spirit / 100 (Priest Spiritual Guidance) - Armor conversion: SPELL_AURA_MOD_SPELL_HEALING_OF_ARMOR_PERCENT (199) x armor / 100 (Turtle Ironclad) Percents are read straight from Spell.dbc, so it's generic across any aura-175/199 talent/buff including Turtle customs, and gated on SPELL_ATTR_ PASSIVE for the known-spell-bitmap walk. Spirit/Armor come from UNIT_FIELD_ STAT4 (+0x250) / UNIT_FIELD_RESISTANCES[0] (+0x254). Item flat healing routes through the shared Item::StatAccum engine rather than re-implementing the item spell/suffix/enchant walk: extract a reusable ApplyEnchant() (from ApplyRandomSuffix) plus a Value() reader, and read ITEM_MOD_SPELL_HEALING_DONE_SHORT. The healing sum is expensive (StatAccum over 19 items + buff table + the 27k known-spell bitmap), so it's cached and recomputed only when a player stat input changes. New Player::StatSignal (a pull-based epoch) is bumped from the aura hooks (player-guarded), the equipment observer, and the spell learn/ unlearn writers (0x4B25B0 / 0x4B2C50) -- so buffs, gear, and talent respecs all invalidate instantly. A coarse world-tick recompute remains only as a backstop against a missed signal. --- README.md | 2 +- docs/API.md | 50 +++++++ src/Offsets.h | 58 ++++++++ src/aura/Source.cpp | 13 ++ src/item/StatAccum.cpp | 67 +++++---- src/item/StatAccum.h | 10 ++ src/player/Equipment.cpp | 4 + src/player/StatSignal.cpp | 28 ++++ src/player/StatSignal.h | 38 +++++ src/spell/BonusDamage.cpp | 293 ++++++++++++++++++++++++++++++++++++++ src/spell/Info.cpp | 30 ++++ 11 files changed, 564 insertions(+), 29 deletions(-) create mode 100644 src/player/StatSignal.cpp create mode 100644 src/player/StatSignal.h create mode 100644 src/spell/BonusDamage.cpp diff --git a/README.md b/README.md index 0fe94925..3c102b46 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Full per-function reference: **[docs/API.md](docs/API.md)**. | [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.GetQuestIDForLogIndex`, `C_QuestLog.GetTitleForQuestID`, `C_QuestLog.IsOnQuest`, `C_QuestLog.IsQuestDataCachedByID`, `C_QuestLog.IsUnitOnQuest`, `C_QuestLog.RequestLoadQuestByID`, `GetQuestLogLeaderBoardID` | | [Screen](docs/API.md#screen) | `GetPhysicalScreenSize` | -| [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.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.IsRangedAutoAttackSpell`, `C_Spell.IsSelfBuff`, `C_Spell.IsSpellHarmful`, `C_Spell.IsSpellHelpful`, `C_Spell.IsSpellInRange`, `C_Spell.IsSpellPassive`, `C_Spell.IsSpellUsable`, `C_Spell.SpellHasRange`, `C_Spell.UnitCastingInfo`, `C_Spell.UnitChannelInfo`, `CancelSpellByName`, `CastSpellNoToggle`, `GetCraftSpellID`, `GetSpellInfo`, `GetSpellLink`, `GetSpellRadius`, `GetSpellRequiredTargetLevel`, `GetSpellSchool`, `IsHarmfulSpell`, `IsHelpfulSpell`, `IsPassiveSpell`, `IsPlayerSpell`, `IsSpellKnown`, `IsUsableSpell`, `SpellHasRange` | +| [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.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.IsRangedAutoAttackSpell`, `C_Spell.IsSelfBuff`, `C_Spell.IsSpellHarmful`, `C_Spell.IsSpellHelpful`, `C_Spell.IsSpellInRange`, `C_Spell.IsSpellPassive`, `C_Spell.IsSpellUsable`, `C_Spell.SpellHasRange`, `C_Spell.UnitCastingInfo`, `C_Spell.UnitChannelInfo`, `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.GetSkillLineName`, `C_SpellBook.GetSkillLineRank`, `C_SpellBook.GetSpellLevelLearned`, `C_SpellBook.GetSpellSkillLine`, `C_SpellBook.IsAutoAttackSpellBookItem`, `C_SpellBook.IsRangedAutoAttackSpellBookItem`, `FindSpellBookSlotByID` | | [State](docs/API.md#state) | `CancelShapeshiftForm`, `Dismount`, `GetMirrorTimerInfo`, `GetMirrorTimerProgress`, `GetShapeshiftFormID`, `IsAssistingRitual`, `IsFalling`, `IsInGroup`, `IsInRaid`, `IsLoggedIn`, `IsMounted`, `IsStealthed`, `IsSwimming` | | [Table](docs/API.md#table) | `table.wipe` | diff --git a/docs/API.md b/docs/API.md index c76d8d38..423dc25c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -370,6 +370,8 @@ build instructions. - [`C_Spell.IsSpellPassive(spellID)`](#c_spellisspellpassivespellid) - [`IsPlayerSpell(spellID)`](#isplayerspellspellid) - [`IsSpellKnown(spellID, [isPet])`](#isspellknownspellid-ispet) + - [`GetSpellBonusDamage(school)`](#getspellbonusdamageschool) + - [`GetSpellBonusHealing()`](#getspellbonushealing) - [`IsUsableSpell(spell)` / `IsUsableSpell(slot, bookType)`](#isusablespellspell--isusablespellslot-booktype) - [`C_Spell.IsSpellUsable(spellID)`](#c_spellisspellusablespellid) - [`C_Spell.GetSpellCooldown(spellIdentifier)`](#c_spellgetspellcooldownspellidentifier) @@ -8997,6 +8999,54 @@ function does the same spellbook walk in its inner helper at `0x0053B4E0` (player array `[0x00BE6D88]`, pet array `[0x00BE7D98]`, same shape just different addresses). +### `GetSpellBonusDamage(school)` + +Returns the local player's flat spell-damage bonus (spell power) for a +given magic school, as a number. `school` is **1-based**: `1` Physical, +`2` Holy, `3` Fire, `4` Nature, `5` Frost, `6` Shadow, `7` Arcane. Raises +a usage error for a missing / out-of-range school; returns `0` before +you're in the world. + +```lua +GetSpellBonusDamage(3) -- your +Fire spell damage +GetSpellBonusDamage(6) -- your +Shadow spell damage +``` + +### `GetSpellBonusHealing()` + +Returns the local player's flat healing bonus, as a number. + +```lua +GetSpellBonusHealing() -- your +Healing +``` + +> **Damage is an exact field read; healing is derived.** +> +> `GetSpellBonusDamage` reads the client's fully-computed value directly +> from the CGPlayer sub-struct (`PLAYER_FIELD_MOD_DAMAGE_DONE_POS − _NEG` +> per school). That field isn't in the *broadcast* descriptor — the +> vanilla server never sends it there, which is why it looks absent — but +> the client keeps a computed copy for its own use, with gear, enchants, +> buffs, talents, and set bonuses all baked in. So the value is exact and +> complete. (Same source nampower's `GetSpellPower` reads.) +> +> `GetSpellBonusHealing` has no such field — vanilla 1.12 never had a +> healing-done field at all (confirmed in-game: toggling a pure +healing +> item moved no field in the player struct) — so it's **derived** in two +> parts, both from `Spell.dbc`: (1) flat healing = the sum of every +> `SPELL_AURA_MOD_HEALING_DONE` off gear equip-effects, item enchants +> (permanent + weapon oils), random suffixes, and active buffs; plus (2) +> talent/buff stat-conversions, mirroring the server's own +> `SpellBaseHealingBonusDone` — the sum of `SPELL_AURA_MOD_SPELL_HEALING_OF` +> `_STAT_PERCENT` (aura 175) × total Spirit / 100 over your passive talents +> (Priest *Spiritual Guidance*) and active buffs. Part 2 reads the talent +> percent directly, so it's **generic** (any aura-175 talent/buff, including +> Turtle customs) and exact — e.g. Spiritual Guidance 5/5 with 182 Spirit +> adds `int(182 × 25 / 100) = 45`. +> +> Residual: assumes talent ranks supersede (only the learned rank is known) +> and misses set-bonus healing granted via a set-completion spell. + ### `IsUsableSpell(spell)` / `IsUsableSpell(slot, bookType)` Returns `(usable, noMana)` for a spell, matching the modern diff --git a/src/Offsets.h b/src/Offsets.h index 9966290b..5b7a6654 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -798,6 +798,19 @@ enum Offsets { // mov edx, [eax + 0x110] // movzx eax, byte ptr [edx + 0x7B] OFF_UNIT_DESCRIPTOR_POWER_TYPE_BYTE = 0x7B, + // UNIT_FIELD_STAT0..4 — the fully-computed (base+item+buff) primary + // stats, broadcast in the descriptor. Order Str/Agi/Sta/Int/Spirit; + // STAT4 (Spirit) = fieldIndex 0x94 → +0x250 (from the UpdateField name + // table; cross-checked in-game: descriptor +0x250 read 173→182 when a + // +9-Spirit item was equipped). What GetStat(STAT_SPIRIT) returns + // server-side; used by GetSpellBonusHealing for the Spiritual-Guidance + // (aura 175) spirit→healing conversion. + OFF_UNIT_FIELD_STAT_SPIRIT = 0x250, + // UNIT_FIELD_RESISTANCES[0] = armor (the fully-computed total), fieldIndex + // 0x95 → +0x254 (7 resistances: armor, then the 6 magic schools). What + // GetArmor() / GetResistance(SPELL_SCHOOL_NORMAL) returns; used by + // GetSpellBonusHealing for Turtle's Ironclad (aura 199) armor→healing. + OFF_UNIT_FIELD_RESISTANCE_ARMOR = 0x254, OFF_UNIT_FIELD_FLAGS = 0xA0, UNIT_FLAG_PLAYER_CONTROLLED = 0x08, // Bit 19 of UNIT_FIELD_FLAGS — `Script_UnitAffectingCombat` at @@ -868,6 +881,27 @@ enum Offsets { UNIT_AURA_TOTAL = 48, UNIT_AURA_VISIBLE_MASK = 0x0E, // nibble mask used by the engine's visibility gate + // PLAYER_FIELD_MOD_DAMAGE_DONE_POS/NEG — the player's per-school spell + // damage bonus. Offsets from the engine's own UpdateField name/index + // table in `.rdata` (20-byte entries `{char* name, u32 fieldIndex, u32 + // count, ...}` at VA 0x83B6C8): POS = fieldIndex 0x3F5 count 7 → byte + // offset fieldIndex*4 = 0xFD4; NEG = 0x3FC → 0xFF0. Seven int32 each, + // one per school (0 physical .. 6 arcane); net bonus = POS − NEG. + // + // **Read these off `[player + OFF_CGPLAYER_INFO]` (the +0xE68 CGPlayer + // sub-struct), NOT the broadcast descriptor at +0x110.** The descriptor + // copy is never sent to the client and reads zero (verified in-game: the + // whole post-skills PLAYER descriptor region is zero on a geared L60 — + // vanilla never displayed spell power, so the server doesn't broadcast + // it). The +0xE68 struct holds the client's fully-computed value + // (gear + enchants + buffs + talents + sets baked in). Same base + + // offsets nampower's GetSpellPower uses; verified 613 generic / 647 Fire + // on a geared mage. Read by GetSpellBonusDamage in [src/spell/BonusDamage.cpp]. + // (No MOD_HEALING_DONE equivalent — vanilla lacks the field entirely; + // GetSpellBonusHealing is derived instead.) + OFF_PLAYER_FIELD_MOD_DAMAGE_DONE_POS = 0xFD4, + OFF_PLAYER_FIELD_MOD_DAMAGE_DONE_NEG = 0xFF0, + // Reusable "is this spell record a user-visible aura" predicate. // `__fastcall(spellRecord*) -> bool`. Checks Spell.dbc Attributes // (high bit of byte at +0x18 must be clear), AttributesEx bit @@ -1804,6 +1838,16 @@ enum Offsets { // last use"). Negative = single-use, destroyed when count hits 0. // `GetItemCount(includeUses=true)` uses abs() for the multiplier. OFF_DESCRIPTOR_SPELL_CHARGES_0 = 0x28, + // ITEM_FIELD_ENCHANTMENT block (fields 16..36, per the +0x48 + // enchant-charges note above) — 7 enchant slots, 3 dwords each + // `{enchantID, duration, charges}`. Slot 0 = permanent enchant, + // slot 1 = temporary (weapon oils / sharpening stones). The + // enchant ID indexes SpellItemEnchantment.dbc. Block base = field + // 16 = +0x40 (field 15 FLAGS at +0x3C precedes it); slot stride + // 0x0C, enchant ID at slot+0x00. Used by spell/BonusDamage.cpp to + // fold enchant-granted spell power into GetSpellBonusDamage. + OFF_DESCRIPTOR_ENCHANTMENT_ID = 0x40, + DESCRIPTOR_ENCHANTMENT_SLOT_STRIDE = 0x0C, // ITEM_FIELD_DURABILITY (current) and ITEM_FIELD_MAXDURABILITY (max) live // adjacent to each other in the descriptor as plain dwords. Verified in // `Script_GetInventoryItemBroken` (`0x004C8590`): after resolving the @@ -3130,6 +3174,18 @@ enum Offsets { // size matches Spell.dbc's row count. Pre-login the slot is NULL. VAR_PLAYER_SPELL_BITMAP = 0x00B710FC, + // Player spell-knowledge writers — the two functions that mutate the + // bitmap above. Learn (`FUN_004b25b0`) sets the bit, rebuilds the + // 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 + // 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. + FUN_LEARN_SPELL = 0x004B25B0, + FUN_UNLEARN_SPELL = 0x004B2C50, + // Spell-rank-chain knowledge check — `char __thiscall(player /*ecx*/, // spellID)`. Walks `spellID`'s forward rank chain (the class/race- // resolved chain via `0x0060C7C0`) and returns nonzero if the player @@ -5039,6 +5095,8 @@ enum Offsets { // sum). AttributesEx2 (+0x24) bit 0x20000000 disables spell mods. OFF_SPELL_RECORD_FAMILY_NAME = 0x280, // u32 OFF_SPELL_RECORD_FAMILY_FLAGS = 0x284, // u64 + OFF_SPELL_RECORD_ATTRIBUTES = 0x18, // u32 (base Attributes) + SPELL_ATTR_PASSIVE = 0x40, // bit 6 — always-on aura OFF_SPELL_RECORD_ATTRIBUTES_EX2 = 0x24, // u32 SPELL_ATTR_EX2_NO_SPELL_MODS = 0x20000000, diff --git a/src/aura/Source.cpp b/src/aura/Source.cpp index 686ae45e..52871100 100644 --- a/src/aura/Source.cpp +++ b/src/aura/Source.cpp @@ -20,6 +20,7 @@ #include "Game.h" #include "Offsets.h" #include "net/PacketReader.h" +#include "player/StatSignal.h" #include "spell/Lookup.h" #include "tick/WorldTick.h" #include "unit/Identity.h" @@ -288,6 +289,15 @@ int8_t KindForSlot(int slot) { return slot >= Offsets::UNIT_AURA_BUFF_COUNT ? KIND_HARMFUL : KIND_HELPFUL; } +// Bump the player-stat-inputs signal when an aura change hits the LOCAL +// player — buffs/debuffs move GetSpellBonusHealing's flat and Spirit/Armor +// terms, so its lazy cache must invalidate. Guarded on the player object so +// other units' aura churn (combat) doesn't needlessly invalidate it. +void NotifyIfPlayer(void *unit) { + if (static_cast(unit) == Unit::Identity::PlayerObject()) + Player::StatSignal::Notify(); +} + // OnAuraAdded — a new aura occupies a slot (gives the spellId directly). using OnAuraAdded_t = void(__fastcall *)(void *unit, void *edx, uint32_t slot, uint32_t spellId); @@ -297,6 +307,7 @@ void __fastcall OnAuraAdded_h(void *unit, void *edx, uint32_t slot, uint32_t spellId) { g_origOnAuraAdded(unit, edx, slot, spellId); StampApplication(unit, spellId, KindForSlot(static_cast(slot))); + NotifyIfPlayer(unit); } const Game::HookAutoRegister _hookAuraAdded{ @@ -317,6 +328,7 @@ void __fastcall OnAuraStacksChanged_h(void *unit, void *edx, int slot, unit, Aura::Data::ReadSpellID(static_cast(unit), slot), KindForSlot(slot)); + NotifyIfPlayer(unit); } const Game::HookAutoRegister _hookAuraStacks{ @@ -346,6 +358,7 @@ void __fastcall OnAuraRemoved_h(void *unit, void *edx, uint32_t slot, g_origOnAuraRemoved(unit, edx, slot, spellId); (void)slot; Evict(Unit::Identity::GuidForObject(unit), spellId); + NotifyIfPlayer(unit); } const Game::HookAutoRegister _hookAuraRemoved{ diff --git a/src/item/StatAccum.cpp b/src/item/StatAccum.cpp index 0f685624..900a4967 100644 --- a/src/item/StatAccum.cpp +++ b/src/item/StatAccum.cpp @@ -279,6 +279,15 @@ void AddByKey(Accum *acc, const char *key, long delta) { } } +long Value(const Accum *acc, const char *key) { + if (acc == nullptr || key == nullptr) + return 0; + for (int i = 0; i < kCount; ++i) + if (std::strcmp(acc[i].key, key) == 0) + return acc[i].value; + return 0; +} + const uint8_t *FetchRecord(uint32_t itemID) { auto fn = reinterpret_cast(Offsets::FUN_DBCACHE_ITEMSTATS_GET_RECORD); auto *cache = reinterpret_cast(Offsets::VAR_ITEMDB_CACHE); @@ -306,6 +315,34 @@ double ComputeDPS(const uint8_t *record) { return avgTotal / (static_cast(delayMs) / 1000.0); } +void ApplyEnchant(Accum *acc, uint32_t enchantID, long sign) { + if (enchantID == 0) + return; + const uint8_t *en = DBC::Record(Offsets::VAR_SPELLITEMENCHANT_RECORDS, + Offsets::VAR_SPELLITEMENCHANT_COUNT, enchantID); + if (en == nullptr) + return; + auto type = reinterpret_cast(en + Offsets::OFF_SPELLITEMENCHANT_TYPE); + auto amount = reinterpret_cast(en + Offsets::OFF_SPELLITEMENCHANT_AMOUNT); + auto arg = reinterpret_cast(en + Offsets::OFF_SPELLITEMENCHANT_ARG); + for (int i = 0; i < 3; ++i) { // SpellItemEnchantment has 3 effect slots + switch (type[i]) { + case 3: // equip spell — stat/resist value lives in the spell + AddSpellStatAuras(acc, arg[i], sign); + break; + case 4: // resistance — arg = school index (0 = armor) + AddByKey(acc, ResistKey(arg[i]), sign * static_cast(amount[i])); + break; + case 5: // direct stat — arg = ItemModType, amount = value + AddByKey(acc, StatKeyForItemModType(static_cast(arg[i])), + sign * static_cast(amount[i])); + break; + default: // 1 proc / 2 weapon-damage / 6 totem / 7 use spell + break; + } + } +} + void ApplyRandomSuffix(Accum *acc, int suffixID, long sign) { if (suffixID <= 0) return; @@ -316,34 +353,8 @@ void ApplyRandomSuffix(Accum *acc, int suffixID, long sign) { return; auto enchants = reinterpret_cast( rp + Offsets::OFF_ITEMRANDOMPROP_ENCHANT); - for (int s = 0; s < Offsets::ITEMRANDOMPROP_ENCHANT_SLOT_COUNT; ++s) { - const uint32_t enchantID = enchants[s]; - if (enchantID == 0) - continue; - const uint8_t *en = DBC::Record(Offsets::VAR_SPELLITEMENCHANT_RECORDS, - Offsets::VAR_SPELLITEMENCHANT_COUNT, enchantID); - if (en == nullptr) - continue; - auto type = reinterpret_cast(en + Offsets::OFF_SPELLITEMENCHANT_TYPE); - auto amount = reinterpret_cast(en + Offsets::OFF_SPELLITEMENCHANT_AMOUNT); - auto arg = reinterpret_cast(en + Offsets::OFF_SPELLITEMENCHANT_ARG); - for (int i = 0; i < 3; ++i) { // SpellItemEnchantment has 3 effect slots - switch (type[i]) { - case 3: // equip spell — stat/resist value lives in the spell - AddSpellStatAuras(acc, arg[i], sign); - break; - case 4: // resistance — arg = school index (0 = armor) - AddByKey(acc, ResistKey(arg[i]), sign * static_cast(amount[i])); - break; - case 5: // direct stat — arg = ItemModType, amount = value - AddByKey(acc, StatKeyForItemModType(static_cast(arg[i])), - sign * static_cast(amount[i])); - break; - default: // 1 proc / 2 weapon-damage / 6 totem / 7 use spell - break; - } - } - } + for (int s = 0; s < Offsets::ITEMRANDOMPROP_ENCHANT_SLOT_COUNT; ++s) + ApplyEnchant(acc, enchants[s], sign); } void AccumulateRecord(Accum *acc, const uint8_t *record, long sign) { diff --git a/src/item/StatAccum.h b/src/item/StatAccum.h index 33781c43..afa781e6 100644 --- a/src/item/StatAccum.h +++ b/src/item/StatAccum.h @@ -51,6 +51,9 @@ void Init(Accum *acc); // a zero delta). Linear scan — the table is small and fixed. void AddByKey(Accum *acc, const char *key, long delta); +// Read the accumulated value for `key` (0 for an unknown key). Linear scan. +long Value(const Accum *acc, const char *key); + // Passive cache peek for an item's `ItemStats_C` record. Does NOT warm // the cache (returns nullptr for an uncached item) — see the item-cache // race note in CLAUDE.md. @@ -66,6 +69,13 @@ void AccumulateRecord(Accum *acc, const uint8_t *record, long sign); // suffixID <= 0. void ApplyRandomSuffix(Accum *acc, int suffixID, long sign); +// Fold a single SpellItemEnchantment record (by enchant ID) into `acc`, +// scaled by `sign`. Handles equip-spell (type 3), resistance (4), and +// direct-stat (5) enchant effects. Shared by `ApplyRandomSuffix` (a suffix's +// enchant slots) and callers reading an item's *applied* permanent/temporary +// enchants off its CGItem descriptor. No-op for enchantID 0. +void ApplyEnchant(Accum *acc, uint32_t enchantID, long sign); + // Weapon DPS = average damage / swing time, or 0 for non-weapons. double ComputeDPS(const uint8_t *record); diff --git a/src/player/Equipment.cpp b/src/player/Equipment.cpp index 1631910a..1da5fd95 100644 --- a/src/player/Equipment.cpp +++ b/src/player/Equipment.cpp @@ -52,6 +52,7 @@ #include "Offsets.h" #include "equipmentset/Locations.h" #include "event/Custom.h" +#include "player/StatSignal.h" #include "unit/Identity.h" #include @@ -112,6 +113,9 @@ int __fastcall EquipSlotChanged_cb(uint32_t fieldOffset, uint32_t /*size*/, Event::Custom::FireIdSuccess(Event::Custom::Lookup(kEvtEquipmentChanged), slot0 + 1, SlotHasItem(guidLo, guidHi, slot0)); + // Gear swap changes item +healing and Spirit/Armor — invalidate the + // GetSpellBonusHealing cache. + Player::StatSignal::Notify(); } return 1; } diff --git a/src/player/StatSignal.cpp b/src/player/StatSignal.cpp new file mode 100644 index 00000000..f2c34ca9 --- /dev/null +++ b/src/player/StatSignal.cpp @@ -0,0 +1,28 @@ +// 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 . + +#include "player/StatSignal.h" + +namespace Player::StatSignal { + +namespace { +// Starts at 1 so a consumer whose cached epoch is default-0 always computes on +// its first query. +uint32_t g_epoch = 1; +} // namespace + +void Notify() { ++g_epoch; } + +uint32_t Epoch() { return g_epoch; } + +} // namespace Player::StatSignal diff --git a/src/player/StatSignal.h b/src/player/StatSignal.h new file mode 100644 index 00000000..d3263060 --- /dev/null +++ b/src/player/StatSignal.h @@ -0,0 +1,38 @@ +// 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 + +// A pull-based "the local player's stat inputs changed" signal. `Notify()` is +// called from the aura and equipment hooks whenever the player gains/loses an +// aura or swaps gear — the state that feeds derived stats like +// `GetSpellBonusHealing` (flat +healing, plus the Spirit/Armor talent +// conversions that scale with those descriptor fields). +// +// Unlike Tick::WorldTick (push / per-frame callback), this is a monotonic +// epoch that consumers POLL: a lazy cache recomputes only when `Epoch()` +// differs from the value it last computed at, so a per-frame query is O(1) +// between real changes and never does work on idle frames. +namespace Player::StatSignal { + +// Bump the epoch — called from the aura / equipment hooks on a +// player-affecting change. +void Notify(); + +// Current epoch; increments on each `Notify()`. A consumer caches the value it +// last recomputed at and recomputes only when this differs. +uint32_t Epoch(); + +} // namespace Player::StatSignal diff --git a/src/spell/BonusDamage.cpp b/src/spell/BonusDamage.cpp new file mode 100644 index 00000000..d1324297 --- /dev/null +++ b/src/spell/BonusDamage.cpp @@ -0,0 +1,293 @@ +// 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 . + +// `GetSpellBonusDamage(school)` / `GetSpellBonusHealing()` — the local +// player's flat spell-damage (per school) and healing bonus. +// +// **Spell damage is a direct field read.** The value lives in the CGPlayer +// sub-struct at `[player + OFF_CGPLAYER_INFO]` (the +0xE68 blob), NOT the +// broadcast UpdateField descriptor at `+0x110` — the descriptor copy of +// this field is never sent to the client and reads zero (which sent an +// earlier version of this module down a "derive it from gear" path). The +// +0xE68 copy is the client's fully-computed value: `MOD_DAMAGE_DONE_POS[7]` +// at `+0xFD4`, `MOD_DAMAGE_DONE_NEG[7]` at `+0xFF0`, one int32 per school; +// net = POS − NEG. Because it's the finished value, gear + enchants + buffs +// + talents + set bonuses are all already baked in. +// +// This mirrors nampower's `Script_GetSpellPower` (same base + offsets), +// cross-verified in-game: a geared mage reads 613 generic across the magic +// schools with Fire at 647 (a +34 fire-specific piece on top of the 613). +// +// **Healing has no such field** — vanilla 1.12 never had `MOD_HEALING_DONE` +// (TBC addition; `PLAYER_FIELD_BYTES` follows `_PCT` directly), and nothing +// client-side computes a healing total (verified in-game: toggling a pure +// +44-healing item moved NO field in the +0xE68 struct). So +// `GetSpellBonusHealing` is DERIVED in two parts, both read from `Spell.dbc`: +// +// 1. Flat healing — Σ `SPELL_AURA_MOD_HEALING_DONE` (aura 135) off gear +// equip-effects, item enchants, random suffixes, and active buffs. +// 2. Talent/buff stat→healing — the server's own `SpellBaseHealingBonusDone` +// sums `SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT` (aura 175) × +// total Spirit / 100 over the unit's aura-175 auras. We mirror it: read +// total Spirit from `UNIT_FIELD_STAT4` (descriptor +0x250), then sum +// aura-175 percents over PASSIVE known spells (talents — Spiritual +// Guidance, `Spell.dbc` ranks 14901/15028..15031 = 5/10/15/20/25%) plus +// active buffs. Generic (any aura-175 talent/buff, incl. Turtle customs) +// and robust — it reads the percent directly, no client-vs-server value +// delta. +// +// An earlier attempt derived (2) as (spell_damage_field − derived_gear_damage) +// — the part of the damage field gear doesn't explain. That was FRAGILE: the +// field reflects values AFTER SpellMods, but our gear sum used raw DBC values. +// Inner Fire (10951) is +60 in the DBC but +78 live (Improved Inner Fire, a +// +15%/rank SpellMod), so an 18-point gap leaked into healing when that pure +// +damage buff was gained. Reading aura 175 directly (above) sidesteps it. +// +// Residual: assumes talent ranks supersede (only the learned rank is known — +// otherwise summed) and misses set-bonus healing granted via a set spell. + +#include "Game.h" +#include "Offsets.h" +#include "dbc/Lookup.h" +#include "item/ID.h" +#include "item/Location.h" +#include "item/StatAccum.h" +#include "player/StatSignal.h" +#include "tick/WorldTick.h" +#include "unit/Identity.h" + +#include + +namespace Spell::BonusDamage { + +namespace { + +// --------------------------------------------------------------------------- +// Spell damage — direct read from the CGPlayer +0xE68 sub-struct. +// --------------------------------------------------------------------------- + +const uint8_t *PlayerFields() { + const uint8_t *player = Unit::Identity::PlayerObject(); + if (player == nullptr) + return nullptr; + return *reinterpret_cast( + player + Offsets::OFF_CGPLAYER_INFO); +} + +// Net spell damage for a 0-based school (0=physical .. 6=arcane). POS is the +// full per-school value (generic "+spell damage" is already folded into every +// magic school by the server), NEG the signed-magnitude negative accumulator. +long SpellDamageForSchool(int school0) { + const uint8_t *pf = PlayerFields(); + if (pf == nullptr) + return 0; + const int32_t pos = *reinterpret_cast( + pf + Offsets::OFF_PLAYER_FIELD_MOD_DAMAGE_DONE_POS + school0 * 4); + const int32_t neg = *reinterpret_cast( + pf + Offsets::OFF_PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + school0 * 4); + return static_cast(pos) - static_cast(neg); +} + +// --------------------------------------------------------------------------- +// Healing — derived (no client field exists in vanilla). +// +// Item flat +healing goes through the shared Item::StatAccum engine (base +// record + on-equip spells + random suffix + applied enchants) — exactly the +// ITEM_MOD_SPELL_HEALING_DONE_SHORT (aura 135) value GetItemStats reports, so +// the item spell/suffix/enchant walk isn't re-implemented here. Buff / talent +// healing (flat + Spirit/Armor conversions) is decoded from Spell.dbc below. +// --------------------------------------------------------------------------- + +// Flat +healing contributed by one equipped item, via Item::StatAccum. +long ItemFlatHealing(const uint8_t *cgItem) { + if (cgItem == nullptr) + return 0; + Item::StatAccum::Accum acc[Item::StatAccum::kCount]; + Item::StatAccum::Init(acc); + + const int itemID = Item::ID::FromCGItem(cgItem); + if (itemID > 0) + Item::StatAccum::AccumulateRecord( + acc, Item::StatAccum::FetchRecord(static_cast(itemID)), +1); + + auto *desc = *reinterpret_cast( + cgItem + Offsets::OFF_ITEM_DESCRIPTOR); + if (desc != nullptr) { + // Random suffix ("… of Restoration") + applied permanent (slot 0) and + // temporary (slot 1) enchants (Healing Power, Mana Oil, …). + Item::StatAccum::ApplyRandomSuffix( + acc, *reinterpret_cast( + desc + Offsets::OFF_DESCRIPTOR_RANDOM_PROPERTY), +1); + for (int slot = 0; slot <= 1; ++slot) + Item::StatAccum::ApplyEnchant( + acc, *reinterpret_cast( + desc + Offsets::OFF_DESCRIPTOR_ENCHANTMENT_ID + + slot * Offsets::DESCRIPTOR_ENCHANTMENT_SLOT_STRIDE), +1); + } + return Item::StatAccum::Value(acc, "ITEM_MOD_SPELL_HEALING_DONE_SHORT"); +} + +// --- Buff / talent healing auras (flat + Spirit/Armor conversions) --- +// One decoder for every healing aura a buff or passive talent can carry, +// mirroring the server's SpellBaseHealingBonusDone: +// 135 MOD_HEALING_DONE → flat += amount +// 175 MOD_SPELL_HEALING_OF_STAT_PERCENT → += Spirit × amount / 100 (Spiritual Guidance) +// 199 MOD_SPELL_HEALING_OF_ARMOR_PERCENT → += Armor × amount / 100 (Turtle Ironclad) +// Amounts/percents are read straight from Spell.dbc — generic (any talent/buff +// using these auras, incl. Turtle customs) and robust (no client-vs-server +// value delta). `requirePassive` gates the bitmap walk to always-on talents, +// so a *known but not-currently-cast* buff (Divine Spirit) isn't counted as +// on; active buffs pass `requirePassive == false`. +constexpr int kAuraModHealingDone = 135; +constexpr int kAuraModHealingOfStatPercent = 175; // × Spirit +constexpr int kAuraModHealingOfArmorPercent = 199; // × Armor (Turtle Ironclad) + +void AddSpellHealingAuras(long &total, int spellID, int32_t spirit, + int32_t armor, bool requirePassive) { + if (spellID <= 0) + return; + const uint8_t *sp = DBC::Record(Offsets::VAR_SPELL_RECORDS, + Offsets::VAR_SPELL_RECORD_COUNT, + static_cast(spellID)); + if (sp == nullptr) + return; + if (requirePassive && + !(*reinterpret_cast(sp + Offsets::OFF_SPELL_RECORD_ATTRIBUTES) & + Offsets::SPELL_ATTR_PASSIVE)) + return; + auto aura = reinterpret_cast( + sp + Offsets::OFF_SPELL_RECORD_EFFECT_APPLY_AURA_NAME); + auto base = reinterpret_cast( + sp + Offsets::OFF_SPELL_RECORD_EFFECT_BASE_POINTS); + auto dice = reinterpret_cast( + sp + Offsets::OFF_SPELL_RECORD_EFFECT_BASE_DICE); + for (int i = 0; i < Offsets::SPELL_RECORD_EFFECT_COUNT; ++i) { + const long amount = static_cast(base[i]) + static_cast(dice[i]); + if (aura[i] == kAuraModHealingDone) + total += amount; + else if (aura[i] == kAuraModHealingOfStatPercent) + total += static_cast(spirit) * amount / 100; + else if (aura[i] == kAuraModHealingOfArmorPercent) + total += static_cast(armor) * amount / 100; + } +} + +long ComputeHealing() { + long total = 0; + + // Items — flat +healing via the shared StatAccum engine. + for (int slot = 1; slot <= 19; ++slot) + total += ItemFlatHealing(Item::Location::ResolveEquipmentSlot(slot)); + + // Player Spirit / Armor for the aura-175 / aura-199 conversions. + const uint8_t *desc = Unit::Identity::PlayerDescriptor(); + const int32_t spirit = desc ? *reinterpret_cast( + desc + Offsets::OFF_UNIT_FIELD_STAT_SPIRIT) : 0; + const int32_t armor = desc ? *reinterpret_cast( + desc + Offsets::OFF_UNIT_FIELD_RESISTANCE_ARMOR) : 0; + + // Active buffs — flat healing + Spirit/Armor conversions, one pass. + auto *table = reinterpret_cast( + static_cast(Offsets::VAR_PLAYER_BUFF_TABLE)); + for (int i = 0; i < Offsets::PLAYER_BUFF_TABLE_COUNT; ++i) { + const uint8_t *entry = table + i * Offsets::PLAYER_BUFF_ENTRY_STRIDE; + if (*reinterpret_cast( + entry + Offsets::OFF_PLAYER_BUFF_SLOT_CODE) < 0) + continue; + AddSpellHealingAuras(total, *reinterpret_cast( + entry + Offsets::OFF_PLAYER_BUFF_SPELL_ID), + spirit, armor, /*requirePassive=*/false); + } + + // Passive talents — Spirit/Armor conversions (Spiritual Guidance, Ironclad) + // and any passive flat healing, via the known-spell bitmap (bounded by + // spellCount). The passive gate assumes ranks supersede (only the learned + // rank is known), so no per-rank dedup is needed. + auto *bitmap = *reinterpret_cast( + static_cast(Offsets::VAR_PLAYER_SPELL_BITMAP)); + const int spellCount = *reinterpret_cast( + static_cast(Offsets::VAR_SPELL_RECORD_COUNT)); + if (bitmap != nullptr && spellCount > 0) { + for (int id = 1; id <= spellCount; ++id) + if (bitmap[id >> 5] & (1u << (id & 31))) + AddSpellHealingAuras(total, id, spirit, armor, /*requirePassive=*/true); + } + + return total; +} + +// Event-driven cache for the derived healing sum. The walk (StatAccum over 19 +// items + the buff table + the known-spell bitmap) is expensive, so we +// recompute it ONLY when the player's stat inputs change — Player::StatSignal +// is bumped from the aura and equipment hooks, so a per-frame +// GetSpellBonusHealing poll is O(1) between real gear/buff changes. +// +// Every input to the sum is now event-driven: the aura, equipment, and +// spell-learn/unlearn hooks all bump Player::StatSignal (buffs, gear, and +// talent respecs respectively). This coarse world-tick recompute (at most once +// per kFallbackTicks frames, ~4s) is a pure backstop against a missed signal — +// e.g. a player aura the object-pointer guard in aura/Source didn't match — +// bounding staleness rather than being the primary mechanism. +constexpr int kFallbackTicks = 256; +uint32_t g_cachedEpoch = 0; // 0 = never computed (epoch starts at 1) +int g_ticksSinceCompute = 0; +long g_cachedHealing = 0; + +void OnTick() { ++g_ticksSinceCompute; } +const Tick::WorldTick::AutoSubscribe _tick{&OnTick}; + +long CurrentHealing() { + const uint32_t epoch = Player::StatSignal::Epoch(); + if (epoch != g_cachedEpoch || g_ticksSinceCompute >= kFallbackTicks) { + g_cachedHealing = ComputeHealing(); + g_cachedEpoch = epoch; + g_ticksSinceCompute = 0; + } + return g_cachedHealing; +} + +// --------------------------------------------------------------------------- +// Lua bindings. +// --------------------------------------------------------------------------- + +// `GetSpellBonusDamage(school)` → number. `school` is 1-based (1=Physical +// through 7=Arcane). Raises the usage error for a missing / out-of-range +// school, matching 3.3.5's Script_GetSpellBonusDamage (0x0060E310). +int __fastcall Script_GetSpellBonusDamage(void *L) { + const int school = + Game::Lua::IsNumber(L, 1) ? static_cast(Game::Lua::ToNumber(L, 1)) : 0; + const unsigned idx = static_cast(school - 1); + if (idx >= static_cast(Offsets::SPELL_SCHOOL_COUNT)) { + Game::Lua::Error(L, "Usage: GetSpellBonusDamage(school)"); + return 0; + } + Game::Lua::PushNumber(L, static_cast(SpellDamageForSchool(static_cast(idx)))); + return 1; +} + +// `GetSpellBonusHealing()` → number. The player's flat healing bonus (derived). +int __fastcall Script_GetSpellBonusHealing(void *L) { + Game::Lua::PushNumber(L, static_cast(CurrentHealing())); + return 1; +} + +void RegisterLuaFunctions() { + Game::Lua::RegisterGlobalFunction("GetSpellBonusDamage", &Script_GetSpellBonusDamage); + Game::Lua::RegisterGlobalFunction("GetSpellBonusHealing", &Script_GetSpellBonusHealing); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +} // namespace + +} // namespace Spell::BonusDamage diff --git a/src/spell/Info.cpp b/src/spell/Info.cpp index a15dabb9..9180cc5a 100644 --- a/src/spell/Info.cpp +++ b/src/spell/Info.cpp @@ -13,6 +13,7 @@ #include "Game.h" #include "Offsets.h" +#include "player/StatSignal.h" #include "spell/Arg.h" #include "spell/Lookup.h" @@ -586,6 +587,35 @@ 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)}; + static void RegisterLuaFunctions() { Game::Lua::RegisterGlobalFunction("GetSpellInfo", &Script_GetSpellInfo); Game::Lua::RegisterGlobalFunction("GetSpellLink", &Script_GetSpellLink);