Compare commits

...
18 Commits
Author SHA1 Message Date
Brues 772cd5ec15 fix(luasyntax): recover call args for loadstring'd vararg chunks
WoW's Lua 5.0 main chunks are not vararg (unlike stock 5.0), so a chunk
called with args had no `arg` to back the transpiled `...` and the old
`local arg={n=0}` fallback silently dropped them --
loadstring("return ...")(1,2,3) yielded nothing.

Compile non-addon vararg chunks (loadstring, /run, XML handler bodies)
as a real 5.0 vararg closure instead: wrap the body in
`return function(...) ... end` and call the main once after a successful
compile, so the caller receives the inner function whose genuine 5.0
`arg` carries the call args. Helper captures stay in the outer main
(runs once at load in the default env, preserving the setfenv-sandbox
rationale); the prefix is newline-free and the closing `end` rides its
own appended line, so error line numbers are unchanged. Addon file
chunks keep the (addonName, addonTable) preamble path.

Verified in-game: loadstring("print(select('#',...),...)")(1,2,3)
prints "3 1 2 3".
2026-08-26 20:24:15 -05:00
Brues a962c76f09 feat(aura): real isFromPlayerOrPlayerPet; fix castByPlayer to Era semantics
Populate AuraData's isFromPlayerOrPlayerPet from the cached caster GUID's
HIGHGUID prefix (player 0x0000 / pet 0xF140, confirmed in tortoise-wow
ObjectGuid.h) instead of hardcoding false. The UnitAura tuple's
castByPlayer (position 13) is the same value under retail's older name --
Era defines it as "applied by a player, their pet or vehicle", not the
local player -- so both now share one HIGHGUID test in ResolveDisplay.
The local-player question stays with the PLAYER filter, unchanged.

False on a cache miss (cast not observed this session); totem buffs read
false (vanilla totems carry the creature prefix, not pet).
2026-08-26 14:34:35 -05:00
Brues 292e206dee fix(aura): seat descriptor slots on cast captures FIFO, not newest-first
When two casters' same-spellID DoTs land in one descriptor-update batch,
the server assigns their slots ascending in cast order
(_AddSpellAuraHolder's first-free-slot scan, verified in tortoise-wow)
and the client diff dispatcher FUN_00604d00 fires OnAuraAdded in
ascending slot order (both loops are plain slot = 0..0x2F walks). The
first application therefore belongs to the earliest cast, and seating
the NEWEST unbound capture paired the two casters' timers and
attribution backwards.

Seat the oldest unbound capture instead, bounded by a 3s window that
covers instant applications and max-range projectile flight (Fireball's
DoT applies at impact) while skipping hit-but-never-applied captures.
The old "older = resisted" rationale for newest-first was moot: resisted
and immune targets sit in SMSG_SPELL_GO's miss list, which ParseSpellGo
never reads, so they never create captures at all.
2026-08-26 14:19:51 -05:00
Brues eef7140722 feat(combat): add StartAttack / StopAttack globals
Backport the non-toggling melee auto-attack verbs. 1.12 ships only the
toggling AttackTarget (FUN_006131A0), so /startattack can't guarantee it
won't cancel an in-progress swing. These call the engine's own start
(FUN_005ECB70, sends CMSG_ATTACKSWING) and stop (FUN_005ECAC0) primitives
directly, split into the two idempotent verbs.

StartAttack takes an optional unit-token target (resolved under pcall so a
name/bad token can't raise, falling back to the current target); with no
arg it validates and attacks the current target via FUN_00612DF0.
2026-08-26 13:49:44 -05:00
Brues 5279c463ed feat(slash): add /click handler and SLASH_CLICK locale strings
Register SlashCmdList["CLICK"], routing through SecureCmdOptionParse and
GetClickFrame to click a named button. Parse name + button only: 1.12's
Button:Click has no down/up path (verified in the base vmethod), so the
retail `down` arg has nothing to act on and a nil button defaults to
LeftButton natively.

Add SLASH_CLICK1/2 to all locale files from Classic Era GlobalStrings.
2026-08-26 12:28:30 -05:00
Brues 855b338736 feat(frame): add GetClickFrame global
Backport the engine-registered C global behind the /click command: resolve
a frame by its global name, returning it only when _G[name] holds a real
frame whose GetName() matches. Mirrors 3.3.5's Script_GetClickFrame; reads
the name from CFrameScriptObject vtable slot +4, verified against 1.12's
own Script_GetName.
2026-08-26 12:01:33 -05:00
Brues 6ca6af1497 fix(slash): route /focus, /clearfocus, /equipset through SecureCmdOptionParse 2026-08-26 11:30:32 -05:00
Brues 1170a4e63a fix(texture): mask via texgen for SetMask so SetTexCoord sprites clip right
SetMask rode the minimap BLIP recipe (explicit second UV stream, uv1 = uv0),
so the mask sampled at the base's texcoords - a SetTexCoord'd sprite made
unit 1 sample that same sub-rect of the MASK image, showing a corner chunk
of the shape instead of the shape.

Retire that path: the path mask is now one extra unit in the texgen draw
(MaskedRegionDrawImpl), its matrix built from the BASE region's own rect
(SetTexCoordModifiesRect crop gate included) plus the base's SetRotation so
a mask keeps following a rotated texture. The angle-0 matrix is exactly the
old recipe's formula re-expressed through positions (see BuildMaskMatrix),
so default 0..1-texcoord textures render identically; sprites become the
fixed case, matching retail (SetMask ignores SetTexCoord).

Side effect: SetMask and AddMaskTexture now compose (alpha intersection)
instead of object masks winning; the path mask occupies one of the 7 units.
2026-08-25 22:28:21 -05:00
Brues 0c8468cf2f refactor(reload): auto-register per-/reload cleanup; fix Time::Timer stale refs
Modules that keep reload-fragile file-static state (Lua registry refs,
frame/object-pointer-keyed maps, cached event-slot indices) each expose a
PrepareForReload() that DllMain called from the FrameScript_Initialize hook.
That list was hand-maintained, so a new module could silently forget to wire
itself in -- the failure mode behind the Frame::Attributes stale-ref bug and
Tooltip::SetEvents issue #33.

Add Game::ReloadAutoRegister + Game::RunReloadCleanups(), mirroring the
existing ModuleAutoRegister / HookAutoRegister / WorldTick::AutoSubscribe
patterns. Each module self-registers with one file-scope line after its
PrepareForReload:

    static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};

DllMain's 11-call manual list collapses to a single RunReloadCleanups(); a
new module can no longer be forgotten. Player::NameCache::Flush stays an
explicit call -- it's a save-before-teardown, not a stale-state clear, and
also runs on the glue-return path.

A sweep of all file-static state found one uncovered module: Time::Timer
pins C_Timer.After/NewTimer/NewTicker callbacks in the Lua registry but never
released them on /reload -- a surviving/stale ref could fire a dead closure.
Add Time::Timer::PrepareForReload (release each pending timer's registry
callback, clear the queue) and self-register it.

- Game.{h,cpp}: ReloadAutoRegister + RunReloadCleanups.
- DllMain.cpp: collapse the manual list to RunReloadCleanups(); drop 6
  now-dead includes.
- 11 existing reload modules + Time::Timer: add the self-register line.

Behavior-preserving (same cleanups, before the Lua teardown); auto-register
order is unspecified across TUs but every callback only clears its own state.
2026-08-25 18:37:44 -05:00
Brues 5196aab4b8 fix(frame): clear attribute maps on /reload to stop stale-ref SetAttribute error
Frame::Attributes kept two file-static maps keyed by the frame's C object
pointer -- g_attrHandlers (OnAttributeChanged handler refs) and
g_unitByFrame (unit tokens for the mouse-focus poll) -- and never cleared
them across a /reload. The Lua reset kills the handler refs, but the map
entries persist, and the allocator recycles frame addresses. So a new
frame reusing an old address, then getting a SetAttribute call, made
FireAttributeChanged fire a DEAD handler ref through the (protected)
invoker; the engine error handler still printed it as an error "in
function SetAttribute" with no Lua frame and an empty message.

SecureStateDriverManager sets OnAttributeChanged every session, so there
was always at least one entry to go stale -- this was the "SetAttribute
occasionally errors after /reload" report (pfUI UpdateVisibility ->
SetAttribute). Same class of bug as Tooltip::SetEvents issue #33.

Add Frame::Attributes::PrepareForReload() clearing both maps, wired from
FrameScript_Initialize_h alongside the other per-reload cleaners.

Also harden EnableFrameMouse (a best-effort side effect of setting the
"unit" attribute): it did SetTop(L, 1) to set up the engine EnableMouse
call, which destroyed the (name, value) at stack[2]/[3] that
FireAttributeChanged reads right after -- handing any OnAttributeChanged
handler a nil arg2. It now invokes the setter through lua_pcall at the top
of the stack and restores the caller's stack, so DoSet's (self, name,
value) survives, and a best-effort mouse-enable can never surface an error
in the addon's SetAttribute.
2026-08-25 18:22:49 -05:00
Brues 536c5e3c51 feat(frame): add PreClick/PostClick button scripts
Backport the modern PreClick/PostClick button scripts as real,
SetScript/GetScript/HookScript-able handlers. Vanilla 1.12 has only
OnClick and OnDoubleClick on buttons.

