mirror of
https://github.com/brues-code/ClassicAPI.git
synced 2026-11-16 16:10:36 +00:00
v1.17.0
106
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
8bc43b455c |
fix(unit): trace UnitInLineOfSight like the server's LoS check
The server traces one segment with each end at its own unit's collision height. The UnitXP_SP3-derived level-look pass traced both ends at the shorter unit's height first and returned "in sight" when that cleared, so segments slipping under overhangs read clear while casts still failed with SPELL_FAILED_LINE_OF_SIGHT. Keep only the server's trace. Also correct the docs: the 0x100111 class word already tests doodads and game objects. |
||
|
|
e827e319be |
fix(unit): match 4.3.4 UnitIsInMyGuild resolution order
Try the engine's by-name search first (party then loaded players, exact, mode 3, as 4.3.4's ClosestObjectMatch call) and decide a loaded hit on the guild key, so a nearby guildmate's name works before GuildRoster(). Tokens resolve to a name through the NameCache and go to the roster, which now compares names ignoring case (SStrCmpI). |
||
|
|
a61ff06e9a |
feat(unit): add UnitSelectionColor and UnitSelectionType
4.3.4's selection colour is one ladder over a GUID with an extended flag: the unit's virtual calls it with 1, Script_UnitSelectionColor with 0. Retail exposes the flag as useExtendedColors and names each rung (UnitSelectionType 0 Hostile .. 9 Dead). 1.12 inlines the extended ladder into CGUnit_C::GetSelectionHighlightColor and has no Lua surface. Both globals walk that ladder rung for rung with the engine's own predicates (CanAttack, IsPVPUI, CGPartyInfo::IsMember, UnitReaction, health) plus the friend rung, so the extended colour is the one the circle and the name draw. A GUID with no unit object takes 4.3.4's no-object branch, with the PvP bit from the group stats block that Script_UnitIsPVP reads. FriendNameColor.cpp becomes SelectionColor.cpp so the engine-side friend patches and the Lua ladder share one colour table. |
||
|
|
167815f27b |
feat(unit): color friends' names light blue
4.3.4's selection colour checks the friends list after the party for a player-controlled unit neither side can attack, and gives it #53C8FF. 1.12's CGUnit_C::GetSelectionHighlightColor has the same ladder without that rung, so its two not-in-party exits now return the friend colour for a friend. The name above the head and the selection circle both take it. FRIENDLIST_UPDATE marks every name record's colour dirty through the engine's own mark-all, so a change shows at once. AutoPrepare's 6-byte call patcher moves to Common::ReplaceWithCall, which takes any instruction length. |
||
|
|
81c4aedb06 |
feat(target): show icons over the soft enemy and soft friend
SoftTargetIconEnemy and SoftTargetIconFriend draw the hover cursor image over softenemy and softfriend, beside the soft interact icon. One unit gets one icon. SoftTargetLowPriorityIcons lets the plain pointer count as an icon image. SetUnitCursorTexture now honors includeLowPriority (defaulting to SoftTargetLowPriorityIcons) and clears the texture when it returns false, as retail does. |
||
|
|
81eaf24748 |
feat(target): add the soft enemy and soft friend
Add the softenemy, softfriend, anyenemy and anyfriend unit tokens, the PLAYER_SOFT_ENEMY_CHANGED and PLAYER_SOFT_FRIEND_CHANGED events, and the SoftTargetEnemy*, SoftTargetFriend* and SoftTargetMatchLocked cvars, with Classic Era's defaults. anyleftinteract is the same as anyinteract. The soft-target scan moves to Target::SoftTarget, shared by interact, enemy and friend. Its arc now follows the camera, not the character. |
||
|
|
cf5e9c8ee7 |
feat(target): add SetUnitCursorTexture and the soft-interact icon
SetUnitCursorTexture(texture, unit) sets a texture to the cursor image the mouse shows over the unit, the Unable form when out of reach. It takes the engine's own image: the cursor name table, or a game object's record-named cursor through FormatGameObjectCursorFile. The softinteract object now shows that image over it (SoftTargetIconInteract, default 1; SoftTargetNameplateSize, default 19, is its size). A unit's icon sits where 1.12 seats a nameplate, from GetNamePlateScreenPos; an object's uses GetNamePosition's no-attachment rule (1.25 x scale x box height) with the same 2/3-yard lift. The icon is a texture on the world frame, anchored to its BOTTOMLEFT the way SeatNamePlate anchors a plate, and hides off screen. |
||
|
|
622478df04 |
feat(target): add the soft-interact target and Interact Key
Backports the Interact Key: the SoftTargetInteract, SoftTargetInteractArc, SoftTargetInteractRange and SoftTargetInteractRangeIsHard cvars (Classic Era defaults, so it is off until set), the softinteract and anyinteract unit tokens, PLAYER_SOFT_INTERACT_CHANGED, and C_PlayerInteractionManager.InteractUnit. INTERACTTARGET and INTERACTMOUSEOVER now use Blizzard's bodies, which interact with anyinteract. The pick is the closest object the hover cursor would show an interact cursor for: the unit and corpse cursor classifiers run with SetCursorMode captured (Cursor::Hover), and game objects use GetCursor. It also needs the tab-target collector's drawn test, the arc (arc 1 is the collector's pi/6 front cone, arc 0 a 1.2-yard strip measured in Classic Era) and the range capped by targetNearestDistance. It runs on the UI frame tick, as on the world tick every world node reads as culled. anyinteract is the target when it can be interacted with, else softinteract, as probed on retail. UnitTokenFromGUID now returns softinteract, last, in retail's order. |
||
|
|
929b6f5c60 |
feat(spell): add autoStand, autoDismount and autoUnshift
Backports 4.3.4's cast settings. With one set to 1, a cast that 1.12 refuses because the player sits, is mounted, or is in a form that the spell excludes now stands, dismounts or leaves the form, then casts. Mirrors 4.3.4's split: the caster check's mount, stand and form rungs pass when the action is allowed and note it, and the cast request runs the noted actions once every rung has passed. A form refusal for "only in form" is never handled, and the usability check honors autoUnshift so the button stays lit, as Spell_C_IsUsableAction does. All three default to 0, so 1.12 behavior is unchanged until set. CancelShapeshiftForm now shares the aura-cancel walk with the dismount. |
||
|
|
fd7843b8b3 |
feat(aura): add RAID and CANCELABLE filters, fix stale player timers
Use the engine's own aura tests where C_UnitAuras guessed or gave up: - RAID calls the two tests behind UnitBuff/UnitDebuff's raid-filter argument (castable buff 0x4B3870, known dispel type 0x4B3920); isRaid reports the same answer. - CANCELABLE / NOT_CANCELABLE read the descriptor's cancelable bit. - PLAYER also counts a caster whose charmer or creator is the player (totems, guardians, charmed units), as 4.3.4's IsAuraCaster does. The charmer-or-creator read moves to Unit::Identity::OwnerGuid. - Filter tokens and spell-name lookups ignore case (SStrCmpI). - castByPlayer (UnitAura position 13) is a player caster only, as in 4.3.4; isFromPlayerOrPlayerPet keeps pets. - canApplyAura: the player or pet knows the spell and it applies an aura. - Player timers look up the buff record by slot and honour its until-cancelled flag, so a permanent aura no longer reads the stale expiry its slot kept from an earlier aura. Corrects the player-buff record and visible-aura comments in Offsets.h. |
||
|
|
9ab6627d90 |
feat(unit): add InteractUnit and the INTERACTTARGET / INTERACTMOUSEOVER bindings
InteractUnit(unit [, exactMatch]) is 4.3.4's Script_InteractUnit. It resolves the argument the way 4.3.4 does: - "mouseover" reads the hovered-object GUID, which in 1.12 is any object type (units, game objects, corpses). - A unit token resolves to its GUID. - Any other text runs the engine's by-name search with TYPEMASK_OBJECT. It then calls 1.12's own OnSpriteRightClick (0x00492820), the function a world right-click runs, so targeting, the object's right-click and the autoloot modifier all come from the engine. 4.3.4's taint gate is dropped because 1.12 has no secure environment. Both bindings are spliced into the TARGETING group, as in 4.3.4. Their names are added to every locale, using Blizzard's strings. |
||
|
|
77fb074191 |
feat(tooltip): add SetAnchorType, IsUnit, ANCHOR_TOP/BOTTOM and two getters
Cross-checked against 4.3.4's Tooltip_Scripts: - GameTooltip:SetAnchorType(type [, x [, y]]) was missing in 1.12, but the shipped GameTooltip_ShowCompareItem port (and pfUI) call it. It stores the offsets and, with an owner, the anchor, then runs the engine's position routine with force. - GetMinimumWidth and GetPadding read the fields 1.12's SetMinimumWidth and SetPadding already write; GetPadding returns the stored internal value, as 4.3.4 does. - IsUnit(unit) compares GUIDs and returns 1 or nil. The token is probed first, because 1.12's resolver raises on an unknown name. - 1.12's SetOwner has nine anchor names and sends every other one to ANCHOR_LEFT. ANCHOR_TOP and ANCHOR_BOTTOM get codes of their own; one hook on the position routine places them, and SetOwner and GetAnchorType are re-registered to know the names. ANCHOR_CURSOR_RIGHT is not added. |
||
|
|
aeb3bdf07b |
feat(playercache): resolve GetPlayerInfoByName through the engine's name search
C_PlayerCache.GetPlayerInfoByName read only the persistent NameCache, so it returned nothing for every name while that cache was off, even for a player standing next to you. It now resolves the name to a GUID first (Player::Info::GuidFromName): the engine's own by-name search behind TargetByName (party and raid members, including out-of-range ones, then every visible player), then the friends list, then the persistent cache. The result is built from that GUID by the same code as GetPlayerInfoByGUID. The engine search is wrapped once as Unit::Identity::FindGuidByName, which UnitTokenFromName now uses too. |
||
|
|
9d3bdfb6ad |
feat(focus): follow 4.3.4's focus, and give every unit event to focus, nameplates and marks
Every unit event the engine fires now reaches focus, nameplateN and
markN, as 4.3.4 does for its focus: the unit gets a script-registration
bit, so the engine watches its fields, and whatever the engine fires
for the unit fires for the token too.
- A co-hook on the registration recompute (FUN_0060c520) keeps bit
0x8000 on units with one of these tokens. Post-init runs it too, so a
unit coming back into range is watched again. 0x2000 is SuperWoW's
and WeirdUtils' sparkle bit on every unit.
- nampower replaces the broadcast (0x00515E50) and the combat feedback
(0x00494600) with detours that never call the original, so neither
can be co-hooked. Their 38 + 4 CALL/JMP sites, which no loaded DLL
touches, are redirected to functions that call the original address
and then fire for the unit's tokens. Sites are found by a .text scan
and patched only when the counts match Ghidra's xrefs.
- The tokens gain UNIT_COMBAT, UNIT_NAME_UPDATE, UNIT_PORTRAIT_UPDATE,
UNIT_MODEL_CHANGED, UNIT_CLASSIFICATION_CHANGED and group-stat
updates. TokenObserver now serves only focustarget: with SuperWoW
every unit is engine-watched, so an observer would double-fire.
Focus drop rules follow 4.3.4 where 1.12 has the data: out of range is
kept for you, your pet, a party or raid member or their pet (the
engine's own target rule); death while not friendly, or arrival already
dead and not friendly; becoming not selectable. Death and the flag act
on the change. 1.12 has no duel exception and no SMSG_BREAK_TARGET.
%f in sent chat (4.3.4's ChatParserParseText) becomes the focus's name,
with a {rtN} prefix when marked, or FOCUS_TOKEN_NOT_FOUND.
The .text bounds move into Offsets.h (shared with interface/Export).
The focus still survives /reload; focustarget events stay as a
ClassicAPI extension.
|
||
|
|
27d8f90f03 |
fix(unit): UnitFactionGroup("player") answers while addons load (#79)
* fix(unit): UnitFactionGroup("player") answers while addons load
Script_UnitFactionGroup resolves "player" through the in-world unit
descriptor, so it returns nil at file scope, ADDON_LOADED and
VARIABLES_LOADED and only answers from PLAYER_LOGIN. UnitName, UnitRace
and UnitClass already answer then, and later clients answer
UnitFactionGroup too, so ported addons read it at file scope. AceDB-3.0
does exactly that to build its "<faction> - <realm>" profile key, and
fails to load on nil ("attempt to concatenate local 'factionKey'").
Co-hook the engine function: when it answers nothing for the "player"
token, fall back to the login-time race byte (VAR_PLAYER_RACE_BYTE) and
the same race -> faction-group chain its player branch uses. That chain
moves out of C_CreatureInfo.GetFactionInfo into a shared
Creature::Info::FactionGroupForRace; GetFactionInfo's behavior is
unchanged. Once the player object exists the engine answers by itself.
Adds FUN_SCRIPT_UNIT_FACTION_GROUP (slot 13 of table 0x00850438).
Measured in-game before the fix (Octo 1.18.1 client, Human):
UnitFactionGroup("player") = nil at file load / ADDON_LOADED /
VARIABLES_LOADED, "Alliance" from PLAYER_LOGIN; UnitName/UnitRace
answer at every stage.
Verified in-game after the fix (same client and character):
UnitFactionGroup("player") is "Alliance" at file load, ADDON_LOADED and
VARIABLES_LOADED, and AceDB-3.0 sets up Zygor Guides Viewer 2.0's saved
settings.
* fix(unit): keep UnitFactionGroup's in-world nil; describe both engine branches
Script_UnitFactionGroup reads the live faction template when the unit's
object is in the world, and only falls back to the name cache's race when
it isn't. The race fallback now runs only under that same condition (no
player object), so an in-world nil (e.g. charmed by a monster) stays nil
instead of turning into the race's faction. Comments and API.md now say
which engine branch the fallback mirrors.
---------
Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
|
||
|
|
46dc198505 |
feat(tooltip): add GameTooltip:GetUnit
GetUnit() returns (name, unitToken). The engine drops the token after
SetUnit resolves it to a GUID, so it is kept where it enters:
- SetUnit is re-registered in front of the engine method and stages
the token; it binds in the unit-builder co-hook that SetEvents
already owns, before OnTooltipSetUnit fires.
- A build with no staged token is the world mouseover ("mouseover");
the in-place refresh keeps the bound token.
- Unit-frame hover (Frame::Attributes) stages the frame's unit, since
the engine resolves "mouseover" only for a live object and an
offline or far group member has none.
The name follows Script_UnitName's order (live object, group roster
slot, name cache), so offline members resolve for GetUnit and
GetUnitGUID alike.
|
||
|
|
40abcabe9d |
fix(unit): read the creature id from the unit's live entry, not the GUID
UnitCreatureID and C_CreatureInfo.GetCreatureID extracted the template from
GUID bits 24-47. On the (v)mangos family that is the spawn row's FIRST
creature id: Creature::CreateFromProto builds the GUID from creature_id[0]
and applies the rolled template through UpdateEntry -> SetEntry only, and a
respawn re-rolls. Turtle's creature table has up to four ids per row (6,935
of 79,773 rows use more than one), so mobs with different names reported the
same id — every Gordunni ogre from a {5236, 5238, 5239} row read 5236.
New Unit::CreatureID reads the entry the engine keys the creature NAME query
on: the instance block at [[unit+0x08]+0x0C] (FUN_00604600's own read), with
the GUID bits only as the out-of-view fallback for creature GUIDs. The
descriptor's OBJECT_FIELD_ENTRY slot reads 0 for creatures on this client,
as it does for items, so it is documented as unusable. Pet GUIDs pack the pet
number, not a template, so Guid::CreatureEntry now returns 0 for them; pets
in view report their real template from the block.
Verified in-game on Turtle: Gordunni Shaman / Battlemaster / Mage-Lord read
5236 / 5238 / 5239 while all three carry 5236 in the GUID.
|
||
|
|
61db68dd7f |
fix(lua): gate frame-method self with the engine's own type check
Every engine frame method validates its `self` in three steps before
touching it: lua_type == table, resolve to the CFrameScriptObject, then
the IsA(typeId) vmethod at vtable+0x10. We did the first two and skipped
the third, so ResolveObject handed back a pointer for ANY frame and the
method cast it to whatever type it expected.
That was reachable from plain Lua, not just through a mirror or a hook.
The per-type method dispatcher is an __index handler that rawgeti's the
method closure out of the Lua registry, so frame methods are ordinary
first-class values, and
GameTooltip.SetSpellByID(ShapeshiftButton1, 133)
reached the tooltip builder with a Button, writing tooltip fields through
Button memory. The engine refuses that same call with "Wrong object type
for member function".
Game::Lua::ResolveTypedObject runs the engine's prologue and raises the
engine's own three error strings, read from .data rather than reinvented.
FrameScriptTypeId mirrors the lazy id assignment, so a check is valid
before any stock method of the type has run. Seven per-type wrappers stop
a call site pairing a method with the wrong class's id, and
ResolveTypedObjectAny covers a method that more than one type reaches.
45 call sites across 19 files now gate self. model/DisplayInfo.cpp had
already worked this out for Model alone and loses its private copy.
Type ids are per CLASS, one shared by all of that class's methods. Each
was read from the prologue of a method that can only belong to its class:
a base-class method registered into several tables carries the BASE id, so
sampling GetObjectType or GetDrawLayer would have produced a gate that
accepts unrelated types. Frame comes from Script_RegisterEvent and Texture
from Script_SetDesaturated, both cross-checked against the first entry of
their table.
Deliberately left ungated: the binding `owner` in bindings/Api.cpp and the
three co-hook sites in texture/Atlas.cpp. Each only uses the pointer as an
identity key and never casts it, so a gate would tighten the contract for
no safety gain -- and raising inside a co-hook would fire before the
original ran.
Verified in-game: the Button-as-tooltip call now raises the engine's
error; a Button still reaches a Frame-registry method
(button:SetAttribute round-trips), so IsA does accept derived types; and
fontstring:GetRotation() still answers -- that reader is registered on
both the Texture and FontString registries and needs the id pair rather
than the Texture id alone.
|
||
|
|
36c367a6d6 |
feat(macro): native #showtooltip, conditional slash commands, and a display API for addons (#48)
* feat(macro): native #showtooltip/#show, conditional /cast and /use
Backport the macro display system to the engine:
- Macro::ShowTooltip resolves `#showtooltip [cond] value` / `#show` (and
the bare form over the macro's /cast and /use lines, first match wins)
through the Lua SecureCmdOptionParse on the world tick and writes the
result into the engine's per-macro spell cache (+0x564/+0x568), which
every action reader already consumes. Repaints go through the engine's
own slot-changed notifier. Item targets are cached alongside.
Re-evaluates on modifier / mouseover / target / combat changes and every
200 ms otherwise. Yields entirely when SuperCleveRoidMacros is loaded.
- The `?` icon rule is a co-hook on the macro icon getter, so action
buttons and the drag cursor both show the resolved icon; GetMacroInfo,
GameTooltip:SetAction, GetActionCooldown, GetActionCount and
IsConsumableAction are re-registered in front of the engine for macro
slots with a resolved directive and tail-call it otherwise.
- Macro::RunBody re-implements the engine's body runner so `#` lines
never reach chat; Macro::Execute skips them too.
- /cast and /use in the embedded addon (3.3.5 handler shape): items
first, [@unit] via C_Spell.CastAtUnit, 1..19 = inventory slot, other
numbers stay spellIDs. SecureCmdOptionParse: a group whose only piece
is @unit passes only while the unit exists (3.3.5 passes it
unconditionally). C_Item.GetItemCount accepts names. GetMacroItem
added; GetMacroSpell now reflects the directive.
- Offsets.h: 0x004F0F40 was the macroID -> MacroEntry resolver,
mislabeled as a spell-state cache; renamed FUN_MACRO_ID_TO_ENTRY, with
the action-bar / macro-runner constants this needs added and verified.
* feat(unit): add IsUnitToken for token-vs-name dispatch
Vanilla ships each "act on a unit" verb as two Lua entries, one taking a
unit token and one taking a character name, and each errors on the other
kind of input. Conditional slash commands need to accept either, because
SecureCmdOptionParse hands back a token for `/target [@focus]` and a name
for `/target Bob` through the same variable.
IsUnitToken(value) answers which one a string is by calling the engine's
own token resolver inside lua_pcall and reporting whether it returned or
threw. Consulting the resolver rather than matching a token list here
keeps the answer correct for every family it knows, including this
client's native GUID literals and our own focus / nameplateN / markN,
which unit/TokenExtensions.cpp hooks onto the same function. It reports
whether the text names a token, not whether a unit is there, so "target"
with nothing targeted is still true.
if IsUnitToken(x) then TargetUnit(x) else TargetByName(x) end
Additive on purpose. Merging the pairs into a modern TargetUnit /
AssistUnit / FollowUnit was written and reverted: those names are common
enough for other DLLs and addons to replace that re-registration is
silently last-one-wins, with no error and no trampoline to chain. That
mechanism is only safe for names nobody else contends.
Offsets.h records two findings from decompiling the resolver. The throw
is raised by its callee, not by FUN_RESOLVE_UNIT_TOKEN, which is a thin
wrapper returning 0 on a miss. And this client reaches the error through
a patched fallthrough that first parses a 0x<hex> GUID literal, so GUID
unit tokens resolve natively with no SuperWoW loaded.
* feat(addon): backport the conditional slash commands
Adds 27 commands that take [conditions] through SecureCmdOptionParse,
following the 3.3.5 SecureCmdList handler shapes: targeting
(/targetexact, /cleartarget, /targetlasttarget, /targetlastenemy,
/targetenemy, /targetfriend, /targetenemyplayer, /targetfriendplayer,
/targetparty, /targetraid), casting and state (/stopcasting, /cancelaura,
/cancelform, /dismount), equipment (/equip, /equipslot), action bars
(/changeactionbar, /swapactionbar) and the pet family.
/target, /assist and /follow gain conditions by replacing the FrameXML
handlers, which is the only way to add them. Plain input keeps working:
each routes through IsUnitToken to the engine's token entry or its
by-name entry, where the old handler always went by name.
Three natives have a different shape here than the 3.3.5 handlers assume,
so those bodies are not straight ports. PetAttack takes no target and
always sends the pet at the current target. ChangeActionBarPage takes no
page and only fires ACTIONBAR_PAGE_CHANGED, so CURRENT_ACTIONBAR_PAGE is
set first. Pet autocast is a spellbook-slot toggle with no enable and
disable entries, so a name is resolved against the pet book and on/off
read the state and toggle only on a mismatch. /cancelaura needs no buff
walk, since CancelSpellByName already matches a player buff by name.
Not ported for want of a native: /targetlastfriend, and the /mt and /ma
family, which needs party assignments the client does not have.
Command names come from the locale files, with the localized name taken
from the matching Blizzard GlobalStrings and the English one alongside.
zhCN ships English for all 27. The short aliases retail also carries
(/eq, /tar) are left out, since those collide with addon shorthands.
* fix(macro): resolve item link values in #showtooltip
`#showtooltip` over a `/use item:6948` line showed no icon. The directive
evaluator built its item argument as `{0, 0, value}`, hardcoding the whole
value as a NAME, so the `item:N` and pasted-link forms could never match
and the value fell through to the spell lookup. `/use` itself was fine,
which is why the macro cast the item but the button stayed blank.
The link parsing already existed for the Lua entries. Split it out as
`Item::Arg::ResolveString` and call that instead of hand-building the
argument, so both paths read the forms the same way.
A bare number keeps skipping the item lookup: `ResolveString` reads "6948"
as an itemID, and a bare number that is not an equipment slot has to stay
a spellID per the documented `/cast 5019` rule.
An explicit itemID now also resolves when none is carried, falling back to
the ID after the bag and equipment walk misses. The icon and tooltip come
from the item record, and the tooltip path already handled an unheld item
through a hyperlink, so a macro naming an item in the bank or one written
before looting it now displays. Names are still limited to what you hold,
since 1.12 has no name-keyed item cache.
* fix(macro): make [@cursor] work in /cast, /use and #showtooltip
`/use [@cursor] item:4390` did nothing and its `#showtooltip` showed the
question mark. Two causes, both in the addon.
The parser rejected the clause. A group whose only piece is `@unit` passes
only while that unit exists, and the existence test ran UnitExists on
`cursor`, which is not a unit token. The engine raises there, the pcall
caught it, and the group failed. `none` was already exempt; `cursor` joins
it, since both name something other than a unit and neither can be tested
that way.
Nothing routed the target once it did pass. `SecureCmdUseItem` sent every
target through UseItemByName, which takes a unit GUID, and the spell branch
had only the on-unit and default cases. A `cursor` target now goes to
C_Item.UseAtCursor and C_Spell.CastAtCursor, which were written as the
`[@cursor]` analogs but had no caller. SecureCmdItemParse has already
turned a bag or inventory slot into a link, so one item call covers every
value form.
`#showtooltip` needed no change: the value resolves once the clause passes.
* feat(macro): accept a character name as a macro target
`/cast [target=Feral] Rejuvenation` did nothing. A `@unit` or `target=unit`
piece takes a character name as well as a unit token, but nothing here
turned a name into something the unit functions accept, and the existence
gate ran UnitExists on it, which raises for a string that names no token.
`UnitTokenFromName(name [, exactMatch])` runs the engine's own by-name
search — `FUN_UNIT_FIND_BY_NAME`, the one behind TargetByName, AssistByName
and FollowByName — and reports the winner as a token: a standard one when
it fits, else the GUID literal, which this client's resolver takes too. It
walks party, then raid, then every loaded unit, so it reaches units no
token names. Prefix match by default, nearest first, like TargetByName.
`GroupPasses` now resolves a named target once and uses it for both jobs:
the bare-group existence test (`[@Feral][] Spell` falls through when they
are not around) and the conditions, which previously raised on a name.
The pcall that already guarded the existence test is what tells a token
from a name, so a token target costs no more than before.
The slash handlers resolve the target the same way before handing it to
CastAtUnit, UseItemByName, FocusUnit or StartAttack, and drop the command
when a named unit is not around.
* feat(macro): drop a ground-target item at your feet with [@player]
`/use [@player] item:4390` sent the grenade through UseItemByName, which
passes a target GUID but never commits the placement, so the reticle came
up instead of the grenade landing. Route a `player` target to
`C_Item.UseAtUnit` instead, which commits at the unit's position.
Only your own position is offered. Aiming a ground-target item at another
unit is not something the game lets you do by hand, so the slash handler
does not either; every other unit target keeps going to UseItemByName.
`C_Item.UseAtUnit` now dispatches with the unit's GUID rather than a zero
target, matching `C_Spell.CastAtUnit`. Without that, routing `@player`
through it would have cost a non-ground item its target: a bandage or a
scroll would fire at the current selection instead of at you. It now
covers both kinds of on-use item, the way CastAtUnit covers both kinds of
spell.
* fix(macro): stop /cast [@unit] aiming ground spells at that unit
The same aim the item side was just denied: `/cast [@target] Flamestrike`
dropped the reticle on the target with no click, for any unit. Placing a
ground spell somewhere you could not put it by hand is aim the player has
not earned, and it should not differ between a spell and a grenade.
`/cast [@player]` and `/cast [@cursor]` still place, since both name a
position you can already aim at. Every other unit still has the spell cast
on it when it takes a unit target, which is what `@unit` is for; only the
ground-placement leg is dropped, leaving the reticle up exactly as casting
by hand does.
`C_Spell.CastAtUnit` keeps the whole primitive and gains a third argument
for the choice, defaulting to placing so the API and its callers are
unchanged. The restriction lives in the slash handler, the same split the
item side uses, where `C_Item.UseAtUnit` stays unrestricted and only
`/use` limits itself to `@player`.
`Spell::AtCursor::GroundPlacementPending` reports whether the in-flight
placement is a ground one, so the handler can leave that reticle up while
still cancelling a placement for a unit the engine did not accept. Leaving
that armed would strand the cursor.
* fix(item): stop a bad unit raising out of C_Item.UseItemByName
The optional `unit` went straight to the engine's token resolver, which
raises for a string that names no token. Both the code comment and the
API docs promised the opposite, that an unrecognized string is no target,
matching the no-op contract the item argument already has.
It is reachable without an addon calling the function directly: secure
button attributes and key bindings both feed it a configured string, so a
`unit="foo"` attribute raised inside a click handler.
Probe with Unit::TokenResolve::IsUnitToken first and treat anything else
as no target, which makes the documented contract true.
C_Item.UseAtUnit keeps raising, which is deliberate and now stated in its
docs: it is the companion of C_Spell.CastAtUnit, which documents the same
behavior as matching UnitHealth("garbage").
* feat(macro): let an addon publish its own macro display
`C_Macro.SetMacroDisplay(macroSlot, value)` hands a macro's resolution to
the display path, for an addon that parses macros itself. It is aimed at
SuperCleveRoidMacros, which today replaces ten action globals plus
GameTooltip.SetAction to put its answers on the bar, and borrows an
unrelated action slot to get a range check for a macro.
None of that is needed. Writing the spell into the engine's own per-macro
cache is what makes cooldown, range, usable, current and auto-repeat
correct for a macro button, with nothing overridden, and the icon then
reaches two places a Lua override cannot: the cursor while a macro is
dragged, and the macro window grid, both of which come from an engine
getter we hook.
The value takes the forms a `#showtooltip` value takes, so a publisher
hands over what it would have written in the macro. Three states: a value
to show, false for claimed-but-nothing-matched, nil to release.
Ownership is per macro. A published one is not parsed or re-evaluated by
us and is honored even while yielding; the rest stay ours. Nothing is
re-evaluated for the publisher, but a published resolution is re-applied
whenever the engine's re-parse overwrites the cache, so a macro edit
cannot silently replace it.
The wholesale stand-down when SuperCleveRoidMacros is loaded is lifted by
`CleveRoids.ClassicAPIMacroDisplay`, which a build sets to say it drives
us. Forks without it keep the all-or-nothing yield, so an older one cannot
end up fighting for the same buttons.
* fix(macro): accept the !Name prefix in /cast and #showtooltip
`#showtooltip` over `/cast !Shoot` showed nothing and the line cast
nothing: the `!` prefix, which asks for a toggle ability to be started
but never turned off, was never part of vanilla and no name resolver
knew it.
Split it in two.
The NAME is normalized in the one co-hook on the engine's single
name -> spellbook-slot resolver, which already owned the numeric
spellID form (so `spell/CastByID.cpp` becomes `spell/NameResolve.cpp`).
`FUN_RESOLVE_SPELL_NAME_TO_BOOK_ID` calls that resolver, so a single
strip covers the runtime cast, `Spell::Arg`, the `#showtooltip`
resolution and the engine's own macro parser -- which is what lets
`IsAutoRepeatAction` light a `/cast !Shoot` button even while macro
display is yielded to SuperCleveRoidMacros.
The BEHAVIOR stays in Lua: `SecureCmdCast` strips the prefix and casts
through the existing `CastSpellNoToggle`, which asks the engine whether
the ability is already up first. `CastSpellByName` cannot carry it --
re-registering that global is off limits and nampower already co-hooks
it.
`CastSpellNoToggle` gains the `placeGroundSpell` argument that
`C_Spell.CastAtUnit` has, so `/cast [@target] !X` keeps the rule that
only your own feet and the cursor place a ground-target spell. It also
tolerates a `!` on its own input now, since its auto-repeat name
compare is ours rather than the engine's.
* feat(item): take an item location wherever an item action takes an item
`C_Item.UseAtCursor`, `UseAtUnit`, `UseItemByName` and `EquipItemByName`
took an item reference only - an itemID, `item:N`, a link, or a name - and
resolved it by searching the bags for the first match. Holding two stacks of
the same item, or two copies enchanted differently, there was no way to say
which one you meant.
They now also take an item location: `{bagID=B, slotIndex=S}`,
`{equipmentSlotIndex=N}`, or an item GUID string - the shapes
`C_Item.GetItemID` already took. A location names one exact item.
`Item::Location::FindItemArgOrLocation` owns the overload; the old `Resolve`
(locations, pointer) and the new `ResolveItemArgOrLocation` (either, pointer)
are wrappers over it, so the classification and the walk live in one place.
None of the four call sites resolves anything itself any more.
A table is only ever a location, and so is a string that parses as a strict
`0x` + 16 hex digit GUID, which no item link or item name can look like. The
form is decided from the argument alone and committed to: a location resolve
STOMPS the Lua stack (`PackBagSlot` overwrites the first slots with its own
arguments), so falling back to the reference forms after one had run would
re-read the argument as whatever it left behind - a bag index read as an
itemID, which names an unrelated item.
`EquipItemByName` needs the source coordinates too, since the swap packet
carries them, which is what the detail form is for. An
`{equipmentSlotIndex=N}` location names a worn item, so with a `dstSlot` it
routes to `Item::Swap::FromPaperdoll` - that is how a ring 11<->12, trinket
13<->14 or weapon 16<->17 move is expressed. Without a `dstSlot` there is no
slot for the engine to pick, so that combination does nothing.
Its `lua_settop(L, 0)` ahead of `ClearCursor` is gone: `Script_ClearCursor`
(`0x004895B0`) is `FUN_00495190(1, 1)` and a return - no arguments, no stack
reads. Dropping it lets the item resolve run after the cursor clear, which a
location needs: while an item is held its slot reads empty, so the location
it came from would otherwise resolve to nothing.
* refactor: centralize the item constants and the icon-path build
Four copies of the ItemStats displayInfoID -> `Interface\Icons\<name>`
chain had accumulated - `item/GetData`, `item/Info`, `container/ItemInfo`
and the new `item/Icon` - and they had already drifted: two checked for an
empty icon name and two did not. `Item::Icon::PathForDisplayInfoID` is now
the one builder and the other three call it, so a change to that chain has
a single site. `PathForItemID` is it plus the cache lookup.
`action/ItemState` had local constants shadowing values already in
`Offsets.h`: `kItemSpellSlots` for `ITEMSTATS_SPELL_SLOT_COUNT`, and a bare
`trigger == 0` for `ITEM_SPELLTRIGGER_ON_USE`. `INVTYPE_AMMO` / `THROWN`
existed in two files, and the engine runner's `0x400` macro line buffer in
two more, so those move to `Offsets.h` as well - `INVTYPE_*` next to the
string table they index, `MACRO_LINE_BUFFER_SIZE` next to the delimiters.
CLAUDE.md's rule, and duplicated offsets drifting is exactly what it was
written for.
* fix(macro): indented directives, release, and icon-getter re-entry
Three defects found reviewing the `#showtooltip` work, plus dead code.
A directive typed with a leading space was lost AND leaked to chat.
`ParseDirective` and the two `#`-line filters all tested byte 0, but the
tokenizer splits on `\r\n` only, so ` #showtooltip` arrives with its space:
the parse missed it, and then `Macro::RunBody` / `Macro::Execute` failed to
recognize the comment and dispatched the line through `EXECUTE_CHAT_LINE` -
the /say this feature exists to stop. All three skip blanks now, as does
`CastCommandArgs` so an indented `/cast` line is still collected, and the
runner dispatches the trimmed line so an indented command works at all.
`C_Macro.SetMacroDisplay(slot, nil)` left the publisher's spell in place.
`Release` cleared our entry and asked for a rescan, but `Rescan` only marks
an entry dirty when it has a directive with options - so for a macro with
no directive of its own, nothing ever rewrote `+0x564`, and the button, its
tooltip, cooldown and auto-repeat state stayed on the published spell until
the engine happened to re-parse. It now hands the field back to the engine
by running the engine's own parser, then repaints.
The macro icon getter could run Lua from under a click. `FUN_MACRO_ICON_PATH`
has two callers and one is `FUN_MACRO_PICKUP`, inside the UseAction core, so
`Lookup`'s catch-up could evaluate conditions through `SecureCmdOptionParse`
and fire `ACTIONBAR_SLOT_CHANGED` into addon handlers while the drag was on
the stack - the re-entrancy hazard CLAUDE.md records for `Tooltip::SetEvents`.
`LookupPassive` reads only what the entries already hold; the world tick
does the work and repaints, so a resolution can be one tick behind an edit.
Also drop `Active()` (no callers) and `RunBody`'s unused trampoline, and
correct the header's reference to a module that does not exist: the icon
comes from `Macro::IconPath`, not `Action::Texture`.
* fix(slash): five conditional-command defects, and cheaper option passes
`/cast 5019` could consume an item. A bare number that is not an
equipment slot is a spellID, but it reached the item lookup, which reads a
number as an itemID - so carrying item 5019 used it instead of casting the
spell. `Macro::ShowTooltip::ResolveValue` already guarded this exact case,
so the button showed the spell while the click used an item.
Every bare `/targetenemy` stepped backwards. The cycling selectors pass
the parsed value as their reverse flag, and a clause that matches with no
value yields the empty string - which is a true boolean in Lua. Six
commands were affected in their most common form.
`/cast [@none] Spell` did nothing. `@none` names no unit, but only
`@cursor` was exempted from the token resolve, so `none` went to the
by-name search and the cast was dropped. It now means no unit, which is
the untargeted form of the verb; `/target [@none]` clears the target, as
documented. The other unit verbs no longer feed `none` to that search
either - it matches on the START of a name, so it would find a Nonek.
`/assist [@target] Bob` ignored Bob. `/target` and `/follow` both let a
trailing name win over an explicit `target=target`; assist did not.
`/use [@player] 0 1` used the wrong item. The position branches ran before
the bag branch, so a named slot was thrown away and the item re-found by
link - the first match anywhere, which with two stacks is the wrong one.
Every form now resolves to one item and goes through one call, which also
means a slot is aimed by `@unit` like a name is, and that `/use` always
uses: clicking a bag slot sells the item at a merchant and repairs it
under the repair cursor (`Script_UseContainerItem` branches on the
merchant GUID and on cursor mode 0x11), which a typed command must not do.
`GroupPasses` also stopped paying for an answer it discards. A group with
conditions only needs a token, so it asks `IsUnitToken` rather than
`pcall(UnitExists)` - the conditions test existence themselves. The
existence path keeps its single pcall, and a name, which costs an
object-manager search, is remembered for the rest of the pass.
|
||
|
|
b81f672ad7 |
fix(aura): classify auras by polarity flag, not slot range
The server seats buffs in slots 0..31 and debuffs in 32..47 only while it can: once the 16 debuff slots are full, _AddSpellAuraHolder parks further debuffs in free BUFF slots and sets UNIT_FLAG_AURAS_VISIBLE so the client still renders them (tortoise-wow, verified). Classifying by slot range therefore reported those as buffs -- absent from HARMFUL, and wrong in isHelpful / isHarmful. Confirmed live on a 20-aura target: 18 harmful, two of them sitting in buff slots, where the old code returned 16. Every visible aura carries its real polarity in the per-slot flag nibble (SpellAuraHolder::SetAuraFlag writes 0x04 positive / 0x08 negative), so HELPFUL / HARMFUL now select on that instead. All the walkers -- by index, by spell ID, by name, GetUnitAuras, GetAuraSlots -- share one order helper, SlotInFilterOrder, which visits the polarity's home range first and the other range after, so every index is unchanged whenever nothing has spilled. Aura::Source's KindForSlot classifies the same way, keeping the descriptor-drop fallback consistent with the query paths. The out-of-range group array carries spell IDs with no flags, so that path stays range-based -- the seating range is the only polarity it has. GameTooltip:SetUnitAura now bridges the two index spaces. The engine's SetUnitBuff / SetUnitDebuff index their own slot RANGE, which diverges from the polarity index space as soon as a debuff spills, so the method resolves (index, filter) to an absolute slot and hands the engine the index that slot holds within its own range, picking the method by where the slot lives. It counts with the engine's TOOLTIP visibility predicate (FUN_GAMETOOLTIP_AURA_VISIBLE = 0x00534DF0), not the UnitBuff one (0x00519860): the latter adds a per-player immunity-bitmap check off record +0x2B0, so the two index spaces are not interchangeable. Both decompiled to confirm the walks being mirrored. The aura tooltip builder only ever receives spellId / level / stacks, so a debuff parked in a buff slot renders identically through SetUnitBuff. Note this is deliberately MORE than the engine does: stock UnitBuff / UnitDebuff split by slot range and show a spilled debuff as a buff. Retail's contract is the aura's actual polarity, and the descriptor already carries it, so we report that. |
||
|
|
993c82cca7 |
refactor: route unit-token resolution through Game::ResolveUnitToken
Sweep the ~35 modules that each hand-rolled a `ResolveUnitToken_t` typedef plus `reinterpret_cast<…>(Offsets::FUN_RESOLVE_UNIT_TOKEN)` onto the shared `Game::ResolveUnitToken` helper. Behavior-identical — it is the same engine function — and net -87 lines. The typedef now lives in exactly one place (Game.cpp). unit/Position.h is a header, so it gains an `#include "Game.h"`; every other touched file already pulled Game.h in. No offsets, logic, or unrelated typedefs were changed. |
||
|
|
94e77ef5af |
feat(unit): UnitCreatedBySpell + consolidate the unit-token resolver
Add `UnitCreatedBySpell(unit)` — the spell that summoned a unit (a totem's totem-drop spell, a pet/guardian's summon spell), read from the unit's UNIT_CREATED_BY_SPELL descriptor field (byte +0x230). It is the same field the engine's unit-title builder consults to pick the Pet/Minion/Guardian/ Creation title, and it is broadcast, so it resolves for any unit in range. This is the summoning spell, distinct from the (server-only) spell a totem casts. Also add a single `Game::ResolveUnitToken(token)` helper that wraps the engine token->CGUnit* resolver, and route unit/Pet.cpp through it plus the Game::Read<T> field accessors — removing the hand-rolled ResolveUnitToken_t typedef and raw reinterpret_casts from this module. The name was already referenced in Offsets.h and CLAUDE.md but had never been implemented. |
||
|
|
c06bed9158 |
feat(unit): add GetSheathState
Vanilla 1.12 ships ToggleSheath but no getter for the player's drawn-weapon type. Add GetSheathState(), which returns the modern 1-based value: 1 = None (sheathed), 2 = Melee, 3 = Ranged. The engine stores the sheath state as a plain CGUnit int member at +0xD40 (0-based: 0 sheathed, 1 melee, 2 ranged) -- the same field its own toggler FUN_005EB480 reads to pick the next state and its setter FUN_00611CF0 writes. GetSheathState reads the local player's value and adds 1 for the Lua contract. - Add OFF_UNIT_SHEATH_STATE (0xD40) with RE-provenance comment. - Document under docs/API.md (State section) and the README index. - Also list the Tracking API in the README function index (missed in the prior tracking commit). |
||
|
|
7f52afeef4 |
perf(event): fire custom events through O(1) AutoReserve::Slot()
Every custom-event fire resolved its name to a slot via Event::Custom::Lookup - a linear strcmp scan over the ~46-entry reservation table, on every single fire. The slot itself was already cached per table build; only the name->reservation hop was repeated. On a client that is purely CPU-bound, that is wasted work on paths that burst exactly when frames are scarce (nameplate churn, cast spam, loot rolls, mouse/modifier input). AutoReserve now remembers its reservation index (the ctor's dedup resolves duplicate names to the same entry) and exposes Slot() - two loads. Reload safety is unchanged and stays centralized: Slot() reads through the shared table PrepareForReload/RetryClaims maintain, so the value can never go stale. Lookup is deleted; LookupByName remains for engine-defined names. All fire sites converted to the instance handle: - CastEvents: the k* name constants become the AutoReserve instances, so all 19 fire sites stay textually identical; the Fire/FireReticle/ FireRemote helpers take the reservation by reference. - equipmentset: reservations move into Set.h as C++17 inline consts so the Data and Api TUs share one handle. - Cache::QueryLoad::Register takes the AutoReserve pointer instead of an event-name string (creature/gameobject callers updated). - Tts keeps its lazy VanillaTTS-stand-down reservations via null-guarded pointers set at registration. - GlobalMouse/InputEvents/lossofcontrol instances moved above their fire sites (static-init list order is irrelevant). |
||
|
|
a2d25cef8b |
fix(object): gate ByGuid on the registry root to survive out-of-world calls
The engine resolver FUN_OBJECT_RESOLVE_BY_GUID funnels unconditionally into FUN_00464890, whose first action loads the registry root from [VAR_LOCAL_PLAYER_PTR] and derefs its +0x24 hash mask with no null check. That root is NULL out of world (login, loading screens, logout teardown), so any resolve reaching it mid-transition dies with ERROR #132 (MOV EAX,[EDX+0x24], EDX=0) - hit in the wild by Aura::Source's SMSG_SPELL_GO path, whose Store/Claim eviction consults DescriptorListsAura while packets still dispatch during transitions. Promote the readiness predicate from Unit::TokenObserver's private RegistryReady into Object::RegistryReady (object/Resolve.h) and gate ByGuid on it, returning nullptr out of world. That is both the contract ByGuid's comment already promised ("pre-world ... safe from any context") and provably behavior-preserving: a zero result is the engine's own handled "not found" case (verified in Ghidra - 0x468460 null-checks the node; 0x464870 itself returns 0 for guid==0), and out of world the call had no non-crashing outcome. Every ByGuid call site already null-checks. TokenObserver now delegates to the shared helper. Fixes #34 |
||
|
|
c54556f6a1 |
refactor: centralize engine field/global access via Game::Read/Ref/Ptr
Replace the raw `*reinterpret_cast<const T *>(base + Offsets::OFF_X)` idiom (and its double-cast variant when base wasn't already a byte pointer) with three typed accessors in Game.h: Game::Read<T>(base, offset) field value read Game::Ref<T>(base, offset) writable field lvalue Game::Ptr<T>(base, offset) pointer to a field (arrays / out-params) Game::Read<T>(address) / Ref<T>(address) fixed-VA globals Pure mechanical refactor, zero behavior change: ~330 cast sites across 84 files collapse to 651 helper calls. Offsets stay in Offsets.h per the single-source-of-truth rule — the helpers only remove the cast noise and fold away the inner `reinterpret_cast<uint8_t*>(obj)` base casts. Left as raw casts by design: FUN_* function-pointer casts, void*/char* VA handles passed as arguments (caches, method registries), subobject- anchor pointers fed to __thiscall helpers, `void *volatile` player-ptr readiness gates (converting would strip volatile), and VA-as-array-base captures that are subscripted later. |
||
|
|
9b34ceff9e |
feat(unit): add UnitCreatureID(unit)
The unit-token twin of C_CreatureInfo.GetCreatureID — resolves the token to a GUID and reads the creature-template entry vanilla packs into bits 24-47. nil for players, empty tokens, and non-creature/pet GUIDs. Factor the entry extraction + creature/pet gate out of GetCreatureID into a shared Guid::CreatureEntry so both callers use one source of truth for the GUID bit layout. |
||
|
|
0df8885045 |
refactor(offsets): collapse duplicate object type-mask enum (OBJ_TYPE_* -> TYPEMASK_*)
OBJ_TYPE_* was a partial second naming of the same object-type bits as the complete TYPEMASK_* set (OBJ_TYPE_ITEM=2=TYPEMASK_ITEM, ... GAMEOBJECT =0x20 both) -- a single-source-of-truth violation. Repoint all ~18 references to TYPEMASK_* (identical values, behavior-preserving) and delete the OBJ_TYPE_* definitions, folding their derivation notes (bitmask semantics, FUN_004F8DB0 for PLAYER, FUN_0052AA20 for GAMEOBJECT, FUN_00529FE0 SetUnit) into the surviving TYPEMASK_* comment. |
||
|
|
2612118ff6 |
refactor(object): centralize GUID->object resolution in Object::ByGuid
Every caller of the engine object resolver (0x00468460) re-declared the
same __fastcall typedef and split the GUID into lo/hi by hand -- 30 call
sites across 28 files. Add object/Resolve.{h,cpp} with
void *Object::ByGuid(int typeMask, uint64_t guid, const char *debugName, int priority)
and route every site through it (behavior-identical: same typeMask,
debugName, priority per site; single-uint64 callers pass guid, split-lo/hi
callers reconstruct it).
Also collapse the duplicate offset constant: FUN_CLNT_OBJ_MGR_OBJECT_PTR
was a second name for the same 0x00468460 address as
FUN_OBJECT_RESOLVE_BY_GUID (a single-source-of-truth violation). Remove
it; the ABI-equivalent (u32,void*,u64,int) view it documented is folded
into the surviving constant's comment.
|
||
|
|
b72c52d9f7 |
refactor(identity): share NameForGuid, drop friendlist copies
Add Unit::Identity::NameForGuid(guid) -- a passive NameCache peek that returns the cached character name -- and replace the two identical local copies in friendlist/IsFriend and friendlist/IsIgnored. Both files no longer touch Offsets directly, so drop the now-dead include. |
||
|
|
1447317cd3 |
refactor(dbc): route class/race/area name lookups through DBC::Names
Add DBC::RaceToken (race client-filename token) and make AreaName skip the parent Record lookup when resolveToParent is false, then replace the inline ChrClasses/ChrRaces/AreaTable name+token reads across the codebase with the shared helpers: player/Info, creature/Info, player/LocationInfo, unit/ClassBase, unit/RaceBase, map/Areas, taxi/Map, loot/History (drops its verbatim ClassTokenForId), classes/Info (drops local Records/LocaleIndex). All behavior-preserving -- the helpers wrap the same DBC::Record / LocalizedField / StringField calls with identical id==0 / out-of-range / empty-string -> nullptr semantics (verified against Lookup.cpp). Left alone: NameCache's reverse token->id resolvers (no forward helper fits) and the Record() reads of non-name fields in spell/Mod, map/Overlays, creature/Info. |
||
|
|
b8bd0bce4e |
fix(unit): gate +0xE68 sub-struct reads on OBJECT_TYPE_PLAYER, not PLAYER_CONTROLLED
The CGPlayer sub-struct at [unit+0xE68] (guild key, PLAYER_FLAGS, quest list, visible items) exists only on real player objects. Reads of it were gated on UNIT_FLAG_PLAYER_CONTROLLED, but the server sets that flag on pets, totems, guardians, companions, and MC'd creatures too (Turtle UnitDefines.h; Pet.cpp/SpellEffects.cpp/SpellAuras.cpp setters) -- all TYPEID_UNIT creatures with no such sub-struct. On one of them the +0xE68 pointer is garbage-but-non-null, so the null check passes and the deref AVs (ERROR #132, pfUI issue #34: UnitIsInMyGuild on a nameplate pet/totem, frequent in crowded dungeons/raids). Add Unit::Flags::IsPlayerObject (m_objectType == OBJECT_TYPE_PLAYER via [obj+0x14]) and use it as the gate at every arbitrary-unit +0xE68 reader: - UnitIsInMyGuild (ReadGuildKey) -- the reported crash - UnitIsAFK/UnitIsDND (TestPlayerFlag) -- same latent crash on a pet - IsUnitOnQuest (Quest::Log::UnitHasQuest) - GetInventoryItemID (non-local unit visible-items path) Local-player-only readers are unaffected. IsPlayerControlled stays for minion/ownership classification (Unit::Pet), which wants the broad flag. |
||
|
|
0c27d61839 |
unit: add markN raid-target-marker unit tokens
"mark1".."mark8" (star..skull) now work as unit tokens against the whole
Script_Unit* surface, and fire per-token unit events (UNIT_HEALTH, ...)
with arg1 == "markN" -- the same TokenObserver path focus/nameplateN use.
Resolution: a markN branch in the FUN_TOKEN_TO_GUID hook
(unit/TokenExtensions.cpp) reads the engine's 8-slot marker table
(VAR_RAID_TARGET_GUIDS = 0x00B71368, mark{1..8} = table[N-1]), so every
stock Unit* gains the token for free and "mark1target" composes via the
existing suffix walker.
Events: unit/RaidTarget.cpp runs a WorldTick watcher that diffs the marker
table and attaches/detaches one descriptor observer per marked unit,
deferring registration until the unit is in the object table (a unit can
be marked while out of range and enter later) -- the same range handling
Focus does, x8. One distinct callback per slot fires its fixed "markN"
token. Idle (no markers set) costs 8 compares and no object lookups; a
marker on a non-unit is never observed.
Verified the array shape against the binary (reverse lookup FUN_004bb190
walks 8 uint64 slots) and against nampower's CGRaidInfo_m_raidtargets.
Docs added under Unit tokens (markN); README token table updated.
|
||
|
|
29e3dab24a |
UNIT_SPELLCAST_* event family + GUID unit tokens (#11)
* spell: backport UNIT_SPELLCAST_* events for the local player
Adds the TBC+ cast/channel events (START, STOP, DELAYED, SUCCEEDED,
INTERRUPTED, FAILED, SENT, CHANNEL_START, CHANNEL_UPDATE, CHANNEL_STOP)
for the player, so cast-bar / rotation addons written against the modern
signature work on 1.12. Each carries (unit, castGUID, spellID, spellName,
rank) -- SENT inserts `target` at arg2 -- with a synthesized modern-shape
castGUID (Cast-3-0-0-0-<spellID>-<castUID>) shared across all of a cast's
events so START pairs with STOP. arg1 is always "player" (player-only phase).
The events are derived, not independently tracked: Spell::Cast already
hooks every cast/channel path for UnitCastingInfo/UnitChannelInfo, so
Spell::CastEvents reuses that state.
- START/STOP/DELAYED/CHANNEL_START/STOP: polled from Cast's OnWorldTick
against the previous snapshot.
- SUCCEEDED: fired from the SMSG_SPELL_GO hook (covers instants too).
Deferred for channels so it lands after CHANNEL_START (modern order).
- INTERRUPTED/FAILED: split by result code in a Spell_C_SpellFailed
co-hook -- a started cast that aborts (kick/move/LoS) fires INTERRUPTED
(repeated per retry, reusing the cast guid); a pre-cast rejection fires
FAILED.
- SENT: minted from the CMSG_CAST_SPELL send, threading its castGUID
forward so all of a cast's events share one guid.
- CHANNEL_UPDATE: from a new MSG_CHANNEL_UPDATE co-hook, which also
re-anchors g_channel.endMs to the server's remaining time so channel
pushback (which shortens vanilla channels) shows in UnitChannelInfo.
Every fire is gated on Event::Custom::HasListeners (new), so the system
costs one pointer-compare per transition when no addon registers.
Supporting changes:
- Net::SendObserver: shared co-hook on the NetClient send funnel with an
AutoSubscribe list, so CastEvents (SENT) and ComboDuration (combo-point
capture) both watch outgoing packets without owning the hook. Extracted
from ComboDuration's private hook.
- Cast.cpp: player channel now self-expires at its computed endMs in the
poll (was cleared only by the ~1s-lagged +0x228 field, so CHANNEL_STOP
trailed the real end by ~1s); wrap-safe delta compare so a long-uptime
ms tick past 2^31 can't misfire it.
Player-only; remote-unit fan-out, FAILED_QUIET, and empowered casts are
not implemented.
* spell: extend UNIT_SPELLCAST_* to non-player units (phase 2)
Fires the six observable cast/channel events -- START, STOP,
CHANNEL_START, CHANNEL_STOP, SUCCEEDED, INTERRUPTED -- for other units,
not just the player. Each is fanned out once per unit token currently
mapping to the caster (target / focus / nameplateN / party / raid / pet /
mouseover), so a target frame, a party frame, and a nameplate cast bar
all get their own event with a shared castGUID -- matching retail.
Token fan-out reuses the engine's own GUID->token reverse map
(FUN_00515c50, nampower's unfilled GetNamesFromGUID) for native tokens,
plus focus/nameplate which the engine can't see, via
Unit::Identity::TokensForGUID. SuperWoW's raw-GUID token ("0x...") is
filtered out so only standard tokens fan out.
Remote events are derived from Spell::Cast's existing packet hooks:
- START / CHANNEL_START from HandleSpellStart (SMSG_SPELL_START)
- SUCCEEDED from the SPELL_GO hook (Aura::Source)
- STOP / CHANNEL_STOP at the computed end, or on abort
- INTERRUPTED (casts only) from HandleCastAborted (ClearCastingSpell /
failure packets)
A per-caster state machine (PollRemote, from OnWorldTick) fires them in
modern order; a channel's SPELL_GO cast->channel ClearCastingSpell is
filtered so it doesn't self-interrupt at its own start.
Not fired for remotes (data is caster-only / client-local): SENT,
DELAYED, FAILED, CHANNEL_UPDATE.
Also in this change:
- castGUID follows type rule from https://warcraft.wiki.gg/wiki/GUID#Cast : real casts are Type 3 with a
time-based castUID (low 23 bits = UNIX second, high bits = per-second
counter, matching retail's structure), threaded across a cast's events
(player and remote converge on the same value); FAILED is Type 2 with
a flat incrementing integer.
- Channels never fire INTERRUPTED (player or remote) -- retail emits
only CHANNEL_STOP whether a channel completes or is cut short.
arg1 is the caster's unit token ("player" or another token); the
spellName / rank tail extensions are unchanged.
* spell: return the castGUID as UnitCastingInfo's castID
UnitCastingInfo / CastingInfo now return the cast's castGUID as castID
(return 7) instead of nil -- the same string the UNIT_SPELLCAST_* events
carry, so an addon can correlate the polled info with the events. It's
pulled from Spell::CastEvents (the single source of the castUID) via a new
CurrentCastGuid accessor, and works for the player and remote units. The
timing stays sourced from Spell::Cast -- only the castGUID crosses over,
so there's no duplication of cast state.
UnitChannelInfo is left retail-exact (no castID; channels don't carry
one), even though our channel events do include the shared castGUID.
Also corrects the spell-cast-GUID spec attribution in comments/docs to
warcraft.wiki.gg/wiki/GUID#Cast (it was wrongly credited to Wowhead).
* spell: add UNIT_SPELLCAST_RETICLE_TARGET / _CLEAR events
Backports the ground-target reticle events for the player:
RETICLE_TARGET when an AoE placement reticle comes up (Blizzard, Flare,
Rain of Fire, ...), RETICLE_CLEAR when it's cancelled. Args are
(unit, "", spellID, spellName, rank); arg1 is always "player".
Driven by polling the engine's targeting-flag global (0x00CECAC0 -- the
predicate behind SpellIsTargeting) from OnWorldTick: 0->nonzero fires
RETICLE_TARGET with the pending spellID (0x00CEAC58, written by
Spell_C_CastSpell); nonzero->0 fires RETICLE_CLEAR. CLEAR is suppressed
on placement (a CMSG_CAST_SPELL for the reticle spell went out, seen via
the shared send observer), so it fires only on a genuine cancel --
matching retail, which emits no CLEAR when the spell is placed/cast.
The castGUID slot (arg2) is "" rather than retail's nil: there's no cast
to identify yet, and the engine's event dispatcher can't emit a nil
mid-argument-list (a NULL %s corrupts the args after it -- the nil trick
only survives as the last arg). unit (arg1) and spellID (arg3) are exact.
* spell: fire UNIT_SPELLCAST_FAILED_QUIET for the quiet result whitelist
Vanilla's Spell_C_SpellFailed dropped SPELL_FAILED_DONT_REPORT silently.
Modern surfaces suppressed (no-error-text) failures as
UNIT_SPELLCAST_FAILED_QUIET rather than FAILED.
Verified against the 3.3.5 client's unit-spellcast dispatch (FUN_007fecc0),
which selects the QUIET event for a fixed 3-code whitelist, mapped to 1.12's
SpellCastResult enum (FUN_006e23e0):
CHARMED (0x14) . DONT_REPORT (0x17) . SPELL_IN_PROGRESS (0x61)
SPELL_IN_PROGRESS (casting while already casting / a nampower spell-queue
rejection) is the common case that previously mis-fired as a loud FAILED.
* unit: accept raw GUID literals as unit tokens
Fold a "0x<hex>" branch into the existing FUN_TOKEN_TO_GUID hook so every
Unit* function (UnitName, UnitHealth, UnitClass, UnitExists, ...) accepts a
64-bit GUID literal in place of a token. The parsed GUID goes straight to
the engine's own object-manager lookup (the path "player" takes), so an
unloaded/out-of-range GUID resolves to nil like any absent unit, no error.
Reuses the existing suffix walker, so "0x...target" composes.
Gated on SuperWoW's absence (GetModuleHandleA("SuperWoWhook.dll"), cached):
SuperWoW already provides GUID input via its own resolver hook, so when it
is loaded we defer to avoid two layers parsing the same string. Behaves
identically either way. Input direction only.
|
||
|
|
46597f6587 |
unit: fire UPDATE_MOUSEOVER_UNIT on mouseover loss
Vanilla fires UPDATE_MOUSEOVER_UNIT only when a mouseover unit is gained;
moving the cursor off a unit clears the mouseover and signals nothing.
Retail fires for both gain and loss, so addons watching
UnitExists("mouseover") can react when it goes false. This restores the
loss fire.
Co-hooks the engine's mouseover set/clear chokepoint (FUN_00492890) --
the ONLY writer of the mouseover GUID globals, so every gain/loss/change
flows through it. Resolves whether the mouseover is a unit before and
after the original and fires the event on the unit->non-unit transition.
Gating on unit TYPE (not just "GUID present -> absent") is load-bearing:
the same GUID slot also holds gameobjects and items, which never fire a
gain, so a naive present->absent test spuriously fired when moving off a
herb node or chest (reported in testing). The unit|player object-mask
resolve fixes that; the !hasUnit half prevents a double-fire on any
->unit transition the engine already covered inline.
Change-gated target (per-frame would spam the gain event while
hovering), so it's a cool hook. Documented in API.md (loss-fire fix
subsection + TOC) and Events.md notes.
|
||
|
|
cd280ac307 |
state: add IsIndoors / IsOutdoors globals
Backport the modern `IsIndoors()` / `IsOutdoors()` no-arg globals to 1.12. Both return 1 when the condition holds, nil otherwise (the historical retail contract, also what SuperWoW 2.2 uses), so `if IsOutdoors()` and `IsOutdoors() == 1` both work. Recomputed live from the engine's WMO geometry query, so they flip as the player crosses an interior threshold rather than tracking zone/area; nil pre-world. The signal is a live WMO query, not a cached flag. Vanilla ships no Lua binding for it, and the static anchors all dead-ended (the WMO runtime flag bits differ from 3.3.5; ZONE_CHANGED_INDOORS is never fired with a literal event ID; WMOAreaTable is only the area-naming path). SuperWoW 2.2 exposes `IsIndoors`, so decoding its handler gave the exact recipe: resolve the local player object, then call FUN_00612cc0(unit) -- a thunk that reads the unit world/collision context at +0xE0 and tail-jumps to the WMO query FUN_006706f0 (nonzero = outdoors, fully null-safe). Same shape as the 3.3.5 client's IsIndoors (unit+0xB8), so cross-confirmed. Added Offsets::FUN_UNIT_IS_OUTDOORS with the full trail; the two functions live in Unit::State next to IsMounted / IsSwimming and share Unit::Identity::PlayerObject(). |
||
|
|
f13aa1943d |
unit: add UnitPosition(unit)
Backport the modern UnitPosition -> posY, posX, posZ, instanceID. Reads any visible unit's world position through the shared Unit::Position helper (CGObject::GetPosition vtable slot 5 -- same path UnitDistanceSquared uses), so no group/taint restriction like retail: works for target, mouseover, nameplates, in-range party/raid. nil when the unit has no known position. Retail return order (posY=world Y/west, posX=world X/north, posZ=height); instanceID is the current Map.dbc id. Verified in-game: squared delta of two UnitPosition reads matches UnitDistanceSquared exactly. Note: SuperWoW also defines a global UnitPosition with a different shape; last registrant wins if both load. Documented in docs/API.md. |
||
|
|
c01dceabb8 |
unit: class/race fall back to the player-info cache out of range
UnitClassBase / UnitRaceBase resolved via FUN_RESOLVE_UNIT_TOKEN and returned
(nil,nil) for a groupmate on another map -- but the engine's own UnitClass /
UnitRace fall back to the cached player-info record there (verified in-game:
UnitClass("raid1")="Priest", UnitRace("raid1")="Human" while our descriptor
path yielded nil). Give ours the same fallback: on a descriptor miss, read
class (+0x140) / race (+0x138) from the NameCache record by GUID. Verified
fixed: UnitClassBase("raid1")=("PRIEST",5), UnitRaceBase("raid1")=("Human",1).
That engine-NameCache peek existed in four places (the two above plus
loot/History and player/Info). Collapsed them into one primitive,
Unit::Identity::PlayerInfoRecord(guid) -> record* (null callback = peek only),
and pointed all four at it. FUN_PLAYER_INFO_LOOKUP is now called in exactly
one spot.
|
||
|
|
365df6b882 |
group: add Group::MemberStats, generalize the out-of-range roster reader
Extract the roster fallback (added for UnitPower) into a shared Group::MemberStats reader and give it the full picture. Lookup(guid) tries the party stats block (FUN_GROUP_MEMBER_STATS_LOOKUP) then the raid slot (FUN_GROUP_MEMBER_SLOT_LOOKUP) -- the object-independent group roster fed by SMSG_PARTY_MEMBER_STATS -- and returns health, maxHealth, power, maxPower, powerType, level, areaId, online (both paths) plus dead, subgroup, rank (raid path). Raid-struct layout mapped from Script_GetRaidRosterInfo (0x004bb560): subgroup@+8, rank@+0xc, flags@+0x18 (bit0 online, bit2 dead), level@+0x22, areaId@+0x24, plus the health/power fields already used. UnitPower/Max/Missing now go through it (no behavior change -- verified target still reads UnitPower == UnitMana == 2896 on a different map), and UnitHealthMissing gains the same fallback so it no longer returns 0 for an out-of-range groupmate. UnitPowerType already had the engine's own roster fallback (0x00517940) and needs nothing. The extra fields (level/area/online/dead/subgroup/rank) are populated but not yet consumed -- groundwork for fixing UnitLevel / UnitIsConnected / UnitIsDead and a full GetRaidRosterInfo for out-of-range members. |
||
|
|
72de6c0960 |
unit: fall back to the group roster for out-of-range power reads
UnitPower / UnitPowerMax / UnitPowerMissing read the CGUnit descriptor directly, so they returned 0 for a party/raid member on a different map (no live object). The engine's UnitMana/UnitManaMax don't -- they fall back to the cached member stats from SMSG_PARTY_MEMBER_STATS. Mirror that fallback: when ResolveArgs finds no live object, resolve token -> GUID and read the member's primary power from the party stats block (FUN_GROUP_MEMBER_STATS_LOOKUP: type@+9, cur@+0xe, max@+0x10) then the raid slot (FUN_GROUP_MEMBER_SLOT_LOOKUP: type@+0x58, cur@+0x60, max@+0x62), all u16 -- exactly Script_UnitMana (0x00517670) / Script_UnitManaMax (0x005177e0). Verified in-game: a different-map target now reports UnitPower == UnitMana (2896) instead of 0. Limitation (inherent): the roster caches only the member's primary power, so an explicit non-primary powerType returns 0 out of range. Reached only after ResolveArgs fails on an already-valid token, so TokenToGUID can't raise. |
||
|
|
eeba4ada9d |
focus: keep focus on party/raid members that leave range
3.3.5 does not drop focus the instant a unit leaves the object table -- its
object-teardown purge (FUN_00524350) is gated by FUN_00512a30, which is
"party-member (FUN_0052d310) OR raid-member (FUN_00573200)". So a groupmate
whose CGUnit is destroyed by going out of range/LoS keeps focus and reattaches
when they return; only non-group units clear on despawn. (Verified in 3.3.5
via Ghidra: focus GUID at DAT_00bd07d0/d4, sole writer FUN_0051ff20, purge
gate decoded to the party/raid roster checks.)
OnWorldTick now mirrors that gate: on an ObjectByGUID miss it keeps focus when
IsGroupMemberGuid(g_focusGUID) -- reading the object-independent roster GUIDs
(VAR_PARTY_GUIDS 4-slot array + VAR_RAID_MEMBER_PTRS 40-slot member-ptr array,
GUID at *member+0) -- otherwise clears as before. A new g_focusObserved flag
tracks whether the "focus" unit-event observers are attached to a live object;
they die with the object on despawn, so OnWorldTick re-registers them when a
groupmate returns to range, and Set() registers only against a resolvable
object (deferring to OnWorldTick when focusing an out-of-range member).
Corrects the earlier note claiming vanilla/modern drop focus on mere range
loss -- that was wrong; the drop is object-teardown gated by group membership.
While a groupmate is out of range UnitExists("focus") is still false (no client
object to read), but the focus survives and snaps back live on their return.
|
||
|
|
5f13c63c99 |
unit: add UnitSpellHaste(unit) -- backport of the TBC+ haste getter
Vanilla 1.12 has no spell-haste API. UnitSpellHaste reads UNIT_MOD_CAST_SPEED
(the cast-time multiplier at descriptor +0x22c that the server folds into
SpellEntry::GetCastTime) and converts it to the modern haste percentage:
haste% = (1 / modCastSpeed - 1) * 100
so 1.0 -> 0, 0.5 (half cast time) -> 100, and a slow like Curse of Tongues
(>1.0) -> negative. This is the Blizzard-shaped surface over the same field
nampower exposes raw as GetUnitField(unit, "modCastSpeed"), letting addons
drop that dependency (raw multiplier recoverable as 1/(1 + haste/100)).
Formula verified byte-exact against 4.3.4's Script_UnitSpellHaste
(FUN_004555b0): `(C1 / mult) * C2 - C2` with C1=1.0, C2=100.0 and a
div-by-zero guard -- the constants are forced by "unhasted must read 0" and
"return a percentage". The 4.3.4 field lives at desc+0x10c; +0x22c is the
verified 1.12 offset. Our div-guard uses `> 0` vs retail's `!= 0` (identical
for the always-positive cast-speed field, marginally more defensive).
New src/unit/SpellHaste.cpp + OFF_UNIT_MOD_CAST_SPEED; docs + README updated.
|
||
|
|
afa1f62720 |
unit: add the unmodified arg to UnitPower / UnitPowerMax
Completes the retail signature UnitPower(unit [, powerType [, unmodified]]) (and UnitPowerMax). A truthy third arg skips the per-type display divisor and returns the raw internal value, via the same ToBoolean(L, 3) path already used by UnitPowerMissing. Verified in-game on a warrior (rage, divisor 10): UnitPower(1)=96 UnitPower(1,true)=961 (floor(961/10)=96) UnitPowerMax(1)=100 UnitPowerMax(1,true)=1000 UnitPowerMissing(1)=4 UnitPowerMissing(1,true)=39 The missing=4 (not 3) confirms the display-value subtraction: 100-96, not (1000-961)/10 floored to 3. Docs updated (signature, TOC anchor, unmodified note). |
||
|
|
c369373efe |
unit: add UnitPowerMissing(unit [, powerType [, unmodified]])
The power analogue of UnitHealthMissing: returns UnitPowerMax - UnitPower for the given type in one native call. Reuses the Power module's ResolveArgs / PowerDivisor, so it inherits the primary-power fallback (powerType omitted) and per-type display divisor. The unmodified third arg (truthy) skips the divisor for the raw internal deficit, matching retail's UnitPower. Subtracts the two display values (each integer-divided) rather than dividing the raw difference, so it equals UnitPowerMax(...) - UnitPower(...) exactly -- the rage case would otherwise be off by one (100/5 -> 95, not (1000-55)/10 = 94). Returns 0 for invalid units and for types the unit has no pool for (e.g. energy on a mana user). Verified in-game: mana 6685-5929 = 756. Docs + README updated. |
||
|
|
1c86d0dead |
unit: add UnitHealthMissing(unit)
Returns the health deficit -- the equivalent of UnitHealthMax(unit) - UnitHealth(unit) -- in one native call, so healing addons don't call both engine getters and subtract in Lua every frame. One token resolve + two descriptor field reads (HEALTH +0x40, MAXHEALTH +0x58); no display divisor (health is stored at face value), clamped at 0. Tracks the engine's own UnitHealth/UnitHealthMax exactly in both forms: real values (player 3600-1 = 3599) and vanilla's percentage form for non-grouped units (target 100-85 = 15). Returns 0 for a valid-but-absent unit, matching UnitHealth's convention. |
||
|
|
786428c9fb |
focus/who: reset per-character state on logout
Both modules held per-character state in process globals that the DLL never cleared on a logout -> character-select -> login (the DLL is not reloaded across that transition), the same bug class as the equipment-set leak. Focus: g_focusGUID / g_focusTargetGUID carried a dead GUID from the prior character into the next. The WorldTick despawn probe self-healed it within a tick, but fired a spurious PLAYER_FOCUS_CHANGED and could not cover a GUID collision. Clear it from a GlueModuleAutoRegister, which fires on the world->glue return a logout triggers but NOT on /reload -- so focus still survives /reload (retail behavior) and drops only on logout. Who: a /who whose SMSG_WHO response never crossed a logout left g_inFlight stuck (IsWhoQueryPending wrongly true for the next character) and the VAR_WHO_TO_UI_FLAG override forced on (routing the next character's /who to the WhoList). Reset in-flight state and restore the flag on every in-game Lua (re)build via ModuleAutoRegister, which fires per login and per /reload before any addon runs -- previously only ResetIfStuck's lazy 10s-on-next- send backstop covered this. |
||
|
|
7531223b9a |
nameplate: assign stable slots instead of a compacting list
Switch nameplateN indexing from a compacting vector (append on ADDED, erase + shift-down on REMOVED) to retail-exact slot assignment: a plate keeps its slot for its whole lifetime, a removal frees the slot, and the next new plate reuses the lowest free one. Survivors are never renumbered when another plate is removed - matching modern WoW, where a middle plate vanishing leaves the others' tokens unchanged and its slot goes vacant until reused. g_orderedGUIDs -> g_slots (sparse; free slots hold GUID 0, trailing empties trimmed). GetGUIDByIndex returns 0 for a free or out-of-range slot; new GetSlotCount exposes the high-water mark. The reverse token walk in Unit::Identity now scans 1..GetSlotCount() and skips gaps instead of stopping at the first 0. The per-plate observer lifecycle is unchanged (keyed on GUID: register on ADD, unregister on REMOVE). Verified in-game: 3 plates in slots 1/2/3, removing the middle one leaves slots 1 and 3 occupied and 2 vacant - no renumber. |
||
|
|
cb4e428592 |
unit: fire per-token unit events for focustarget
Extend the focus observer to the focus unit's current target, so UNIT_HEALTH / UNIT_AURA / ... fire with arg1 == "focustarget" like a native token. Unlike focus (a sticky GUID), the focustarget GUID is volatile - it changes whenever the focus re-targets, and vanilla fires no event for a unit changing its target (UNIT_FIELD_TARGET, field 10, has no event-table slot). So the WorldTick watcher re-reads the focus's target each tick and re-points a second TokenObserver at it only when that identity changes; the focustarget events themselves still fire event-driven through the observer (only the re-pointing is tick-gated, <=1 tick lag). Set() drops the stale focustarget observer immediately on a focus change/clear. Verified in-game: focustarget events fire and re-point when the focus switches targets. |
||
|
|
e7e2fe05dc |
unit: guard TokenObserver against a null observer-registry root
Register/Unregister funnel through FUN_00464890, which dereferences the client/player-rooted observer registry at [VAR_LOCAL_PLAYER_PTR] (+0x24). That root is null out of world (login, loading screens, logout teardown), where the helper null-derefs -> ERROR #132 (ACCESS_VIOLATION reading 0x24). The nameplate teardown on world-exit fires NAME_PLATE_UNIT_REMOVED for every plate, each calling Unregister while the root was already null -> crash. Player::Equipment never hit this because it only registers from the enter-world hook; focus/nameplate register from Lua / WorldTick, which can run mid-transition. Gate both Register and Unregister on RegistryReady() ([VAR_LOCAL_PLAYER_PTR] != null). Out of world there are no live objects or observer nodes to touch anyway - nodes die with their objects on teardown, and in-world callers re-register / clean up on the next tick. |
||
|
|
d7078827fd |
unit: fire per-token unit events for focus and nameplateN
Make the synthetic focus / nameplateN unit tokens first-class sources of the standard per-token unit events (UNIT_HEALTH, UNIT_MANA, UNIT_AURA, UNIT_LEVEL, ...): arg1 == "focus" / "nameplateN" now fires just like "party1", so focus and nameplate frames can update event-driven instead of polling. Vanilla fires these events only for units it "watches" (target/party/raid/pet/mouseover) - FUN_0060c520 recomputes a unit's token-category mask and, on 0->nonzero, FUN_0051bbb0 registers bank-UNIT descriptor-field observers whose callback broadcasts the field's event to the guid's tokens (field index == event id; health +0x40 = event 16 = UNIT_HEALTH). Focus and nameplates are not watch categories, so they never fired. New Unit::TokenObserver replicates that watch registration (FUN_0051bbb0's field set + per-index sizes) with a caller-supplied callback, via the engine's own observer registrar - the same API Player::Equipment uses. No hooks: zero MinHook trampolines, hence no collision risk (the reason this beats co-hooking the broadcast). The registrar appends a fresh node per (guid, field), so our observers coexist with the engine's - a unit that is target AND focus AND a nameplate fires all three tokens. Node lifetime is engine-managed (nodes die with the object; unregister no-ops post-despawn). - Focus: register/unregister in Unit::Focus::Set. - Nameplates: register on NAME_PLATE_UNIT_ADDED, unregister on _REMOVED and (all) in PrepareForReload, since objects survive /reload; the callback resolves the changed guid to its current plate index at fire time. Offsets cross-confirmed against nampower's offsets.hpp (SendUnitSignal 0x515e50, StringParamFormat "%s" 0x82e280, SignalEventParam 0x703f50, UNIT_HEALTH 16); the GUID->token reverse map nampower left as a TODO is FUN_00515c50. |