Two co-hooks (same technique as Tooltip::SetEvents):
- FUN_BUTTON_SCRIPT_RESOLVER: recognize the two names, returning an
  external per-button {handler, context} cell (a button has no free
  slot, and the resolver contract is just "return where the handler
  lives"). This makes them SetScript/GetScript/HookScript-able.
- FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT (the arg'd script runner), gated on
  slotPtr == frame + OFF_BUTTON_ONCLICK_HANDLER (0x4CC): fire PreClick
  before / PostClick after the OnClick, re-invoking with the same
  (fmt, varargs) so both receive arg1 = the button name like OnClick.

Deliberately NOT the button click vmethod FUN_00779540 -- SuperWoW
inline-hooks it for click-casting and a second MinHook there faults
(ERROR #132). The runner is uncontested and fires at the same top-level
dispatch level, so its exec-context stamp is valid.

Cells are keyed by button pointer and cleared on /reload
(PrepareForReload, wired in FrameScript_Initialize_h), matching the
tooltip-cell lifetime.

Limitation (documented): PreClick/PostClick fire only when the button
also has an OnClick handler, since the runner only runs for a non-empty
slot. Bracketing an existing OnClick is the common case; the no-OnClick
path would need the SuperWoW-owned vmethod.

Verified in-game: programmatic and real mouse clicks fire pre,click,post
with matching button-name args, and GetScript round-trips.

- Add offsets FUN_BUTTON_SCRIPT_RESOLVER, OFF_BUTTON_ONCLICK_HANDLER,
  FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT.
- Document under docs/API.md (Frame section) and the README index.
2026-08-25 17:43:41 -05:00
Brues 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).
2026-08-25 15:53:10 -05:00
Brues e793f80f6b feat(spell): add minimap tracking enumeration
Vanilla 1.12 only stores the single active tracking spell
(VAR_ACTIVE_TRACKING_SPELL, 0xBC6378) and never enumerates the tracking
abilities the player knows. Add GetNumTrackingTypes/GetTrackingInfo/
SetTracking, which rebuild that list by scanning the player spellbook for
spells whose EffectApplyAuraName is Track Creatures/Resources/Stealthed
(44/45/151) -- the same discriminator the engine's own active-tracker
updater (FUN_004E4170) uses. This reproduces pfUI's hardcoded tracking
table with no table to maintain and auto-covers server-custom trackers
(e.g. Turtle's Find Trees, 52917).

- GetTrackingInfo returns name, texture, active, category ("spell"),
  spellID; active is read from VAR_ACTIVE_TRACKING_SPELL.
- SetTracking selects a tracker by tail-calling the engine's
  Script_CastSpell(slot, "spell").
- Add offsets VAR_ACTIVE_TRACKING_SPELL and FUN_SCRIPT_CAST_SPELL
  (0x4B42F0), both with RE-provenance comments.
- Document under docs/API.md (Tracking section).

Verified in-game on a Hunter (8 trackers) and a Dwarf racial (1):
active flips on SetTracking, texture matches native GetTrackingTexture,
out-of-range returns nil.
2026-08-24 23:16:34 -05:00
Brues ded767bf19 feat(aura,turtle): support Turtle's Stinging Nettle serpent sting timers
The hunter talent (403; rank passives 51579/51580) makes Mongoose Bite
and triggered fire traps apply the highest known Serpent Sting rank at
20/40% of its duration. Server-side it's a direct AddAura (tortoise-wow
ApplyStingingNettle) — no SMSG_SPELL_GO for the sting — so the cache
seated it caster-less at the full 15s base.

Aura::Source gains a generalized triggered-application rule table (the
judgement-attribution shape, rule-driven): a registered trigger's
SPELL_GO — local player casts only — arms its hit targets for 2s, and a
caster-less application matching the rule's family/mask consumes the arm
in StampApplication (player attribution + the server's own
max(1, base × pct / 100) with player duration mods). Rules can be gated
on a talent passive, read live from the spell-knowledge bitmap at
trigger time so respecs are honored. Because the server's re-apply over
an existing shorter sting reuses the descriptor slot (no OnAuraAdded —
verified in-game with chained Mongoose Bites), the trigger also
refreshes the player's existing cached entry in place, honoring the
server's keep-the-longer-remaining guard. The arm consume runs BEFORE
the WasRecentPlayerCast attribution: the arm names the exact target,
while the recent-cast window is spell-scoped only — a real sting cast at
unit A must not stamp its full duration onto a nettle application on
unit B; a real cast's own application stays protected by the cast-owned
entry guard.

Turtle::StingingNettle registers the rules behind the Turtle::Detected
latch: fire traps by family mask (hunter 0x4 selects exactly the eight
trap-effect spells the server's script binding lists — rank-proof),
Mongoose Bite by exact IDs (its bit 0x2 is shared with Raptor Strike,
which does not trigger nettle). The percents come from the rank spells'
own EffectBasePoints[0] + 1 — the same DBC value the server's
CalculateSimpleValue reads — with the server's 20/40 fallback.
2026-08-24 22:47:52 -05:00
Brues 70a69b64fd fix(spell): fire UNIT_SPELLCAST_DELAYED when the server reconciles cast time
The server scales ranged abilities' cast times by ranged attack speed
(SpellEntry::GetCastTime's IsRangedSpell branch — quiver/Quick Shots),
which the client's prediction helper FUN_006e3340 can't see (its only
caster factor is the spell-haste mult at descriptor +0x22c). So Steady
and Aimed Shot bars started at the fixed 1.5s/2.5s prediction; the
confirming SMSG_SPELL_START already snapped g_cast.endMs to the server's
authoritative castTime, but nothing told addons — the bar kept the
duration it read at UNIT_SPELLCAST_START.

PollPlayer now snapshots the cast's endMs instead of its delayMs and
fires UNIT_SPELLCAST_DELAYED on any end movement — one signal covering
pushback (previously detected via delayMs growth) and the server
reconcile in either direction. Cast bars re-read UnitCastingInfo on
DELAYED and pick up the corrected end. If the packet ever beats the
first poll, START itself carries the corrected end and no DELAYED fires.

Fixes brues-code/pfUI#43
2026-08-24 21:57:11 -05:00
Brues 0f5b50ea14 feat(aura): refresh paladin judgement timers off swings and re-judges
The judgement debuff's duration is maintained server-side with no
client-visible aura change: the paladin's white swings refresh it
(tortoise-wow Unit::DealMeleeDamage - any nonzero melee damage
RefreshHolder's every SPELLFAMILY_PALADIN + SPELL_ATTR_EX3_ALWAYS_HIT
aura the attacker cast on the victim), and a re-judge is an in-place
holder refresh that dirties no descriptor field. Aura::Source's
countdown therefore ran to zero while the debuff stayed up
(brues-code/pfUI#45).

Two client-side triggers mirror the server exactly:

- Swings: Aura::JudgementRefresh subscribes to SMSG_ATTACKERSTATEUPDATE
  (wire format verified against the server's own SendAttackStateUpdate
  writer) and on totalDamage > 0 calls the caster-STRICT
  Aura::Source::RefreshJudgements(victim, attacker) - strict because a
  swing gives no proof of ownership, and adopting there would let any
  tank's white swings pin another paladin's judgement timer.

- The Judgement cast (20271, the one spell every seal judges through):
  the debuff itself is cast server-side with no SPELL_GO the client
  hears (verified live - entries were seated caster-less by
  OnAuraAdded), so the Judgement cast's own SPELL_GO is what names the
  owner. HandleSpellGo refresh-with-adoption's the victim's existing
  judgement entries (the re-judge case) and arms a 2s attribution
  window that StampApplication consumes to give the freshly applied
  debuff its caster - which is what makes the strict swing matching
  work at all.

Refreshes re-fire UNIT_AURA via the existing deferred signal;
StoreFromCast now signals on its in-place recast path too, since an
identity-preserving refresh changes no descriptor field and
event-driven aura bars would never re-read the new timing.

Ability damage (Crusader/Holy Strike) is deliberately NOT a trigger:
melee-class spell damage never routes through the server's refresh
block (DealMeleeDamage's only caller is the white-swing path).

Verified in-game: every landing swing snaps the cached expiration to
now + 10s and pfUI's timer follows; misses/dodges (totalDamage 0) do
not refresh; re-judging resets the timer.

Fixes brues-code/pfUI#45
2026-08-24 18:58:46 -05:00
Brues be6dc200fe fix(addon): restore MouseIsOver's stock 1/nil return contract
The embedded addon replaces FrameXML's MouseIsOver with a wrapper over
the native region:IsMouseOver(), which returns a boolean. Stock 1.12's
MouseIsOver (UIParent.lua:1718) returns 1 on hit and nil otherwise, and
vanilla-era addons compare against that literal - Quiver gates every
widget click on `MouseIsOver(f) == 1`, which `true` silently fails,
deadening its entire config dialog (buttons, checkboxes, icon clicks).

Return 1/nil from the wrapper. 1 is truthy, so modern-style
`if MouseIsOver(f) then` callers are unaffected.
2026-08-24 10:37:39 -05:00
Brues 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).
2026-08-24 10:11:10 -05:00
69 changed files with 2150 additions and 417 deletions
@@ -7,19 +7,42 @@ function RegisterNewSlashCommand(callback, command, commandAlias)
end
SlashCmdList["FOCUS"] = function(msg)
if msg == "" then
FocusUnit();
else
FocusUnit(msg);
end
if ( msg == "" ) then
FocusUnit();
else
local action, target = SecureCmdOptionParse(msg);
if ( action ) then
if ( not target or target == "focus" ) then
target = action;
end
FocusUnit(target);
end
end
end
SlashCmdList["CLEARFOCUS"] = function(msg)
ClearFocus()
if ( SecureCmdOptionParse(msg) ) then
ClearFocus();
end
end
SlashCmdList["EQUIP_SET"] = function(msg)
if msg ~= "" then
C_EquipmentSet.UseEquipmentSet(C_EquipmentSet.GetEquipmentSetID(msg))
end
local set = SecureCmdOptionParse(msg);
if ( set and set ~= "" ) then
C_EquipmentSet.UseEquipmentSet(C_EquipmentSet.GetEquipmentSetID(set))
end
end
SlashCmdList["CLICK"] = function(msg)
local action = SecureCmdOptionParse(msg);
if ( action and action ~= "" ) then
local name, mouseButton = string.match(action, "([^%s]+)%s+([^%s]+)");
if ( not name ) then
name = action;
end
local button = GetClickFrame(name);
if ( button and button:IsObjectType("Button") ) then
button:Click(mouseButton);
end
end
end
+3 -1
View File
@@ -1,3 +1,5 @@
function MouseIsOver(region, topOffset, bottomOffset, leftOffset, rightOffset)
return region:IsMouseOver(topOffset, bottomOffset, leftOffset, rightOffset);
if region:IsMouseOver(topOffset, bottomOffset, leftOffset, rightOffset) then
return 1;
end
end
+2
View File
@@ -80,6 +80,8 @@ SET_NOTE = "Notiz eintragen";
SILVER_AMOUNT_SYMBOL = "S";
SLASH_CLEARFOCUS1 = "/fokusaufheben";
SLASH_CLEARFOCUS2 = "/clearfocus";
SLASH_CLICK1 = "/klick";
SLASH_CLICK2 = "/click";
SLASH_EQUIP_SET1 = "/Ausrüstungsset";
SLASH_EQUIP_SET2 = "/equipset";
SLASH_FOCUS1 = "/fokus";
+2
View File
@@ -81,6 +81,8 @@ SILVER_AMOUNT_SYMBOL = "s";
SILVER_AMOUNT_TEXTURE = "%d|TInterface\\MoneyFrame\\UI-MoneyIcons:%d:%d:0:0:4:1:1:2:0:1|t";
SLASH_CLEARFOCUS1 = "/clearfocus";
SLASH_CLEARFOCUS2 = "/clearfocus";
SLASH_CLICK1 = "/click";
SLASH_CLICK2 = "/click";
SLASH_EQUIP_SET1 = "/equipset";
SLASH_EQUIP_SET2 = "/equipset";
SLASH_FOCUS1 = "/focus";
+2
View File
@@ -80,6 +80,8 @@ SET_NOTE = "Establecer nota";
SILVER_AMOUNT_SYMBOL = "p";
SLASH_CLEARFOCUS1 = "/quitarenfoque";
SLASH_CLEARFOCUS2 = "/clearfocus";
SLASH_CLICK1 = "/clic";
SLASH_CLICK2 = "/click";
SLASH_EQUIP_SET1 = "/conjequip";
SLASH_EQUIP_SET2 = "/equipset";
SLASH_FOCUS1 = "/enfoque";
+2
View File
@@ -80,6 +80,8 @@ SET_NOTE = "Écrire une note";
SILVER_AMOUNT_SYMBOL = "a";
SLASH_CLEARFOCUS1 = "/clearfocus";
SLASH_CLEARFOCUS2 = "/annulerfocal";
SLASH_CLICK1 = "/click";
SLASH_CLICK2 = "/cliquer";
SLASH_EQUIP_SET1 = "/equipset";
SLASH_EQUIP_SET2 = "/équipens";
SLASH_FOCUS1 = "/focus";
+2
View File
@@ -80,6 +80,8 @@ SET_NOTE = "Добавить заметку";
SILVER_AMOUNT_SYMBOL = "с";
SLASH_CLEARFOCUS1 = "/clearfocus";
SLASH_CLEARFOCUS2 = "/сбросфокуса";
SLASH_CLICK1 = "/click";
SLASH_CLICK2 = "/щелчок";
SLASH_EQUIP_SET1 = "/комплект";
SLASH_EQUIP_SET2 = "/equipset";
SLASH_FOCUS1 = "/focus";
+2
View File
@@ -80,6 +80,8 @@ SET_NOTE = "设置备注";
SILVER_AMOUNT_SYMBOL = "银";
SLASH_CLEARFOCUS1 = "/clearfocus";
SLASH_CLEARFOCUS2 = "/clearfocus";
SLASH_CLICK1 = "/click";
SLASH_CLICK2 = "/click";
SLASH_EQUIP_SET1 = "/equipset";
SLASH_EQUIP_SET2 = "/equipset";
SLASH_FOCUS1 = "/focus";
+2
View File
@@ -80,6 +80,8 @@ SET_NOTE = "設定註記";
SILVER_AMOUNT_SYMBOL = "銀";
SLASH_CLEARFOCUS1 = "/clearfocus";
SLASH_CLEARFOCUS2 = "/清除專注目標";
SLASH_CLICK1 = "/click";
SLASH_CLICK2 = "/點擊";
SLASH_EQUIP_SET1 = "/equipset";
SLASH_EQUIP_SET2 = "/裝備套裝";
SLASH_FOCUS1 = "/focus";
+4 -3
View File
@@ -55,7 +55,7 @@ reference in **[docs/API.md](docs/API.md)**.
| [ChatBubbles](docs/API.md#chatbubbles) | `C_ChatBubbles.GetAllChatBubbles` |
| [Class](docs/API.md#class) | `FillLocalizedClassList` |
| [ColorUtil](docs/API.md#colorutil) | `C_ColorUtil.ConvertRGBToHSV`, `C_ColorUtil.ConvertHSVToRGB`, `C_ColorUtil.ConvertHSVToHSL`, `C_ColorUtil.ConvertHSLToHSV`, `C_ColorUtil.ConvertHSLToRGB`, `C_ColorUtil.GenerateTextColorCode`, `C_ColorUtil.WrapTextInColor`, `C_ColorUtil.WrapTextInColorCode` |
| [Combat](docs/API.md#combat) | `InCombatLockdown` |
| [Combat](docs/API.md#combat) | `InCombatLockdown`, `StartAttack`, `StopAttack` |
| [CVar](docs/API.md#cvar) | `C_CVar.GetCVarBool` |
| [Cursor](docs/API.md#cursor) | `GetCursorInfo` |
| [Container](docs/API.md#container) | `C_Container.CalculateTotalNumberOfFreeBagSlots`, `C_Container.GetContainerItemCharges`, `C_Container.GetContainerItemDurability`, `C_Container.GetContainerItemID`, `C_Container.GetContainerItemInfo`, `C_Container.GetContainerItemRepairCost`, `C_Container.GetContainerNumFreeSlots`, `C_Container.GetItemCooldown`, `C_Container.HasContainerItem`, `C_Container.IsContainerItemOpenable`, `C_Container.MoveItem`, `C_Container.PlayerHasHearthstone`, `C_Container.SwapItems`, `C_Container.UseHearthstone`, `GetItemCooldown` |
@@ -67,7 +67,7 @@ reference in **[docs/API.md](docs/API.md)**.
| [Expansion](docs/API.md#expansion) | `ClassicExpansionAtLeast`, `ClassicExpansionAtMost`, `GetClassicExpansionLevel` |
| [Faction](docs/API.md#faction) | `C_Reputation.GetFactionDataByIndex`, `C_Reputation.GetFactionStandings`, `C_Reputation.GetLastStandingChange`, `C_Reputation.GetWatchedFactionData`, `C_Reputation.SetWatchedFactionByID`, `GetFactionIDByIndex`, `GetFactionInfoByID`, `GetFactionParentID` |
| [Focus](docs/API.md#focus) | `ClearFocus`, `FocusUnit` |
| [Frame](docs/API.md#frame) | `region:SetPoint("point")` (one-arg form), `region:SetSize`, `region:GetSize`, `region:IsMouseOver`, `region:GetRect`, `region:IsDragging`, `GetMouseFoci`, `frame:SetShown`, `fontstring:GetStringHeight`, `fontstring:GetUnboundedStringWidth`, `fontstring:GetWrappedWidth`, `fontstring:GetNumLines`, `fontstring:GetLineHeight`, `fontstring:IsTruncated`, `fontstring:SetMaxLines`, `fontstring:GetMaxLines`, `fontstring:SetFormattedText`, `texture:SetRotation`, `texture:GetRotation`, `texture:SetVertexOffset`, `texture:GetVertexOffset`, `texture:SetColorTexture`, `texture:SetMask`, `frame:CreateMaskTexture`, `texture:AddMaskTexture`, `texture:RemoveMaskTexture`, `texture:GetNumMaskTextures`, `texture:GetMaskTexture`, `fontstring:SetRotation`, `fontstring:GetRotation`, `frame:SetResizeBounds`, `frame:HookScript`, `frame:IsEventRegistered`, `frame:GetEffectiveAlpha`, `frame:SetAttribute`, `frame:SetAttributeNoHandler`, `frame:ClearAttribute`, `frame:GetAttribute`, `OnAttributeChanged` (script), `SetModernScriptArgs`, `GetModernScriptArgs`, `SecureCmdOptionParse`, `RegisterStateDriver`, `UnregisterStateDriver`, `RegisterAttributeDriver`, `UnregisterAttributeDriver`, `RegisterUnitWatch`, `UnregisterUnitWatch`, `UnitWatchRegistered`, `SecureButton_GetAttribute`, `SecureButton_GetUnit` |
| [Frame](docs/API.md#frame) | `region:SetPoint("point")` (one-arg form), `region:SetSize`, `region:GetSize`, `region:IsMouseOver`, `region:GetRect`, `region:IsDragging`, `GetMouseFoci`, `frame:SetShown`, `fontstring:GetStringHeight`, `fontstring:GetUnboundedStringWidth`, `fontstring:GetWrappedWidth`, `fontstring:GetNumLines`, `fontstring:GetLineHeight`, `fontstring:IsTruncated`, `fontstring:SetMaxLines`, `fontstring:GetMaxLines`, `fontstring:SetFormattedText`, `texture:SetRotation`, `texture:GetRotation`, `texture:SetVertexOffset`, `texture:GetVertexOffset`, `texture:SetColorTexture`, `texture:SetMask`, `frame:CreateMaskTexture`, `texture:AddMaskTexture`, `texture:RemoveMaskTexture`, `texture:GetNumMaskTextures`, `texture:GetMaskTexture`, `fontstring:SetRotation`, `fontstring:GetRotation`, `frame:SetResizeBounds`, `frame:HookScript`, `frame:IsEventRegistered`, `frame:GetEffectiveAlpha`, `frame:SetAttribute`, `frame:SetAttributeNoHandler`, `frame:ClearAttribute`, `frame:GetAttribute`, `OnAttributeChanged` (script), `SetModernScriptArgs`, `GetModernScriptArgs`, `SecureCmdOptionParse`, `RegisterStateDriver`, `UnregisterStateDriver`, `RegisterAttributeDriver`, `UnregisterAttributeDriver`, `RegisterUnitWatch`, `UnregisterUnitWatch`, `UnitWatchRegistered`, `SecureButton_GetAttribute`, `SecureButton_GetUnit`, `PreClick` (script), `PostClick` (script), `GetClickFrame` |
| [FriendList](docs/API.md#friendlist) | `C_FriendList.GetFriendInfo`, `C_FriendList.GetFriendInfoByIndex`, `C_FriendList.GetNumFriends`, `C_FriendList.GetNumOnlineFriends`, `C_FriendList.GetNumWhoResults`, `C_FriendList.GetWhoInfo`, `C_FriendList.IsFriend`, `C_FriendList.IsIgnored`, `C_FriendList.IsIgnoredByGuid`, `C_FriendList.IsWhoQueryPending`, `C_FriendList.SendWhoQueryByName`, `C_FriendList.SetFriendNotes`, `C_FriendList.SetFriendNotesByIndex` |
| [GameObject](docs/API.md#gameobject) | `C_GameObjectInfo.GetGameObjectInfoByID`, `C_GameObjectInfo.RequestLoadGameObjectByID`, `ClosestGameObjectPosition` |
| [Glue](docs/API.md#glue) | `C_Glue.IsOnGlueScreen` |
@@ -93,13 +93,14 @@ reference in **[docs/API.md](docs/API.md)**.
| [Quest](docs/API.md#quest) | `C_QuestLog.GetNumQuestObjectives`, `C_QuestLog.GetQuestDetails`, `C_QuestLog.GetHeaderIndexForQuest`, `C_QuestLog.GetLogIndexForQuestID`, `C_QuestLog.GetQuestIDForLogIndex`, `C_QuestLog.GetTitleForQuestID`, `C_QuestLog.IsOnQuest`, `C_QuestLog.IsQuestDataCachedByID`, `C_QuestLog.IsUnitOnQuest`, `C_QuestLog.RequestLoadQuestByID`, `GetQuestLogLeaderBoardID` |
| [Spell](docs/API.md#spell) | `C_Spell.CancelSpellByID`, `C_Spell.CastAtCursor`, `C_Spell.CastAtUnit`, `C_Spell.CastingInfo`, `C_Spell.ChannelInfo`, `C_Spell.DoesSpellExist`, `C_Spell.GetSchoolString`, `C_Spell.GetSpellCooldown`, `C_Spell.GetSpellDescription`, `C_Spell.GetSpellDispelType`, `C_Spell.GetSpellEffectMechanics`, `C_Spell.GetSpellInfo`, `C_Spell.GetSpellLevelInfo`, `C_Spell.GetSpellLink`, `C_Spell.GetSpellMechanicByID`, `C_Spell.GetSpellName`, `C_Spell.GetSpellPowerCost`, `C_Spell.GetSpellRadius`, `C_Spell.GetSpellReagents`, `C_Spell.GetSpellRequiredTargetLevel`, `C_Spell.GetSpellSubtext`, `C_Spell.GetSpellTexture`, `C_Spell.IsAutoAttackSpell`, `C_Spell.IsCurrentSpell`, `C_Spell.IsNextMeleeSpell`, `C_Spell.IsRangedAutoAttackSpell`, `C_Spell.IsSelfBuff`, `C_Spell.IsSpellHarmful`, `C_Spell.IsSpellHelpful`, `C_Spell.IsSpellInRange`, `C_Spell.IsSpellPassive`, `C_Spell.IsSpellUsable`, `C_Spell.ResetsMeleeSwing`, `C_Spell.SpellHasRange`, `C_Spell.UnitCastingInfo`, `C_Spell.UnitChannelInfo`, `CanDualWield`, `CancelSpellByName`, `CastSpellNoToggle`, `GetCraftSpellID`, `GetSpellBonusDamage`, `GetSpellBonusHealing`, `GetSpellInfo`, `GetSpellLink`, `GetSpellRadius`, `GetSpellRequiredTargetLevel`, `GetSpellSchool`, `IsHarmfulSpell`, `IsHelpfulSpell`, `IsPassiveSpell`, `IsPlayerSpell`, `IsSpellKnown`, `IsUsableSpell`, `SpellHasRange` |
| [SpellBook](docs/API.md#spellbook) | `C_SpellBook.GetCurrentLevelSpells`, `C_SpellBook.GetSkillLineName`, `C_SpellBook.GetSkillLineRank`, `C_SpellBook.GetSpellBookItemInfo`, `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`, `IsIndoors`, `IsInGroup`, `IsInRaid`, `IsLoggedIn`, `IsMounted`, `IsOutdoors`, `IsStealthed`, `IsSwimming` |
| [State](docs/API.md#state) | `CancelShapeshiftForm`, `Dismount`, `GetMirrorTimerInfo`, `GetMirrorTimerProgress`, `GetShapeshiftFormID`, `GetSheathState`, `IsAssistingRitual`, `IsFalling`, `IsIndoors`, `IsInGroup`, `IsInRaid`, `IsLoggedIn`, `IsMounted`, `IsOutdoors`, `IsStealthed`, `IsSwimming` |
| [System](docs/API.md#system) | `CopyToClipboard`, `GetPhysicalScreenSize` |
| [Talent](docs/API.md#talent) | `GetTalentIDByIndex`, `GetTalentSpellID` |
| [Targeting](docs/API.md#targeting) | `GetPlayerFacing`, `TargetDirectionEnemy`, `TargetDirectionFriend`, `TargetNearest`, `TargetNearestEnemyPlayer`, `TargetNearestFriendPlayer` |
| [TaxiMap](docs/API.md#taximap) | `C_TaxiMap.GetTaxiNodesForMap`, `C_TaxiMap.GetAllTaxiNodes`, `C_TaxiMap.GetTaxiPaths`, `C_TaxiMap.GetTaxiPathWaypoints`, `C_TaxiMap.GetTaxiRoute` |
| [Time](docs/API.md#time) | `C_DateAndTime.AdjustTimeByDays`, `C_DateAndTime.AdjustTimeByMinutes`, `C_DateAndTime.CompareCalendarTime`, `C_DateAndTime.GetCalendarTimeFromEpoch`, `C_DateAndTime.GetCurrentCalendarTime`, `C_DateAndTime.GetSecondsUntilDailyReset`, `C_DateAndTime.GetServerTimeLocal`, `C_Timer.After`, `C_Timer.NewTicker`, `C_Timer.NewTimer`, `GetServerTime`, `GetTimeCached` |
| [Totem](docs/API.md#totem) | `GetTotemInfo`, `GetTotemTimeLeft`, `GetTotemDuration`, `TargetTotem` |
| [Tracking](docs/API.md#tracking) | `GetNumTrackingTypes`, `GetTrackingInfo`, `SetTracking` |
| [TradeSkillUI](docs/API.md#tradeskillui) | `C_TradeSkillUI.GetTradeSkillListLink`, `C_TradeSkillUI.GetCraftListLink`, `C_TradeSkillUI.GetTradeSkillListRecipes` |
| [UIColor](docs/API.md#uicolor) | `C_UIColor.GetColors` |
| [Unit](docs/API.md#unit) | `ClosestUnitPosition`, `GetUnitSpeed`, `UnitClassBase`, `UnitCreatureFamilyID`, `UnitCreatureID`, `UnitCreatureTypeID`, `UnitDistanceSquared`, `UnitGUID`, `UnitHealthMissing`, `UnitInLineOfSight`, `UnitInRange`, `UnitIsAFK`, `UnitIsDND`, `UnitIsFeignDeath`, `UnitIsInMyGuild`, `UnitIsMinion`, `UnitIsOtherPlayersPet`, `UnitIsPet`, `UnitIsPossessed`, `UnitOwnerGUID`, `UnitPosition`, `UnitPower`, `UnitPowerMax`, `UnitPowerMissing`, `UnitPowerType`, `UnitRaceBase`, `UnitSpellHaste`, `UnitSpellTargetName`, `UnitStandState`, `UnitSubName`, `UnitTokenFromGUID` |
+171 -12
View File
@@ -55,6 +55,8 @@ build instructions.
- [Combat](#combat)
- [`InCombatLockdown()`](#incombatlockdown)
- [`StartAttack([target])`](#startattacktarget)
- [`StopAttack()`](#stopattack)
- [Console](#console)
- [`ExportInterfaceFiles art|code` (console command)](#exportinterfacefiles-artcode-console-command)
@@ -203,6 +205,8 @@ build instructions.
- [`RegisterAttributeDriver` / `UnregisterAttributeDriver`](#registerattributedriver--unregisterattributedriver)
- [`RegisterUnitWatch` / `UnregisterUnitWatch` / `UnitWatchRegistered`](#registerunitwatch--unregisterunitwatch--unitwatchregistered)
- [`SecureButton_GetAttribute` / `SecureButton_GetUnit`](#securebutton_getattribute--securebutton_getunit)
- [`PreClick` / `PostClick` button scripts](#preclick--postclick-button-scripts)
- [`GetClickFrame(name)`](#getclickframename)
- [FriendList](#friendlist)
- [`C_FriendList.SendWhoQueryByName(name)`](#c_friendlistsendwhoquerybynamename)
@@ -540,6 +544,7 @@ build instructions.
- [`GetMirrorTimerInfo(index)` / `GetMirrorTimerProgress(label)`](#getmirrortimerinfoindex--getmirrortimerprogresslabel)
- [`GetShapeshiftFormID()`](#getshapeshiftformid)
- [`CancelShapeshiftForm()`](#cancelshapeshiftform)
- [`GetSheathState()`](#getsheathstate)
- [System](#system)
- [`GetPhysicalScreenSize()`](#getphysicalscreensize)
@@ -584,6 +589,11 @@ build instructions.
- [`GetTotemDuration(slot)`](#gettotemdurationslot)
- [`TargetTotem(slot)`](#targettotemslot)
- [Tracking](#tracking)
- [`GetNumTrackingTypes()`](#getnumtrackingtypes)
- [`GetTrackingInfo(index)`](#gettrackinginfoindex)
- [`SetTracking(index)`](#settrackingindex)
- [TradeSkillUI](#tradeskillui)
- [`C_TradeSkillUI.GetTradeSkillListLink()`](#c_tradeskilluigettradeskilllistlink)
- [`C_TradeSkillUI.GetCraftListLink()`](#c_tradeskilluigetcraftlistlink)
@@ -1449,6 +1459,26 @@ if UnitAffectingCombat("player") then
end
```
### `StartAttack([target])`
Starts your melee auto-attack. The vanilla `AttackTarget()` turns the attack on
or off with each call. `StartAttack` only starts it — a call while you attack
your current target does not toggle the attack off. So a `/startattack` macro
can use it safely.
With no argument, it attacks your current target. With a unit token (`"target"`,
`"focus"`, `"party1"`), it attacks that unit. A name or an unknown token uses the
current target instead. If there is no valid target, nothing happens.
```lua
StartAttack() -- attack the current target; never cancels an attack
StartAttack("focus") -- attack your focus unit
```
### `StopAttack()`
Stops your melee auto-attack. If you are not attacking, the call does nothing.
## Console
### `ExportInterfaceFiles art|code` (console command)
@@ -4460,7 +4490,7 @@ masking — only the special-cased minimap.
`path` is a mask texture. The mask's ALPHA channel is the shape: where the mask
is opaque the texture shows, where the mask is transparent the texture is
hidden. The mask is sampled across the texture's own texture coordinates, so it
hidden. The mask stretches across the texture's full display area, so it always
lines up with the texture. Pass `nil` or `""` to remove the mask; the texture
returns to its full rectangle.
@@ -4486,10 +4516,12 @@ t:SetMask("Interface\\AddOns\\MyAddon\\round") -- or your own mask texture
t:SetMask(nil) -- remove the mask
```
> One difference from later clients: the mask follows the texture's own
> coordinates. If you crop the texture with `SetTexCoord`, the mask follows the
> cropped region rather than the full display area. For a normal, uncropped
> texture the two are the same.
> The mask ignores `SetTexCoord`, the same as later clients. If you crop the
> texture to one sprite of a sprite sheet, the full mask shape still clips that
> sprite. The mask follows
> [`texture:SetRotation`](#texturesetrotationangle--cx-cy). It also combines
> with masks from [`texture:AddMaskTexture`](#textureaddmasktexturemask): the
> texture shows only where every mask is opaque.
### `frame:CreateMaskTexture([name, layer, ...])`
@@ -4521,8 +4553,9 @@ texture shows; where the mask is transparent the texture is hidden.
Call it again with a different mask to add another. A texture with several masks
shows only where ALL of them are opaque — the masks intersect. So two circles
show their overlapping lens, and a square plus a circle show a square with
rounded corners. Up to 7 masks apply at once. Masks cannot subtract, so you
cannot cut a hole with this.
rounded corners. Up to 7 masks apply at once. A mask set with
[`texture:SetMask`](#texturesetmaskpath) uses one of the 7 slots. Masks cannot
subtract, so you cannot cut a hole with this.
A mask honors [`texture:SetRotation`](#texturesetrotationangle--cx-cy): rotate
the mask and its clip shape turns with it. The mask can also move or resize each
@@ -4955,6 +4988,51 @@ it to find a frame's unit.
has no combat lockdown or taint, so nothing here is protected — the names exist
for addon compatibility.
### `PreClick` / `PostClick` button scripts
Two button scripts that run immediately before and after `OnClick`. Vanilla
1.12 has only `OnClick` and `OnDoubleClick` on buttons. Patch 2.0 added
`PreClick` and `PostClick`. They are real scripts: set them with `SetScript`,
read them with `GetScript`, and hook them with `HookScript`.
One click runs the three handlers in this order:
```
PreClick -> OnClick -> PostClick
```
Each handler gets `arg1` — the mouse button name (`"LeftButton"`,
`"RightButton"`, …) — the same value `OnClick` gets. With modern positional
arguments on (the default), the handler signature is `function(self, button)`.
```lua
local btn = CreateFrame("Button", "MyButton", UIParent)
btn:SetScript("PreClick", function() print("before the click:", arg1) end)
btn:SetScript("OnClick", function() print("the click") end)
btn:SetScript("PostClick", function(self, button) print("after the click:", button) end)
```
**The button must also have an `OnClick` handler.** `PreClick` and `PostClick`
fire around `OnClick`. A button with no `OnClick` set fires neither. This serves
the normal use: run code just before or after a button's click action. (Modern
WoW fires them even with no `OnClick`; that path is not available on this
client.)
### `GetClickFrame(name)`
Returns the frame with the given global name. The `/click` command uses it to
change a frame name into the frame.
The function returns the frame only when `_G[name]` holds a real frame, and the
`GetName()` of that frame is equal to `name`. If the global holds a different
value, a plain table, or a frame with a different name, the function returns
nil. This name test makes sure that a changed global does not return the wrong
frame.
```lua
GetClickFrame("MyButton") -- the frame named "MyButton", or nil
```
## FriendList
### `C_FriendList.SendWhoQueryByName(name)`
@@ -13413,6 +13491,29 @@ Mirrors 3.3.5a's `Script_CancelShapeshiftForm` inner (`FUN_00726CE0`),
which does the same effect-array scan + form-id match before issuing
its cancel packet. Vanilla just lacks the public Lua surface.
### `GetSheathState()`
Returns the weapon type that the player has drawn. Takes no arguments.
The value is 1-based:
| Value | Meaning |
|-------|---------|
| `1` | None. The weapons are put away. |
| `2` | A melee weapon is drawn. |
| `3` | A ranged weapon is drawn. |
Returns `1` before the player object exists (out of world).
```lua
if GetSheathState() == 3 then
-- the ranged weapon is out
end
```
Vanilla 1.12 has `ToggleSheath()` but no matching getter. `GetSheathState`
adds the query, with the same 1-based values that modern WoW returns. To
change the state, use the built-in `ToggleSheath()`.
## System
Host/OS-level helpers that aren't tied to a game domain.
@@ -14141,6 +14242,62 @@ Looks up the totem creature's live GUID (object-manager scan for the
player-owned creature of the slot's tracked entry) and sets the target
through the same engine path `TargetUnit` uses (`CMSG_SET_SELECTION`).
## Tracking
Vanilla 1.12 stores only the tracking spell that is active now. It does
not keep a list of the tracking spells you know. These globals add that
list. A minimap addon can then build a tracking menu without a hardcoded
spell table.
A tracking spell is a spell in your spellbook that finds creatures,
resources, or hidden units. This is the same test the engine uses to find
the active tracker. The list covers Find Herbs, Find Minerals, Find
Treasure, the Hunter Track spells, Sense Undead, Sense Demons, and Track
Humanoids. It also covers server-added trackers, such as Turtle's Find
Trees. You do not have to maintain a spell list.
### `GetNumTrackingTypes()`
Returns the number of tracking spells in your spellbook.
```lua
GetNumTrackingTypes() -- for example, 8 for a Hunter
```
### `GetTrackingInfo(index)`
`index` starts at 1 and follows spellbook order. The function returns
these five values, or `nil` if `index` is out of range:
| # | Value | Type | Notes |
|---|-------|------|-------|
| 1 | `name` | string | Localized spell name. |
| 2 | `texture` | string | Icon path. Give it to `texture:SetTexture(...)`. `nil` if the icon is missing. |
| 3 | `active` | boolean | `true` when this tracker is the one now in effect. |
| 4 | `category` | string | Always `"spell"`. Vanilla has no non-spell trackers. |
| 5 | `spellID` | number | The tracking spell's ID. This is a ClassicAPI extra. The retail 5th value is `nested`, which has no meaning here. |
```lua
local name, texture, active, category, spellID = GetTrackingInfo(1)
```
### `SetTracking(index)`
Turns on the tracking spell at `index`. In vanilla, you select a tracker
when you cast its spell. This function casts it. For an out-of-range
index, it does nothing. To turn tracking off, use the built-in
`CancelTrackingBuff()`.
```lua
for i = 1, GetNumTrackingTypes() do
local name = GetTrackingInfo(i)
if name == "Find Herbs" then
SetTracking(i)
break
end
end
```
## TradeSkillUI
Backports the 2.x+ **trade-skill list link** — the shareable
@@ -15180,7 +15337,8 @@ these functions surface them, exactly as the built-in `UnitBuff` /
| `sourceGUID` | string | caster's `"0x…"` GUID string from the same cache. **ClassicAPI extension — not a retail `AuraData` field.** Set whenever a caster is known, including when `sourceUnit` is `nil` (caster left token range). Stable for the session, unlike the volatile nameplate token; doubles as a unit token under SuperWoW. `nil` on a cache miss |
| `charges` / `maxCharges` | number | always `0` — vanilla has stacks, not charges |
| `timeMod` | number | always `1` — vanilla has no haste-affected auras |
| `isStealable`, `isBossAura`, `isFromPlayerOrPlayerPet`, `isNameplateOnly`, `nameplateShowAll`, `nameplateShowPersonal`, `canApplyAura`, `shouldConsolidate`, `isRaid` | boolean | always `false` — modern UI concepts vanilla doesn't have |
| `isFromPlayerOrPlayerPet` | boolean | true when a player — any player, not only you — or a player's pet applied the aura. Read from the cached caster GUID, so it is `false` when the cast was not seen this session. Totem buffs read `false`: a vanilla totem is a creature, not a pet |
| `isStealable`, `isBossAura`, `isNameplateOnly`, `nameplateShowAll`, `nameplateShowPersonal`, `canApplyAura`, `shouldConsolidate`, `isRaid` | boolean | always `false` — modern UI concepts vanilla doesn't have |
| `auraInstanceID`, `points` | (absent) | omitted from the table — Lua read yields nil, matching modern semantics for "field doesn't apply" |
### Filter parsing
@@ -15341,14 +15499,15 @@ nameplateShowAll, timeMod
Returns a single `nil` when the unit has fewer than `index` matching auras.
`dispelType` is the dispel-type string (`"Magic"`, `"Curse"`, `"Disease"`,
`"Poison"`, or `nil`). `source` is the caster's unit token, or `nil` when the cast
was not seen this session. `castByPlayer` is true when the local player cast the
aura. `filter` takes the same tokens as `GetAuraDataByIndex`.
was not seen this session. `castByPlayer` is true when a player — any player, not
only you — or a player's pet applied the aura, and false when the cast was not
seen this session. `filter` takes the same tokens as `GetAuraDataByIndex`.
The values are the `GetAuraDataByIndex` fields in the classic `UnitAura` order,
with two field-name differences from the table: position 12 is `isBossDebuff`
(the table field is `isBossAura`) and position 13 is `castByPlayer` (the table
field is `isFromPlayerOrPlayerPet`). On 1.12 the boss field is always false;
`castByPlayer` is reported truthfully.
field is `isFromPlayerOrPlayerPet`, the same value). On 1.12 the boss field is
always false; `castByPlayer` is reported truthfully.
### `C_UnitAuras.UnitBuff(unit, index [, filter])` / `UnitDebuff(unit, index [, filter])`
+10 -50
View File
@@ -16,15 +16,11 @@
#include "MinHook.h"
#include "Offsets.h"
#include "event/Custom.h"
#include "luasyntax/StringMethods.h"
#include "model/DisplayInfo.h"
#include "nameplate/Walk.h"
#include "player/NameCache.h"
#include "text/InlineTexture.h"
#include "text/InlineTexturePool.h"
#include "texture/Mask.h"
#include "texture/Transform.h"
#include "tooltip/SetEvents.h"
static Game::FrameScript_Initialize_t FrameScript_Initialize_o = nullptr;
static Game::LoadScriptFunctions_t LoadScriptFunctions_o = nullptr;
@@ -40,53 +36,17 @@ static FrameRegisterEvent_t FrameRegisterEvent_o = nullptr;
static void __fastcall InvalidFunctionPtrCheck_h() {}
static bool __fastcall FrameScript_Initialize_h() {
// BEFORE the engine tears down the old event table (at the start of
// FrameScript_Initialize), invalidate our cached slot indices. The
// table is rebuilt at a fresh allocation; the old slots are stale.
Event::Custom::PrepareForReload();
// Fire every module's PrepareForReload BEFORE the engine tears down the old
// event table / Lua state. Each module that keeps reload-fragile state (Lua
// refs, frame-pointer-keyed maps, cached event-slot indices) self-registers
// via `static const Game::ReloadAutoRegister _reload{&PrepareForReload};`,
// so this one call clears them all — a new module can't forget to wire in
// (see the ReloadAutoRegister doc in Game.h). This hook fires on both
// `/reload` and `/logout` (the engine re-inits the Lua state in both).
Game::RunReloadCleanups();
// Clear the nameplate diff state so currently-visible plates
// refire CREATED and UNIT_ADDED on the next tick — re-presents
// them to the freshly reloaded UI, matching modern WoW. The
// wrappers themselves now live in the engine's own registry
// (via `FrameScript_Object::ScriptRegister`), which the engine
// tears down and rebuilds across the Lua reset — no per-module
// cache to clear here.
NamePlate::Events::PrepareForReload();
// The reload teardown destroys every icon pool texture, fontstring,
// and text node — forget all inline-icon pointers now so nothing
// touches them (see InlineTexture.h / InlineTexturePool.h).
Text::InlineTexture::PrepareForReload();
Text::InlineTexturePool::PrepareForReload();
// Drop per-region corner transforms (SetRotation / SetVertexOffset) — the
// reload destroys every addon texture and the region pool reuses their pointers.
Texture::Transform::PrepareForReload();
// Drop per-region texture masks for the same reason (SetMask).
Texture::Mask::PrepareForReload();
// Drop pending character-dress jobs and their engine compositors — the
// reload destroys every Model frame the jobs point at.
Model::DisplayInfo::PrepareForReload();
// Drop the per-tooltip OnTooltipSet* handler cells — the reload destroys
// and recreates every tooltip object, and the handler refs die with the
// Lua reset (issue #33: the cell table filled after ~18 reloads, then
// recycled tooltip addresses fired dead refs).
Tooltip::SetEvents::PrepareForReload();
// Forget the captured `string` table before the world Lua state resets
// (this hook also fires on /logout, where the state's tables die) —
// string-method resolution fails closed (stock index error) until
// LoadScriptFunctions re-captures.
LuaSyntax::StringMethods::PrepareForReload();
// Persist the name cache before the engine starts tearing down.
// This hook fires on both `/reload` and `/logout` (the engine
// re-initializes Lua state in both cases), giving us a clean
// deterministic save point for the common lifecycle events.
// Persist the name cache before the engine tears down — a SAVE, not a clear,
// so it stays an explicit call rather than a ReloadAutoRegister.
Player::NameCache::Flush();
FrameScript_Initialize_o();
+10
View File
@@ -288,6 +288,7 @@ namespace {
ModuleAutoRegister *g_moduleHead = nullptr;
GlueModuleAutoRegister *g_glueModuleHead = nullptr;
HookAutoRegister *g_hookHead = nullptr;
ReloadAutoRegister *g_reloadHead = nullptr;
} // namespace
ModuleAutoRegister::ModuleAutoRegister(Fn f) : fn(f), next(g_moduleHead) {
@@ -309,6 +310,15 @@ void RunGlueModuleRegistrations() {
node->fn();
}
ReloadAutoRegister::ReloadAutoRegister(Fn f) : fn(f), next(g_reloadHead) {
g_reloadHead = this;
}
void RunReloadCleanups() {
for (auto *node = g_reloadHead; node != nullptr; node = node->next)
node->fn();
}
HookAutoRegister::HookAutoRegister(uintptr_t target, void *hook, void **original)
: target(target), hook(hook), original(original), next(g_hookHead) {
g_hookHead = this;
+31
View File
@@ -412,4 +412,35 @@ struct HookAutoRegister {
// and stops on first failure.
bool RunHookRegistrations();
// Self-registration for per-/reload state cleanup. A module that keeps
// file-static state which goes STALE across a game /reload declares a
// file-scope `static const Game::ReloadAutoRegister _reload{&PrepareForReload};`
// right after its `void PrepareForReload()`. `RunReloadCleanups()` — called
// from the FrameScript_Initialize hook, BEFORE the engine tears down the Lua
// state — fires them all, so DllMain no longer hand-maintains the list and a
// new module can't forget to wire itself in.
//
// State is "reload-fragile" when it survives in C++ but its meaning does not:
// - Lua registry refs / handler cells (the Lua reset invalidates them);
// - maps/sets keyed by a frame/object POINTER (the allocator recycles
// addresses, so an old entry aliases an unrelated new object);
// - cached event-slot indices (the engine rebuilds the event table).
// Firing a stale entry is the recurring bug this prevents (Tooltip::SetEvents
// issue #33, Frame::Attributes). A pure-C++ cache keyed by spellID/itemID is
// NOT fragile and must not register.
//
// Same lifetime + ordering rules as ModuleAutoRegister: static-init chaining,
// undefined cross-TU order — fine, because each callback only clears its OWN
// state. This is the "clear stale state" category only; a save-before-teardown
// like Player::NameCache::Flush stays an explicit DllMain call (it persists
// rather than clears, and also runs on the glue-return path).
struct ReloadAutoRegister {
using Fn = void (*)();
explicit ReloadAutoRegister(Fn fn);
Fn fn;
ReloadAutoRegister *next;
};
void RunReloadCleanups();
} // namespace Game
+93 -5
View File
@@ -226,6 +226,35 @@ enum Offsets {
// so a pointer-keyed cell never goes stale). Same pattern + ABI modeling as
// FUN_GAMETOOLTIP_SCRIPT_RESOLVER.
FUN_FRAME_SCRIPT_RESOLVER = 0x0076A0D0,
// Button widget script-name resolver — __thiscall(button, const char *name)
// -> int* slot, 0 for an unknown name. Sits at vtable+0xC on all four
// button-family vtables (Button + subclasses). Delegates to the base frame
// resolver FUN_FRAME_SCRIPT_RESOLVER first, then maps the two button
// scripts: OnClick -> button+0x4CC, OnDoubleClick -> button+0x4D4 (each an
// 8-byte {handler, context} slot). Vanilla has no PreClick/PostClick, so
// `Frame::ClickEvents` co-hooks this to hand out an external per-button cell
// for those two names — same technique as FUN_GAMETOOLTIP_SCRIPT_RESOLVER.
FUN_BUTTON_SCRIPT_RESOLVER = 0x00778C50,
// Button OnClick script slot offset (the resolver's OnClick return). Used
// by `Frame::ClickEvents` to recognize an OnClick fire at the runner hook
// below: the fire passes slotPtr == button + this offset.
OFF_BUTTON_ONCLICK_HANDLER = 0x4CC,
// Frame-script runner WITH exec-context stamping — __cdecl(void *frame,
// int *slotPtr, const char *fmt, void *vaPtr). Saves DAT_00ceeac0, stamps
// it from slotPtr[1] (the cell's context), then calls FUN_FRAME_RUN_SCRIPT_ARGS
// (the arg'd runner Frame::ScriptArgs hooks) and restores. Every arg'd
// input-script fire funnels through here via FUN_007026F0 (its variadic
// forwarder); the event dispatcher FUN_00703F50 is the only other caller.
// `Frame::ClickEvents` co-hooks it, gates on `slotPtr == frame +
// OFF_BUTTON_ONCLICK_HANDLER` (an exact OnClick match — no other fire passes
// that slot address), and fires PreClick before / PostClick after by
// re-invoking with the same (fmt, vaPtr) so the button-name arg is reused.
// Deliberately NOT the button click vmethod FUN_00779540, which SuperWoW
// inline-hooks for click-casting (a second hook there faults, ERROR #132 —
// see the note near FUN_SCRIPT_FRAME_GET_STRATA); this runner is uncontested.
FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT = 0x00702710,
// The other per-object tooltip builders, co-hooked the same way as
// FUN_GAMETOOLTIP_BUILD_ITEM to back OnTooltipSetSpell / OnTooltipSetUnit /
// OnTooltipSetGameObject (see Tooltip::SetEvents). Each is the single funnel
@@ -1755,6 +1784,15 @@ enum Offsets {
// from SMSG_SPELL_START, not server-broadcast state).
OFF_UNIT_CAST_SPELL = 0xC8C,
// CGUnit field: the unit's sheath state as a plain int member (NOT a
// descriptor UpdateField). 0 = sheathed / no weapon shown, 1 = melee
// weapon drawn, 2 = ranged weapon drawn. Read and written by the engine's
// own sheath toggler `FUN_005EB480` (behind `ToggleSheath`) and its setter
// `FUN_00611CF0` (`*(this+0xD40) = newState`, saving the prior state to
// `+0xD3C`). `Unit::Sheath::GetSheathState` reads the local player's value
// and returns it 1-based (Lua's GetSheathState is 1=None/2=Melee/3=Ranged).
OFF_UNIT_SHEATH_STATE = 0xD40,
// NetClient message dispatch — `__thiscall void(void *conn, uint32_t
// arg, CDataStore *packet)`. Reads the u16 opcode off the packet
// cursor, then invokes `[conn + opcode*4 + 0x74]` (the handler table
@@ -1785,6 +1823,13 @@ enum Offsets {
SMSG_SPELL_CHANNEL_UPDATE = 0x13A,
SMSG_SPELL_DELAYED = 0x1E2,
SMSG_SPELL_FAILED_OTHER = 0x2A6,
// Melee swing result broadcast. Body (verified against the server's own
// writer, tortoise-wow Unit::SendAttackStateUpdate): u32 hitInfo,
// packedGuid attacker, packedGuid victim, u32 totalDamage, u8 subCount,
// per-sub {u32 school, f32 coeff, u32 damage, u32 absorb, i32 resist},
// u32 targetState, u32, u32 spellId, u32 blocked. `Aura::JudgementRefresh`
// reads through totalDamage.
SMSG_ATTACKERSTATEUPDATE = 0x14A,
// NetClient send — `__thiscall void(void *conn, CDataStore *packet)`.
// The outgoing counterpart of FUN_NET_MESSAGE_DISPATCH: every CMSG the
@@ -4102,6 +4147,15 @@ enum Offsets {
VAR_PET_SPELLBOOK = 0x00B6F098,
SPELLBOOK_MAX_SLOTS = 0x400,
// Active minimap-tracking spell ID (0 = none). Vanilla tracks exactly
// one active tracker as a plain int here, derived from the player's
// active Track Creatures/Resources/Stealthed aura by `FUN_004E4170`
// (an aura-descriptor observer registered by `FUN_004E4100`). Read by
// `Script_GetTrackingTexture` (`0x004E4A20`), `Script_CancelTrackingBuff`
// (`0x004E4A80`), and `GameTooltip:SetTrackingSpell` (`0x00532C50`);
// `Spell::Tracking::GetTrackingInfo` reads it to report `active`.
VAR_ACTIVE_TRACKING_SPELL = 0x00BC6378,
// Player-spell-knowledge bitmap — `[VAR_PLAYER_SPELL_BITMAP]` is a
// pointer to a dword bitmap covering all spellIDs the player has
// learned, including talent passives, racials, profession recipes,
@@ -4372,6 +4426,15 @@ enum Offsets {
// results). Callable directly from C++ — push args on stack, call.
FUN_SCRIPT_CAST_SPELL_BY_NAME = 0x004B4AB0,
// `Script_CastSpell` — engine's Lua wrapper for the slot-based
// `CastSpell(spellbookSlot, bookType)` global. `int __fastcall(void *L)`.
// Parses (slot, bookType) from stack[1]/[2] via `FUN_004B3EC0`, then
// dispatches through `FUN_SPELL_CAST_DISPATCH` with the current target
// (or self). Raises "Invalid spell slot in CastSpell" for a bad slot.
// Callable from C++ by preparing the stack and tail-calling it (the
// `Spell::Tracking::SetTracking` "select = cast" path does this).
FUN_SCRIPT_CAST_SPELL = 0x004B42F0,
// Inner spell-cast dispatcher — `__fastcall(slot, bookType, targetGuidLo,
// targetGuidHi)`. `Script_CastSpellByName` calls this after resolving
// the spell name to a spellbook slot. For ground-target spells, the
@@ -6347,6 +6410,23 @@ enum Offsets {
FUN_GET_OBJECT_BY_GUID = 0x00468460,
OBJECT_TYPE_ITEM = 2,
// Melee auto-attack primitives (back StartAttack / StopAttack). 1.12
// exposes only the toggling AttackTarget (0x00489B50 -> FUN_006131A0);
// these are the non-toggling start/stop it calls internally.
// START: __thiscall(player, const uint64_t *targetGuid). Validates
// CanAttack on the target, sends CMSG_ATTACKSWING (opcode 0x141), and
// stamps the victim GUID at [player+0xC48]. Idempotent / switch-aware
// on a valid target (never stops an in-progress attack); an
// unattackable target while attacking routes to STOP.
// STOP: __fastcall(player). Clears the attack state; self-guards on the
// attack flag, so it is a no-op (safe) when not attacking.
// RESOLVE_TARGET: __thiscall(player, uint64_t *outGuid) -> int. Validates
// the player's CURRENT target (charm/fear/confuse redirect + CanAttack)
// and writes its GUID; returns 0 (and posts the UI error) if invalid.
FUN_ATTACK_START = 0x005ECB70,
FUN_ATTACK_STOP = 0x005ECAC0,
FUN_ATTACK_RESOLVE_TARGET = 0x00612DF0,
// Inbox — array of mail-entry pointers behind a slot indirection.
// The address itself holds a heap pointer (`MOV ECX, [imm32]` in
// the engine), so reading the array requires one extra deref
@@ -6499,6 +6579,12 @@ enum Offsets {
// SPELL_ATTR_EX3_IGNORE_CASTER_MODIFIERS (verified via disassembly; the
// server enum agrees). NOT AttributesEx2's bit 29 (that's CANT_CRIT).
SPELL_ATTR_EX3_IGNORE_CASTER_MODIFIERS = 0x20000000,
// AttributesEx3 bit 18 — the paladin judgement-debuff marker. The server's
// melee-swing judgement refresh selects auras by SPELLFAMILY_PALADIN +
// this bit (tortoise-wow SpellDefines.h SPELL_ATTR_EX3_ALWAYS_HIT,
// Unit::DealMeleeDamage). Verified in the client Spell.dbc: all 14
// Judgement of Light/Wisdom/Justice/Crusader debuff ranks carry it.
SPELL_ATTR_EX3_ALWAYS_HIT = 0x00040000,
// AttributesEx channel bits (CHANNELED_1 0x4 | CHANNELED_2 0x40) and the
// AttributesEx2 autorepeat flag (bit 5, Auto Shot / Shoot) — each shared
// by more than one module, so kept here rather than redefined locally.
@@ -6971,11 +7057,13 @@ enum Offsets {
// but FUN_004eae10 sets it EXPLICITLY — we mirror that.
// * The SECOND vertex UV stream (uv1) DOES feed unit 1 (FUN_004eae10
// passes a distinct uv1 = this+0x50), so uv1 = uv0 makes unit 1 sample
// the mask at the base's own texcoords — exactly SetMask semantics.
// uv1 is the LAST explicit UV slot that exists: the vertex-format
// component table at 0x008097A8 (13 formats × 13 components) has no
// format with a third UV set, so masks past the first CANNOT ride an
// explicit stream — they use texgen (below).
// the mask at the base's own texcoords. SetMask originally rode this
// recipe but was moved to texgen (below): texcoord-relative sampling
// breaks for SetTexCoord'd sprites (the mask gets sampled at the same
// sub-rect OF THE MASK IMAGE), and uv1 is the LAST explicit UV slot
// that exists — the vertex-format component table at 0x008097A8
// (13 formats × 13 components) has no format with a third UV set, so
// masks past the first cannot ride an explicit stream anyway.
GXRS_TEXTURE0 = 0x17, // texture bind, +unit 0..7 (via FUN_GX_RS_SET_PTR)
GXRS_COMBINER0 = 0x1F, // combiner preset, +unit 0..7 (via FUN_GX_RS_SET)
GXRS_COMBINE_MODULATE = 1, // preset value: COLOROP=MODULATE, ALPHAOP=MODULATE
+6 -9
View File
@@ -68,12 +68,9 @@ namespace AuctionHouse::PostItem {
namespace {
constexpr const char *kEvtStart = "AUCTION_MULTISELL_START";
constexpr const char *kEvtUpdate = "AUCTION_MULTISELL_UPDATE";
constexpr const char *kEvtFailure = "AUCTION_MULTISELL_FAILURE";
const Event::Custom::AutoReserve _r1{kEvtStart};
const Event::Custom::AutoReserve _r2{kEvtUpdate};
const Event::Custom::AutoReserve _r3{kEvtFailure};
const Event::Custom::AutoReserve _evtStart{"AUCTION_MULTISELL_START"};
const Event::Custom::AutoReserve _evtUpdate{"AUCTION_MULTISELL_UPDATE"};
const Event::Custom::AutoReserve _evtFailure{"AUCTION_MULTISELL_FAILURE"};
// Generous per-step abort bound. A split or a post is one server round-trip
// (~tens of frames); 600 frames (~10s at 60fps) means "something's wrong"
@@ -206,7 +203,7 @@ bool FindFreeGeneralSlot(void *L, int *outBag, int *outSlot) {
void Finish(bool success) {
g_job.active = false;
if (!success)
Event::Custom::Fire(Event::Custom::Lookup(kEvtFailure), "");
Event::Custom::Fire(_evtFailure.Slot(), "");
// success needs no event: the last PostWait already fired
// AUCTION_MULTISELL_UPDATE(total, total).
}
@@ -279,7 +276,7 @@ void Tick() {
// Post confirmed once the server pulls the item out of the slot.
if (w.item == nullptr || w.guid != g_job.postGuid) {
++g_job.postedStacks;
Event::Custom::Fire(Event::Custom::Lookup(kEvtUpdate), "%d%d",
Event::Custom::Fire(_evtUpdate.Slot(), "%d%d",
g_job.postedStacks, g_job.totalStacks);
g_job.phase = Phase::Idle;
g_job.waitTicks = 0;
@@ -400,7 +397,7 @@ int __fastcall Script_C_AuctionHouse_PostItem(void *L) {
g_job.runTime = runTime;
g_job.phase = Phase::Idle;
Event::Custom::Fire(Event::Custom::Lookup(kEvtStart), "");
Event::Custom::Fire(_evtStart.Slot(), "");
Game::Lua::PushBool(L, true);
return 1;
}
+12 -6
View File
@@ -451,9 +451,15 @@ const char *DispelName(uint32_t dispelTypeID) {
// The display fields resolved from a spell record + caster, shared by the table
// emitter (`BuildTable`) and the positional emitter (`PushPositional`) so the
// name / icon / dispel-name lookups live in exactly one place. `castByPlayer` is
// the positional tuple's field #13; the table uses `isFromPlayerOrPlayerPet`
// instead, mirroring retail's own divergence between the two aura shapes.
// name / icon / dispel-name lookups live in exactly one place. `castByPlayer`
// is the positional tuple's field #13 and the table's
// `isFromPlayerOrPlayerPet` — same value, retail's two names for the two aura
// shapes. Both mean "applied by ANY player or a player's pet" (Era
// semantics), not the local player — that's the `PLAYER` filter's job. The
// answer is the caster GUID's HIGHGUID prefix: player 0x0000 / pet 0xF140
// (server-confirmed in tortoise-wow ObjectGuid.h). Vanilla totems carry the
// creature prefix, so totem buffs read false. False on a cache miss (cast not
// observed), since a GUID of 0 classifies as neither.
struct Display {
const char *name;
const char *icon;
@@ -472,8 +478,7 @@ static Display ResolveDisplay(uint32_t spellID, uint64_t casterGuid) {
d.name = LocalizedSpellName(spellRecord);
d.icon = SpellIconPath(spellRecord);
d.dispelName = DispelName(dispelTypeID);
d.castByPlayer =
casterGuid != 0 && casterGuid == Unit::Identity::PlayerGuid();
d.castByPlayer = Guid::IsPlayer(casterGuid) || Guid::IsPet(casterGuid);
return d;
}
@@ -523,10 +528,11 @@ static void BuildTable(void *L, uint32_t spellID, int applications,
Game::Lua::SetFieldNumber(L, "maxCharges", 0);
Game::Lua::SetFieldNumber(L, "timeMod", 1);
Game::Lua::SetFieldBool(L, "isFromPlayerOrPlayerPet", disp.castByPlayer);
// Boolean fields whose modern semantics don't apply in vanilla.
Game::Lua::SetFieldBool(L, "isStealable", false);
Game::Lua::SetFieldBool(L, "isBossAura", false);
Game::Lua::SetFieldBool(L, "isFromPlayerOrPlayerPet", false);
Game::Lua::SetFieldBool(L, "isNameplateOnly", false);
Game::Lua::SetFieldBool(L, "nameplateShowAll", false);
Game::Lua::SetFieldBool(L, "nameplateShowPersonal", false);
+78
View File
@@ -0,0 +1,78 @@
// 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 <https://www.gnu.org/licenses/>.
// Paladin judgement melee refresh — client mirror of the server's white-swing
// rule (pfUI#45: the judgement debuff's timer ran to zero while the debuff
// stayed up through the paladin's auto-attacks).
//
// The server rule (tortoise-wow Unit::DealMeleeDamage, vmangos lineage): a
// melee swing that dealt ANY damage (`totalDamage > 0` — misses/dodges/parries
// deal none) refreshes every aura on the victim that the attacker cast whose
// spell is SPELLFAMILY_PALADIN with SPELL_ATTR_EX3_ALWAYS_HIT — the judgement
// marker (all 14 Judgement of Light/Wisdom/Justice/Crusader debuff ranks carry
// it, verified in the client Spell.dbc). RefreshHolder resets the holder to
// its own full duration.
//
// The edit itself is packet-silent (UpdateAuraDuration is self-scoped — the
// same blindness every Turtle::DurationMods rule works around), but its
// TRIGGER is not: DealMeleeDamage's only caller is Unit::AttackerStateUpdate
// (white swings), which then broadcasts SMSG_ATTACKERSTATEUPDATE to everyone
// in range — attacker, victim, and totalDamage are its first fields (wire
// format verified against the server's own SendAttackStateUpdate writer; see
// Offsets.h at SMSG_ATTACKERSTATEUPDATE). So the swing packet is an exact
// client-side stand-in for the refresh, for ANY paladin's judgements — ours
// or a raid member's.
//
// Ability damage (Crusader/Holy Strike) does NOT reach that server block —
// melee-class spell damage never routes through DealMeleeDamage on this core
// — so no rule is registered for it. Re-judging is covered separately: the
// judgement debuff is cast as a real triggered spell, its SMSG_SPELL_GO
// refreshes the cache entry via StoreFromCast.
//
// Not gated on Turtle::Detected(): the block is vmangos-lineage core (the
// classic "judgements are refreshed by the paladin's melee attacks"
// mechanic), and the refresh only ever touches existing judgement entries
// with a matching known caster — on a server without the mechanic the debuff
// would genuinely expire, removing the entry via OnAuraRemoved before drift
// could show.
#include "Offsets.h"
#include "aura/Source.h"
#include "net/PacketDispatch.h"
#include "net/PacketReader.h"
#include <cstdint>
namespace Aura::JudgementRefresh {
namespace {
void OnPacket(uint32_t opcode, Net::CDataStore *packet) {
if (opcode != Offsets::SMSG_ATTACKERSTATEUPDATE || packet == nullptr)
return;
Net::Read<uint32_t>(packet); // hitInfo — the damage gate below subsumes it
const uint64_t attacker = Net::ReadPackedGuid(packet);
const uint64_t victim = Net::ReadPackedGuid(packet);
const uint32_t totalDamage = Net::Read<uint32_t>(packet);
// The server's exact gate: any nonzero melee damage refreshes; a fully
// avoided/absorbed swing (totalDamage 0) does not.
if (totalDamage == 0 || attacker == 0 || victim == 0)
return;
Aura::Source::RefreshJudgements(victim, attacker);
}
const Net::PacketDispatch::AutoSubscribe _sub{&OnPacket};
} // namespace
} // namespace Aura::JudgementRefresh
+418 -13
View File
@@ -238,14 +238,28 @@ Entry *FindBySlot(uint64_t targetGuid, uint32_t spellId, int slot) {
return nullptr;
}
// The newest cast capture for this aura still awaiting a descriptor slot —
// what an `OnAuraAdded` for `(target, spell)` is seating. Newest wins because
// SpellGo precedes the application by a packet, so the freshest unbound entry
// is the cast that just landed; an older one is a capture that never seated
// (fully resisted, immune) and is left to expire on its own. "Newest" is the
// smallest `Time::Clock::Elapsed(stamp, now)` — a wrap-safe signed difference;
// a raw `stampMs >` compare inverts across the 2^32 ms tick wrap.
Entry *FindFreshestUnbound(uint64_t targetGuid, uint32_t spellId, uint32_t now) {
// A capture older than this is not the one an arriving application seats. An
// instant aura's application follows its SpellGo within a server tick plus
// latency (a few hundred ms); a projectile's (Fireball's DoT) follows at
// impact — up to ~1.5s of flight at max range. 3s absorbs both plus lag, yet
// stays far below any DoT's duration, so a capture whose application never
// came (hit but aura-rejected: death race, effect-level immunity on a mixed
// spell) can't be seated by a later same-spell cast's application. Fully
// resisted/immune casts never create captures at all — they sit in
// SMSG_SPELL_GO's miss list, and ParseSpellGo reads only the hit list.
constexpr uint32_t kSeatWindowMs = 3000;
// The cast capture an `OnAuraAdded` for `(target, spell)` is seating: the
// OLDEST unbound capture still inside the seat window — FIFO. When two
// casters' same-spellID DoTs land in one descriptor-update batch, the server
// assigned their slots in cast order (`_AddSpellAuraHolder`'s ascending
// first-free-slot scan) and the client's diff dispatcher (`FUN_00604d00`)
// fires OnAuraAdded in ascending slot order — verified: both its loops are
// plain `slot = 0..0x2F` walks. So the FIRST application belongs to the
// EARLIEST cast; seating newest-first paired the two casters' timers and
// attribution backwards. Elapsed times use `Time::Clock::Elapsed` — a raw
// `stampMs` compare inverts across the 2^32 ms tick wrap.
Entry *FindOldestUnbound(uint64_t targetGuid, uint32_t spellId, uint32_t now) {
Entry *best = nullptr;
uint32_t bestElapsed = 0;
for (int i = 0; i < g_usedHigh; ++i) {
@@ -254,7 +268,9 @@ Entry *FindFreshestUnbound(uint64_t targetGuid, uint32_t spellId, uint32_t now)
e.slot != SLOT_UNBOUND)
continue;
const uint32_t elapsed = Time::Clock::Elapsed(e.stampMs, now);
if (best == nullptr || elapsed < bestElapsed) {
if (elapsed > kSeatWindowMs)
continue;
if (best == nullptr || elapsed > bestElapsed) {
best = &e;
bestElapsed = elapsed;
}
@@ -340,6 +356,10 @@ Entry *Claim(uint32_t now) {
// ---- Writes --------------------------------------------------------------
// Defined in the duration-modifier section below; used by StoreFromCast's
// refresh path too.
void SignalAuraChanged(uint64_t guid);
// The SpellGo hook: authoritative caster + caster-modified (talented) timing.
// Identity is `(target, spell, caster)`, so a second caster of the same spell
// opens its own entry instead of overwriting the first's, and a recast by the
@@ -373,6 +393,12 @@ void StoreFromCast(uint64_t targetGuid, uint32_t spellId, uint64_t casterGuid,
e->casterGuid = casterGuid;
e->expirationMs = expirationMs;
e->durationMs = durationMs;
// An in-place recast refresh changes no descriptor field, so the engine
// fires no UNIT_AURA — event-driven consumers (aura-bar addons counting
// down a once-read duration) would never re-read the new timing. Signal it
// ourselves (deferred to the world tick, coalesced). A NEW application
// doesn't need this: its descriptor write fires the engine's own event.
SignalAuraChanged(targetGuid);
}
// The OnAuraAdded / OnAuraStacksChanged application hooks: a descriptor slot,
@@ -396,7 +422,7 @@ void StoreFromApplication(uint64_t targetGuid, uint32_t spellId,
Entry *e = FindBySlot(targetGuid, spellId, slot);
if (e == nullptr)
e = FindFreshestUnbound(targetGuid, spellId, now);
e = FindOldestUnbound(targetGuid, spellId, now);
if (e == nullptr && slot < 0)
e = FindSole(targetGuid, spellId);
if (e == nullptr) {
@@ -810,6 +836,279 @@ void OnWorldTick() {
const Tick::WorldTick::AutoSubscribe _tickSub{&OnWorldTick};
// ---- Paladin judgement identity + refresh (pfUI#45) ----------------------
//
// The judgement debuff (Judgement of Light/Wisdom/Justice/Crusader) is cast
// SERVER-side as a triggered spell whose SMSG_SPELL_GO never reaches the
// client, so its cache entry is seated caster-less by OnAuraAdded — and the
// server's refresh mechanics are keyed by caster. The one attributable
// signal is the Judgement CAST itself (SPELL_PALADIN_JUDGEMENT, the single
// spell every seal judges through): its SPELL_GO names caster and victim.
// HandleSpellGo uses it to (a) refresh existing judgement entries WITH
// adoption — a re-judge is an in-place RefreshHolder server-side, no
// descriptor change, no OnAuraAdded — and (b) arm a short window so the
// fresh debuff's application gets attributed to the judging caster. From
// then on the caster-STRICT swing refresh (Aura::JudgementRefresh's
// SMSG_ATTACKERSTATEUPDATE subscriber) can do its job.
constexpr uint32_t kSpellJudgement = 20271; // server SPELL_PALADIN_JUDGEMENT
// The server's judgement-debuff selector, verbatim from its melee-refresh
// block (tortoise-wow Unit::DealMeleeDamage): SPELLFAMILY_PALADIN +
// SPELL_ATTR_EX3_ALWAYS_HIT. All 14 debuff ranks carry it (client DBC
// verified); no shared family-flag mask exists (each seal's debuff has its
// own bit), which is why this isn't an AddDurationMod rule.
bool IsJudgementSpell(const uint8_t *rec) {
constexpr uint32_t kPaladinFamily = 10; // SPELLFAMILY_PALADIN
if (rec == nullptr)
return false;
if (*reinterpret_cast<const uint32_t *>(
rec + Offsets::OFF_SPELL_RECORD_FAMILY_NAME) != kPaladinFamily)
return false;
return (*reinterpret_cast<const uint32_t *>(
rec + Offsets::OFF_SPELL_RECORD_ATTRIBUTES_EX3) &
Offsets::SPELL_ATTR_EX3_ALWAYS_HIT) != 0;
}
// Armed attribution: a Judgement cast went off from `caster` at `victim`;
// the triggered debuff's OnAuraAdded lands ~a server tick later (SPELL_GO
// precedes the aura's SMSG_UPDATE_OBJECT — the same ordering kEvictGraceMs
// exists for). One-shot, short TTL so a judge whose debuff never lands
// can't mis-attribute a later application.
struct JudgeArm {
uint64_t victim;
uint64_t caster;
uint32_t untilMs;
};
constexpr int kJudgeArmMax = 4; // simultaneous judging paladins in view
constexpr uint32_t kJudgeArmTtlMs = 2000;
JudgeArm g_judgeArms[kJudgeArmMax];
void ArmJudgementAttribution(uint64_t victim, uint64_t caster) {
const uint32_t now = NowMs();
JudgeArm *slot = nullptr;
for (auto &a : g_judgeArms) {
if (a.victim == victim && a.caster == caster) {
slot = &a; // re-judge inside the TTL — refresh in place
break;
}
if (slot == nullptr &&
(a.victim == 0 || Time::Clock::Reached(now, a.untilMs)))
slot = &a;
}
if (slot == nullptr)
slot = &g_judgeArms[0]; // all live (>4 paladins?) — steal the first
*slot = {victim, caster, now + kJudgeArmTtlMs};
}
// The caster armed for `victim`, or 0. One-shot: consumed on hit.
uint64_t ConsumeJudgementAttribution(uint64_t victim, uint32_t now) {
for (auto &a : g_judgeArms) {
if (a.victim != victim || a.victim == 0 ||
Time::Clock::Reached(now, a.untilMs))
continue;
const uint64_t caster = a.caster;
a = {};
return caster;
}
return 0;
}
// Shared body of the two refresh triggers. `adopt` lets the Judgement-cast
// path claim a caster-less entry (the cast is proof of ownership); the swing
// path stays caster-strict — a swing gives no proof, and adopting there
// would let any tank's white swings pin another paladin's judgement timer.
int RefreshJudgementsImpl(uint64_t unitGuid, uint64_t attackerGuid, bool adopt) {
if (unitGuid == 0 || attackerGuid == 0)
return 0;
const uint32_t now = NowMs();
int refreshed = 0;
for (int i = 0; i < g_usedHigh; ++i) {
Entry &e = g_cache[i];
if (!e.used || e.targetGuid != unitGuid)
continue;
if (e.casterGuid != attackerGuid && !(adopt && e.casterGuid == 0))
continue;
if (e.durationMs == 0)
continue; // never invent a duration
if (!IsJudgementSpell(
Spell::Lookup::RecordForID(static_cast<int>(e.spellId))))
continue;
if (e.casterGuid == 0)
e.casterGuid = attackerGuid; // adoption claim
e.expirationMs = now + e.durationMs; // RefreshHolder → own duration
e.stampMs = now;
SignalAuraChanged(e.targetGuid);
++refreshed;
}
return refreshed;
}
// ---- Triggered applications (server AddAura inference) --------------------
//
// Some server mechanics APPLY an aura as a side effect of another spell via a
// direct AddAura — no cast, no SMSG_SPELL_GO for the applied aura, and a
// duration the packet stream never carries. The application itself reaches
// the client only as a descriptor change (OnAuraAdded → caster-less, base
// duration). But the TRIGGER's SMSG_SPELL_GO is visible, so — same shape as
// the judgement attribution above — a registered trigger cast by the local
// player arms its hit targets for a short window, and the caster-less
// application that follows consumes the arm: player attribution + the rule's
// percentage of the aura's own (player-modified) base duration, mirroring
// the server's `max(1, CalculateDuration(caster) * pct / 100)`.
//
// Registered from src/turtle (Stinging Nettle: Mongoose Bite / fire-trap
// effects apply the highest known Serpent Sting rank at 20/40%). Local
// player only — a rule may be gated on a talent-granted passive
// (`gateSpellId`), and other players' talents aren't client-knowable.
struct TriggeredApplication {
uint32_t triggerSpellId; // exact trigger spell; 0 = match by family+mask below
uint32_t triggerFamily; // (triggerSpellId==0) trigger's SpellFamilyName
uint64_t triggerMask; // (triggerSpellId==0) family-flag overlap — rank-proof
uint32_t gateSpellId; // rule live only while the player knows this; 0 = always
uint32_t affectedFamily; // applied aura's SpellFamilyName
uint64_t affectedMask; // + family-flag overlap
int32_t durationPct; // applied duration = pct% of its own base
};
constexpr int kTrigAppMax = 32;
TriggeredApplication g_trigApps[kTrigAppMax];
int g_trigAppCount = 0;
// Talent gate: does the player currently know `spellID`? The engine's
// spell-knowledge bitmap (same store IsPlayerSpell reads — covers talent
// passives), checked live at trigger time so respecs are honored.
bool PlayerKnowsSpell(uint32_t spellID) {
if (spellID == 0)
return false;
auto *bitmap = Game::Read<const uint32_t *>(
static_cast<uintptr_t>(Offsets::VAR_PLAYER_SPELL_BITMAP));
if (bitmap == nullptr)
return false;
const uint32_t spellCount = Game::Read<uint32_t>(
static_cast<uintptr_t>(Offsets::VAR_SPELL_RECORD_COUNT));
if (spellID > spellCount)
return false;
return (bitmap[spellID >> 5] & (1u << (spellID & 31))) != 0;
}
// Armed rule instance awaiting its application on `victim`. Caster is
// implicitly the local player (only player triggers arm).
struct TrigAppArm {
uint64_t victim; // 0 = empty
uint32_t affectedFamily;
uint64_t affectedMask;
int32_t durationPct;
uint32_t untilMs;
};
constexpr int kTrigAppArmMax = 8;
constexpr uint32_t kTrigAppArmTtlMs = 2000;
TrigAppArm g_trigAppArms[kTrigAppArmMax];
// Mirror the server's re-apply on an EXISTING matching aura at trigger time
// (tortoise-wow ApplyStingingNettle): an existing holder from this caster
// whose remaining time exceeds the scaled duration is kept; otherwise the
// server re-AddAura's at the scaled duration — a remove+add of the same
// spellID that reuses the descriptor slot, so NO OnAuraAdded fires and the
// armed window is never consumed (verified in-game: chained Mongoose Bites
// left the first application's timer running out). The trigger is the only
// audible signal, so the refresh happens here. A caster-less matching entry
// is adopted and stamped unconditionally: it's a nettle application whose
// arm was missed, seated by the application hook at the WRONG base duration,
// so its remaining time can't gate the mirror — and the player's trigger is
// proof of ownership, same as the judgement-cast adoption.
void RefreshTriggeredExisting(uint64_t victim, const TriggeredApplication &r,
uint32_t now) {
for (int i = 0; i < g_usedHigh; ++i) {
Entry &e = g_cache[i];
if (!e.used || e.targetGuid != victim)
continue;
const bool mine = e.casterGuid == Unit::Identity::PlayerGuid();
if (!mine && e.casterGuid != 0)
continue; // another caster's aura — not ours to touch
const uint8_t *rec =
Spell::Lookup::RecordForID(static_cast<int>(e.spellId));
if (!Spell::Lookup::IsFitToFamily(rec, r.affectedFamily,
r.affectedMask))
continue;
const uint32_t base = SpellDurationMs(rec, /*casterIsPlayer*/ true);
if (base == 0)
continue;
uint32_t newMs = base * static_cast<uint32_t>(r.durationPct) / 100;
if (newMs == 0)
newMs = 1;
// The server's keep-the-longer guard, applied only to trusted
// (player-stamped) timing. An elapsed timer yields Remaining 0 and
// refreshes — the invisible server re-adds are exactly what let it
// elapse while the aura stayed up.
if (mine && e.expirationMs != 0 &&
Time::Clock::Remaining(now, e.expirationMs) > newMs)
continue;
e.casterGuid = Unit::Identity::PlayerGuid();
e.durationMs = newMs;
e.expirationMs = now + newMs;
e.stampMs = now;
SignalAuraChanged(victim);
break; // one aura instance per (target, spell, caster) — server touches one holder
}
}
// A player trigger cast landed on `victim`: arm the first live rule for this
// trigger (rules sharing a trigger are registration-ordered — the higher
// talent rank registers first, so its gate wins while known). Also refreshes
// an existing matching aura in place (see RefreshTriggeredExisting) — the arm
// only covers applications that reach the descriptor as a change.
void ArmTriggeredApplications(uint64_t victim, uint32_t triggerSpellId,
const uint8_t *triggerRec) {
for (int i = 0; i < g_trigAppCount; ++i) {
const TriggeredApplication &r = g_trigApps[i];
if (r.triggerSpellId != 0
? r.triggerSpellId != triggerSpellId
: !Spell::Lookup::IsFitToFamily(triggerRec, r.triggerFamily,
r.triggerMask))
continue;
if (r.gateSpellId != 0 && !PlayerKnowsSpell(r.gateSpellId))
continue;
const uint32_t now = NowMs();
RefreshTriggeredExisting(victim, r, now);
TrigAppArm *slot = nullptr;
for (auto &a : g_trigAppArms) {
if (a.victim == victim && a.affectedFamily == r.affectedFamily &&
a.affectedMask == r.affectedMask) {
slot = &a; // re-trigger inside the TTL — refresh in place
break;
}
if (slot == nullptr &&
(a.victim == 0 || Time::Clock::Reached(now, a.untilMs)))
slot = &a;
}
if (slot == nullptr)
slot = &g_trigAppArms[0]; // all live — steal the first
*slot = {victim, r.affectedFamily, r.affectedMask, r.durationPct,
now + kTrigAppArmTtlMs};
return;
}
}
// The armed duration percent for a caster-less application of `rec` on
// `victim`, or 0. One-shot: consumed on hit.
int32_t ConsumeTriggeredApplication(uint64_t victim, const uint8_t *rec,
uint32_t now) {
if (victim == 0 || rec == nullptr)
return 0;
for (auto &a : g_trigAppArms) {
if (a.victim != victim || Time::Clock::Reached(now, a.untilMs))
continue;
if (!Spell::Lookup::IsFitToFamily(rec, a.affectedFamily,
a.affectedMask))
continue;
const int32_t pct = a.durationPct;
a = {};
return pct;
}
return 0;
}
// ---- SMSG_SPELL_GO co-hook ----------------------------------------------
// The hit-target list is all we need: each entry is a unit the cast landed
@@ -847,7 +1146,27 @@ void HandleSpellGo(uint64_t caster, uint32_t spellId, const uint64_t *targets,
// before the aura gate below: the trigger spell applies no aura itself.
ApplyDurationModifiers(spellId, caster, targets, numTargets);
// Judgement: refresh-with-adoption for a re-judge (in-place server
// refresh, no aura event) and arm attribution for the fresh debuff that
// follows. Before the aura gate — Judgement itself applies no aura.
if (spellId == kSpellJudgement) {
for (int i = 0; i < numTargets; ++i) {
RefreshJudgementsImpl(targets[i], caster, /*adopt*/ true);
ArmJudgementAttribution(targets[i], caster);
}
}
const uint8_t *rec = Spell::Lookup::RecordForID(static_cast<int>(spellId));
// Triggered-application rules (Stinging Nettle): a registered trigger
// cast by the local player arms its hit targets so the server-added aura
// that follows (no SPELL_GO of its own) gets player attribution + the
// rule's scaled duration. Before the aura gate — Mongoose Bite applies
// no aura of its own.
if (g_trigAppCount != 0 && caster == Unit::Identity::PlayerGuid())
for (int i = 0; i < numTargets; ++i)
ArmTriggeredApplications(targets[i], spellId, rec);
if (!SpellAppliesAura(rec))
return;
@@ -933,9 +1252,38 @@ void StampApplication(void *unit, uint32_t spellId, int slot) {
// (and attribute the caster) — SpellGo couldn't always land the talented
// value on this target's entry. Otherwise base (we lack other casters'
// mods). See WasRecentPlayerCast.
const bool byPlayer = WasRecentPlayerCast(spellId);
const uint32_t durationMs = SpellDurationMs(rec, byPlayer);
const uint64_t caster = byPlayer ? Unit::Identity::PlayerGuid() : 0;
uint64_t caster = 0;
uint32_t durationMs = 0;
// A triggered-application arm (Stinging Nettle): the server AddAura'd
// this aura off the player's trigger cast at a scaled duration —
// attribute the player and mirror the server's max(1, base × pct / 100),
// player-modified base since the player is the caster. Checked BEFORE
// the recent-cast window below: the arm names this exact TARGET, while
// WasRecentPlayerCast is spell-scoped only — a real Serpent Sting cast
// at unit A must not stamp its full duration onto a nettle application
// landing on unit B moments later. The order is safe for a real cast's
// own application: its entry is already cast-owned (StoreFromCast), and
// StoreFromApplication never overwrites an owned entry's timing.
if (const int32_t pct = ConsumeTriggeredApplication(unitGuid, rec, NowMs())) {
const uint32_t playerBase = SpellDurationMs(rec, /*player*/ true);
if (playerBase > 0) {
caster = Unit::Identity::PlayerGuid();
durationMs = playerBase * static_cast<uint32_t>(pct) / 100;
if (durationMs == 0)
durationMs = 1;
}
}
if (caster == 0) {
const bool byPlayer = WasRecentPlayerCast(spellId);
durationMs = SpellDurationMs(rec, byPlayer);
caster = byPlayer ? Unit::Identity::PlayerGuid() : 0;
// A judgement debuff is cast server-side (no SPELL_GO, so neither
// path above can name its caster) — attribute it to the paladin
// whose Judgement cast just armed this victim. See the judgement
// section.
if (caster == 0 && IsJudgementSpell(rec))
caster = ConsumeJudgementAttribution(unitGuid, NowMs());
}
const uint32_t expirationMs = durationMs > 0 ? NowMs() + durationMs : 0;
StoreFromApplication(unitGuid, spellId, caster, expirationMs, durationMs,
slot, KindForSlot(slot));
@@ -1043,6 +1391,63 @@ bool AddDurationMod(uint32_t triggerSpellId, uint32_t affectedFamily,
affectedIcon, op, valueMs);
}
namespace {
bool RegisterTriggeredApplication(uint32_t triggerSpellId,
uint32_t triggerFamily, uint64_t triggerMask,
uint32_t gateSpellId, uint32_t affectedFamily,
uint64_t affectedMask, int32_t durationPct) {
// Trigger must be identified one way or the other.
if ((triggerSpellId == 0 && (triggerFamily == 0 || triggerMask == 0)) ||
affectedMask == 0 || durationPct <= 0)
return false;
for (int i = 0; i < g_trigAppCount; ++i) { // replace an identical rule
TriggeredApplication &r = g_trigApps[i];
if (r.triggerSpellId == triggerSpellId &&
r.triggerFamily == triggerFamily && r.triggerMask == triggerMask &&
r.gateSpellId == gateSpellId && r.affectedFamily == affectedFamily &&
r.affectedMask == affectedMask) {
r.durationPct = durationPct;
return true;
}
}
if (g_trigAppCount >= kTrigAppMax)
return false;
g_trigApps[g_trigAppCount++] = {triggerSpellId, triggerFamily, triggerMask,
gateSpellId, affectedFamily,
affectedMask, durationPct};
return true;
}
} // namespace
bool AddTriggeredApplication(uint32_t triggerSpellId, uint32_t gateSpellId,
uint32_t affectedFamily, uint64_t affectedMask,
int32_t durationPct) {
return RegisterTriggeredApplication(triggerSpellId, /*triggerFamily*/ 0,
/*triggerMask*/ 0, gateSpellId,
affectedFamily, affectedMask,
durationPct);
}
bool AddTriggeredApplicationByFamily(uint32_t triggerFamily,
uint64_t triggerMask, uint32_t gateSpellId,
uint32_t affectedFamily,
uint64_t affectedMask,
int32_t durationPct) {
return RegisterTriggeredApplication(/*triggerSpellId*/ 0, triggerFamily,
triggerMask, gateSpellId,
affectedFamily, affectedMask,
durationPct);
}
int RefreshJudgements(uint64_t unitGuid, uint64_t attackerGuid) {
// Caster-strict (no adoption) — the Judgement-cast path inside
// HandleSpellGo is the one with proof of ownership; see
// RefreshJudgementsImpl.
return RefreshJudgementsImpl(unitGuid, attackerGuid, /*adopt*/ false);
}
uint32_t RefreshDurationByFamily(uint64_t unitGuid, uint32_t family,
uint64_t mask, uint32_t icon,
uint64_t casterGuid) {
+48
View File
@@ -69,6 +69,21 @@ uint32_t RefreshDurationByFamily(uint64_t unitGuid, uint32_t family,
uint64_t mask, uint32_t icon,
uint64_t casterGuid);
// Mirrors the server's melee-swing judgement refresh (tortoise-wow
// Unit::DealMeleeDamage): a white swing from `attackerGuid` that dealt any
// damage refreshes every aura it cast on `unitGuid` whose spell is
// SPELLFAMILY_PALADIN with SPELL_ATTR_EX3_ALWAYS_HIT (the judgement-debuff
// marker — all Judgement of Light/Wisdom/Justice/Crusader ranks) back to its
// own applied duration. Caster-strict: entries with an unknown caster are
// left alone (a swing gives no proof of ownership). The caster comes from
// the Judgement-cast attribution inside the SpellGo path — the debuff itself
// is cast server-side with no client-visible SPELL_GO, so the Judgement cast
// (20271) is what names the owner: it refresh-with-adoption's existing
// entries (re-judge = in-place server refresh, no aura event) and arms the
// fresh application's attribution. Returns the number refreshed. Fed by
// Aura::JudgementRefresh's SMSG_ATTACKERSTATEUPDATE subscriber.
int RefreshJudgements(uint64_t unitGuid, uint64_t attackerGuid);
// Op codes for AddDurationMod (mirror the Lua op strings).
enum DurationModOp {
DURATION_MOD_REFRESH = 0,
@@ -88,6 +103,39 @@ bool AddDurationMod(uint32_t triggerSpellId, uint32_t affectedFamily,
uint64_t affectedMask, uint32_t affectedIcon, int op,
int32_t valueMs);
// Register a server "triggered application" rule from C++: `triggerSpellId`'s
// SMSG_SPELL_GO — local player casts only — arms its hit targets for a short
// window, and a caster-less aura application on an armed target matching
// `affectedFamily` + a family-flag overlap with `affectedMask` is attributed
// to the player at `durationPct` percent of the aura's own player-modified
// base duration (the server's `max(1, CalculateDuration(caster) * pct / 100)`).
// For server mechanics that AddAura an aura off another spell's hit with no
// cast packet of its own (Turtle's Stinging Nettle: Mongoose Bite / fire-trap
// effects apply the highest known Serpent Sting rank at 20/40% duration).
// A re-trigger over an EXISTING matching aura is also handled: the server's
// re-add reuses the descriptor slot (no application event), so the trigger
// additionally refreshes the player's existing cached entry in place,
// honoring the server's keep-the-longer-remaining guard.
// `gateSpellId` (0 = none) keeps the rule live only while the player knows
// that spell (a talent-granted passive), read from the spell-knowledge bitmap
// at trigger time so respecs are honored; rules matching the same trigger are
// tried in registration order and the first live one arms (register the
// higher talent rank first). Returns false on bad input or a full table.
bool AddTriggeredApplication(uint32_t triggerSpellId, uint32_t gateSpellId,
uint32_t affectedFamily, uint64_t affectedMask,
int32_t durationPct);
// Family-mask trigger form of the above: the trigger matches any cast whose
// spell is SpellFamilyName `triggerFamily` with a family-flag overlap of
// `triggerMask` — rank-proof when the bit selects exactly the trigger set
// (verify against the DBC that no unrelated spell shares it first: hunter
// 0x4 is exactly the fire-trap effects, but 0x2 is Mongoose Bite AND Raptor
// Strike, so that trigger needs the exact-ID form).
bool AddTriggeredApplicationByFamily(uint32_t triggerFamily,
uint64_t triggerMask, uint32_t gateSpellId,
uint32_t affectedFamily,
uint64_t affectedMask, int32_t durationPct);
// One cached aura, as returned by `Enumerate`.
struct CachedAura {
uint32_t spellId;
+1 -1
View File
@@ -143,7 +143,7 @@ void OnWorldTick() {
static_cast<uintptr_t>(Offsets::VAR_IN_WORLD)) == 0)
return;
g_pending = false;
const int slot = Event::Custom::Lookup(kEventName);
const int slot = _reserve.Slot();
if (slot >= 0)
Event::Custom::Fire(slot, "");
// Notify C++ subscribers of the bag-change frame (see UpdateDelayed.h).
+7 -7
View File
@@ -61,8 +61,8 @@ constexpr int kMaxWaitTicks = 1200; // give up and fire failure after this many
struct Registered {
void *cache;
const char *eventName;
uintptr_t getRecord; // this cache class's _GetRecord
const Event::Custom::AutoReserve *reserve; // completion event's reservation
uintptr_t getRecord; // this cache class's _GetRecord
Pending pending[kMaxPending];
int pendingCount;
};
@@ -79,8 +79,7 @@ Registered *Find(void *cache) {
}
void Fire(const Registered *r, uint32_t id, bool success) {
Event::Custom::FireIdSuccess(Event::Custom::Lookup(r->eventName),
static_cast<int>(id), success);
Event::Custom::FireIdSuccess(r->reserve->Slot(), static_cast<int>(id), success);
}
int FindPending(const Registered *r, uint32_t id) {
@@ -176,15 +175,16 @@ const Tick::WorldTick::AutoSubscribe _tickSub{&OnWorldTick};
} // namespace
void Register(void *cacheInstance, const char *eventName, uintptr_t getRecordAddr) {
if (cacheInstance == nullptr || eventName == nullptr || getRecordAddr == 0)
void Register(void *cacheInstance, const Event::Custom::AutoReserve *reserve,
uintptr_t getRecordAddr) {
if (cacheInstance == nullptr || reserve == nullptr || getRecordAddr == 0)
return;
if (Find(cacheInstance) != nullptr) // idempotent (safe across /reload)
return;
if (g_cacheCount >= kMaxCaches)
return;
g_caches[g_cacheCount].cache = cacheInstance;
g_caches[g_cacheCount].eventName = eventName;
g_caches[g_cacheCount].reserve = reserve;
g_caches[g_cacheCount].getRecord = getRecordAddr;
g_caches[g_cacheCount].pendingCount = 0;
++g_cacheCount;
+14 -10
View File
@@ -15,6 +15,10 @@
#include <cstdint>
namespace Event::Custom {
struct AutoReserve;
}
// Shared async-load machinery for the client query caches that aren't
// item/quest — creature, gameobject, and (potentially) the other
// SMSG_*_QUERY caches. Modeled on `Item::Data`'s pending/timeout/event
@@ -30,10 +34,9 @@
// functions, so hooking creature's and gameobject's separately is fine);
// item/quest have their own parsers and aren't touched.
//
// static const char *kEvent = "CREATURE_DATA_LOAD_RESULT";
// static const Event::Custom::AutoReserve _r{kEvent}; // reserve the event
// static const Event::Custom::AutoReserve _r{"CREATURE_DATA_LOAD_RESULT"};
// ...
// Cache::QueryLoad::Register(cacheInstance, kEvent,
// Cache::QueryLoad::Register(cacheInstance, &_r,
// Offsets::FUN_CREATURE_GET_RECORD); // at init
// Cache::QueryLoad::RequestLoad(cacheInstance, id); // fire a load
//
@@ -44,13 +47,14 @@ namespace Cache::QueryLoad {
// Register a query cache for async-load tracking. `cacheInstance` is the
// cache global (e.g. `Offsets::VAR_CREATURE_CACHE` cast to void*);
// `eventName` is a Custom event the caller has reserved via
// `Event::Custom::AutoReserve`, fired `(id, success)` on completion;
// `getRecordAddr` is the cache class's `_GetRecord` (e.g.
// `Offsets::FUN_CREATURE_GET_RECORD`). `cacheInstance`/`eventName` must
// outlive the process (pass static values). Idempotent — calling again
// for the same cache is a no-op (safe across /reload).
void Register(void *cacheInstance, const char *eventName, uintptr_t getRecordAddr);
// `reserve` is the caller's `Event::Custom::AutoReserve` for the
// completion event, fired `(id, success)`; `getRecordAddr` is the cache
// class's `_GetRecord` (e.g. `Offsets::FUN_CREATURE_GET_RECORD`).
// `cacheInstance`/`reserve` must outlive the process (pass statics).
// Idempotent — calling again for the same cache is a no-op (safe across
// /reload).
void Register(void *cacheInstance, const Event::Custom::AutoReserve *reserve,
uintptr_t getRecordAddr);
// True if `id` is already in the cache (pure peek, no network query).
bool IsCached(void *cacheInstance, uint32_t id);
+111
View File
@@ -0,0 +1,111 @@
// 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 <https://www.gnu.org/licenses/>.
// `StartAttack([target])` / `StopAttack()` — the non-toggling melee
// auto-attack verbs. Vanilla 1.12 ships only `AttackTarget()`, which
// *toggles* (start <-> stop each call), so a `/startattack` can't guarantee
// it won't cancel an in-progress swing. These split the engine's own attack
// machinery into the two explicit, idempotent verbs modern clients expose.
//
// 1.12's `AttackTarget` (`0x00489B50`) is `FUN_006131A0`: resolve the target,
// then `isAttacking ? stop : start`. We call the same start/stop primitives
// directly (see the `FUN_ATTACK_*` notes in Offsets.h), skipping the toggle:
// StartAttack -> the "start" leg only (idempotent; switches or no-ops on a
// valid target, never stops it).
// StopAttack -> the "stop" leg only (self-guards, so a no-op when idle).
#include "Game.h"
#include "Offsets.h"
#include "unit/Identity.h"
#include <cstdint>
namespace Combat::Attack {
namespace {
using Start_t = void(__thiscall *)(void *player, const uint64_t *targetGuid);
using Stop_t = void(__fastcall *)(void *player);
using ResolveTarget_t = int(__thiscall *)(void *player, uint64_t *outGuid);
// Resolve an optional unit-token argument to a GUID without raising.
// `Unit::Identity::GuidForToken` raises for non-token strings (a name or
// garbage — 1.12 has no name->GUID resolver), so run it under `pcall`; a raise
// or an empty token yields 0, which the caller treats as "use current target".
int __fastcall ResolveTokenThunk(void *L) {
using namespace Game::Lua;
const char *token = ToString(L, 1);
const uint64_t g = (token && *token) ? Unit::Identity::GuidForToken(token) : 0;
PushNumber(L, static_cast<double>(static_cast<uint32_t>(g)));
PushNumber(L, static_cast<double>(static_cast<uint32_t>(g >> 32)));
return 2;
}
uint64_t SafeResolveToken(void *L, const char *token) {
using namespace Game::Lua;
if (token == nullptr || *token == '\0')
return 0;
const int base = GetTop(L);
PushCClosure(L, &ResolveTokenThunk, 0);
PushString(L, token);
uint64_t guid = 0;
if (PCall(L, 1, 2, 0) == 0) {
const uint32_t lo = static_cast<uint32_t>(ToNumber(L, -2));
const uint32_t hi = static_cast<uint32_t>(ToNumber(L, -1));
guid = (static_cast<uint64_t>(hi) << 32) | lo;
}
SetTop(L, base); // drop the results (or the caught error message)
return guid;
}
} // namespace
static int __fastcall Script_StartAttack(void *L) {
auto *player = const_cast<uint8_t *>(Unit::Identity::PlayerObject());
if (player == nullptr)
return 0;
uint64_t target = SafeResolveToken(L, Game::Lua::ToString(L, 1));
if (target == 0) {
// No explicit target given (or unresolvable): validate and take the
// current target. Returns 0 — and posts the engine's own UI error —
// when there's nothing valid to attack.
auto resolve =
reinterpret_cast<ResolveTarget_t>(Offsets::FUN_ATTACK_RESOLVE_TARGET);
if (resolve(player, &target) == 0)
return 0;
}
reinterpret_cast<Start_t>(Offsets::FUN_ATTACK_START)(player, &target);
return 0;
}
static int __fastcall Script_StopAttack(void *L) {
(void)L;
auto *player = const_cast<uint8_t *>(Unit::Identity::PlayerObject());
if (player == nullptr)
return 0;
reinterpret_cast<Stop_t>(Offsets::FUN_ATTACK_STOP)(player);
return 0;
}
static void RegisterLuaFunctions() {
Game::Lua::RegisterGlobalFunction("StartAttack", &Script_StartAttack);
Game::Lua::RegisterGlobalFunction("StopAttack", &Script_StopAttack);
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace Combat::Attack
+1 -1
View File
@@ -361,7 +361,7 @@ void RegisterLuaFunctions() {
Game::Lua::RegisterTableFunction("C_CreatureInfo", "GetCreatureTypeIDs",
&Script_GetCreatureTypeIDs);
Cache::QueryLoad::Register(reinterpret_cast<void *>(Offsets::VAR_CREATURE_CACHE),
kCreatureDataLoadResult, Offsets::FUN_CREATURE_GET_RECORD);
&_reserveLoadResult, Offsets::FUN_CREATURE_GET_RECORD);
}
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
+3 -6
View File
@@ -386,7 +386,7 @@ int __fastcall Script_UseEquipmentSet(void *L) {
const uint32_t setID = ArgSetID(L, 1);
const Set *s = Data::FindByID(setID);
if (s == nullptr) {
const int evt = Event::Custom::Lookup(kSwapFinishedEvent);
const int evt = kEvtSwapFinished.Slot();
if (evt >= 0)
Event::Custom::Fire(evt, "%d%d", 0, static_cast<int>(setID));
Game::Lua::PushBoolean(L, 0);
@@ -396,7 +396,7 @@ int __fastcall Script_UseEquipmentSet(void *L) {
// Fire PENDING right after the set-exists check, before any of
// the swap work. Addon UI can use this to gate swap-in-progress
// visuals.
const int pendingEvt = Event::Custom::Lookup(kSwapPendingEvent);
const int pendingEvt = kEvtSwapPending.Slot();
if (pendingEvt >= 0)
Event::Custom::Fire(pendingEvt, "%d", static_cast<int>(setID));
@@ -569,7 +569,7 @@ int __fastcall Script_UseEquipmentSet(void *L) {
virtualPaperdoll[targetSlot - 1] = 0;
}
const int evt = Event::Custom::Lookup(kSwapFinishedEvent);
const int evt = kEvtSwapFinished.Slot();
if (evt >= 0)
Event::Custom::Fire(evt, "%d%d", 1, static_cast<int>(setID));
@@ -620,8 +620,5 @@ static void RegisterLuaFunctions() {
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
static const Event::Custom::AutoReserve _reserve{kEventName};
static const Event::Custom::AutoReserve _reservePending{kSwapPendingEvent};
static const Event::Custom::AutoReserve _reserveFinished{kSwapFinishedEvent};
} // namespace EquipmentSet::Api
+1 -1
View File
@@ -75,7 +75,7 @@ uint32_t NextAvailableID() {
}
void FireChanged() {
const int slot = Event::Custom::Lookup(kEventName);
const int slot = kEvtSetsChanged.Slot();
if (slot >= 0)
Event::Custom::Fire(slot, "");
}
+8 -5
View File
@@ -13,6 +13,8 @@
#pragma once
#include "event/Custom.h"
#include <cstdint>
#include <string>
@@ -109,8 +111,9 @@ constexpr int LOC_MISSING = -1;
// coincidence, not load-bearing).
constexpr int LOC_IGNORED = 1;
// Custom event names. All three are reserved at module-init time
// via `Event::Custom::AutoReserve` in `Api.cpp`.
// Custom event reservations, shared by the Data and Api TUs (C++17 inline
// variables — one instance each; the AutoReserve ctor dedups by name anyway).
// Fire via `kEvt*.Slot()`.
//
// EQUIPMENT_SETS_CHANGED — no payload; fires on any mutation
// (create / save / modify / delete /
@@ -130,8 +133,8 @@ constexpr int LOC_IGNORED = 1;
// pickup→equip pair actually completed,
// matching modern's "we dispatched"
// definition of success).
constexpr const char *kEventName = "EQUIPMENT_SETS_CHANGED";
constexpr const char *kSwapPendingEvent = "EQUIPMENT_SWAP_PENDING";
constexpr const char *kSwapFinishedEvent = "EQUIPMENT_SWAP_FINISHED";
inline const Event::Custom::AutoReserve kEvtSetsChanged{"EQUIPMENT_SETS_CHANGED"};
inline const Event::Custom::AutoReserve kEvtSwapPending{"EQUIPMENT_SWAP_PENDING"};
inline const Event::Custom::AutoReserve kEvtSwapFinished{"EQUIPMENT_SWAP_FINISHED"};
} // namespace EquipmentSet
+12 -10
View File
@@ -244,25 +244,25 @@ void Grow() {
} // namespace
AutoReserve::AutoReserve(const char *name) {
if (name == nullptr || g_reservedCount >= MAX_RESERVED)
if (name == nullptr)
return;
// Dedup: a name reserved twice resolves both instances to the one entry.
for (int i = 0; i < g_reservedCount; ++i) {
if (std::strcmp(g_reserved[i].name, name) == 0)
if (std::strcmp(g_reserved[i].name, name) == 0) {
index_ = i;
return;
}
}
if (g_reservedCount >= MAX_RESERVED)
return; // overflow — index_ stays -1, Slot() reports unclaimed
g_reserved[g_reservedCount].name = name;
g_reserved[g_reservedCount].slot = -1;
index_ = g_reservedCount;
++g_reservedCount;
}
int Lookup(const char *name) {
if (name == nullptr)
return -1;
for (int i = 0; i < g_reservedCount; ++i) {
if (std::strcmp(g_reserved[i].name, name) == 0)
return g_reserved[i].slot;
}
return -1;
int AutoReserve::Slot() const {
return index_ >= 0 ? g_reserved[index_].slot : -1;
}
int LookupByName(const char *name) {
@@ -320,6 +320,8 @@ void PrepareForReload() {
g_growLatched = false; // re-arm the one-shot grow for the new table
}
static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};
// Diagnostic Lua functions — registered via the auto-register pattern
// at the bottom of this file. Not on any hot path.
namespace {
+22 -17
View File
@@ -37,31 +37,36 @@ namespace Event::Custom {
// DLL operate on the table independently of the others.
//
// The name pointer must outlive the engine (a string literal does).
// Same name reserved twice is deduped; reserving more than `MAX_RESERVED`
// names total (see Custom.cpp) silently drops the overflow — keep that cap
// above the codebase-wide `AutoReserve` count.
// Same name reserved twice is deduped (both instances resolve to the same
// reservation); reserving more than `MAX_RESERVED` names total (see
// Custom.cpp) silently drops the overflow — keep that cap above the
// codebase-wide `AutoReserve` count.
//
// Fire through the instance: `Fire(_r.Slot(), …)`. `Slot()` is the O(1)
// read of the reservation's current slot id — it resolves through the
// shared reservation table, so reload invalidation (`PrepareForReload`)
// and re-claiming (`RetryClaims`) stay centralized and the value is never
// stale. Returns -1 while unclaimed (before the first Lua-side
// `RegisterEvent` triggers `RetryClaims`), which `Fire` treats as a no-op.
// Do NOT cache the return across frames — read it at fire time (the read
// is two loads; there is nothing to save).
struct AutoReserve {
explicit AutoReserve(const char *name);
};
int Slot() const;
// Returns the slot id currently assigned to `name`, or -1 if not yet
// claimed (e.g. before the first Lua-side `RegisterEvent` has
// triggered `RetryClaims`). Slot indices may change across `/reload`,
// so call this at fire time rather than caching the value.
//
// Only consults our reservation cache — for engine-defined events
// (UNIT_FACTION, BAG_UPDATE, etc.) use `LookupByName`.
int Lookup(const char *name);
private:
int index_ = -1; // into the reservation table; -1 = dropped (overflow)
};
// Walks the live engine event table at `[VAR_EVENT_TABLE_BASE_PTR]`
// looking for an entry whose name strcmps equal to `name`. Returns
// the slot index, or -1 if no entry matches.
//
// Works for both engine-defined events AND our `AutoReserve`-claimed
// custom events (both populate the same table). Slightly slower than
// `Lookup` (O(table size) vs O(reservations)) — prefer `Lookup` for
// names we've reserved. Use this for engine-defined events we want to
// fire ourselves (e.g., polyfilling missing event dispatches).
// custom events (both populate the same table). O(table size) — for
// names we've reserved, prefer the O(1) `AutoReserve::Slot()`. Use this
// for engine-defined events we want to fire ourselves (e.g., polyfilling
// missing event dispatches).
int LookupByName(const char *name);
// True iff at least one frame is currently registered for the event in
@@ -88,7 +93,7 @@ bool HasListeners(int slot);
// Fire(slot, "%s%d", keyName, down); // MODIFIER_STATE_CHANGED(key, down)
//
// No-op for `eventID < 0`, which lets callers cheaply guard on the
// `Lookup()` result without an explicit if.
// `Slot()` result without an explicit if.
template <typename... Args>
inline void Fire(int eventID, const char *format, Args... args) {
if (eventID < 0)
+1 -1
View File
@@ -98,7 +98,7 @@ void __fastcall FireNotify_h(int factionID, int delta) {
// any addon relying on the chat event firing first would expect.
FireNotify_o(factionID, delta);
const int slot = Event::Custom::Lookup(kEventName);
const int slot = _reserve.Slot();
if (slot >= 0)
Event::Custom::Fire(slot, "%d%d%d", factionID, newStanding, delta);
+46 -4
View File
@@ -103,6 +103,8 @@
// (`FUN_FRAME_SCRIPT_RESOLVER`) and handing out an external per-frame cell for
// that name — the `Tooltip::SetEvents` analog, applied to every frame.
#include "frame/Attributes.h"
#include "Game.h"
#include "Offsets.h"
#include "baselib/Ascii.h"
@@ -945,11 +947,30 @@ void FireAttributeChanged(void *L, void *frame, const char *name) {
// ---- the methods -----------------------------------------------------------
// Enables the frame's mouse so it can become the mouse-focus (a bare frame
// otherwise never registers as hovered). Operates on self at index 1.
// otherwise never registers as hovered).
//
// Two properties, both deliberate:
// * STACK-NEUTRAL. The old form did SetTop(L, 1) to set up (self, true) for
// the engine setter, which DESTROYED the (name, value) at stack[2]/[3] that
// FireAttributeChanged reads right after — handing any OnAttributeChanged
// handler a nil `arg2`. We instead push the call at the top and restore the
// caller's stack, so DoSet's (self, name, value) survives intact.
// * PROTECTED. SetAttribute is Frame-scoped (VAR_FRAME_METHOD_REGISTRY), so
// `self` is a real Frame and the setter's type check normally passes;
// invoking through lua_pcall is belt-and-suspenders so a best-effort side
// effect can never surface an error in the addon's SetAttribute. (Calling
// via pcall is also what lets us pass the args at the callee's own stack
// base without clobbering ours.)
void EnableFrameMouse(void *L) {
Game::Lua::SetTop(L, 1); // (self)
Game::Lua::PushBoolean(L, 1);
CallScript(Offsets::FUN_SCRIPT_FRAME_ENABLEMOUSE, L);
const int top = Game::Lua::GetTop(L);
Game::Lua::PushCClosure(
L,
reinterpret_cast<Game::Lua::CFunction>(Offsets::FUN_SCRIPT_FRAME_ENABLEMOUSE),
0);
Game::Lua::PushValue(L, 1); // self (the frame)
Game::Lua::PushBoolean(L, 1); // enable = true
Game::Lua::PCall(L, 2, 0, 0); // best-effort; swallow a transient type error
Game::Lua::SetTop(L, top); // restore the caller's stack
}
int DoSet(void *L, bool fireHandler) { // (self, name, value)
@@ -1088,4 +1109,25 @@ const Tick::WorldTick::AutoSubscribe _tick{&MouseoverTick};
} // namespace
// Drop every per-frame map before a /reload (or logout) resets the Lua state.
// Both are keyed by the frame's C object pointer, which the allocator recycles
// across a reload:
// * g_attrHandlers holds OnAttributeChanged handler refs. The refs die with
// the Lua reset, so a stale entry whose address a new frame reuses would
// fire a DEAD ref from FireAttributeChanged — the invoker's protected pcall
// catches it, but the engine error handler still prints it as an error "in
// SetAttribute" (SecureStateDriverManager sets OnAttributeChanged every
// session, so there's always at least one entry to go stale). This was the
// "SetAttribute occasionally errors after /reload" report; same class of
// bug as Tooltip::SetEvents issue #33.
// * g_unitByFrame maps a frame to its `unit` token for the mouse-focus poll;
// a stale entry at a reused address would point the mouseover at the wrong
// unit and mislead the isNew mouse-enable gate.
void PrepareForReload() {
g_attrHandlers.clear();
g_unitByFrame.clear();
}
static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};
} // namespace Frame::Attributes
+25
View File
@@ -0,0 +1,25 @@
// 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 <https://www.gnu.org/licenses/>.
#pragma once
namespace Frame::Attributes {
// Drop the per-frame attribute-handler and unit-token maps before a /reload (or
// logout) resets the Lua state and recycles frame object pointers. Without it, a
// stale OnAttributeChanged ref fires from a new frame that reused an old
// address (surfaces as "SetAttribute occasionally errors after /reload"). Wired
// from `FrameScript_Initialize_h` in DllMain.cpp alongside the other cleaners.
void PrepareForReload();
} // namespace Frame::Attributes
+181
View File
@@ -0,0 +1,181 @@
// 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 <https://www.gnu.org/licenses/>.
// `button:SetScript("PreClick"|"PostClick", fn)` — backport of the modern
// button scripts that fire immediately before and after OnClick, as real frame
// scripts settable via the standard SetScript / GetScript / HookScript. Vanilla
// 1.12 has only OnClick and OnDoubleClick on buttons.
//
// 1.12 already has the script-dispatch machinery, just not these two names.
// Two co-hooks (same shape as Tooltip::SetEvents):
//
// - The Button script resolver FUN_BUTTON_SCRIPT_RESOLVER maps a script name
// to its handler slot (OnClick -> button+0x4CC, …). SetScript/GetScript/
// HookScript all go through it. We co-hook it: for PreClick/PostClick
// (which the engine doesn't know) we hand back a pointer to an external
// per-button cell — a button object has no free slot for two new scripts,
// and the resolver's only contract is "return the address the script lives
// at", so external storage works exactly like an in-object slot.
//
// - The engine fires a button's OnClick through the arg'd script runner
// FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT(frame, frame+0x4CC, "%s", &buttonName).
// We co-hook that runner and, when the fired slot IS the OnClick slot,
// re-invoke the runner for our PreClick cell first, then let OnClick run,
// then re-invoke for PostClick — reusing the SAME (fmt, varargs) so
// PreClick/PostClick receive arg1 = the button name exactly like OnClick.
//
// Why the runner and not the button click vmethod (FUN_00779540): SuperWoW
// inline-hooks that vmethod for click-casting, and a second MinHook there
// corrupts the trampoline (ERROR #132 — see Offsets.h). The runner is
// uncontested, fires at the same top-level dispatch level (so its exec-context
// stamp is valid), and the OnClick slot address is an exact gate.
//
// Limitation: because the runner only runs when a slot is non-empty, PreClick/
// PostClick fire only when the button also has an OnClick handler set. Modern
// fires them regardless; on this client that would require hooking the click
// vmethod, which SuperWoW owns. Bracketing an existing OnClick is the common
// case and the one this backport serves.
#include "frame/ClickEvents.h"
#include "Game.h"
#include "Offsets.h"
#include <cstdint>
#include <unordered_map>
namespace Frame::ClickEvents {
namespace {
enum ScriptKind { SK_PRECLICK = 0, SK_POSTCLICK, SK_COUNT };
// Matched case-insensitively against the resolver's input name.
constexpr const char *kNamesLower[SK_COUNT] = {"preclick", "postclick"};
// Per-button storage: one 8-byte {handler, context} slot per script kind. Only
// buttons that actually had SetScript("PreClick"/"PostClick", …) called get an
// entry, so the map stays small. unordered_map nodes are pointer-stable, so a
// cell address handed to the engine stays valid until PrepareForReload clears
// the map (buttons and their handler refs die on /reload).
struct Cell {
uint32_t slot[SK_COUNT][2]; // [kind] = {handler ref, exec context}
};
std::unordered_map<void *, Cell> g_cells;
uint32_t *SlotFor(void *button, int kind, bool create) {
auto it = g_cells.find(button);
if (it != g_cells.end())
return it->second.slot[kind];
if (!create)
return nullptr;
Cell &c = g_cells[button];
for (auto &s : c.slot) {
s[0] = 0;
s[1] = 0;
}
return c.slot[kind];
}
bool EqualsIgnoreCase(const char *s, const char *literal) {
if (s == nullptr)
return false;
for (;; ++s, ++literal) {
unsigned char a = static_cast<unsigned char>(*s);
const unsigned char b = static_cast<unsigned char>(*literal);
if (a >= 'A' && a <= 'Z')
a = static_cast<unsigned char>(a + 32);
if (a != b)
return false;
if (b == 0)
return true;
}
}
// Recursion guard: a PreClick/OnClick/PostClick handler can programmatically
// click a button again. While bracketing, further OnClick fires pass straight
// through (the nested click still runs — it just doesn't get its own nested
// PreClick/PostClick), which prevents runaway from a self-clicking handler.
int g_firing = 0;
// --- Resolver co-hook (Button script-name -> slot) ---------------------
using Resolver_t = int(__fastcall *)(void *self, void *edx, const char *name);
Resolver_t g_resolverOriginal = nullptr;
int __fastcall Resolver_h(void *self, void *edx, const char *name) {
const int engineSlot = g_resolverOriginal(self, edx, name);
if (engineSlot != 0) // a base-frame or existing button script — leave it
return engineSlot;
for (int k = 0; k < SK_COUNT; ++k)
if (EqualsIgnoreCase(name, kNamesLower[k]))
return reinterpret_cast<int>(SlotFor(self, k, /*create*/ true));
return 0;
}
// --- Runner co-hook (fire PreClick before / PostClick after OnClick) ---
using RunScript_t = void(__cdecl *)(void *frame, uint32_t *slotPtr,
const char *fmt, void *varargs);
RunScript_t g_runOriginal = nullptr;
// Fire the handler (if any) for `kind` on `frame`, reusing the OnClick fire's
// own (fmt, varargs) so arg1 = the button name. We call the original runner
// directly (its exec-context stamp is valid at this dispatch level). The runner
// balances the Lua stack itself; we snapshot/restore the top as cheap insurance
// against any imbalance leaking to the still-running button click code.
void FireCell(void *frame, int kind, const char *fmt, void *varargs) {
uint32_t *slot = SlotFor(frame, kind, /*create*/ false);
if (slot == nullptr || slot[0] == 0)
return;
void *L = Game::Lua::State();
const int savedTop = (L != nullptr) ? Game::Lua::GetTop(L) : 0;
g_runOriginal(frame, slot, fmt, varargs);
if (L != nullptr)
Game::Lua::SetTop(L, savedTop);
}
void __cdecl RunScript_h(void *frame, uint32_t *slotPtr, const char *fmt,
void *varargs) {
const auto onClickSlot = reinterpret_cast<uint32_t *>(
reinterpret_cast<char *>(frame) + Offsets::OFF_BUTTON_ONCLICK_HANDLER);
if (slotPtr != onClickSlot || g_firing > 0) {
g_runOriginal(frame, slotPtr, fmt, varargs);
return;
}
++g_firing;
FireCell(frame, SK_PRECLICK, fmt, varargs);
g_runOriginal(frame, slotPtr, fmt, varargs); // the button's OnClick
FireCell(frame, SK_POSTCLICK, fmt, varargs);
--g_firing;
}
static const Game::HookAutoRegister _resolverHook{
Offsets::FUN_BUTTON_SCRIPT_RESOLVER,
reinterpret_cast<void *>(&Resolver_h),
reinterpret_cast<void **>(&g_resolverOriginal)};
static const Game::HookAutoRegister _runnerHook{
Offsets::FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT,
reinterpret_cast<void *>(&RunScript_h),
reinterpret_cast<void **>(&g_runOriginal)};
} // namespace
void PrepareForReload() {
g_cells.clear();
}
static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};
} // namespace Frame::ClickEvents
+25
View File
@@ -0,0 +1,25 @@
// 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 <https://www.gnu.org/licenses/>.
#pragma once
namespace Frame::ClickEvents {
// Drop every per-button PreClick/PostClick handler cell before a `/reload` (or
// logout) tears down the button objects and resets the Lua state. The handler
// refs die with the Lua reset, and a recycled button address must not fire a
// stale ref. Wired from `FrameScript_Initialize_h` in DllMain.cpp, alongside
// the other per-reload cleaners.
void PrepareForReload();
} // namespace Frame::ClickEvents
+99
View File
@@ -0,0 +1,99 @@
// 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 <https://www.gnu.org/licenses/>.
// `GetClickFrame(name)` — backport of the C global WoW registers for the
// `/click` handler to resolve a frame by its global name. Vanilla 1.12
// never shipped it; 3.3.5's `Script_GetClickFrame` (`0x00564130`) is the
// reference.
//
// It lives in the DLL, not addon Lua, because Blizzard shipped it as an
// engine-registered C global — the backport mirrors where the real
// function lives, not the fact that Lua could fake it.
//
// Behaviour, matching the 3.3.5 resolver `FUN_00562990` (minus its private
// name→frame memoization cache, which is only a perf optimization over the
// global lookup):
// 1. `_G[name]` — a plain global-table lookup.
// 2. The value must be a frame wrapper table backed by a
// `CFrameScriptObject`.
// 3. Its real `GetName()` must equal `name`. This is the load-bearing
// check: it stops a reassigned global (`_G["Foo"] = someOtherFrame`)
// from resolving to a differently-named frame.
// Return the frame on a match, otherwise nil.
//
// `GetName()` is the object's vtable slot +4 (`__thiscall`, returns
// `const char *`) — verified from 1.12's own `Script_GetName`
// (`0x0079FF60` / `0x007A1390`), which resolves self the same way and reads
// the name from that slot. It's a base virtual present on every
// `CFrameScriptObject` subtype, so calling it after `ResolveObject` is
// safe without the RTTI subtype gate `Script_GetName` does first.
#include "Game.h"
#include "Offsets.h"
#include <cstring>
namespace Frame::ClickFrame {
namespace {
// CFrameScriptObject::GetName — vtable slot +4, thiscall, no args.
using GetName_t = const char *(__thiscall *)(void *self);
const char *ObjectName(void *obj) {
auto vtable = *reinterpret_cast<void ***>(obj);
auto getName = reinterpret_cast<GetName_t>(vtable[1]);
return getName(obj);
}
} // namespace
static int __fastcall Script_GetClickFrame(void *L) {
using namespace Game::Lua;
if (GetTop(L) < 1) {
Error(L, "Usage: GetClickFrame(\"name\")");
return 0;
}
const char *name = ToString(L, 1);
if (name == nullptr) {
PushNil(L);
return 1;
}
// getglobal(name): push _G[name].
PushString(L, name);
GetTable(L, GLOBALS_INDEX);
if (Type(L, -1) != TYPE_TABLE) {
PushNil(L);
return 1;
}
void *obj = ResolveObject(L, -1);
if (obj != nullptr) {
const char *objName = ObjectName(obj);
if (objName != nullptr && std::strcmp(objName, name) == 0)
// The wrapper table is still on top — return it as-is.
return 1;
}
PushNil(L);
return 1;
}
static void RegisterLuaFunctions() {
Game::Lua::RegisterGlobalFunction("GetClickFrame", &Script_GetClickFrame);
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace Frame::ClickFrame
+1 -1
View File
@@ -107,7 +107,7 @@ void RegisterLuaFunctions() {
Game::Lua::RegisterTableFunction("C_GameObjectInfo", "RequestLoadGameObjectByID",
&Script_RequestLoadGameObjectByID);
Cache::QueryLoad::Register(reinterpret_cast<void *>(Offsets::VAR_GAMEOBJECT_CACHE),
kGameObjectDataLoadResult, Offsets::FUN_GAMEOBJECT_GET_RECORD);
&_reserveLoadResult, Offsets::FUN_GAMEOBJECT_GET_RECORD);
}
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
+3 -5
View File
@@ -64,8 +64,8 @@ namespace Input::GlobalMouse {
namespace {
constexpr const char *kDownEvent = "GLOBAL_MOUSE_DOWN";
constexpr const char *kUpEvent = "GLOBAL_MOUSE_UP";
const Event::Custom::AutoReserve _reserveDown{"GLOBAL_MOUSE_DOWN"};
const Event::Custom::AutoReserve _reserveUp{"GLOBAL_MOUSE_UP"};
// Held-state bitmap — bit `i` set means the button with 1-based
// `IsMouseButtonDown` ID `i+1` is currently held. Modern API IDs:
@@ -154,7 +154,7 @@ void ProcessMouseMessage(UINT msg, WPARAM wParam) {
else g_mouseButtonMask &= ~bit;
}
const int slot = Event::Custom::Lookup(down ? kDownEvent : kUpEvent);
const int slot = (down ? _reserveDown : _reserveUp).Slot();
if (slot >= 0)
Event::Custom::Fire(slot, "%s", name);
}
@@ -241,8 +241,6 @@ void RegisterLuaFunctions() {
InstallHook();
}
const Event::Custom::AutoReserve _reserveDown{kDownEvent};
const Event::Custom::AutoReserve _reserveUp{kUpEvent};
const Tick::WorldTick::AutoSubscribe _evict{&EvictTick};
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
+3 -5
View File
@@ -102,11 +102,9 @@ void SetBit(int bitIdx, bool down) {
if (down) g_modifierMask |= bit;
else g_modifierMask &= ~bit;
// Slot was assigned when the engine populated its event table; our
// hook on `RebuildEventTable` recorded the index. Lookup at fire
// time rather than caching because `/reload` re-runs the rebuild
// and the index may shift.
const int slot = Event::Custom::Lookup(kModifierStateChanged);
// Read the slot at fire time (never cache it) — `/reload` rebuilds the
// event table and the reservation re-claims, which may shift the index.
const int slot = _reserveModifierStateChanged.Slot();
if (slot >= 0)
Event::Custom::Fire(slot, "%s%d", kKeyName[bitIdx], static_cast<int>(down));
}
+4 -4
View File
@@ -58,13 +58,13 @@ static const Event::Custom::AutoReserve _reserveItemDataLoadResult{kItemDataLoad
static const Event::Custom::AutoReserve _reserveGetItemInfoReceived{kGetItemInfoReceived};
static void FireGetItemInfoReceived(int itemID, bool success) {
Event::Custom::FireIdSuccess(Event::Custom::Lookup(kGetItemInfoReceived),
itemID, success);
Event::Custom::FireIdSuccess(_reserveGetItemInfoReceived.Slot(), itemID,
success);
}
static void FireItemDataLoadResult(int itemID, bool success) {
Event::Custom::FireIdSuccess(Event::Custom::Lookup(kItemDataLoadResult),
itemID, success);
Event::Custom::FireIdSuccess(_reserveItemDataLoadResult.Slot(), itemID,
success);
}
// Item-load callbacks are __stdcall, 2 args / 8 bytes — matching the
+1 -1
View File
@@ -318,7 +318,7 @@ void AppendNonBagOwned(uint64_t *out, int *count) {
}
void FireChanged() {
Event::Custom::Fire(Event::Custom::Lookup(kEvtNewItems), "");
Event::Custom::Fire(_r.Slot(), "");
}
// Login-baseline handler. Runs every frame but does no work once the
+4 -5
View File
@@ -344,7 +344,7 @@ StartFn_t g_origStart = nullptr;
// structurally: a new item appears or the ring evicts an old one (shifting
// every index).
void FireFullUpdate() {
Event::Custom::Fire(Event::Custom::Lookup(kFullUpdate), "");
Event::Custom::Fire(_evFullUpdate.Slot(), "");
}
// START_ROLL: let the original build the store node, then read the item's
@@ -373,8 +373,7 @@ void __fastcall Roll_h(void *msg, void *ctx, int a3) {
if (structural)
FireFullUpdate();
if (itemIdx > 0)
Event::Custom::Fire(Event::Custom::Lookup(kRollChanged), "%d%d", itemIdx,
playerIdx);
Event::Custom::Fire(_evRollChanged.Slot(), "%d%d", itemIdx, playerIdx);
}
void __fastcall Won_h(void *ctx, void *msg, int a3) {
@@ -388,7 +387,7 @@ void __fastcall Won_h(void *ctx, void *msg, int a3) {
if (structural)
FireFullUpdate();
if (itemIdx > 0)
Event::Custom::Fire(Event::Custom::Lookup(kRollComplete), "%d", itemIdx);
Event::Custom::Fire(_evRollComplete.Slot(), "%d", itemIdx);
}
void __fastcall Passed_h(void *ctx, void *msg) {
@@ -402,7 +401,7 @@ void __fastcall Passed_h(void *ctx, void *msg) {
if (structural)
FireFullUpdate();
if (itemIdx > 0)
Event::Custom::Fire(Event::Custom::Lookup(kRollComplete), "%d", itemIdx);
Event::Custom::Fire(_evRollComplete.Slot(), "%d", itemIdx);
}
const Game::HookAutoRegister _hookRoll{
+1 -1
View File
@@ -267,7 +267,7 @@ void Complete() {
s_scan.currentGuid = 0;
s_scan.suppressEvents = false;
s_scan.lootMode = false;
Event::Custom::Fire(Event::Custom::Lookup(kEventCompleted), "");
Event::Custom::Fire(_reserve.Slot(), "");
}
void TryStartNext() {
+4 -6
View File
@@ -223,8 +223,8 @@ int BuildList(LocEntry *out, int maxOut) {
// lesson). The scan is bounded (16 debuff slots) and early-outs when idle, so
// the per-frame cost is negligible.
constexpr const char *kEventAdded = "LOSS_OF_CONTROL_ADDED";
constexpr const char *kEventUpdate = "LOSS_OF_CONTROL_UPDATE";
const Event::Custom::AutoReserve _reserveAdded{"LOSS_OF_CONTROL_ADDED"};
const Event::Custom::AutoReserve _reserveUpdate{"LOSS_OF_CONTROL_UPDATE"};
// Identity of an active effect for frame-to-frame diffing: a CC is keyed by
// spellID, a school interrupt by its school mask (spellID 0).
@@ -255,7 +255,7 @@ void OnWorldTick() {
for (int i = 0; i < n; ++i) {
if (!ContainsKey(g_prev, g_prevCount, cur[i])) {
// A newly-applied effect -> LOSS_OF_CONTROL_ADDED(eventIndex).
Event::Custom::Fire(Event::Custom::Lookup(kEventAdded), "%d", i + 1);
Event::Custom::Fire(_reserveAdded.Slot(), "%d", i + 1);
changed = true;
}
}
@@ -269,15 +269,13 @@ void OnWorldTick() {
// forward-compatible with per-unit tracking and matches modern WoW, whose
// LOSS_OF_CONTROL_UPDATE carries the unit token.
if (changed)
Event::Custom::Fire(Event::Custom::Lookup(kEventUpdate), "%s", "player");
Event::Custom::Fire(_reserveUpdate.Slot(), "%s", "player");
for (int i = 0; i < n; ++i)
g_prev[i] = cur[i];
g_prevCount = n;
}
static const Event::Custom::AutoReserve _reserveAdded{kEventAdded};
static const Event::Custom::AutoReserve _reserveUpdate{kEventUpdate};
static const Tick::WorldTick::AutoSubscribe _tick{&OnWorldTick};
// `C_LossOfControl.GetActiveLossOfControlDataCount()` -> number.
+2
View File
@@ -202,4 +202,6 @@ void PrepareForReload() {
g_gameSlot.tv.value = nullptr;
}
static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};
} // namespace LuaSyntax::StringMethods
+39 -20
View File
@@ -79,11 +79,12 @@
// `...` yields the name + a per-addon shared table. `__addonns` returns the
// same table for every file of an addon (registry-backed). The preamble is
// newline-free (line numbers preserved).
// * Non-addon vararg chunks (RunScript `/run`, XML <OnLoad>, loadstring) get a
// `local arg = {n=0}` fallback: their main chunk is not vararg, so a
// top-level `...` would otherwise be `unpack(nil)` and throw where 5.1
// yields nothing. A chunk called with args (`loadstring(...)(a,b)`) can't
// recover them — this build doesn't populate `arg` for called chunks.
// * Non-addon vararg chunks (RunScript `/run`, XML handler bodies,
// `loadstring`) compile as a REAL 5.0 vararg closure: the body is wrapped
// `return function(...) … end` and the main is called once at load, so
// the caller receives the inner function whose own `arg` carries real
// call args — `loadstring("return ...")(a, b)` yields a, b, matching 5.1
// called-chunk semantics (the old `local arg={n=0}` fallback lost them).
// The `__addonns` global is CONTEXT-GATED (see `Script_AddonNS`): it only
// answers for the addon mid-load, for its own name — so it cannot be used
// at runtime to read another addon's private table. Cross-addon access is
@@ -1300,6 +1301,7 @@ int __fastcall LoadBuffer_h(void *L, const char *buff, unsigned size, const char
pre += "local unpack=unpack;";
bool armed = false;
bool wrapped = false;
char addon[128];
if (didVararg) {
if (fromFileFunnel && AddonNameFromChunk(name, addon, sizeof addon)) {
@@ -1311,20 +1313,26 @@ int __fastcall LoadBuffer_h(void *L, const char *buff, unsigned size, const char
armed = true;
} else {
// Top-level `...` OUTSIDE the addon file funnel — RunScript (`/run`),
// XML <OnLoad>, or loadstring. Vanilla's main / RunScript chunk is
// NOT vararg, so `arg` is nil there and the `unpack(arg)` we emit
// would throw where 5.1's `...` yields nothing. Bind a chunk-local
// empty vararg table so those chunks match 5.1 (top-level `...`
// yields nothing). A vararg function's own `arg` local shadows this
// at its own scope, so nested `function(...)` bodies are unaffected.
//
// Limitation (verified in-game): a loadstring'd chunk CALLED with
// args — `loadstring("return ...")(a,b)` — can't recover them. This
// build does not populate `arg` for a called chunk, and `...` is not
// a real 5.0 expression, so there is no source for the call args.
// Not a regression: without the rewrite that chunk fails to compile
// outright. This case is vanishingly rare in addons.
pre += "local arg={n=0};";
// XML handler bodies, or loadstring. Vanilla's main chunk is NOT
// vararg (verified in-game): `arg` is nil there, and no rewrite can
// read call args the VM never captured. So compile the chunk as a
// REAL 5.0 vararg closure instead: wrap the body in
// `return function(...) … end` and, after a successful compile,
// call the main once so the caller receives the inner function.
// The inner's own 5.0 `arg` then carries whatever the caller
// passes — `loadstring("return ...")(a, b)` yields a, b — matching
// 5.1 called-chunk semantics. Chunks the engine calls with zero
// args (RunScript, OnLoad) see an empty `arg` exactly as the old
// `local arg={n=0}` fallback gave them; XML handlers invoked
// through Frame::ScriptArgs' positional push now receive those
// args through `...` as well — the modern handler shape. The
// helper captures stay in the OUTER main, which runs once at load
// in the default environment, so the sandbox rationale above is
// preserved (the inner binds them as upvalues). The prefix is
// newline-free and the synthetic `end` rides on its own appended
// final line, so existing line numbers are preserved.
pre += "return function(...) ";
wrapped = true;
}
}
@@ -1341,10 +1349,15 @@ int __fastcall LoadBuffer_h(void *L, const char *buff, unsigned size, const char
? 3
: 0;
std::string full;
full.reserve(bodyLen + pre.size() + 4);
full.reserve(bodyLen + pre.size() + 8);
full.append(body, bom); // keep a leading BOM ahead of the preamble
full += pre;
full.append(body + bom, bodyLen - bom);
// Close the vararg wrap on its OWN line: a body ending in a line comment
// (`-- foo` with no trailing newline) would otherwise swallow the `end`.
// Appending a final line shifts no existing line numbers.
if (wrapped)
full += "\nend";
// Grant this chunk (and only this chunk) the right to fetch its own
// namespace via `__addonns`; the preamble consumes the grant as the chunk's
@@ -1357,6 +1370,12 @@ int __fastcall LoadBuffer_h(void *L, const char *buff, unsigned size, const char
g_origLoadBuffer(L, full.data(), static_cast<unsigned>(full.size()), name);
if (armed && rc != 0)
g_loadingAddon[0] = '\0';
// Materialize the wrapped chunk's inner function. The main is helper-local
// binds plus `return function(...) … end` — closure creation only, it
// cannot raise — so a plain lua_call is safe, and it leaves the inner
// function exactly where the engine expects the compiled chunk.
if (wrapped && rc == 0)
Game::Lua::Call(L, 0, 1);
return rc;
}
+2
View File
@@ -433,4 +433,6 @@ void PrepareForReload() {
CancelJob(job);
}
static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};
} // namespace Model::DisplayInfo
+13 -15
View File
@@ -59,13 +59,9 @@ namespace NamePlate::Events {
namespace {
constexpr const char *kEventCreated = "NAME_PLATE_CREATED";
constexpr const char *kEventUnitAdded = "NAME_PLATE_UNIT_ADDED";
constexpr const char *kEventUnitRemoved = "NAME_PLATE_UNIT_REMOVED";
const Event::Custom::AutoReserve _r1{kEventCreated};
const Event::Custom::AutoReserve _r2{kEventUnitAdded};
const Event::Custom::AutoReserve _r3{kEventUnitRemoved};
const Event::Custom::AutoReserve _evtCreated{"NAME_PLATE_CREATED"};
const Event::Custom::AutoReserve _evtUnitAdded{"NAME_PLATE_UNIT_ADDED"};
const Event::Custom::AutoReserve _evtUnitRemoved{"NAME_PLATE_UNIT_REMOVED"};
// Previous tick's snapshot — GUID → nameplate-frame pointer for each
// nameplated unit. Compared against the next tick's walk to compute
@@ -112,14 +108,14 @@ int AssignSlot(uint64_t guid) {
return static_cast<int>(g_slots.size() - 1);
}
// Fire `eventName` with a pre-formatted string as `arg1`. The engine
// Fire `event` with a pre-formatted string as `arg1`. The engine
// dispatcher's `%s` format code pushes the C string into `_G.arg1`
// as a Lua string — no escaping concerns for our own input
// (`"nameplateN"`).
void FireWithString(const char *eventName, const char *value) {
void FireWithString(const Event::Custom::AutoReserve &event, const char *value) {
if (value == nullptr)
return;
const int slot = Event::Custom::Lookup(eventName);
const int slot = event.Slot();
if (slot < 0)
return;
Event::Custom::Fire(slot, "%s", value);
@@ -172,10 +168,10 @@ using LuaRefRef_t = int(__fastcall *)(void *L, int t);
using LuaRefUnref_t = void(__fastcall *)(void *L, int t, int ref);
using LuaRawGetI_t = void(__fastcall *)(void *L, int t, int n);
void FireWithFrame(const char *eventName, void *frame) {
void FireWithFrame(const Event::Custom::AutoReserve &event, void *frame) {
if (frame == nullptr)
return;
const int slot = Event::Custom::Lookup(eventName);
const int slot = event.Slot();
if (slot < 0)
return;
@@ -229,7 +225,7 @@ void OnWorldTick() {
// event handler.
for (const auto &kv : g_currentTickPlates) {
if (g_seenPlates.insert(kv.second).second)
FireWithFrame(kEventCreated, const_cast<void *>(kv.second));
FireWithFrame(_evtCreated, const_cast<void *>(kv.second));
if (g_lastTickPlates.find(kv.first) == g_lastTickPlates.end()) {
const int slot = AssignSlot(kv.first);
// Watch this unit's fields so UNIT_HEALTH/UNIT_AURA/… fire with
@@ -237,7 +233,7 @@ void OnWorldTick() {
// target/party/raid tokens, not nameplates).
Unit::TokenObserver::Register(kv.first, &NamePlateFieldCb);
char tokenBuf[24];
FireWithString(kEventUnitAdded,
FireWithString(_evtUnitAdded,
FormatNamePlateToken(tokenBuf, sizeof tokenBuf, slot + 1));
}
}
@@ -254,7 +250,7 @@ void OnWorldTick() {
continue;
const int oneBased = static_cast<int>(it - g_slots.begin()) + 1;
char tokenBuf[24];
FireWithString(kEventUnitRemoved,
FireWithString(_evtUnitRemoved,
FormatNamePlateToken(tokenBuf, sizeof tokenBuf, oneBased));
Unit::TokenObserver::Unregister(kv.first, &NamePlateFieldCb);
*it = 0; // free the slot (no shift of survivors)
@@ -294,6 +290,8 @@ void PrepareForReload() {
g_slots.clear();
}
static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};
// Exposed via `nameplate/Walk.h` so the `nameplateN` token resolver
// in `unit/TokenExtensions.cpp` can map an index to a GUID without seeing
// the internal array. Returns 0 for an out-of-range OR currently-free slot.
+2 -3
View File
@@ -109,8 +109,7 @@ int __fastcall EquipSlotChanged_cb(uint32_t fieldOffset, uint32_t /*size*/,
const int slot0 =
static_cast<int>(fieldOffset - Offsets::OFF_DESC_PLAYER_EQUIP_FIRST) >> 3;
if (slot0 >= 0 && slot0 < Offsets::DESC_PLAYER_EQUIP_SLOTS) {
Event::Custom::FireIdSuccess(Event::Custom::Lookup(kEvtEquipmentChanged),
slot0 + 1,
Event::Custom::FireIdSuccess(_r.Slot(), slot0 + 1,
SlotHasItem(guidLo, guidHi, slot0));
// Gear swap changes item +healing and Spirit/Armor — invalidate the
// GetSpellBonusHealing cache.
@@ -225,7 +224,7 @@ void __fastcall AlertsRecompute_h() {
return;
}
if (changed)
Event::Custom::Fire(Event::Custom::Lookup(kEvtDurability), "");
Event::Custom::Fire(_r2.Slot(), "");
}
static const Game::HookAutoRegister _alertsHook{
+1 -2
View File
@@ -68,8 +68,7 @@ void __fastcall BindPointUpdateHandler_h(void *packetBuffer) {
static_cast<uintptr_t>(Offsets::VAR_IN_WORLD)) == 0)
return;
const int slot = Event::Custom::Lookup(kEventName);
Event::Custom::Fire(slot, "");
Event::Custom::Fire(_reserve.Slot(), "");
}
} // namespace
+12 -18
View File
@@ -43,12 +43,12 @@ namespace Player::InputEvents {
namespace {
constexpr const char *kStartedMovingEvent = "PLAYER_STARTED_MOVING";
constexpr const char *kStoppedMovingEvent = "PLAYER_STOPPED_MOVING";
constexpr const char *kStartedLookingEvent = "PLAYER_STARTED_LOOKING";
constexpr const char *kStoppedLookingEvent = "PLAYER_STOPPED_LOOKING";
constexpr const char *kStartedTurningEvent = "PLAYER_STARTED_TURNING";
constexpr const char *kStoppedTurningEvent = "PLAYER_STOPPED_TURNING";
const Event::Custom::AutoReserve _reserveStartedMoving{"PLAYER_STARTED_MOVING"};
const Event::Custom::AutoReserve _reserveStoppedMoving{"PLAYER_STOPPED_MOVING"};
const Event::Custom::AutoReserve _reserveStartedLooking{"PLAYER_STARTED_LOOKING"};
const Event::Custom::AutoReserve _reserveStoppedLooking{"PLAYER_STOPPED_LOOKING"};
const Event::Custom::AutoReserve _reserveStartedTurning{"PLAYER_STARTED_TURNING"};
const Event::Custom::AutoReserve _reserveStoppedTurning{"PLAYER_STOPPED_TURNING"};
// Below this per-frame delta, treat the yaw as stable. Picks up
// real rotation (smallest user-perceptible RMB-drag is ~0.5°/frame
@@ -85,12 +85,12 @@ const uint8_t *Camera() {
gameState, Offsets::OFF_GAME_STATE_CAMERA_PTR);
}
void FireTransition(bool now, bool &prev, const char *startedName,
const char *stoppedName) {
void FireTransition(bool now, bool &prev, const Event::Custom::AutoReserve &started,
const Event::Custom::AutoReserve &stopped) {
if (now == prev)
return;
prev = now;
const int slot = Event::Custom::Lookup(now ? startedName : stoppedName);
const int slot = (now ? started : stopped).Slot();
if (slot >= 0)
Event::Custom::Fire(slot, "");
}
@@ -172,19 +172,13 @@ void OnWorldTick() {
g_havePrevCameraYaw = true;
}
FireTransition(moving, g_wasMoving, kStartedMovingEvent, kStoppedMovingEvent);
FireTransition(turning, g_wasTurning, kStartedTurningEvent, kStoppedTurningEvent);
FireTransition(looking, g_wasLooking, kStartedLookingEvent, kStoppedLookingEvent);
FireTransition(moving, g_wasMoving, _reserveStartedMoving, _reserveStoppedMoving);
FireTransition(turning, g_wasTurning, _reserveStartedTurning, _reserveStoppedTurning);
FireTransition(looking, g_wasLooking, _reserveStartedLooking, _reserveStoppedLooking);
}
} // namespace
static const Event::Custom::AutoReserve _reserveStartedMoving{kStartedMovingEvent};
static const Event::Custom::AutoReserve _reserveStoppedMoving{kStoppedMovingEvent};
static const Event::Custom::AutoReserve _reserveStartedLooking{kStartedLookingEvent};
static const Event::Custom::AutoReserve _reserveStoppedLooking{kStoppedLookingEvent};
static const Event::Custom::AutoReserve _reserveStartedTurning{kStartedTurningEvent};
static const Event::Custom::AutoReserve _reserveStoppedTurning{kStoppedTurningEvent};
static const Tick::WorldTick::AutoSubscribe _tickSub{&OnWorldTick};
} // namespace Player::InputEvents
+3 -3
View File
@@ -33,8 +33,8 @@ static const Event::Custom::AutoReserve _reserveQuestDataLoadResult{kQuestDataLo
static void __stdcall QuestLoadCallback(void *userData, int success) {
const auto questID =
static_cast<int>(reinterpret_cast<uintptr_t>(userData));
Event::Custom::FireIdSuccess(Event::Custom::Lookup(kQuestDataLoadResult),
questID, success != 0);
Event::Custom::FireIdSuccess(_reserveQuestDataLoadResult.Slot(), questID,
success != 0);
}
static void RequestAndMaybeNotify(uint32_t questID) {
@@ -45,7 +45,7 @@ static void RequestAndMaybeNotify(uint32_t questID) {
// invoking our callback. Fire the event ourselves so addons get the
// notification regardless of cache state, matching modern semantics.
if (wasCached) {
Event::Custom::FireIdSuccess(Event::Custom::Lookup(kQuestDataLoadResult),
Event::Custom::FireIdSuccess(_reserveQuestDataLoadResult.Slot(),
static_cast<int>(questID), true);
}
}
+2 -2
View File
@@ -157,7 +157,7 @@ void __fastcall QuestLogRebuild_h(int param_1) {
// (login or post-reload). Modern WoW's QUEST_ACCEPTED doesn't
// fire on initial sync either; we match that.
if (newCount == 1) {
const int slot = Event::Custom::Lookup(kAcceptedEventName);
const int slot = _reserveAccepted.Slot();
if (slot >= 0)
Event::Custom::Fire(slot, "%d%d", firstNewIdx, firstNewID);
}
@@ -168,7 +168,7 @@ void __fastcall QuestLogRebuild_h(int param_1) {
// all but one of the previous character's quests (1 removal, N
// additions in the same rebuild).
if (removedCount == 1 && newCount <= 1) {
const int slot = Event::Custom::Lookup(kRemovedEventName);
const int slot = _reserveRemoved.Slot();
if (slot >= 0)
Event::Custom::Fire(slot, "%d", firstRemovedID);
}
+1 -2
View File
@@ -77,8 +77,7 @@ int __fastcall Handler_h(void *thisPlayer, void *edx, void *packetStream) {
const int result = Handler_o(thisPlayer, edx, packetStream);
if (questID > 0) {
const int slot = Event::Custom::Lookup(kEventName);
Event::Custom::Fire(slot, "%u%u%u",
Event::Custom::Fire(_reserve.Slot(), "%u%u%u",
questID, xpReward, moneyReward);
}
+13 -9
View File
@@ -514,14 +514,18 @@ void HandleSpellStart(uint64_t caster, int spellID, uint32_t castTime,
now - g_cast.startMs < kCastStartDedupMs) {
// Confirming packet. Keep startMs (no visual restart), but SNAP the
// end time to the server's authoritative castTime. The client stamp
// came from FUN_006e3340, which folds in the caster's cast-speed /
// ranged-haste multiplier (descriptor +0x22c) — right for spells the
// server also hastes (Aimed/Multi-Shot), WRONG for ones it doesn't.
// Volley is the case that surfaced this: not channeled, not sped by
// Quick Shots server-side, so the hasted prediction ended the bar
// early and the player was "still casting after the bar finished."
// The server's castTime is reality; reconcile to it (preserving any
// pushback already accumulated). A no-op when client and server agree.
// came from FUN_006e3340, whose only caster factor is the cast-speed
// multiplier at descriptor +0x22c (UNIT_MOD_CAST_SPEED — spell
// haste); the server additionally scales ranged ABILITIES by ranged
// attack speed (SpellEntry::GetCastTime's IsRangedSpell branch,
// m_modAttackSpeedPct[RANGED_ATTACK] — quiver/Quick Shots), which
// the prediction can't see. Two real divergences so far: Volley
// (client +0x22c hastes it, server doesn't → bar ended early) and
// Steady/Aimed Shot (server ranged-hastes it, client doesn't → bar
// ran long, pfUI#43). The server's castTime is reality; reconcile
// to it (preserving accumulated pushback). A no-op when they agree;
// when they differ, PollPlayer sees the end move and fires
// UNIT_SPELLCAST_DELAYED so cast bars re-read the corrected times.
g_cast.endMs =
g_cast.startMs + static_cast<int>(castTime) + g_cast.delayMs;
g_castTargetGuid = targetGuid; // confirming packet carries the target
@@ -837,7 +841,7 @@ void OnWorldTick() {
// based so it needs no changes to the many stamp/clear sites; ~1 frame
// latency is imperceptible for a cast bar, and every fire is
// listener-gated (near-free when no addon uses these).
Spell::CastEvents::PollPlayer(g_cast.spellID, g_cast.startMs, g_cast.delayMs,
Spell::CastEvents::PollPlayer(g_cast.spellID, g_cast.startMs, g_cast.endMs,
g_channel.spellID, g_channel.startMs);
Spell::CastEvents::PollRemote();
Spell::CastEvents::PollReticle();
+35 -41
View File
@@ -31,33 +31,20 @@ namespace Spell::CastEvents {
namespace {
constexpr const char *kStart = "UNIT_SPELLCAST_START";
constexpr const char *kStop = "UNIT_SPELLCAST_STOP";
constexpr const char *kDelayed = "UNIT_SPELLCAST_DELAYED";
constexpr const char *kChannelStart = "UNIT_SPELLCAST_CHANNEL_START";
constexpr const char *kChannelStop = "UNIT_SPELLCAST_CHANNEL_STOP";
constexpr const char *kChannelUpdate = "UNIT_SPELLCAST_CHANNEL_UPDATE";
constexpr const char *kSucceeded = "UNIT_SPELLCAST_SUCCEEDED";
constexpr const char *kInterrupted = "UNIT_SPELLCAST_INTERRUPTED";
constexpr const char *kFailed = "UNIT_SPELLCAST_FAILED";
constexpr const char *kFailedQuiet = "UNIT_SPELLCAST_FAILED_QUIET";
constexpr const char *kSent = "UNIT_SPELLCAST_SENT";
constexpr const char *kReticleTarget = "UNIT_SPELLCAST_RETICLE_TARGET";
constexpr const char *kReticleClear = "UNIT_SPELLCAST_RETICLE_CLEAR";
const Event::Custom::AutoReserve _rStart{kStart};
const Event::Custom::AutoReserve _rStop{kStop};
const Event::Custom::AutoReserve _rDelayed{kDelayed};
const Event::Custom::AutoReserve _rChannelStart{kChannelStart};
const Event::Custom::AutoReserve _rChannelStop{kChannelStop};
const Event::Custom::AutoReserve _rChannelUpdate{kChannelUpdate};
const Event::Custom::AutoReserve _rSucceeded{kSucceeded};
const Event::Custom::AutoReserve _rInterrupted{kInterrupted};
const Event::Custom::AutoReserve _rFailed{kFailed};
const Event::Custom::AutoReserve _rFailedQuiet{kFailedQuiet};
const Event::Custom::AutoReserve _rSent{kSent};
const Event::Custom::AutoReserve _rReticleTarget{kReticleTarget};
const Event::Custom::AutoReserve _rReticleClear{kReticleClear};
// The reservations double as the fire handles (`k*.Slot()` — O(1)).
const Event::Custom::AutoReserve kStart{"UNIT_SPELLCAST_START"};
const Event::Custom::AutoReserve kStop{"UNIT_SPELLCAST_STOP"};
const Event::Custom::AutoReserve kDelayed{"UNIT_SPELLCAST_DELAYED"};
const Event::Custom::AutoReserve kChannelStart{"UNIT_SPELLCAST_CHANNEL_START"};
const Event::Custom::AutoReserve kChannelStop{"UNIT_SPELLCAST_CHANNEL_STOP"};
const Event::Custom::AutoReserve kChannelUpdate{"UNIT_SPELLCAST_CHANNEL_UPDATE"};
const Event::Custom::AutoReserve kSucceeded{"UNIT_SPELLCAST_SUCCEEDED"};
const Event::Custom::AutoReserve kInterrupted{"UNIT_SPELLCAST_INTERRUPTED"};
const Event::Custom::AutoReserve kFailed{"UNIT_SPELLCAST_FAILED"};
const Event::Custom::AutoReserve kFailedQuiet{"UNIT_SPELLCAST_FAILED_QUIET"};
const Event::Custom::AutoReserve kSent{"UNIT_SPELLCAST_SENT"};
const Event::Custom::AutoReserve kReticleTarget{"UNIT_SPELLCAST_RETICLE_TARGET"};
const Event::Custom::AutoReserve kReticleClear{"UNIT_SPELLCAST_RETICLE_CLEAR"};
// Autoshot spams client-side failures while ramping — nampower filters it
// out of its failure event, so do we.
@@ -108,8 +95,9 @@ void BuildCastGuid(char *out, size_t n, int type, int spellID, int castUID) {
// rank)`. Gated on a listener so an unwatched event does no DBC lookups or
// string formatting. A null name/rank pushes `nil` through the dispatcher's
// `lua_pushstring(NULL) → pushnil` tail-jump, which is fine.
void Fire(const char *eventName, int spellID, int guidNum, int type = 3) {
const int slot = Event::Custom::Lookup(eventName);
void Fire(const Event::Custom::AutoReserve &event, int spellID, int guidNum,
int type = 3) {
const int slot = event.Slot();
if (!Event::Custom::HasListeners(slot))
return;
const uint8_t *rec = Spell::Lookup::RecordForID(spellID);
@@ -127,7 +115,7 @@ void Fire(const char *eventName, int spellID, int guidNum, int type = 3) {
// inserted at arg2. `target` is a unit token (e.g. "target") resolved from
// the cast packet, or "" for self / no-target casts.
void FireSent(int spellID, int guidNum, const char *target) {
const int slot = Event::Custom::Lookup(kSent);
const int slot = kSent.Slot();
if (!Event::Custom::HasListeners(slot))
return;
const uint8_t *rec = Spell::Lookup::RecordForID(spellID);
@@ -148,8 +136,8 @@ void FireSent(int spellID, int guidNum, const char *target) {
// the load-bearing fields — are exact; only arg2 differs (`""` vs `nil`),
// which is inconsequential for a reticle (no cast to identify). spellName /
// rank are our usual extension tail.
void FireReticle(const char *eventName, int spellID) {
const int slot = Event::Custom::Lookup(eventName);
void FireReticle(const Event::Custom::AutoReserve &event, int spellID) {
const int slot = event.Slot();
if (!Event::Custom::HasListeners(slot))
return;
const uint8_t *rec = Spell::Lookup::RecordForID(spellID);
@@ -176,7 +164,7 @@ int g_guidCounter = 0;
int g_castSpell = 0; // 0 = not casting
int g_castStart = 0; // startMs of the tracked cast (detects same-spell recast)
int g_castGuid = 0; // castGUID counter value for the tracked cast
int g_castDelay = 0; // last-seen accumulated pushback (ms)
int g_castEnd = 0; // last-seen endMs (any movement fires DELAYED)
bool g_castSucceeded = false; // SPELL_GO seen for the tracked cast this cast
// UNIT_SPELLCAST_INTERRUPTED de-dup. SpellFailed_h and PollPlayer can both
@@ -382,9 +370,9 @@ const Net::SendObserver::AutoSubscribe _sendSub{&OnSend};
// the payload is fanned out per token (`target` / `focus` / `nameplateN` /
// `party` / `raid` / `mouseover`). Same `(unit, castGUID, spellID, spellName,
// rank)` shape as the player events, just with a non-"player" unit.
void FireRemote(const char *eventName, uint64_t casterGuid, int spellID,
int guidNum) {
const int slot = Event::Custom::Lookup(eventName);
void FireRemote(const Event::Custom::AutoReserve &event, uint64_t casterGuid,
int spellID, int guidNum) {
const int slot = event.Slot();
if (!Event::Custom::HasListeners(slot))
return;
const uint8_t *rec = Spell::Lookup::RecordForID(spellID);
@@ -441,7 +429,7 @@ RemoteEvt *AllocRemoteEvt(uint64_t guid) {
bool PlayerCastSucceeded() { return g_castSucceeded; }
void PollPlayer(int castSpellID, int castStartMs, int castDelayMs,
void PollPlayer(int castSpellID, int castStartMs, int castEndMs,
int channelSpellID, int channelStartMs) {
// ---- Regular cast -------------------------------------------------
// A "new cast" is a different spell OR the same spell re-stamped at a
@@ -474,12 +462,18 @@ void PollPlayer(int castSpellID, int castStartMs, int castDelayMs,
g_castGuid = NextCastGuid(castSpellID);
g_castSpell = castSpellID;
g_castStart = castStartMs;
g_castDelay = castDelayMs;
g_castEnd = castEndMs;
g_castSucceeded = false;
Fire(kStart, castSpellID, g_castGuid);
} else if (g_castSpell != 0 && castDelayMs > g_castDelay) {
// Pushback grew (SMSG_SPELL_DELAYED extended the cast).
g_castDelay = castDelayMs;
} else if (g_castSpell != 0 && castEndMs != g_castEnd) {
// The cast's end moved: pushback (SMSG_SPELL_DELAYED extends it) or
// the confirming SMSG_SPELL_START snapping the client-predicted cast
// time to the server's authoritative one — the server scales ranged
// abilities by ranged attack speed (Steady/Aimed Shot), which the
// client's prediction helper doesn't model, so the confirming packet
// shortens the bar ~RTT after START (pfUI#43). Either direction, the
// addon must re-read the times; DELAYED is the re-read trigger.
g_castEnd = castEndMs;
Fire(kDelayed, g_castSpell, g_castGuid);
}
+6 -2
View File
@@ -45,11 +45,15 @@ namespace Spell::CastEvents {
// after its own upkeep, passing the live `g_cast` / `g_channel` fields.
// Detects, against the previous snapshot:
// - regular cast start / stop / same-spell recast → UNIT_SPELLCAST_START / _STOP
// - accumulated pushback growth → UNIT_SPELLCAST_DELAYED
// - end-time movement (either direction) → UNIT_SPELLCAST_DELAYED
// - channel start / stop → UNIT_SPELLCAST_CHANNEL_START / _STOP
// End-time movement covers both pushback (SMSG_SPELL_DELAYED) and the
// confirming SMSG_SPELL_START reconciling the client-predicted cast time to
// the server's (ranged-haste-scaled Steady/Aimed Shot, pfUI#43) — DELAYED is
// the "re-read the times" trigger, whichever way the end moved.
// Channels never fire INTERRUPTED — retail emits only CHANNEL_STOP for a
// channel whether it ends naturally or is cut short.
void PollPlayer(int castSpellID, int castStartMs, int castDelayMs,
void PollPlayer(int castSpellID, int castStartMs, int castEndMs,
int channelSpellID, int channelStartMs);
// Derive the ground-target reticle events from the engine's targeting flags.
+187
View File
@@ -0,0 +1,187 @@
// 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 <https://www.gnu.org/licenses/>.
#include "Game.h"
#include "Offsets.h"
#include "dbc/Lookup.h"
#include "spell/Lookup.h"
#include <cstdint>
// `GetNumTrackingTypes()` / `GetTrackingInfo(index)` / `SetTracking(index)` —
// backport of the minimap-tracking enumeration the modern client exposes.
//
// Vanilla 1.12 never enumerates the tracking abilities the player KNOWS — it
// only stores the single currently-active tracker as a plain spellID in
// `VAR_ACTIVE_TRACKING_SPELL`, surfaced through `GetTrackingTexture()` /
// `CancelTrackingBuff()` / `GameTooltip:SetTrackingSpell()`. 3.3.5's
// `GetTrackingInfo` iterates a spellbook-derived list of tracking spells and
// reports name/texture/active/category per entry; we rebuild that list here.
//
// A tracking spell is identified exactly the way the engine's own active-
// tracker updater `FUN_004E4170` identifies one: a Spell.dbc record with an
// `EffectApplyAuraName` of Track Creatures (44), Track Resources (45), or
// Track Stealthed (151). That effect-based test reproduces pfUI's hardcoded
// spellID/icon table (Find Herbs/Minerals/Treasure/Trees, every Hunter
// Track*, Sense Undead/Demons, Track Humanoids) with no table to maintain,
// and auto-covers server-custom trackers such as Turtle's Find Trees (52917).
namespace Spell::Tracking {
// Tracking aura effect types — SPELL_AURA_TRACK_* ApplyAura names, the same
// values `FUN_004E4170` scans a spell's three effects for.
static constexpr int32_t AURA_TRACK_CREATURES = 44;
static constexpr int32_t AURA_TRACK_RESOURCES = 45;
static constexpr int32_t AURA_TRACK_STEALTHED = 151;
// True iff `spellID`'s record has any of the three Track* effects.
static bool IsTrackingSpell(int spellID) {
const uint8_t *record = Spell::Lookup::RecordForID(spellID);
if (record == nullptr)
return false;
auto *aura = Game::Ptr<const int32_t>(
record, Offsets::OFF_SPELL_RECORD_EFFECT_APPLY_AURA_NAME);
for (int i = 0; i < Offsets::SPELL_RECORD_EFFECT_COUNT; ++i) {
if (aura[i] == AURA_TRACK_CREATURES || aura[i] == AURA_TRACK_RESOURCES ||
aura[i] == AURA_TRACK_STEALTHED)
return true;
}
return false;
}
// Walks the player spellbook in slot order counting tracking spells. If
// `wantNth >= 1` and an Nth tracking spell exists, writes its spellID and
// 1-based spellbook slot to `*outSpellID` / `*outSlot`. Returns the total
// number of tracking spells found (so callers detect out-of-range by
// comparing the return against `wantNth`).
//
// The spellbook array is zero-padded past the populated count (see
// `Spell::Lookup::FindSpellbookSlot`), so a 0 entry is just an empty slot —
// skip it and keep scanning the full range rather than break, matching the
// existing spellbook walkers.
static int EnumerateTracking(int wantNth, int *outSpellID, int *outSlot) {
auto *book = reinterpret_cast<const int *>(
static_cast<uintptr_t>(Offsets::VAR_PLAYER_SPELLBOOK));
int found = 0;
for (int i = 0; i < Offsets::SPELLBOOK_MAX_SLOTS; ++i) {
const int spellID = book[i];
if (spellID <= 0 || !IsTrackingSpell(spellID))
continue;
++found;
if (found == wantNth) {
if (outSpellID != nullptr)
*outSpellID = spellID;
if (outSlot != nullptr)
*outSlot = i + 1;
}
}
return found;
}
// `GetNumTrackingTypes()` -> number of tracking spells in the player's book.
static int __fastcall Script_GetNumTrackingTypes(void *L) {
Game::Lua::PushNumber(L,
static_cast<double>(EnumerateTracking(0, nullptr, nullptr)));
return 1;
}
// `GetTrackingInfo(index)` -> name, texture, active, category, spellID.
// - index is 1-based into the tracking list (spellbook order).
// - texture is the SpellIcon.dbc path (nil if the icon is missing).
// - active is a boolean: the tracker currently in effect.
// - category is always "spell" — vanilla has no non-spell ("other")
// trackers, unlike 3.3.5's class-masked table.
// - spellID is a ClassicAPI extension (the modern 5th return is `nested`,
// which has no meaning here); handy since selecting/among trackers is
// spellID-driven.
// Returns nil for an out-of-range index.
static int __fastcall Script_GetTrackingInfo(void *L) {
if (!Game::Lua::IsNumber(L, 1)) {
Game::Lua::Error(L, "Usage: GetTrackingInfo(index)");
return 0;
}
const int index = static_cast<int>(Game::Lua::ToNumber(L, 1));
if (index < 1)
return 0;
int spellID = 0;
int slot = 0;
if (EnumerateTracking(index, &spellID, &slot) < index)
return 0; // index past the number of tracking types -> nil
const uint8_t *record = Spell::Lookup::RecordForID(spellID);
const int locale = Game::Read<int>(static_cast<uintptr_t>(Offsets::VAR_LOCALE_INDEX));
const char *name =
Game::Read<const char *>(record, Offsets::OFF_SPELL_NAMES + locale * 4);
const char *texture = nullptr;
const int iconID = Game::Read<int>(record, Offsets::OFF_SPELL_RECORD_ICON_ID);
if (auto *iconRec = DBC::Record(Offsets::VAR_SPELL_ICON_RECORDS,
Offsets::VAR_SPELL_ICON_COUNT,
static_cast<uint32_t>(iconID))) {
texture = Game::Read<const char *>(iconRec, Offsets::OFF_SPELLICON_PATH);
}
const bool active =
Game::Read<int>(static_cast<uintptr_t>(Offsets::VAR_ACTIVE_TRACKING_SPELL)) ==
spellID;
Game::Lua::PushString(L, name); // 1. name (PushString handles NULL -> nil)
Game::Lua::PushString(L, texture); // 2. texture (icon path) or nil
Game::Lua::PushBool(L, active); // 3. active
Game::Lua::PushString(L, "spell"); // 4. category
Game::Lua::PushNumber(L, static_cast<double>(spellID)); // 5. spellID (extension)
return 5;
}
// `SetTracking(index)` — selects (activates) the tracking spell at `index`.
// Vanilla has no "set tracking" primitive: choosing a tracker IS casting its
// spell (the tracking dropdown does exactly this). So we resolve the entry's
// spellbook slot and tail-call the engine's own `Script_CastSpell(slot,
// "spell")` — reusing its slot bounds-check, target resolution, and error
// handling rather than reconstructing the cast path. Returns nil for an
// out-of-range index.
static int __fastcall Script_SetTracking(void *L) {
if (!Game::Lua::IsNumber(L, 1)) {
Game::Lua::Error(L, "Usage: SetTracking(index)");
return 0;
}
const int index = static_cast<int>(Game::Lua::ToNumber(L, 1));
if (index < 1)
return 0;
int spellID = 0;
int slot = 0;
if (EnumerateTracking(index, &spellID, &slot) < index)
return 0;
// Rebuild the stack as CastSpell(slot, "spell") and hand off to the
// engine handler. `slot` is 1-based, matching what a Lua `CastSpell`
// caller passes.
Game::Lua::SetTop(L, 0);
Game::Lua::PushNumber(L, static_cast<double>(slot));
Game::Lua::PushString(L, "spell");
using CastSpell_t = int(__fastcall *)(void *);
auto castSpell = reinterpret_cast<CastSpell_t>(Offsets::FUN_SCRIPT_CAST_SPELL);
return castSpell(L);
}
static void RegisterLuaFunctions() {
Game::Lua::RegisterGlobalFunction("GetNumTrackingTypes",
&Script_GetNumTrackingTypes);
Game::Lua::RegisterGlobalFunction("GetTrackingInfo", &Script_GetTrackingInfo);
Game::Lua::RegisterGlobalFunction("SetTracking", &Script_SetTracking);
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace Spell::Tracking
+2
View File
@@ -2039,4 +2039,6 @@ void PrepareForReload() {
g_nodeBakedColor.clear();
}
static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};
} // namespace Text::InlineTexture
+2
View File
@@ -559,4 +559,6 @@ void PrepareForReload() {
g_maintainDisabled = false; // re-arm the SEH latch for the fresh UI
}
static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};
} // namespace Text::InlineTexturePool
+83 -94
View File
@@ -23,17 +23,23 @@
// bind the mask(s) on texture units 1..N (the MODULATE combiner multiplies each
// mask's alpha into the base's alpha) and re-run the engine's own submit.
//
// Two mask sources, two sampling paths:
// * SetMask("path") — the mask samples at the base's own texcoords, so it
// rides the explicit second UV stream (uv1 = uv0). One mask max: the
// engine's vertex-format table has no third UV set.
// * AddMaskTexture(maskRegion) — positioned masks. These use TEXGEN, the same
// mechanism as the engine's own minimap-disc mask (FUN_004ec440): each
// unit's UV is generated from the raw vertex POSITION and mapped through a
// per-unit texture matrix built from the mask's rect (plus its SetRotation,
// which is just a rotation term in the matrix). No vertex stream needed, so
// up to 7 simultaneous masks (device-stage-cap-clamped), each independently
// positioned, sized, rotated, and animated.
// Two mask sources, ONE sampling path — TEXGEN, the same mechanism as the
// engine's own minimap-disc mask (FUN_004ec440): each unit's UV is generated
// from the raw vertex POSITION and mapped through a per-unit texture matrix.
// No vertex stream is consumed per mask, so up to 7 simultaneous masks
// (device-stage-cap-clamped), and both sources compose (alpha intersection):
// * SetMask("path") — the matrix is built from the BASE region's own rect
// (+ its SetRotation, so the mask follows a rotated base). Position-based
// on purpose: the original recipe here (the minimap BLIP mask's
// FUN_004eae10, explicit second UV stream with uv1 = uv0) sampled the mask
// at the base's texcoords, which breaks for SetTexCoord'd sprites — the
// mask is then sampled at the same sub-rect OF THE MASK IMAGE, showing a
// corner chunk of the shape instead of the shape. Texgen spans the drawn
// quad regardless of texcoords (retail semantics); for default 0..1
// texcoords the two formulas are identical (see BuildMaskMatrix).
// * AddMaskTexture(maskRegion) — positioned masks: matrix from the mask
// region's rect (plus its SetRotation, a rotation term in the matrix);
// each independently positioned, sized, rotated, and animated.
//
// State discipline: the queued draw is only flushed at the indexed submit
// (FUN_GX_PRIM_INDEXED) the engine issues right after this stream call, so the
@@ -130,51 +136,7 @@ using PrimStreams_t = void(__fastcall *)(int count, const void *pos, int posStri
PrimStreams_t g_primStreamsOriginal = nullptr;
// Runs the engine's own submit with the mask bound on unit 1 and uv1 = uv0.
// Returns true if it drew; false if the mask isn't resident yet (caller draws
// the base unmasked this frame and retries next). POD-only body for the SEH
// wrapper.
bool MaskedDrawImpl(void *maskH, int count, const void *pos, int posStride, const void *s3,
int s3Stride, const void *colors, int colorStride, int drop8, int drop9,
const void *uv0, int uv0Stride) {
// Per-frame residency reference (force=1), exactly like the minimap's mask.
void *maskCGx =
reinterpret_cast<GetRenderable_t>(Offsets::FUN_TEXTURE_GET_RENDERABLE)(maskH, 1, nullptr);
if (maskCGx == nullptr)
return false;
auto rs = reinterpret_cast<GxRsSet_t>(Offsets::FUN_GX_RS_SET);
auto rsPtr = reinterpret_cast<GxRsSetPtr_t>(Offsets::FUN_GX_RS_SET_PTR);
// Historical note: this push/pop pair was believed to be a per-unit
// enable/disable; it's actually unit 1's texture-matrix push/pop (binding
// is what enables a stage). The pair is a net no-op here but its
// dirty-marking is part of the exact sequence this path shipped and was
// verified with — left untouched.
reinterpret_cast<GxTexMtxOp_t>(Offsets::FUN_GX_TEXMTX_PUSH)(1);
rsPtr(Offsets::GXRS_TEXTURE0 + 1, maskCGx); // bind mask on unit 1
// Force unit 1's combiner to MODULATE, exactly as the engine's own masked
// draw FUN_004eae10 does (GxRs(0x20, 1)) — robust vs. relying on the
// backend default.
rs(Offsets::GXRS_COMBINER0 + 1, Offsets::GXRS_COMBINE_MODULATE);
// uv1 = uv0 → unit 1 samples the mask at the base's texcoords.
g_primStreamsOriginal(count, pos, posStride, s3, s3Stride, colors, colorStride, drop8, drop9,
uv0, uv0Stride, uv0, uv0Stride);
reinterpret_cast<GxTexMtxOp_t>(Offsets::FUN_GX_TEXMTX_POP)(1);
return true;
}
bool SafeMaskedDraw(void *maskH, int count, const void *pos, int posStride, const void *s3,
int s3Stride, const void *colors, int colorStride, int drop8, int drop9,
const void *uv0, int uv0Stride) {
__try {
return MaskedDrawImpl(maskH, count, pos, posStride, s3, s3Stride, colors, colorStride,
drop8, drop9, uv0, uv0Stride);
} __except (EXCEPTION_EXECUTE_HANDLER) {
g_enabled = false; // disable the feature for the session
return true; // may have partly drawn — don't double-draw
}
}
// --- object mask: clip the base to a positioned mask region ------------------
// --- region rect resolution ---------------------------------------------------
using RegionGetRect_t = int(__thiscall *)(void *anchor, float *outTLBR);
using RegionResolve_t = void(__thiscall *)(void *anchor, int flag);
@@ -197,13 +159,13 @@ bool RegionRect(void *region, float outTLBR[4]) {
return reinterpret_cast<RegionGetRect_t>(Offsets::FUN_REGION_GET_RECT)(anchor, outTLBR) != 0;
}
// --- texgen path: positioned masks on units 1..N -----------------------------
// --- texgen: every mask samples on its own unit, 1..N -------------------------
//
// Each mask unit samples via texgen (object-space position) through a texture
// matrix mapping the raw vertex position to the mask's UV — the engine's own
// minimap-disc-mask mechanism. Outside the mask's rect the UV leaves [0,1] and
// the sampler clamps to the mask's transparent border, clipping the base
// (verified live on the uv1 path; same sampler state).
// (verified live on the original uv1 = uv0 SetMask recipe; same sampler state).
//
// The position→UV map is affine, derived from two verified facts:
// * corner positions and the layout rect share the same anchor-unit space
@@ -219,8 +181,10 @@ bool RegionRect(void *region, float outTLBR[4]) {
// v = ( s·x − c·y + Ty − maskTop ) / maskHd [maskHd = bottom − top]
// with c = cos a, s = sin a, pivot P in rendered space, and
// Tx = Px·(1−c) − s·(midY−Py), Ty = Py + c·(midY−Py) − s·Px
// (a = 0 ⇒ u = (x − left)/W, v = (midY − y − top)/Hd — exactly the shipped and
// verified uv1-path formula re-expressed through positions).
// (a = 0 ⇒ u = (x − left)/W, v = (midY − y − top)/Hd — exactly the retired
// uv1 = uv0 SetMask recipe's formula re-expressed through positions, so a
// path mask on a default-texcoord texture renders identically to that
// shipped-and-verified path).
bool BuildMaskMatrix(const float mr[4], float midY, bool rotated, float angle, float cxN,
float cyN, float out[16]) {
const float mW = mr[3] - mr[1]; // left→right
@@ -285,13 +249,15 @@ void __fastcall PrimIndexed_h(int primType, int indexCount, const void *indices)
// Runs the engine submit with each mask bound on its own unit via texgen. All
// fallible resolution happens before any Gx state is touched; the restores run
// in PrimIndexed_h. POD-only body for the SEH wrapper.
bool MaskedRegionDrawImpl(void *base, void *const *masks, int maskCount, int count,
const void *pos, int posStride, const void *s3, int s3Stride,
const void *colors, int colorStride, int drop8, int drop9,
const void *uv0, int uv0Stride) {
// Stage budget: units 1..(cap−1), 7 max. Extra masks are dropped, first-
// added wins — the base still draws with every mask that fits.
// in PrimIndexed_h. Returns false when a mask isn't resolvable yet (caller
// draws the base unmasked this frame and retries next). POD-only body for the
// SEH wrapper.
bool MaskedRegionDrawImpl(void *base, void *pathMaskH, void *const *masks, int maskCount,
int count, const void *pos, int posStride, const void *s3,
int s3Stride, const void *colors, int colorStride, int drop8,
int drop9, const void *uv0, int uv0Stride) {
// Stage budget: units 1..(cap−1), 7 max. Extra masks are dropped, path
// mask then Add order — the base still draws with every mask that fits.
void *dev = Game::Read<void *>(Offsets::VAR_GX_DEVICE);
if (dev == nullptr)
return false;
@@ -300,8 +266,6 @@ bool MaskedRegionDrawImpl(void *base, void *const *masks, int maskCount, int cou
usable = 7;
if (usable < 1)
return false;
if (maskCount > usable)
maskCount = usable;
float br[4]; // base rect {top, left, bottom, right}
if (!RegionRect(base, br))
@@ -315,26 +279,45 @@ bool MaskedRegionDrawImpl(void *base, void *const *masks, int maskCount, int cou
void *cgx[7];
float mtx[7][16];
for (int i = 0; i < maskCount; ++i) {
int units = 0;
// The path mask (SetMask) spans the base's own rect and follows the base's
// rotation — the exact matrix a mask region covering the base would get.
// Per-frame residency reference (force=1), exactly like the minimap's mask.
if (pathMaskH != nullptr) {
cgx[units] = reinterpret_cast<GetRenderable_t>(Offsets::FUN_TEXTURE_GET_RENDERABLE)(
pathMaskH, 1, nullptr);
if (cgx[units] == nullptr)
return false;
float angle = 0.0f, cxN = 0.5f, cyN = 0.5f;
const bool rotated = Texture::Transform::GetRotation(base, &angle, &cxN, &cyN);
if (!BuildMaskMatrix(br, midY, rotated, angle, cxN, cyN, mtx[units]))
return false;
++units;
}
for (int i = 0; i < maskCount && units < usable; ++i, ++units) {
// The mask's owned HTEXTURE (stored by SetTexture at +0xCC, present
// even while hidden — the draw-entry array only exists after a render,
// which a hidden mask never gets). Resolving to a renderable each frame
// IS the residency reference, exactly like the path-mask path.
// IS the residency reference, same as the path mask above.
void *hTex = Game::Read<void *>(masks[i], Offsets::OFF_SIMPLETEXTURE_HTEXTURE);
if (hTex == nullptr)
return false;
cgx[i] = reinterpret_cast<GetRenderable_t>(Offsets::FUN_TEXTURE_GET_RENDERABLE)(hTex, 1,
nullptr);
if (cgx[i] == nullptr)
cgx[units] = reinterpret_cast<GetRenderable_t>(Offsets::FUN_TEXTURE_GET_RENDERABLE)(
hTex, 1, nullptr);
if (cgx[units] == nullptr)
return false;
float mr[4];
if (!RegionRect(masks[i], mr))
return false;
float angle = 0.0f, cxN = 0.5f, cyN = 0.5f;
const bool rotated = Texture::Transform::GetRotation(masks[i], &angle, &cxN, &cyN);
if (!BuildMaskMatrix(mr, midY, rotated, angle, cxN, cyN, mtx[i]))
if (!BuildMaskMatrix(mr, midY, rotated, angle, cxN, cyN, mtx[units]))
return false;
}
if (units == 0)
return false;
// Infallible tail. Track each push as it lands so a fault mid-sequence
// never pops something that wasn't pushed.
@@ -344,7 +327,7 @@ bool MaskedRegionDrawImpl(void *base, void *const *masks, int maskCount, int cou
auto rsPtr = reinterpret_cast<GxRsSetPtr_t>(Offsets::FUN_GX_RS_SET_PTR);
reinterpret_cast<void(__fastcall *)()>(Offsets::FUN_GX_STATE_PUSH)();
g_pendingRestore = 1u;
for (int i = 0; i < maskCount; ++i) {
for (int i = 0; i < units; ++i) {
const int unit = 1 + i;
rsPtr(Offsets::GXRS_TEXTURE0 + unit, cgx[i]);
rs(Offsets::GXRS_COMBINER0 + unit, Offsets::GXRS_COMBINE_MODULATE);
@@ -358,13 +341,13 @@ bool MaskedRegionDrawImpl(void *base, void *const *masks, int maskCount, int cou
return true;
}
bool SafeMaskedRegionDraw(void *base, void *const *masks, int maskCount, int count,
const void *pos, int posStride, const void *s3, int s3Stride,
const void *colors, int colorStride, int drop8, int drop9,
const void *uv0, int uv0Stride) {
bool SafeMaskedRegionDraw(void *base, void *pathMaskH, void *const *masks, int maskCount,
int count, const void *pos, int posStride, const void *s3,
int s3Stride, const void *colors, int colorStride, int drop8,
int drop9, const void *uv0, int uv0Stride) {
__try {
return MaskedRegionDrawImpl(base, masks, maskCount, count, pos, posStride, s3, s3Stride,
colors, colorStride, drop8, drop9, uv0, uv0Stride);
return MaskedRegionDrawImpl(base, pathMaskH, masks, maskCount, count, pos, posStride, s3,
s3Stride, colors, colorStride, drop8, drop9, uv0, uv0Stride);
} __except (EXCEPTION_EXECUTE_HANDLER) {
RestoreAfterDraw(); // pop exactly what was pushed before the fault
g_enabled = false;
@@ -386,23 +369,27 @@ void __fastcall PrimStreams_h(int count, const void *pos, int posStride, const v
// effectively impossible.
void *region = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(pos) -
Offsets::OFF_SIMPLETEXTURE_CORNERS);
// Positioned mask regions (AddMaskTexture) win over a path mask.
// A path mask (SetMask) and positioned mask regions (AddMaskTexture)
// compose — every mask MODULATEs into the same draw.
void *pathMaskH = nullptr;
if (!g_regionMask.empty()) {
auto it = g_regionMask.find(region);
if (it != g_regionMask.end())
pathMaskH = it->second.handle;
}
void *const *masks = nullptr;
int maskCount = 0;
if (!g_baseMasks.empty()) {
auto mit = g_baseMasks.find(region);
if (mit != g_baseMasks.end() && !mit->second.empty()) {
if (SafeMaskedRegionDraw(region, mit->second.data(),
static_cast<int>(mit->second.size()), count, pos,
posStride, s3, s3Stride, colors, colorStride, drop8,
drop9, uv0, uv0Stride))
return;
masks = mit->second.data();
maskCount = static_cast<int>(mit->second.size());
}
}
auto it = g_regionMask.find(region);
if (it != g_regionMask.end() && it->second.handle != nullptr) {
if (SafeMaskedDraw(it->second.handle, count, pos, posStride, s3, s3Stride, colors,
colorStride, drop8, drop9, uv0, uv0Stride))
return;
}
if ((pathMaskH != nullptr || maskCount > 0) &&
SafeMaskedRegionDraw(region, pathMaskH, masks, maskCount, count, pos, posStride, s3,
s3Stride, colors, colorStride, drop8, drop9, uv0, uv0Stride))
return;
}
g_primStreamsOriginal(count, pos, posStride, s3, s3Stride, colors, colorStride, drop8, drop9,
uv0, uv0Stride, uv1, uv1Stride);
@@ -604,4 +591,6 @@ void PrepareForReload() {
g_maskRegions.clear();
}
static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};
} // namespace Texture::Mask
+2
View File
@@ -674,6 +674,8 @@ void PrepareForReload() {
g_fsBaseline.clear();
}
static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};
// Fresh-bake entry (the inline-texture DrawBuilder co-hook): the emitter just
// baked axis-aligned verts, so capture the baseline and apply the rotation. See
// ApplyToNode / Transform.h for the timing contract.
+16
View File
@@ -293,7 +293,23 @@ void RegisterLuaFunctions() {
} // namespace
// Cancel every pending timer and release its Lua registry callback before a
// /reload (or logout) resets the Lua state. Otherwise g_timers would carry
// entries whose "ClassicAPI.Timer.N" registry callbacks died with the reset:
// the WorldTick fire pass drops a nil callback safely, but a surviving/stale
// registry ref could fire a dead closure. Clearing here is the consistent,
// correct behavior — a reload cancels pending timers, matching modern WoW,
// where C_Timer callbacks are Lua closures that don't survive the reset.
void PrepareForReload() {
if (void *L = Game::Lua::State())
for (const auto &t : g_timers)
ReleaseCallback(L, t.id);
g_timers.clear();
g_nextID = 1;
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};
static const Tick::WorldTick::AutoSubscribe _tick{&Tick};
} // namespace Time::Timer
+2
View File
@@ -253,4 +253,6 @@ void PrepareForReload() {
g_cellCount = 0;
}
static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};
} // namespace Tooltip::SetEvents
+133
View File
@@ -0,0 +1,133 @@
// 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 <https://www.gnu.org/licenses/>.
// Turtle WoW "Stinging Nettle" hunter talent (talent 403; rank passives
// 51579 / 51580): Mongoose Bite and triggered fire traps apply the hunter's
// highest known Serpent Sting rank at 20% (R1) / 40% (R2) of its duration.
//
// Server-side (tortoise-wow spell_hunter.cpp ApplyStingingNettle) the sting
// is a direct `target->AddAura(...)` — no cast, no SMSG_SPELL_GO for the
// sting itself — so the client sees only the descriptor application and
// OnAuraAdded would seat it caster-less at the full 15s base. The TRIGGERS
// are visible, though: Mongoose Bite is a real player cast, and the
// fire-trap effect spells are cast by the trap's OWNER (GameObject::Use
// TYPE_TRAP → pOwner->CastSpell) with non-zero SpellVisual, so they pass
// IsNeedSendToClient and their SMSG_SPELL_GO broadcasts with the hunter as
// caster and the victim in the hit list. Registered as Aura::Source
// triggered-application rules: the trigger arms its hit targets, and the
// caster-less Serpent Sting application that follows consumes the arm
// (player attribution + the server's max(1, base × pct / 100)).
//
// The rank gates are the talent-granted passives, read live from the
// spell-knowledge bitmap at trigger time (respec-safe); R2 registers first
// so its 40% wins while known. The percents come from the rank spells' own
// EffectBasePoints[0] + 1 — the same DBC value the server's
// CalculateSimpleValue reads (19 → 20%, 39 → 40%), with the server's own
// 20/40 fallback — so a Turtle rebalance that patches the client DBC tracks
// automatically.
//
// Server guards that mirror for free: no talent → no arm (gate fails, and
// the server applies nothing); an existing LONGER sting → the server skips
// AddAura entirely → no application event → the arm just expires. A nettle
// re-apply over a SHORTER existing sting reuses the descriptor slot (no
// OnAuraAdded, verified in-game with chained Mongoose Bites), so the arm
// mechanism additionally refreshes the existing cached entry at trigger
// time, mirroring the server's keep-the-longer rule — see
// RefreshTriggeredExisting in aura/Source.cpp. Other hunters' nettle stings
// stay at base duration (their talents aren't client-knowable).
//
// Gated on Turtle::Detected() via a WorldTick latch, like DurationMods —
// the trigger spells exist on stock 1.12, but the mechanic is Turtle's.
#include "Offsets.h"
#include "aura/Source.h"
#include "spell/Lookup.h"
#include "tick/WorldTick.h"
#include "turtle/Detect.h"
#include <cstdint>
namespace Turtle::StingingNettle {
namespace {
constexpr uint32_t kHunter = 9; // SPELLFAMILY_HUNTER
// Serpent Sting's SpellFamilyFlags bit — all player ranks carry it (1978,
// 13549..13555, 25295, and Turtle's added Rank 9, 33459; client DBC
// verified).
constexpr uint64_t kSerpentStingFlag = 0x4000;
constexpr uint32_t kNettleR1 = 51579; // 20%
constexpr uint32_t kNettleR2 = 51580; // 40%
// The rank's duration percent: its record's EffectBasePoints[0] + 1 (the
// server's CalculateSimpleValue), else the server's hardcoded fallback.
int32_t NettlePct(uint32_t rankSpellId, int32_t fallbackPct) {
const uint8_t *rec =
Spell::Lookup::RecordForID(static_cast<int>(rankSpellId));
if (rec == nullptr)
return fallbackPct;
const int32_t pct =
*reinterpret_cast<const int32_t *>(
rec + Offsets::OFF_SPELL_RECORD_EFFECT_BASE_POINTS) +
1;
return pct > 0 ? pct : fallbackPct;
}
// Fire-trap effects' SpellFamilyFlags bit. Verified exhaustively against the
// client Spell.dbc: bit 0x4 in the hunter family selects EXACTLY the eight
// spells Turtle's script binding lists (Immolation Trap Effect r1-5,
// Explosive Trap Effect r1-3) and nothing else — so the mask form is
// rank-proof, covering any future trap rank for free. (Freezing Trap is the
// distinct bit 0x8.)
constexpr uint64_t kFireTrapEffectFlag = 0x4;
// Mongoose Bite ranks must stay EXACT IDs: their family bit (0x2) is shared
// with all eight Raptor Strike ranks — verified against the DBC — and Raptor
// Strike does NOT trigger nettle server-side. Mask-matching it would keep a
// melee-weaving hunter's target permanently armed.
constexpr uint32_t kMongooseBite[] = {1495, 14269, 14270, 14271};
bool g_registered = false;
void RegisterAll() {
const int32_t pctR2 = NettlePct(kNettleR2, 40);
const int32_t pctR1 = NettlePct(kNettleR1, 20);
// Higher rank first — rules matching the same trigger arm in
// registration order, first live gate wins.
Aura::Source::AddTriggeredApplicationByFamily(
kHunter, kFireTrapEffectFlag, kNettleR2, kHunter, kSerpentStingFlag,
pctR2);
Aura::Source::AddTriggeredApplicationByFamily(
kHunter, kFireTrapEffectFlag, kNettleR1, kHunter, kSerpentStingFlag,
pctR1);
for (uint32_t id : kMongooseBite) {
Aura::Source::AddTriggeredApplication(id, kNettleR2, kHunter,
kSerpentStingFlag, pctR2);
Aura::Source::AddTriggeredApplication(id, kNettleR1, kHunter,
kSerpentStingFlag, pctR1);
}
}
void OnTick() {
if (g_registered || !Turtle::Detected())
return;
RegisterAll();
g_registered = true;
}
const Tick::WorldTick::AutoSubscribe _tickSub{&OnTick};
} // namespace
} // namespace Turtle::StingingNettle
+1 -1
View File
@@ -284,7 +284,7 @@ void Set(uint64_t guid) {
TokenObserver::Register(guid, &FocusFieldCb);
g_focusObserved = true;
}
const int slot = Event::Custom::Lookup(kEventName);
const int slot = _reserve.Slot();
if (slot >= 0)
Event::Custom::Fire(slot, "");
}
+1 -2
View File
@@ -173,8 +173,7 @@ void __fastcall BonusActionBarUpdate_h() {
if (current < 0 || current == s_lastForm)
return;
s_lastForm = current;
const int slot = Event::Custom::Lookup(kEventName);
Event::Custom::Fire(slot, "");
Event::Custom::Fire(_reserve.Slot(), "");
}
} // namespace
+61
View File
@@ -0,0 +1,61 @@
// 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 <https://www.gnu.org/licenses/>.
#include "Game.h"
#include "Offsets.h"
#include <cstdint>
namespace Unit::Sheath {
using ResolveUnitToken_t = void *(__fastcall *)(const char *token);
// `GetSheathState()` — returns which weapon type the local player currently
// has drawn. Takes no arguments. The return is **1-based**, matching modern
// WoW's contract:
// 1 = None (weapons sheathed / put away)
// 2 = Melee (melee weapon drawn)
// 3 = Ranged (ranged weapon drawn)
//
// Vanilla 1.12 ships `ToggleSheath` but no getter. The engine keeps the
// sheath state as a plain CGUnit int member at OFF_UNIT_SHEATH_STATE (+0xD40),
// 0-based (0 = sheathed, 1 = melee, 2 = ranged) — the same field the engine's
// own toggler `FUN_005EB480` reads to pick the next state and its setter
// `FUN_00611CF0` writes. We read the local player's value and add 1 for the
// Lua contract.
//
// Returns 1 (None) when the player CGUnit isn't resolvable yet (out of
// world) — the "weapons put away" default. `FUN_RESOLVE_UNIT_TOKEN` returns
// null for `"player"` out of world rather than raising, so this is safe from
// any context.
static int __fastcall Script_GetSheathState(void *L) {
auto resolve = reinterpret_cast<ResolveUnitToken_t>(Offsets::FUN_RESOLVE_UNIT_TOKEN);
auto *player = static_cast<const uint8_t *>(resolve("player"));
int state = 0;
if (player != nullptr)
state = Game::Read<int>(player, Offsets::OFF_UNIT_SHEATH_STATE);
if (state < 0 || state > 2)
state = 0; // guard against any unexpected value (field is 0/1/2)
Game::Lua::PushNumber(L, static_cast<double>(state + 1));
return 1;
}
static void RegisterLuaFunctions() {
Game::Lua::RegisterGlobalFunction("GetSheathState", &Script_GetSheathState);
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace Unit::Sheath
+21 -4
View File
@@ -108,6 +108,19 @@ constexpr const char *kEvtPlaybackStarted = "VOICE_CHAT_TTS_PLAYBACK_STARTED";
constexpr const char *kEvtSpeakTextUpdate = "VOICE_CHAT_TTS_SPEAK_TEXT_UPDATE";
constexpr const char *kEvtVoicesUpdate = "VOICE_CHAT_TTS_VOICES_UPDATE";
// The lazily-created reservations, set by RegisterLuaFunctions. Null while
// standing down for VanillaTTS — but the fire helpers only run from our own
// registered surface, so they never see null in that mode; SlotOf's guard is
// belt-and-suspenders (`Fire(-1)` no-ops).
const Event::Custom::AutoReserve *g_evtPlaybackFailed = nullptr;
const Event::Custom::AutoReserve *g_evtPlaybackFinished = nullptr;
const Event::Custom::AutoReserve *g_evtPlaybackStarted = nullptr;
const Event::Custom::AutoReserve *g_evtVoicesUpdate = nullptr;
int SlotOf(const Event::Custom::AutoReserve *r) {
return r != nullptr ? r->Slot() : -1;
}
// ---------------------------------------------------------------------------
// CVar names + handles (registered in RegisterLuaFunctions)
// ---------------------------------------------------------------------------
@@ -186,18 +199,18 @@ std::wstring Utf8ToWide(const char *s) {
// Event fire helpers (engine dispatcher via Event::Custom)
// ---------------------------------------------------------------------------
void FireVoicesUpdate() {
Event::Custom::Fire(Event::Custom::Lookup(kEvtVoicesUpdate), "");
Event::Custom::Fire(SlotOf(g_evtVoicesUpdate), "");
}
void FirePlaybackStarted(int numConsumers, int utteranceID, int durationMS, int dest) {
Event::Custom::Fire(Event::Custom::Lookup(kEvtPlaybackStarted), "%d%d%d%d",
Event::Custom::Fire(SlotOf(g_evtPlaybackStarted), "%d%d%d%d",
numConsumers, utteranceID, durationMS, dest);
}
void FirePlaybackFinished(int numConsumers, int utteranceID, int dest) {
Event::Custom::Fire(Event::Custom::Lookup(kEvtPlaybackFinished), "%d%d%d",
Event::Custom::Fire(SlotOf(g_evtPlaybackFinished), "%d%d%d",
numConsumers, utteranceID, dest);
}
void FirePlaybackFailed(const char *status, int utteranceID, int dest) {
Event::Custom::Fire(Event::Custom::Lookup(kEvtPlaybackFailed), "%s%d%d",
Event::Custom::Fire(SlotOf(g_evtPlaybackFailed), "%s%d%d",
status, utteranceID, dest);
}
@@ -565,6 +578,10 @@ void RegisterLuaFunctions() {
static const Event::Custom::AutoReserve _r3{kEvtPlaybackStarted};
static const Event::Custom::AutoReserve _r4{kEvtSpeakTextUpdate};
static const Event::Custom::AutoReserve _r5{kEvtVoicesUpdate};
g_evtPlaybackFailed = &_r1;
g_evtPlaybackFinished = &_r2;
g_evtPlaybackStarted = &_r3;
g_evtVoicesUpdate = &_r5;
g_cvarVoice = CVar::Factory::Register(kCVarVoice, "0", 0, &OnVoiceChanged);
g_cvarSpeed = CVar::Factory::Register(kCVarSpeed, "0", 0, &OnSpeedChanged);